# Vaspera Certify MCP Server

Enterprise-grade security certification for codebases **and AI agent systems** with deterministic scanners, LLM-powered analysis, and signed attestations.

[![Self-Certification](https://github.com/RCOLKITT/hardening-mcp/actions/workflows/certify.yml/badge.svg)](https://github.com/RCOLKITT/hardening-mcp/actions/workflows/certify.yml)
[![CI](https://github.com/RCOLKITT/hardening-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/RCOLKITT/hardening-mcp/actions/workflows/ci.yml)
![npm version](https://img.shields.io/npm/v/vaspera)
![License](https://img.shields.io/badge/License-MIT-green)
![Tools](https://img.shields.io/badge/MCP_Tools-117-purple)
![AI Frameworks](https://img.shields.io/badge/AI_Frameworks-5-blue)
![Scanners](https://img.shields.io/badge/Scanners-15-orange)
![Tests](https://img.shields.io/badge/Tests-1972-brightgreen)

> **We pass our own strictest certification on every commit.** The
> Self-Certification badge above is the live result of running this
> product against its own codebase as a blocking CI gate — the one claim
> a scanner-wrapper can't fake. [How it works »](docs/SELF-CERTIFICATION.md)
>
> **Don't trust us — verify.** Any agent certificate can be checked
> independently (`npm run verify:cert -- cert.json`, or `POST /verify`)
> with no token and no trust in Vaspera: it recomputes the content digest
> and checks the signature from the certificate itself.
> [Verifying a certificate »](docs/VERIFYING-A-CERTIFICATE.md)

---

## What's New: Pre-Launch Checklist + Cross-Tenant Proof

**Covers the 11-item pre-launch security checklist** every AI-built app needs — statically in the
free tier, with behavioral runtime proof on Pro. See [docs/pre-launch-checklist.md](docs/pre-launch-checklist.md).

- **`pre_launch_checklist`** — renders all 11 items (RLS, OWASP, headers, rate limits, CAPTCHA/CORS,
  client-exposed secrets, data leaks, error disclosure, …) as PASS / FAIL / NEEDS-RUNTIME for any repo.
- **The full deterministic vibe-safety stack is now default-on and free** — a plain `certification_scan`
  (no `auto_detect` needed) catches the classes that actually breach AI-built apps: **RLS-disabled
  Supabase/Postgres tables**, **client-exposed `NEXT_PUBLIC_*` secrets**, **cross-tenant IDOR / RLS-bypass**,
  **missing auth on endpoints**, **CSRF / CORS / security-headers / missing rate-limits**, **missing
  webhook-signature verification**, plus injection, scalability/DB antipatterns, container/IaC lint, and
  monorepo dependency SCA. See the full [Coverage Matrix](docs/COVERAGE-MATRIX.md) (class × tier × static/proof).
- Cross-tenant IDOR / OWASP A01 is the #1 web risk and the class deterministic SAST structurally misses
  (you can't regex a missing ownership check); the Vaspera detection engine, logic scanner, and
  eval-gated adversary tactics cover it — on by default (opt out per scan with `forceDisable`).
- **Runtime proof (Pro)** — `runtime_verify` exercises your running app to *prove* the behavioral items:
  a two-account cross-tenant isolation probe ("A can't read B") and auth failure-path testing
  (lockout, reset-enumeration, idempotency). A failed proof emits a critical finding that BLOCKS the cert.
- **CCPA / CPRA** compliance framework added (alongside GDPR + 12 others).
- **Self-improvement loop** — `feedback_report_miss` → `rules_propose_from_miss` → `rules_promote`
  turns a missed vulnerability into a regression fixture + a human-approved detection rule.

**Tiering:** Free = all 11 covered statically ($0). Pro = LLM adversarial reasoning + runtime proof of
#2 (cross-tenant) and #3 (auth failure-paths).

> Note: the features above ship in PRs #73–#76 — merge those before this doc set lands.

## What's New in v2.10.0

### Property-Based Testing
Robust scanner testing with fast-check property-based tests:

| Function | Properties Tested |
|----------|-------------------|
| `extractPathParams()` | All 4 framework styles (Express `:id`, Next.js `[id]`, Flask `<id>`, Spring `{id}`) |
| `inferResourceType()` | Singularization invariants (`-ies` → `-y`, `-ses` → `-s`) |
| `analyzeFilePath()` | Test/vendor/generated file classification |

### Expanded Eval Fixtures
22 test fixtures across 11 vulnerability categories (up from 13):

| Category | CWE | Fixtures |
|----------|-----|----------|
| `command-injection` | CWE-78 | 2 |
| `ssrf` | CWE-918 | 2 |
| `xxe` | CWE-611 | 1 |
| `insecure-deserialization` | CWE-502 | 2 |
| `rls-bypass` | CWE-639 | 2 |

### Constitution for Autofix Governance
Policy-based governance for autonomous autofix operations:

```yaml
# .vaspera/constitution.yaml
version: "1.0"
riskTolerance: "conservative"  # conservative | moderate | aggressive

patterns:
  - patternId: "qual-console-log"
    autoApprove: true
  - patternId: "sec-sql-injection"
    autoApprove: false
    requiredReviewer: "security-team"

directories:
  neverAutofix: ["node_modules", "vendor"]
  requireReview: ["src/auth/", "src/crypto/"]

safety:
  dryRunDefault: true
  maxFilesPerRun: 20
  runTestsAfterFix: true
  revertOnTestFailure: true
```

**Constitution Features:**
- **Risk Tolerance** — Control which patterns auto-apply based on risk level
- **Pattern Approvals** — Whitelist/blacklist specific fix patterns with conditions
- **Path Restrictions** — Block autofix in sensitive directories (auth, crypto)
- **Safety Constraints** — Enforce dry-run, test requirements, backup branches

---

## What's New in v2.9.0

### Universal Audit-Defensible Compliance Reports
All 13 compliance frameworks now support audit-defensible report generation:

| Feature | Description |
|---------|-------------|
| **Evidence Bundle** | Cryptographically signed artifacts with Sigstore |
| **Audit Trail Verification** | Hash-chained integrity verification |
| **Attestation Section** | Framework-specific methodology and scope limitations |

**Supported Frameworks:**
- **Traditional:** SOC2, ISO27001, PCI-DSS, HIPAA, 42-CFR-PART-2, GDPR, NIST-800-53, CIS
- **AI/ML:** OWASP-LLM, NIST-AI-RMF, MITRE-ATLAS, EU-AI-ACT, ISO-42001

**New Tool Parameters:**
```json
{
  "collect_evidence": true,
  "verify_audit_trail": true,
  "store_evidence": true,
  "include_attestation": true
}
```

### Healthcare Compliance Bundle
Unified HIPAA + 42 CFR Part 2 assessment for healthcare organizations:
- Single-command assessment for both frameworks
- Cross-reference between HIPAA and SUD confidentiality requirements
- Combined evidence bundle for audit defensibility

### 42 CFR Part 2 Framework
New compliance framework for Substance Use Disorder (SUD) patient record confidentiality:
- 15 controls across consent, disclosure, and security categories
- Cross-mapping to HIPAA Security Rule
- Healthcare-specific attestation content

---

## What's New in v2.8.0

### Agent Batch Submit Tool
New tool for submitting findings from subagent JSON output:
- **`agent_batch_submit`** - Submit all findings in one call when agents run as subagents
- Fixes MCP permission issues when certification agents don't have direct tool access
- Updated certification orchestration docs

### CI/CD Improvements
- Lazy Stripe initialization for builds without env vars
- TypeScript test timeout fixes for CI environments

---

## What's New in v2.7.0

### Plan Enforcement
- Plan limits for free/pro/enterprise tiers
- Certification monthly limits enforced at API level
- Agent count limits based on subscription plan
- Compliance framework access gating

| Limit | Free | Pro | Enterprise |
|-------|------|-----|------------|
| Certifications/month | 3 | 50 | Unlimited |
| Projects | 2 | 20 | Unlimited |
| Agents | 3 | 7 | All |
| Frameworks | SOC2 | SOC2, HIPAA, NIST | All |

---

## What's New in v2.5.0

### Mythos-Class Security Scanners 🔬
Three new deep-analysis scanners for low-level security vulnerabilities:

| Scanner | Focus | Detection |
|---------|-------|-----------|
| **binary-analysis** | Native modules, FFI | Missing RELRO/NX/PIE/CANARY, dangerous imports |
| **memory-safety** | C/C++/Rust memory bugs | Buffer overflow, use-after-free, double-free |
| **race-condition** | Concurrency bugs | TOCTOU, data races, lock issues |

**Binary Analysis** detects:
- Node.js native addons (binding.gyp, *.node)
- Shared libraries without stack protection
- Rust FFI boundaries and Go CGO usage
- Disabled FORTIFY_SOURCE

**Memory Safety** detects:
- Dangerous C functions: `strcpy`, `sprintf`, `gets`, `strcat`
- Buffer overflows (CWE-120, CWE-787)
- Use-after-free (CWE-416), double-free (CWE-415)
- Rust `unsafe` blocks with `transmute`

**Race Conditions** detects:
- TOCTOU (time-of-check-time-of-use) patterns
- Go goroutine data races
- Python threading with shared state
- Java check-then-act anti-patterns

### Semantic AI Agents 🧠
Three new AI-powered agents for deep code analysis:

| Agent | Focus | Capability |
|-------|-------|------------|
| **zero-day-hunter** | Novel vulnerabilities | Logic flaws, auth bypasses, crypto weaknesses |
| **logic-flaw-detector** | Business logic bugs | State inconsistencies, trust boundary issues |
| **exploit-chain** | Attack paths | Chains multiple findings into attack scenarios |

**Exploit Chain Analyzer** automatically:
- Chains vulnerabilities: Info disclosure → RCE, SSRF → Internal API
- Calculates severity escalation (medium + medium = critical)
- Maps to MITRE ATT&CK techniques
- Generates attack scenario narratives

### New MCP Tools
```
certification_scan_binary      # Scan native modules and binaries
certification_semantic_analysis # AI-powered code analysis
certification_analyze_chains   # Analyze finding chains
```

---

## What's New in v2.3.0

### Agent & MCP Security Certification 🤖
First-mover capability for certifying AI agent systems and MCP servers:

- **Prompt Injection Fuzzer** - 200+ payloads to test tool inputs for injection vulnerabilities
- **Exfiltration Path Analysis** - Graph-based detection of secret→network data flow paths
- **Tool Description Drift** - Detect silent changes to MCP tool definitions (rug-pull detection)
- **Permission Minimizer** - Analyze traces to recommend least-privilege permissions
- **Sandbox Audit** - Verify tools don't escape declared execution boundaries
- **Credential Scope Audit** - Flag over-scoped tokens (GitHub PATs, AWS IAM, etc.)

### AI Compliance Frameworks 📋
Five new AI-specific compliance frameworks:

| Framework | Controls | Use Case |
|-----------|----------|----------|
| **OWASP LLM Top 10** | 10 | AI application security |
| **NIST AI RMF** | 33 | Federal AI governance |
| **MITRE ATLAS** | 34 | AI threat modeling |
| **EU AI Act** | 33 | European AI regulation |
| **ISO/IEC 42001** | 38 | AI management systems |

### Signed Transcripts & Attestations ✍️
Tamper-evident audit trails for AI agent sessions:

- **Merkle Chain Integrity** - Cryptographically linked entries for tamper detection
- **Sigstore Signing** - Keyless signatures via Fulcio + Rekor transparency log
- **in-toto Provenance** - SLSA-compatible attestation statements
- **PII Redaction** - 12+ detection patterns (SSN, credit cards, API keys, JWTs)

### Enterprise Integrations 🏢
Production-ready integrations for large deployments:

- **OIDC SSO** - Okta, Auth0, Azure AD, Google with SCIM provisioning
- **OPA Policy Engine** - Rego policy evaluation for certification gates
- **Ticketing** - Jira, ServiceNow, Linear automatic issue creation
- **Chat Notifications** - Slack, Teams, Discord with rich certification cards
- **KMS Signing** - AWS KMS, GCP KMS, HashiCorp Vault for air-gapped deployments

---

## What's New in v2.1.0

### Auto-Detect Languages
Automatically detect project languages and enable appropriate scanners:
- **certification_detect_languages** - Detect JS, Python, Go, Ruby, Java, Docker, Terraform
- **auto_detect mode** - Pass `auto_detect: true` to `certification_scan`
- **Smart scanner selection** - Enables Bandit for Python, Gosec for Go, Brakeman for Ruby, etc.

### Brakeman Scanner (Ruby on Rails)
Complete Ruby security scanning with Brakeman:
- **SQL injection** - ActiveRecord query analysis
- **XSS** - Cross-site scripting in views
- **CSRF** - Cross-site request forgery detection
- **Mass assignment** - Dangerous model updates
- **Remote code execution** - eval, system, backticks
- **CWE mappings** - All findings mapped to CWE identifiers

### GDPR Compliance Framework
Full GDPR compliance mapping with 30+ controls:
- **Principles (Art. 5)** - Lawfulness, purpose limitation, data minimization
- **Data Protection by Design (Art. 25)** - Privacy by default
- **Security of Processing (Art. 32)** - Encryption, integrity, availability
- **Breach Notification (Art. 33-34)** - Incident response requirements
- **Control mapping** - Automatic finding-to-control linking

---

## What's New in v2.0.1

### Batch Auto-Fix
- **autofix_batch** - Apply all safe fixes at once with dry-run support
- **16 fix patterns** - IDOR, rate limiting, CSRF, cookies, SQL injection, XSS, and more

### Scanner Install Helper
- **certification_install_scanners** - Platform-specific install commands
- **run_install option** - Execute installation with confirmation
- **macOS/Linux/Windows** - Automatic platform detection

### SBOM Improvements
- **output_file** - Write SBOM directly to file

---

## What's New in v2.0.0

### Cost Tracking
Track and control LLM API costs across certifications:
- **Token counting** - Track input/output tokens per model
- **Budget limits** - Set cost budgets with automatic abort
- **Cost estimation** - Estimate costs before running
- **13 models supported** - Claude, GPT-4, Gemini pricing

### Consensus Aggregation
Aggregate findings from multiple runs for higher confidence:
- **Record findings** - From external agent runs (Claude, GPT, Gemini, etc.)
- **Disagreement detection** - Flag when runs produce conflicting results
- **Fleiss' kappa reliability** - Statistical inter-rater agreement
- **Weighted consensus** - Configurable weights per source

*Note: These tools aggregate results from external runs. They do not call LLM APIs directly.*

### Compliance Mapping
Map findings to enterprise compliance frameworks:
- **SOC 2 Type II** - All Trust Service Criteria
- **ISO 27001** - Annex A controls
- **PCI-DSS v4.0** - Payment card security
- **HIPAA** - Healthcare data protection
- **GDPR** - EU data protection (v2.1.0)
- **CIS Controls** - Security best practices
- **Control status** - Compliant/At-Risk/Non-Compliant
- **Gap analysis** - Identify missing controls

### SBOM & Provenance
Software Bill of Materials and supply chain security:
- **CycloneDX SBOM** - Dependency inventory
- **SLSA Provenance** - Build attestation
- **Sigstore signing** - Real cryptographic signing via Fulcio + Rekor

*Signing requires OIDC identity (GitHub Actions, GitLab CI, or SIGSTORE_ID_TOKEN).*

---

## Features

### Deterministic Scanner Backbone
Ground every finding in verifiable evidence with industry-standard scanners:
- **Semgrep** - OWASP Top 10, custom rules
- **gitleaks** - Secrets detection
- **npm audit** - Dependency vulnerabilities
- **TypeScript** - Type safety analysis
- **ESLint** - Code quality and security rules
- **Bandit** - Python security analysis
- **Gosec** - Go security checker
- **Brakeman** - Ruby on Rails security (v2.1.0)
- **Trivy** - Container/IaC vulnerability scanning
- **binary-analysis** - Native module security (v2.5.0)
- **memory-safety** - C/C++/Rust memory bugs (v2.5.0)
- **race-condition** - Concurrency vulnerabilities (v2.5.0)

### Enterprise Certification
Multi-agent validation with cross-verification:
- 9 specialized agents: security, reliability, typesafety, performance, quality, redteam, zero-day-hunter, logic-flaw-detector, exploit-chain (v2.5.0)
- Cross-verification between agents for high-confidence findings
- Consensus scoring with certification levels
- Exploit chain analysis for attack path mapping (v2.5.0)

### GitHub Action Integration
CI/CD integration with PR comments and Sigstore signing:
- **Security certification workflow** - Auto-detect languages, run scanners, generate reports
- **Sigstore signing** - OIDC-based signing with Fulcio + Rekor (requires `id-token: write`)
- **Automatic PR comments** - Findings summary on pull requests
- **SARIF upload** - GitHub Security tab integration

See [.github/workflows/certify.yml](.github/workflows/certify.yml) for example.

### Evaluation Harness
Measure scanner accuracy with labeled test fixtures:
- Precision, recall, F1 score metrics
- Stability testing across multiple runs
- Target thresholds for publication

## Quick Start

### Installation

```bash
# Install the CLI + MCP server globally (the npm package is `vaspera`)
npm install -g vaspera

# Verify it runs (the installed binary is `vaspera-hardening`)
vaspera-hardening --help

# …or run it without a global install:
npx -y -p vaspera vaspera-hardening --help
```

From source:

```bash
git clone https://github.com/RCOLKITT/hardening-mcp.git
cd hardening-mcp
npm install && npm run build
node dist/index.js --help
```

### Add to Claude Desktop

Edit `~/Library/Application Support/Claude/claude_desktop_config.json`.
After `npm install -g vaspera`, the `vaspera-hardening` binary is on your PATH:

```json
{
  "mcpServers": {
    "vaspera-hardening": {
      "command": "vaspera-hardening",
      "env": {
        "VASPERA_PROJECTS_DIR": "/path/to/your/projects"
      }
    }
  }
}
```

Prefer not to install globally? Use `npx` instead:

```json
{
  "mcpServers": {
    "vaspera-hardening": {
      "command": "npx",
      "args": ["-y", "-p", "vaspera", "vaspera-hardening"],
      "env": {
        "VASPERA_PROJECTS_DIR": "/path/to/your/projects"
      }
    }
  }
}
```

Running from a source checkout instead? Point `command` at `node` and
`args` at your built `dist/index.js`.

## MCP Tools

### Hardening Commands

| Tool | Description |
|------|-------------|
| `hardening_list_projects` | Discover all projects in workspace |
| `hardening_install` | Install hardening commands into a project |
| `hardening_install_all` | Install commands into all projects |
| `hardening_get_command` | Get a specific command prompt |
| `hardening_read_audit` | Read AUDIT.md from a project |
| `hardening_read_report` | Read HARDENING-REPORT.md |
| `hardening_dashboard` | Portfolio-wide readiness dashboard |
| `hardening_list_commands` | List available commands |

### Enterprise Certification

| Tool | Description |
|------|-------------|
| `certification_start` | Initialize enterprise certification |
| `certification_scan` | Run deterministic scanners (supports `auto_detect`) |
| `certification_detect_languages` | Auto-detect project languages for scanner selection |
| `certification_scanners_available` | Check scanner availability |
| `certification_install_scanners` | Get install commands for missing scanners |
| `certification_status` | Get certification progress |
| `certification_consensus` | Calculate consensus score |
| `certification_finalize` | Generate certification artifacts |
| `certification_dashboard` | Portfolio certification view |

### Mythos-Class Scanners (v2.5.0)

| Tool | Description |
|------|-------------|
| `certification_scan_binary` | Scan compiled code and native modules |
| `certification_semantic_analysis` | AI-powered semantic code analysis |
| `certification_analyze_chains` | Analyze findings for exploitable attack chains |

### Agent Tools

| Tool | Description |
|------|-------------|
| `agent_submit_finding` | Submit a finding from an agent |
| `agent_complete` | Mark agent run as complete |
| `agent_cross_verify` | Cross-verify another agent's finding |
| `redteam_challenge` | Challenge an area marked clean |

### Utilities

| Tool | Description |
|------|-------------|
| `certification_cross_verify` | Batch cross-verify critical findings |
| `certification_summary` | Progressive disclosure summary |
| `certification_filter` | Filter findings by criteria |
| `certification_export_sarif` | Export to SARIF format |
| `autofix_preview` | Preview auto-fix for a finding |
| `autofix_apply` | Apply auto-fix |
| `autofix_batch` | Batch apply all safe fixes |
| `autofix_list_patterns` | List available fix patterns |

### Custom Rules

| Tool | Description |
|------|-------------|
| `rules_load` | Load custom rules from config |
| `rules_templates` | List built-in rule templates |
| `rules_generate_config` | Generate sample rules config |
| `rules_check_file` | Check file against custom rules |

### Evaluation

| Tool | Description |
|------|-------------|
| `certification_eval` | Run evaluation against test fixtures |
| `certification_eval_fixtures` | Get fixture statistics |

### Cost Tracking (v2.0.0)

| Tool | Description |
|------|-------------|
| `cost_track` | Start tracking costs for a certification |
| `cost_estimate` | Estimate cost before running |
| `cost_status` | Get current cost status |
| `cost_report` | Generate cost report |
| `cost_budget` | Set/update budget limits |
| `cost_models` | List supported models and pricing |

### Consensus Aggregation (v2.0.0)

*These tools aggregate findings from external runs - they do NOT call LLM APIs.*

| Tool | Description |
|------|-------------|
| `consensus_record` | Record findings from an external agent run |
| `consensus_calculate` | Calculate consensus with Fleiss' kappa |
| `consensus_disagreements` | Get disagreements between runs |
| `consensus_merged` | Get deduplicated findings after consensus |
| `consensus_summary` | Generate consensus summary |
| `consensus_models` | List model configurations |
| `consensus_clear` | Clear recorded results |

### Compliance Mapping (v2.0.0, enhanced v2.9.0)

| Tool | Description |
|------|-------------|
| `compliance_report` | Generate compliance report for a framework (audit-defensible) |
| `compliance_multi_report` | Generate report for multiple frameworks (audit-defensible) |
| `compliance_controls` | List controls for a framework |
| `healthcare_compliance` | Unified HIPAA + 42 CFR Part 2 assessment (v2.9.0) |

### SBOM & Provenance (v2.0.0)

| Tool | Description |
|------|-------------|
| `sbom_generate` | Generate CycloneDX SBOM |
| `sbom_provenance` | Generate SLSA provenance attestation |
| `sbom_sign` | Sign content with Sigstore (requires OIDC) |
| `sbom_verify_provenance` | Verify provenance attestation |

### Agent & MCP Security (v2.3.0)

| Tool | Description |
|------|-------------|
| `agent_cert_scan` | Full agent-system certification against MCP server |
| `agent_cert_fuzz` | Quick prompt injection fuzzing (CI-friendly, <60s) |
| `agent_cert_attest` | Generate Sigstore-signed attestation bundle |
| `agent_cert_verify` | Verify attestation against live MCP server |
| `agent_cert_watch` | Continuous monitoring with drift detection |
| `agent_scanners_available` | Check agent scanner availability |

**Agent Scanners:**
- `manifest-audit` - Parse MCP manifest, flag security issues
- `tool-description-drift` - Detect silent tool definition changes
- `prompt-injection-fuzzer` - Fuzz inputs with 200+ payloads
- `exfil-path-graph` - Build secret→network data flow graph
- `permission-minimiser` - Recommend tightened permissions from traces
- `supply-chain-mcp` - SBOM + CVE scan for MCP dependencies
- `sandbox-audit` - Verify tools stay within declared boundaries
- `credential-scope-audit` - Flag over-scoped tokens

### AI Compliance Frameworks (v2.3.0)

| Tool | Description |
|------|-------------|
| `compliance_report` | Generate report (now supports AI frameworks) |

**Supported AI Frameworks:**
- `OWASP-LLM` - OWASP LLM Top 10 (10 controls)
- `NIST-AI-RMF` - NIST AI Risk Management Framework (33 controls)
- `MITRE-ATLAS` - ATLAS adversarial ML techniques (34 techniques)
- `EU-AI-ACT` - European AI Act compliance (33 controls)
- `ISO-42001` - ISO/IEC 42001 AI management (38 controls)

### Transcripts & Attestations (v2.3.0)

*Programmatic API - not exposed as MCP tools:*

```typescript
import {
  TranscriptLogger,
  signTranscript,
  verifyTranscriptBundle,
  redactPII
} from "vaspera/dist/transcripts/index.js";

// Create logger with Merkle chain
const logger = new TranscriptLogger("session-123");
logger.logPrompt("User prompt here");
logger.logToolCall("tool_name", "input data");
logger.logToolResult("tool_name", "output data");

// Generate signed transcript
const transcript = logger.generateSignedTranscript();
const bundle = await signTranscript(transcript, logger.getChain());

// Verify integrity
const result = await verifyTranscriptBundle(bundle, logger.getChain());
console.log(result.valid); // true

// Redact PII before logging
const { redacted, redactions } = redactPII("Contact: john@example.com");
// redacted = "Contact: [REDACTED:EMAIL]"
```

### Enterprise Integrations (v2.3.0)

*Programmatic API - not exposed as MCP tools:*

```typescript
import {
  createOIDCClient,
  createTicketingClient,
  createChatClient,
  createOPAClient,
  createKMSClient
} from "vaspera/dist/enterprise/index.js";

// OIDC SSO
const oidc = createOIDCClient({
  provider: "okta",
  clientId: "...",
  clientSecret: "...",
  issuerUrl: "https://company.okta.com",
  redirectUri: "https://app.example.com/callback",
});
const { url } = await oidc.getAuthorizationUrl();

// Ticketing
const jira = createTicketingClient({
  platform: "jira",
  baseUrl: "https://company.atlassian.net",
  apiToken: "...",
  email: "...",
  isCloud: true,
});
const ticket = await jira.createTicket({
  title: "[CRITICAL] SQL Injection in auth.ts",
  description: "...",
  findings: certificationFindings,
});

// Chat notifications
const slack = createChatClient({
  platform: "slack",
  webhookUrl: "https://hooks.slack.com/...",
});
await slack.sendNotification({
  certificationId: "cert-123",
  target: "myapp",
  status: "completed",
  score: 87,
  findings: { total: 12, critical: 0, high: 2, medium: 5, low: 5, info: 0 },
});

// OPA Policy
const opa = createOPAClient({
  mode: "local",
  bundlePath: "./policies/certification.json",
});
const policyResult = await opa.evaluate({ certification: {...} });

// KMS Signing (air-gapped alternative to Sigstore)
const kms = createKMSClient({
  provider: "vault",
  keyId: "signing-key",
  vault: { address: "https://vault.example.com", token: "..." },
});
const signed = await kms.sign(certificationJson);
```

## Typical Workflows

### Run Security Scan

```
You: "Scan this project for security issues"
→ Claude calls certification_scan
→ Returns findings from Semgrep, gitleaks, npm audit, TypeScript
```

### Full Enterprise Certification

```
You: "Start enterprise certification for this project"
→ Claude calls certification_start
→ Claude calls certification_scan (deterministic pre-pass)
→ Claude runs each agent (security, reliability, typesafety, etc.)
→ Claude calls certification_cross_verify (batch verify critical findings)
→ Claude calls certification_consensus
→ Claude calls certification_finalize
→ Generates CERTIFICATION.md and CERTIFICATION.json
```

### Evaluate Scanner Accuracy

```
You: "Run the evaluation harness to test scanner accuracy"
→ Claude calls certification_eval
→ Returns precision, recall, F1 scores against labeled fixtures
```

### Cost-Controlled Certification (v2.0.0)

```
You: "Run certification with a $5 budget limit"
→ Claude calls cost_track with budget: 5.00
→ Claude runs agents, tracking costs in real-time
→ If budget exceeded, certification pauses
→ Claude calls cost_report for final breakdown
```

### Consensus Aggregation (v2.0.0)

```
You: "Calculate consensus from my security agent runs"
→ User runs security agent via different MCP clients or APIs
→ User calls consensus_record for each run's findings
→ Claude calls consensus_calculate for agreement metrics
→ Claude calls consensus_disagreements for disputed findings
```

*Note: Consensus tools aggregate external results. Run agents separately.*

### Compliance Report (v2.0.0)

```
You: "Generate SOC 2 compliance report from certification"
→ Claude calls compliance_report with framework: "SOC2"
→ Returns control-by-control status with findings mapped
→ Identifies at-risk controls and gaps
```

### Generate SBOM (v2.0.0)

```
You: "Generate an SBOM for this project"
→ Claude calls sbom_generate
→ Returns CycloneDX SBOM with all dependencies
→ Claude calls sbom_provenance for build attestation
```

### Install Missing Scanners (v2.0.1)

```
You: "What scanners are missing and how do I install them?"
→ Claude calls certification_install_scanners
→ Returns platform-specific install commands for each scanner
→ Claude calls with run_install: true to execute installation
```

### Batch Auto-Fix (v2.0.1)

```
You: "Apply all safe fixes to the certification findings"
→ Claude calls autofix_batch with dry_run: true (preview)
→ Shows what would be changed
→ Claude calls autofix_batch with dry_run: false (apply)
→ Reports fixes applied by pattern and file
```

### Auto-Detect and Scan (v2.1.0)

```
You: "Scan this project with auto-detection"
→ Claude calls certification_scan with auto_detect: true
→ Detects Python, JavaScript, Go files
→ Automatically enables Bandit, npm-audit, Gosec
→ Returns unified findings from all relevant scanners
```

### GDPR Compliance Report (v2.1.0)

```
You: "Generate GDPR compliance report"
→ Claude calls compliance_report with framework: "GDPR"
→ Maps findings to GDPR articles (Art. 5, 25, 32, etc.)
→ Returns control status with gap analysis
```

### Audit-Defensible Compliance Report (v2.9.0)

```
You: "Generate audit-defensible SOC 2 report"
→ Claude calls compliance_report with:
   - framework: "SOC2"
   - collect_evidence: true
   - verify_audit_trail: true
   - include_attestation: true
→ Collects cryptographically signed evidence bundle
→ Verifies hash-chain integrity of audit trail
→ Generates report with attestation methodology
→ Returns audit-ready documentation
```

### Healthcare Compliance Assessment (v2.9.0)

```
You: "Run healthcare compliance assessment"
→ Claude calls healthcare_compliance
→ Assesses both HIPAA and 42 CFR Part 2 frameworks
→ Generates unified report with cross-references
→ Collects evidence bundle for audit defensibility
```

### Sigstore Signing (v2.1.1)

```
You: "Sign the SBOM with Sigstore"
→ Claude calls sbom_sign with the SBOM content
→ Gets OIDC token from GitHub Actions / GitLab CI
→ Obtains certificate from Fulcio
→ Records signature in Rekor transparency log
→ Returns signed bundle with log index
```

*Requires CI environment with OIDC (GitHub Actions: `permissions: id-token: write`)*

### Agent Security Certification (v2.3.0)

```
You: "Certify this MCP server for prompt injection vulnerabilities"
→ Claude calls agent_cert_scan with target and scanners
→ Runs manifest-audit, prompt-injection-fuzzer, exfil-path-graph
→ Returns findings with severity and remediation
→ Claude calls agent_cert_attest to generate signed bundle
```

### Quick Prompt Injection Fuzz (v2.3.0)

```
You: "Quick fuzz test on this MCP server - CI mode"
→ Claude calls agent_cert_fuzz with corpus: "quick"
→ Runs 50 high-priority payloads in <60 seconds
→ Returns pass/fail for each tool with behavior change detection
```

### AI Compliance Report (v2.3.0)

```
You: "Generate OWASP LLM Top 10 compliance report"
→ Claude calls compliance_report with framework: "OWASP-LLM"
→ Maps findings to LLM01-LLM10 controls
→ Returns control status with gap analysis
→ Identifies prompt injection, sensitive disclosure, excessive agency risks
```

### Binary & Memory Safety Scan (v2.5.0)

```
You: "Scan native modules for security issues"
→ Claude calls certification_scan_binary
→ Detects binding.gyp, *.node, Rust FFI, Go CGO
→ Checks RELRO, NX, PIE, CANARY protections
→ Reports missing stack protections and dangerous imports
```

### Exploit Chain Analysis (v2.5.0)

```
You: "Analyze findings for attack chains"
→ Claude calls certification_analyze_chains
→ Chains SSRF → internal API access
→ Chains XSS → session hijacking
→ Calculates escalated severity (medium + medium = critical)
→ Maps to MITRE ATT&CK techniques
```

### Create Tickets from Findings (v2.3.0)

```typescript
// Programmatic - create Jira tickets for critical/high findings
const jira = createTicketingClient({ platform: "jira", ... });
const result = await jira.createTicketsForFindings(findings, {
  project: "SEC",
  groupByCategory: true,
  minSeverity: "high",
});
console.log(`Created ${result.created.length} tickets`);
```

## Architecture

```
┌─────────────────────────────────────────────────────────────────────────────────────────┐
│                              Codebase Scanner Layer                                      │
├─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┤
│ Semgrep │npm audit│gitleaks │   tsc   │ ESLint  │ Bandit  │  Gosec  │Brakeman │  Trivy │
│ (OWASP) │ (CVEs)  │(secrets)│ (types) │ (lint)  │ (Python)│  (Go)   │ (Ruby)  │ (IaC)  │
└────┬────┴────┬────┴────┬────┴────┬────┴────┬────┴────┬────┴────┬────┴────┬────┴───┬────┘
     │         │         │         │         │         │         │         │        │
     └─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┘
                                              │
┌─────────────────────────────────────────────┼─────────────────────────────────────────┐
│                         Mythos-Class Scanner Layer (v2.5.0)                            │
├─────────────────────┬─────────────────────┬─┴───────────────────┬─────────────────────┤
│   Binary Analysis   │   Memory Safety     │   Race Condition    │   Exploit Chain     │
│  (native modules)   │  (C/C++/Rust bugs)  │  (concurrency)      │   (attack paths)    │
└──────────┬──────────┴──────────┬──────────┴──────────┬──────────┴──────────┬──────────┘
           │                     │                     │                     │
           └─────────────────────┴─────────────────────┴─────────────────────┘
                                              │
┌─────────────────────────────────────────────┼─────────────────────────────────────────┐
│                              Agent Scanner Layer (v2.3.0)                              │
├──────────────┬──────────────┬──────────────┬┴─────────────┬──────────────┬────────────┤
│   Manifest   │  Tool Drift  │   Prompt     │ Exfil Path   │  Permission  │ Credential │
│    Audit     │  Detection   │   Injection  │   Graph      │  Minimizer   │   Scope    │
│              │              │   Fuzzer     │              │              │   Audit    │
└──────┬───────┴──────┬───────┴──────┬───────┴──────┬───────┴──────┬───────┴─────┬──────┘
       │              │              │              │              │             │
       └──────────────┴──────────────┴──────────────┴──────────────┴─────────────┘
                                              │
                                    ┌─────────▼─────────┐
                                    │ Finding Aggregator │
                                    │ (confidence: 100)  │
                                    └─────────┬─────────┘
                                              │
                          ┌───────────────────┴───────────────────┐
                          ▼                                       ▼
                ┌─────────────────┐                     ┌─────────────────┐
                │ Compliance      │                     │ LLM Agents      │
                │ Mapper          │◄────────────────────│ (triage/enrich) │
                │ (10 frameworks) │                     │ + Privacy Agent │
                └────────┬────────┘                     │ + Integrity     │
                         │                              └─────────────────┘
                         ▼
                ┌─────────────────┐
                │ Transcript      │
                │ Logger          │──► Merkle Chain ──► Sigstore Signing
                │ + PII Redaction │
                └────────┬────────┘
                         │
                         ▼
                ┌─────────────────┐
                │ Enterprise      │──► OIDC SSO, OPA Policy, Ticketing, Chat
                │ Integrations    │
                └─────────────────┘
```

## Evidence Validation

Non-deterministic findings are validated to prevent hallucinations:
- Requires evidence (code snippet) for all LLM findings
- Validates evidence matches actual file content
- Deterministic scanner findings (confidence: 100) bypass validation

## Evaluation Metrics

Target metrics for scanner accuracy:

| Metric | Target | Description |
|--------|--------|-------------|
| Precision | >90% | Low false positives |
| Recall | >85% | Catches real issues |
| Stability | >95% | Consistent across runs |
| Agreement | >85% | Cross-agent confirmation |

## GitHub Action

```yaml
- uses: RCOLKITT/vaspera-hardening-action@v1
  with:
    mode: 'diff'  # scan | certify | diff
    fail-on: 'critical'  # critical | high | medium | none
    upload-sarif: true
    comment-on-pr: true
    anthropic-api-key: ${{ secrets.ANTHROPIC_API_KEY }}  # Optional for LLM features
```

## Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `VASPERA_PROJECTS_DIR` | `~/Documents/GitHub` | Base directory to scan |
| `ANTHROPIC_API_KEY` | - | API key for LLM features (optional) |
| `SIGSTORE_ID_TOKEN` | - | OIDC token for Sigstore signing |
| `ACTIONS_ID_TOKEN_REQUEST_TOKEN` | - | GitHub Actions OIDC (auto-set) |
| `VASPERA_OPA_BUNDLE` | - | Path to OPA policy bundle |
| `VASPERA_OPA_SERVER` | - | OPA server URL for remote evaluation |
| `VASPERA_TRANSCRIPT_DIR` | `.vaspera/transcripts` | Transcript storage directory |
| `VASPERA_TELEMETRY_ENABLED` | `unset` (off) | Set to `1` to opt IN to anonymous usage metrics (see [Telemetry](#telemetry)) |
| `VASPERA_TELEMETRY_DISABLED` / `DO_NOT_TRACK` | - | Hard kill switch — suppresses all telemetry even if enabled |

### Enterprise Environment Variables

| Variable | Description |
|----------|-------------|
| `VASPERA_OIDC_ISSUER` | OIDC issuer URL (Okta, Auth0, Azure AD) |
| `VASPERA_OIDC_CLIENT_ID` | OIDC client ID |
| `VASPERA_OIDC_CLIENT_SECRET` | OIDC client secret |
| `VASPERA_JIRA_URL` | Jira instance URL |
| `VASPERA_JIRA_TOKEN` | Jira API token |
| `VASPERA_SLACK_WEBHOOK` | Slack webhook URL |
| `VASPERA_TEAMS_WEBHOOK` | Microsoft Teams webhook URL |
| `VASPERA_AWS_KMS_KEY` | AWS KMS key ARN for signing |
| `VASPERA_VAULT_ADDR` | HashiCorp Vault address |
| `VASPERA_VAULT_TOKEN` | HashiCorp Vault token |

## Telemetry

**Telemetry is OPT-IN and OFF by default.** Vaspera scans private and often
regulated code, so out of the box **nothing leaves your machine**. On the first
run a one-time notice tells you telemetry is off and how to turn it on.

If you want to help improve the product, opt in:

```bash
export VASPERA_TELEMETRY_ENABLED=1
```

When enabled, only **anonymous, aggregate** metrics are sent — a random install
ID, a one-way hash of the project path, the Vaspera version, platform/Node
version, and result counts (score, severity totals, scanner, duration).
**Never** source code, file contents, finding details, secrets, file paths,
repo URLs, org names, or emails. Even with telemetry on, `DO_NOT_TRACK=1` or
`VASPERA_TELEMETRY_DISABLED=1` suppresses everything.

Full, authoritative details — including the exact payload and where it is sent
— are in [TELEMETRY.md](TELEMETRY.md).

## License

MIT
