Skip to content

About

Autonomous Security Guardrails & Governed Remediation for AI-Built Apps. Tri-Mode Parity (CLI, Chat Slash Commands, Native MCP Server), First-Principles Security Suite, Multi-Modal Vision OCR, 86 Rules across 22 Families & Ponytail Patch Bounds.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

128 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TorusGuard Logo

TorusGuard

The Hybrid Governance Security Engine for AI-built web applications.
Pairs the intelligence of your AI Agent with a deterministic Go CLI to enforce strict security boundaries and patch limits.

License: MIT Version npm: v2.2.0 Privacy: Local First Dependencies: Zero SARIF OWASP

Unit Tests: 100% Passing Polyglot Tests: 36/36 Repos Passed Tri-Mode Validation: 6/6 Unseen Stacks Passed Tri-Mode E2E: 16/16 Verified Vision OCR: Tested & Verified Rules: 88/88 Verified

Tri-Mode Parity Go Node.js Python TypeScript Rust


Table of Contents


What Is TorusGuard?

TorusGuard is a zero-dependency, single-binary security engine that scans, hardens, and validates AI-generated codebases. It enforces 88 security rules across 22 architectural families and works across three unified operational modes (Tri-Mode Parity):

  • Mode A: Terminal CLI (Go Binary) — A deterministic scanner and enforcer that runs in your terminal or CI/CD pipeline (torusguard <command>).
  • Mode B: AI Chat Slash Commands — Integrates natively with Antigravity, Cursor, Claude Code, Windsurf, VS Code, and other AI coding assistants via slash commands (/torusguard <command>).
  • Mode C: Native MCP Tools — Stdio Model Context Protocol (JSON-RPC 2.0) interface exposing autonomous security tools and living resources directly to AI agents.

TorusGuard ensures that the code your AI assistant writes is secure before it reaches production.


✨ Features

  • 88 Security Rules across 22 families (Secrets, Auth, SQL Injection, Deserialization, Open Redirects, SSRF, CSRF, GraphQL, Supply Chain, Containers, Git History, ReDoS, AI & RAG, and more)
  • Taint Analysis & Interprocedural Dataflow Engine — Cross-file, interprocedural taint flow tracking from untrusted sources to critical sinks across imports, modules, and call graphs
  • 7-Signal Calibrated Confidence Scorer — Evidence-chain calibration combining rule severity, taint confirmation, taint depth, sanitizer absence, framework context, multi-line evidence, and persistent memory
  • First-Principles Security Suite — Built-in native scanners for Dockerfile/Compose privilege bounds, Git commit log secret mining, exponential regex backtracking, and cross-tenant vector isolation
  • Polyglot Parser & AST Walker — Tree-sitter powered AST traversal with unified CST nodes and symbol resolution across Go, JavaScript, TypeScript, and Python
  • Incremental Hash Cache & Parallel Scanning — SHA-256 mtime incremental scan caching, process-pool parallelization, and continuous file-watcher debounce
  • Line-Level Reflection Module — Semantic patch synthesis (find_snippet / replace_snippet) that accurately replaces exact code blocks without brittle line-number offsets
  • 1/9th Token Bounded Context Extraction — AST context extraction (±3 lines) via scanner.ExtractContext to keep review prompts hyper-efficient and prevent context saturation
  • Ponytail Protocol — Surgical patch bounds (≤35 additions, ≤25 deletions) to prevent full-file rewrites
  • Pre-Apply Snapshots — Automatic .bak rollback snapshots before every code modification
  • SARIF v2.1.0 Export — Standards-compliant output for GitHub Advanced Security, VS Code, and other SARIF consumers
  • Dark-Mode HTML Reports — Single-file visual posture dashboards
  • Golden Fix Recipes — Persistent memory of verified security patterns for reuse
  • SSRF Defense — Built-in private IP blocking and AWS metadata protection in the web validator
  • Fail-Closed Cryptography — No fallback tokens; panics on entropy failure
  • DoS Resilience — 10,000-file scan limit and 5-minute context timeout to prevent resource exhaustion
  • 16+ Language Stack Detection — Go, Rust, Java, C#, PHP, Ruby, Kotlin, Elixir, Dart, Swift, Python, TypeScript, and more
  • Hybrid First-Principles Vision OCR — Built-in zero-dependency stream extractor (PNG chunks, SVG text, EXIF, byte streams) + optional deep neural optical scanning via Tesseract
  • Interactive Terminal Command Center — Launching torusguard with zero arguments renders an interactive, menu-driven command center in the terminal
  • Native MCP Server (Model Context Protocol) — Exposes standard JSON-RPC 2.0 stdio tools and resources for direct agent integration
  • 100% Tri-Mode Parity — Terminal CLI, AI Chat slash commands, and Native MCP Tools share identical governance workflows
  • Curated Awesome Catalog — Full standardized taxonomy of 88 Security Invariants across 22 architectural families

🧪 Proven Compatibility

TorusGuard’s static scanner and enforcement binary have been rigorously tested and confirmed compatible across 20 major technology stacks and frameworks:

Ecosystem Tested Frameworks & Runtimes
JavaScript / TypeScript React, Next.js, Express, Vue, Angular, SvelteKit, NestJS
Python Django, Flask, FastAPI, raw Python scripts
Go Gin
Java / C# (.NET) Spring Boot, ASP.NET Core, .NET Core Middleware
Ruby Ruby on Rails, Sinatra
PHP Laravel, Symfony
Rust Actix Web

🏗️ Autonomous Architecture & Workflow

TorusGuard uses a tri-track architecture where intelligence, deterministic enforcement, and agent tool execution are cleanly separated across three unified operational modes:

flowchart TD
    %% =========================================================================
    %% STAGE 1: TRI-MODE INGRESS GATEWAY
    %% =========================================================================
    subgraph IngressGateway["1. Unified Tri-Mode Ingress Gateway"]
        direction LR
        CLI["<b>Mode A: Terminal CLI</b><br/><code>torusguard &lt;cmd&gt;</code><br/>25 Deterministic Commands"]
        Chat["<b>Mode B: AI Chat Commands</b><br/><code>/torusguard &lt;cmd&gt;</code><br/>Cursor &bull; Claude &bull; Windsurf"]
        MCP["<b>Mode C: Native MCP Server</b><br/><code>torusguard_*</code> (13 Tools &bull; 2 Resources)<br/>Stdio JSON-RPC 2.0 Protocol"]
    end

    %% =========================================================================
    %% STAGE 2: CORE DISPATCHER & RUNTIME KERNEL
    %% =========================================================================
    Kernel["<b>TorusGuard Core Dispatcher &amp; Runtime Kernel</b><br/><code>cmd/torusguard</code> (Single Standalone Go Binary)<br/>Command Parsing &bull; Flag Evaluation (<code>--yes</code>, <code>--html</code>, <code>--rules</code>) &bull; Sandbox Isolation"]

    CLI -->|"Terminal Exec"| Kernel
    Chat -->|"Slash Bridge"| Kernel
    MCP -->|"Agent Tool Call"| Kernel

    %% =========================================================================
    %% STAGE 3: DETECTION & MULTI-MODAL SUITE
    %% =========================================================================
    subgraph DetectionSuite["2. Polyglot Static AST &amp; Multi-Modal Detection Suite"]
        direction TB
        subgraph StaticGroup["Static Code &amp; Dependency Analysis"]
            direction LR
            AST["<b>Polyglot AST &amp; Taint Engine</b><br/>Tree-sitter &bull; 88 Rules across 22 Families<br/>Go &bull; TS/JS &bull; Python &bull; Java &bull; C# &bull; Rust"]
            TGQL["<b>TG-QL Declarative AST DSL</b><br/>Custom YAML Pattern Queries<br/>Syntax Trees &bull; Taint Sinks &bull; Constraints"]
            Reach["<b>Reachability &amp; OpenVEX</b><br/>Callgraph Traversal &bull; Reachable CVEs<br/>Zero Ineffective Dependency Alerts"]
        end
        subgraph DeepGroup["Forensics, RegEx &amp; Vision OCR"]
            direction LR
            OCR["<b>Multi-Modal Vision OCR Engine</b><br/>Tesseract v5.4.0 &bull; Leaked Secrets<br/>Architecture Diagrams &bull; Screenshots"]
            ReDoS["<b>Thompson NFA ReDoS Engine</b><br/>Polynomial &amp; Exponential Exploder<br/>Catastrophic Backtracking Loops"]
            GitMine["<b>Git History &amp; Container Audit</b><br/>Commit Packfile Secret Mining<br/>Dockerfile Non-Root Enforcement"]
        end
    end

    Kernel -->|"Scan Code &amp; Dependencies"| StaticGroup
    Kernel -->|"Analyze Visuals &amp; Commits"| DeepGroup

    %% =========================================================================
    %% STAGE 4: CONSENSUS DELIBERATION & TRIAGE
    %% =========================================================================
    subgraph DeliberationTriage["3. Deliberation Tournament &amp; Evidence Triage"]
        direction TB
        Tournament["<b>3-Perspective Deliberation Tournament</b><br/>Vulnerability Hunter vs. Devil's Advocate / Sanitizer Verifier vs. Ponytail Remediator<br/>Eliminates False Positives &bull; Calibrated Confidence Scoring (0-100%)"]
        PRGate{"<b>Differential PR Diff Gate</b><br/><code>torusguard review</code><br/>Incremental Git Diff Changes?"}
        Tournament --> PRGate
    end

    StaticGroup -->|"Raw AST Findings"| Tournament
    DeepGroup -->|"Extracted Secrets &amp; Complexities"| Tournament

    %% =========================================================================
    %% STAGE 5: GOVERNED REMEDIATION & PONYTAIL LOOP
    %% =========================================================================
    subgraph GovernedRemediation["4. Governed Remediation Loop &amp; Safety Guardrails (Ponytail Protocol)"]
        direction TB
        
        Harden["<b>Surgical Patch Formulation</b><br/>Semantic Line Snippet Replacement<br/>Strict Line Budget: &le;35 Additions &bull; &le;25 Deletions"]
        
        BoundsCheck{"<b>Ponytail Bounds Check</b><br/>Exceeds 35 Add / 25 Del?"}
        RejectDiff["<b>Diff Rejected</b><br/>Excess Churn Detected<br/>Prompt AI for Minimal Snippet"]
        
        SnapshotStore[("<b>Pre-Apply Snapshot Store</b><br/><code>.torusguard/snapshots/&lt;run_id&gt;/</code><br/>Byte-for-Byte Rollback Backup")]
        
        HumanGate{"<b>Human Gate Authorization</b><br/>Explicit <code>--yes</code> or Interactive Confirmation"}
        UserAbort["<b>Operation Aborted</b><br/>Zero Files Touched &bull; Safe Exit"]
        
        ApplyPatch["<b>Atomic Patch Application</b><br/>Apply Unified Surgical Diff to Disk"]
        
        RecheckGate{"<b>Differential Recheck Engine</b><br/><code>torusguard recheck</code><br/>Fix Closed with Zero Regressions?"}
        RollbackExec["<b>Auto-Rollback Triggered!</b><br/>Instant Restoration from Snapshot<br/>Quarantine Candidate Patch"]
        
        Harden --> BoundsCheck
        BoundsCheck -->|"Violation"| RejectDiff
        RejectDiff -.->|"Re-prompt AI"| Harden
        BoundsCheck -->|"Pass (Within Bounds)"| SnapshotStore
        SnapshotStore --> HumanGate
        HumanGate -->|"Denied"| UserAbort
        HumanGate -->|"Approved"| ApplyPatch
        ApplyPatch --> RecheckGate
        RecheckGate -->|"Regressions"| RollbackExec
        RollbackExec -.->|"Restore Clean State"| SnapshotStore
    end

    PRGate -->|"Target Findings"| Harden

    %% =========================================================================
    %% STAGE 6: LIVING SECURITY LEDGER & ENTERPRISE OUTPUTS
    %% =========================================================================
    subgraph EnterpriseDeliverables["5. Living Security Ledger &amp; Enterprise Deliverables"]
        direction TB
        Ledger[("<b>Living Security Ledger</b><br/><code>security_report.md</code><br/>Synchronized Single Source of Truth &bull; Status: RESOLVED 🟢")]
        
        subgraph DeliverableOutputs["Executive Reports &amp; Verified Memory"]
            direction LR
            ThreatModel["<b>STRIDE Threat Model</b><br/><code>SECURITY_THREAT_MODEL.md</code><br/>DFD Architecture Diagrams"]
            SARIF["<b>OASIS SARIF v2.1.0</b><br/>GitHub Advanced Security<br/>CI/CD Security Center"]
            HTMLReport["<b>Executive Dashboard</b><br/>Single-File HTML Report<br/>Interactive Posture Heatmap"]
            GoldenRecipes[("<b>Golden Fix Memory</b><br/><code>.torusguard/recipes/</code><br/>Verified Distilled Fixes")]
        end

        Ledger --> DeliverableOutputs
    end

    RecheckGate -->|"Fix Confirmed (Clean Closure)"| Ledger

    %% =========================================================================
    %% STYLING AND THEME (Modern Dark Cyber Palette)
    %% =========================================================================
    classDef ingressStyle fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#f8fafc;
    classDef routerStyle fill:#1e1b4b,stroke:#6366f1,stroke-width:2px,color:#f8fafc;
    classDef scannerStyle fill:#022c22,stroke:#10b981,stroke-width:2px,color:#f8fafc;
    classDef tourneyStyle fill:#2e1065,stroke:#a855f7,stroke-width:2px,color:#f8fafc;
    classDef gateStyle fill:#451a03,stroke:#f59e0b,stroke-width:2px,color:#fef3c7;
    classDef rejectStyle fill:#450a0a,stroke:#ef4444,stroke-width:2px,color:#fee2e2;
    classDef actionStyle fill:#064e3b,stroke:#34d399,stroke-width:2px,color:#f8fafc;
    classDef dbStyle fill:#1e293b,stroke:#94a3b8,stroke-width:2px,color:#f8fafc;
    classDef ledgerStyle fill:#172554,stroke:#3b82f6,stroke-width:2px,color:#eff6ff;
    classDef outputStyle fill:#042f2e,stroke:#14b8a6,stroke-width:2px,color:#f0fdfa;

    class CLI,Chat,MCP ingressStyle;
    class Kernel routerStyle;
    class AST,TGQL,Reach,OCR,ReDoS,GitMine scannerStyle;
    class Tournament tourneyStyle;
    class PRGate,BoundsCheck,HumanGate,RecheckGate gateStyle;
    class RejectDiff,UserAbort,RollbackExec rejectStyle;
    class Harden,ApplyPatch actionStyle;
    class SnapshotStore,GoldenRecipes dbStyle;
    class Ledger ledgerStyle;
    class ThreatModel,SARIF,HTMLReport outputStyle;
Loading

🌐 Interactive Architecture Visualizations:

  • System Architecture Diagram (HTML) — Dynamic zoomable/pannable pipeline with dark/light themes, live view switching (Tri-Mode Ingress, AST Engine, Multi-Modal Vision OCR, Ponytail Bounds, Fail-Closed Recovery), and SVG/PNG export.
  • Governed Remediation Workflow (HTML) — Step-by-step visual trace of the 7-stage remediation loop, safety gates, and automatic rollback path.

Key design decisions:

  • Tri-Mode Parity: The CLI (Mode A), Chat Slash Commands (Mode B), and Native MCP Tools (Mode C) share the exact same underlying governance and validation rules.
  • Multi-Modal Vision OCR: Images, architecture diagrams, and screenshots are automatically scanned for leaked secrets using Tesseract OCR, bounded by strict 10MB memory safety limits.
  • Deterministic Enforcement: The Go binary handles all deterministic operations (AST scanning, bounds checking, snapshotting, reporting).
  • AI Intelligence: The AI agent handles intelligence-requiring tasks (patch generation, root-cause analysis, remediation formulation).
  • Living Ground Truth: All modes synchronize with security_report.md to prevent finding drift or hallucination.
  • Zero-Bypass Guardrails: Neither human nor AI can bypass Ponytail Protocol bounds (≤35 additions, ≤25 deletions) or the Human Gate before modifying code.

📋 Prerequisites

  • Go 1.25+ (to build from source)
  • Git (for git apply patch operations)
  • Node.js 18+ (for npm package installation)

🚀 Installation & How to Use (3 Options)

TorusGuard can be run without installation via npx, installed globally or locally via npm, compiled from source with go build, or installed via go install.

Option Method Best For Dedicated Guide
Option 1 npm & npx Node.js developers, zero-install CLI, CI/CD 📖 Option 1 Guide
Option 2 Build from Source Contributors, custom rules, Go development 📖 Option 2 Guide
Option 3 Go Install Go projects, single-binary, zero Node.js/npm 📖 Option 3 Guide

Option 1: npm (Primary)

Method A: Direct NPX Zero-Install (Recommended)

Run directly without installing any packages globally or locally:

npx torusguard init

Tip: Use npx torusguard@latest init to guarantee the freshest release.

Method B: Global Installation

npm install -g torusguard
torusguard init

Method C: Local Project Installation

npm install -D torusguard

💡 Using TorusGuard after npm install torusguard:
TorusGuard is a CLI security engine, not an importable JavaScript library. When installed locally, the binary resides in node_modules/.bin/torusguard.
You can run it via:

  • npx torusguard init (npx automatically uses your local node_modules binary)
  • Adding "security:audit": "torusguard audit" to your package.json scripts (npm run security:audit)
  • Direct path: ./node_modules/.bin/torusguard audit
npm package

👉 Read the Full Option 1 (npm & npx) Dedicated Guide →


Option 2: Build from Source (Recommended for Contributors)

git clone https://github.com/githubmofo/TorusGuard.git
cd TorusGuard
go build -o torusguard ./cmd/torusguard

On Windows:

go build -o torusguard.exe ./cmd/torusguard

Run directly:

./torusguard init
./torusguard audit

👉 Read the Full Option 2 (Build from Source) Dedicated Guide →


Option 3: Go Install

Install directly into $GOPATH/bin:

go install github.com/githubmofo/TorusGuard/cmd/torusguard@latest

Verify and run:

torusguard --version
torusguard init

👉 Read the Full Option 3 (Go Install) Dedicated Guide →


🕹️ Interactive Terminal Command Center

The easiest, zero-friction way to run TorusGuard in your terminal without memorizing command names, flags, or syntax:

# Launch interactive center via npx (zero installation):
npx torusguard

# Or using the standalone Go executable:
./torusguard.exe
# on Linux/macOS: ./torusguard

When launched with zero arguments in an interactive terminal, TorusGuard automatically renders a menu-driven command center:

  ╭───────────────────────────────────────────────────────────────────────╮
  │                                                                       │
  │  🛡️  TORUSGUARD COMMAND CENTER                                v2.2.0  │
  │  Interactive Security Engine                                          │
  │                                                                       │
  ╰───────────────────────────────────────────────────────────────────────╯
  ┌─ Quick Actions ───────────────────────────────────────────────────────┐
  │  [1]   🚀 Audit Workspace          (Full AST & Taint Scan)            │
  │  [2]   👁️  OCR Vision Scan          (Images & Diagram Secrets)         │
  │  [3]   📊 Posture Status           (Active Posture & Rules)           │
  │  [4]   🐳 Container Audit          (Dockerfile & Compose Scan)        │
  │  [5]   ⚡ ReDoS Complexity Scan    (Catastrophic Regex Scan)          │
  │  [6]   🤖 AI & RAG Defense         (Prompt Injection & Vectors)       │
  │  [7]   🔍 Git History Mine         (Committed Leaks & Tokens)         │
  │  [8]   🛡️  Harden Candidates       (Ponytail Bounded Patches)         │
  │  [9]   📑 Posture Report           (Generate Visual HTML Report)      │
  │  [10]  📖 Awesome Rules Catalog    (88 Rules Across 22 Families)      │
  │  [0]   ❌ Exit                                                        │
  └───────────────────────────────────────────────────────────────────────┘

💡 How it works: Simply type the number corresponding to your action (for example, 2 for OCR Vision Scan or 1 for Audit Workspace) and press Enter. TorusGuard executes the workflow immediately and prints the 75-column result card.


👁️ How to Use OCR Vision & Secret Scan

The Problem: Secrets Hidden in Images

Software engineers and architects frequently add cloud architecture diagrams (AWS/GCP), database ERDs, terminal screenshots, and API mockups into repository folders like docs/, assets/, or README.md. These images often contain live API keys, AWS credentials, database connection strings, or GitHub access tokens.

Standard linters and static analyzers only inspect text files and are completely blind to images. TorusGuard’s Hybrid First-Principles Vision OCR engine solves this vulnerability.

Key Capabilities

  • Hybrid First-Principles (Zero Dependencies): Pure Go extractor parses PNG metadata chunks (tEXt/zTXt/iTXt), SVG XML tags, EXIF metadata, and raw uncompressed string sequences ($\ge 6$ characters) directly from binary image streams. No external C++ software required.
  • Deep Optical OCR (Optional Neural Engine): If Tesseract OCR is installed in your PATH, TorusGuard automatically runs 300 DPI neural character recognition on flattened pixel rasters.
  • Zero-Crash Resilience: Missing Tesseract? TorusGuard never crashes or aborts your CI pipeline. It seamlessly falls back to first-principles extraction, reports findings, and displays a friendly 1-click install command.
  • Automatic Workspace Auto-Discovery: When run without arguments, TorusGuard traverses the entire project and scans all visual assets (.png, .jpg, .jpeg, .webp, .svg, .bmp).
  • Safe Evidence Masking: Detected credentials are automatically redacted (e.g., AKIA****************) so live keys are never echoed in console logs or shared CI outputs.

Step-by-Step Usage

Option A: Auto-Scan the Entire Workspace

Scan every diagram, screenshot, and image across your repository:

# Via NPX (Node/NPM - zero install)
npx torusguard ocr-scan

# Via Go binary
./torusguard.exe ocr-scan
# on Linux/macOS: ./torusguard ocr-scan

# In AI Agent Chat (Cursor, Claude Code, Windsurf, Antigravity)
/torusguard ocr-scan

Option B: Scan a Specific Diagram or Folder

Point TorusGuard directly to an asset or media directory:

# Scan a specific architecture diagram:
npx torusguard ocr-scan docs/architecture/aws-infrastructure.png

# Scan an assets folder:
npx torusguard ocr-scan ./assets/images/

Sample Output Card

When a secret is detected inside an image, TorusGuard prints a standardized 75-column warning card:

┌─ OCR VISION SECRET SCAN ─────────────────────────────────────────────┐
│ Target: docs/architecture.png                                        │
│ Engine: Hybrid First-Principles + Tesseract OCR                      │
│ Status: 1 Leaked Credential Detected                                 │
│                                                                      │
│ ✖ TG-SEC-002: AWS Access Key ID Detected                             │
│   Extracted: AKIA**************** (Redacted for safety)              │
│   Remediation: Invalidate key in AWS IAM and move to Vault / Env     │
│   Ledger: Synchronized with security_report.md                       │
└──────────────────────────────────────────────────────────────────────┘

What Secrets Does OCR Detect?

TorusGuard scans extracted optical text against 7 canonical credential signatures:

Rule ID Credential Type Signature Pattern Checked Remediation
TG-SEC-001 API & Service Tokens sk-live-..., sk-..., Stripe keys, Bearer tokens Invalidate token; load via environment variable.
TG-SEC-002 AWS Access Key IDs AKIA[0-9A-Z]{16} Rotate AWS IAM credentials immediately.
TG-SEC-003 GitHub Access Tokens ghp_..., github_pat_... Revoke PAT in GitHub Developer Settings.
TG-SEC-004 Database Connection URIs postgres://, mysql://, mongodb+srv:// Replace URI credentials with secret manager references.
TG-SEC-005 Private Keys & Certs -----BEGIN RSA PRIVATE KEY----- Invalidate compromised private key pair.
TG-SEC-006 JSON Web Tokens (JWT) eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,} Invalidate secret and re-sign tokens.
TG-SEC-007 Plaintext Passwords password = "...", db_pass: "..." Scrub password and use KMS / .env secrets.

Optional: Installing Tesseract for Deep Neural OCR

To enable optical recognition on raster pixel screenshots without text metadata, install Tesseract OCR:

  • Windows (PowerShell): winget install UB-Mannheim.TesseractOCR
  • macOS (Homebrew): brew install tesseract
  • Linux (Ubuntu/Debian): sudo apt-get install tesseract-ocr

(Note: If Tesseract is not installed, TorusGuard still inspects all PNG text chunks, SVG XML, EXIF data, and printable string tables natively without errors).


🖥️ How to Use CLI Commands

TorusGuard offers 100% command parity across:

  • npx torusguard <cmd> — Zero-install execution via npm / Node.js
  • ./torusguard.exe <cmd> (or ./torusguard <cmd>) — Native Go executable with 0-byte external runtime footprint
  • /torusguard <cmd> — Direct AI Chat Slash Command inside Cursor, Claude Code, Windsurf, and Antigravity

Complete Command Reference (25 Commands)

🚀 1. Quick Start & Posture Diagnostics

Command NPX Syntax Go Binary Syntax Slash Command What It Does
Command Center npx torusguard ./torusguard /torusguard Launch interactive menu with zero arguments
Init npx torusguard init ./torusguard init /torusguard init Scaffold .torusguard/ workspace & activate rules
Status npx torusguard status ./torusguard status /torusguard status Inspect active posture, stack & rules catalog
Help npx torusguard help ./torusguard help /torusguard help Interactive command guide & flag cheat sheet
Update npx torusguard update ./torusguard update — Check or install the newest engine version

🔍 2. Security Auditing & Deep Scanners

Command NPX Syntax Go Binary Syntax Slash Command What It Does
Audit Workspace npx torusguard audit ./torusguard audit /torusguard audit Polyglot static AST scan & taint flow analysis
OCR Vision Scan npx torusguard ocr-scan [path] ./torusguard ocr-scan [path] /torusguard ocr-scan Hybrid optical & first-principles secret scan
Container Audit npx torusguard container ./torusguard container /torusguard container Audit Dockerfile/Compose for root users & sockets
Git Secret Mining npx torusguard git-mine ./torusguard git-mine /torusguard git-mine Mine git commit packfiles & configs for leaks
ReDoS Analysis npx torusguard redos ./torusguard redos /torusguard redos Check regexes for exponential backtracking
AI & RAG Defense npx torusguard ai-guard ./torusguard ai-guard /torusguard ai-guard Scan prompts for injection & vector tenant leaks
Verify Evidence npx torusguard verify ./torusguard verify /torusguard verify Validate finding evidence against disk fingerprints

🛡️ 3. Governed Remediation & Patching (Ponytail Protocol)

Command NPX Syntax Go Binary Syntax Slash Command What It Does
Harden Fixes npx torusguard harden [patch] ./torusguard harden [patch] /torusguard harden Assert diff bounds ($\le 35$ additions, $\le 25$ deletions)
Apply Patch npx torusguard apply [--yes] ./torusguard apply [--yes] /torusguard apply Apply patch with automatic pre-apply .bak backup
Rollback npx torusguard rollback ./torusguard rollback /torusguard rollback Instantly restore sources from pre-apply snapshot
Recheck Fixes npx torusguard recheck ./torusguard recheck /torusguard recheck Differential re-scan confirming clean fix closure

📊 4. Reports, Compliance & Threat Modeling

Command NPX Syntax Go Binary Syntax Slash Command What It Does
HTML Report npx torusguard report --html ./torusguard report --html /torusguard report Generate single-file visual dark-mode dashboard
SARIF Export npx torusguard report --sarif ./torusguard report --sarif — Export OASIS SARIF v2.1.0 for CI/CD gates
Awesome Recipes npx torusguard recipes ./torusguard recipes /torusguard recipes Explore verified Golden Fix patterns from memory
PR & Git Review npx torusguard review ./torusguard review /torusguard review Differential PR diff review and security gating
Threat Model npx torusguard threatmodel ./torusguard threatmodel /torusguard threatmodel Synthesize STRIDE threat model & Mermaid DFDs
Benchmark Suite npx torusguard benchmark ./torusguard benchmark /torusguard benchmark Run SecurityReviewBench precision/recall test

🌐 5. Authorized Runtime Web Validation

Command NPX Syntax Go Binary Syntax Slash Command What It Does
Authorize Scope npx torusguard authorize ./torusguard authorize /torusguard authorize Cryptographic domain ownership proof & token
Web Validate npx torusguard web-validate ./torusguard web-validate /torusguard web-validate Non-destructive HTTP probing with audit headers
Exploit Check npx torusguard exploit-check ./torusguard exploit-check /torusguard exploit-check Safe inert payload verification (e.g. SQL injection)

🤖 6. AI Agent Protocols & Pipelines

Command NPX Syntax Go Binary Syntax Slash Command What It Does
MCP Server npx torusguard mcp ./torusguard mcp — Stdio JSON-RPC 2.0 interface for AI agents
Full Pipeline npx torusguard full ./torusguard full — Master 7-stage closed-loop security governance

Common CLI Flags Reference

Flag Applicable Commands Description
--yes apply Skip interactive Human Gate confirmation (recommended for CI/CD)
--html report Render single-file visual dark-mode HTML dashboard (report.html)
--sarif report Export OASIS SARIF v2.1.0 structured log (report.sarif)
--rules status Print all 88 active security rules in standardized 75-column cards
--install update Automatically install the newest TorusGuard version from registry
[path] ocr-scan, harden, apply Specify target image file, directory, or patch file path

Practical Command Recipes

Recipe 1: Pre-Commit Security Check

Run a quick, complete security audit and OCR scan before pushing code:

npx torusguard audit
npx torusguard ocr-scan

Recipe 2: Fix a Vulnerability with Zero Risk

Validate that an AI-generated patch is surgical, apply it safely with a backup, and verify it:

# 1. Check patch line budget (<=35 additions, <=25 deletions)
npx torusguard harden fix.patch

# 2. Apply patch (creates .bak snapshot automatically)
npx torusguard apply --yes fix.patch

# 3. Verify fix closed without any new regressions
npx torusguard recheck

# 4. If anything broke, rollback instantly:
npx torusguard rollback

Recipe 3: Generate Visual Posture Report for Your Team

npx torusguard report --html
# Open report.html in any browser for an interactive dashboard!

Remediation Workflow

# 1. Validate a candidate patch against Ponytail bounds
torusguard harden fix.patch

# 2. Apply the patch with rollback snapshot (requires --yes for Human Gate)
torusguard apply --yes fix.patch

# 3. Verify the fix was applied correctly
torusguard recheck

# 4. Roll back if something went wrong
torusguard rollback

Runtime Validation

# Generate authorization token for runtime probing
torusguard authorize

# Probe a running application for security headers
torusguard web-validate

# Send bounded inert payloads to test input handling
torusguard exploit-check

📁 Project Structure

TorusGuard/
├── cmd/torusguard/       # CLI entry point, command router & MCP server
│   ├── main.go           # CLI command router
│   └── mcp.go            # Model Context Protocol (MCP) JSON-RPC 2.0 stdio server
├── internal/
│   ├── apply/            # Patch application + pre-apply snapshot engine
│   ├── harden/           # Ponytail Protocol bounds enforcement & line-level reflection
│   │   ├── patch.go      # Ponytail Protocol bounds verification
│   │   └── reflection.go # Line-level reflection & semantic replacement
│   ├── memory/           # Golden Fix recipe persistence
│   ├── recheck/          # Differential re-scan engine
│   ├── report/           # SARIF v2.1.0 + dark-mode HTML generators
│   ├── rules/            # TG-* rule catalog loader
│   ├── scanner/          # Heuristic polyglot security scanner + Tesseract OCR
│   │   ├── scanner.go    # Polyglot code AST & heuristic scanner
│   │   └── ocr.go        # Multi-modal Vision OCR secret detection
│   ├── termui/           # 75-column terminal UI formatting
│   ├── validate/         # authorize / web-validate / exploit-check / verify
│   └── workspace/        # init + polyglot stack detection
├── .torusguard/          # Generated workspace state
│   ├── rules/            # Active security rule definitions
│   ├── schemas/          # JSON schemas for findings, recipes, etc.
│   ├── memory/           # Persistent security context
│   └── snapshots/        # Pre-apply rollback backups
├── docs/                 # Architecture and usage documentation
├── bin/                  # npm package CLI wrapper
├── go.mod                # Go module (github.com/torusguard/torusguard)
└── package.json          # npm package definition

🔒 Security Invariants & Rule Governance

TorusGuard enforces 88 security invariants across 22 architectural families covering Secrets, Authentication, Multi-Tenant Database Isolation, Input Sanitization, Rate Limiting, AI Agent Prompt Injection, SSRF, Webhooks, WebSockets, CSRF, GraphQL, Supply Chain, Business Logic, Cache Poisoning, Client Bundles, Platform Headers, Polyglot Bypasses, Edge Timeouts, Container & Docker Safety, Git History Secret Mining, Regular Expression Backtracking (ReDoS), and Vector Database RAG Isolation.

📘 Full Rules Catalog & Invariants:
The complete rulebook with formal invariant definitions, severity scores, and testing signatures is maintained in AGENTS.md and the rules/ directory.
You can also explore verified Golden Fix patterns anytime via torusguard recipes or stream the live catalog over MCP via torusguard://rules_catalog.


🤖 AI Agent Integration

TorusGuard works natively inside AI coding assistants. Add the configuration file to your project root and your AI agent automatically enforces TorusGuard security invariants.

Supported Agents

Agent Configuration File Status
Antigravity (Gemini) AGENTS.md ✅ Full support
Claude Code CLAUDE.md ✅ Full support
Cursor .cursorrules ✅ Full support
Windsurf .windsurfrules ✅ Full support
VS Code Copilot AGENTS.md ✅ Full support
Kimi SKILL.md ✅ Full support

Slash Commands (AI Chat Mode)

/torusguard init          # Initialize workspace
/torusguard audit         # Run security + OCR scan; sync security_report.md
/torusguard ocr-scan      # Scan diagram or image assets for leaked credentials
/torusguard harden        # Formulate remediation patches
/torusguard apply         # Apply patches with Human Gate
/torusguard recheck       # Verify fix closure
/torusguard report        # Generate posture report
/torusguard status        # Check posture overview
/torusguard full          # End-to-end 7-stage pipeline

Native MCP Tools (Agent Toolkit Mode)

When configured with .agents/mcp_config.json or mcp_config.json, AI coding agents gain native tool calling (13 Tools & 2 Resources):

  • torusguard_audit: Deep static AST scan + Vision OCR; writes security_report.md
  • torusguard_ocr_scan: Dedicated image credential analysis via Tesseract (5-10MB bounds)
  • torusguard_container: Audits container files for root execution, docker socket exposure, and privileged mode
  • torusguard_git_mine: Mines git commit history and config for leaked credentials and tokens
  • torusguard_redos: Analyzes regex patterns for catastrophic exponential backtracking
  • torusguard_ai_guard: Audits AI agent prompt templates, tool registries, and vector database queries
  • torusguard_verify: Asserts evidence sufficiency & line-shift invariant fingerprint matches
  • torusguard_harden: Validates remediation diff against Ponytail Protocol bounds
  • torusguard_recheck: Differential re-scan confirming fix closure
  • torusguard_review: Differential PR and Git diff incremental review; gate decisions
  • torusguard_threatmodel: Synthesizes STRIDE threat model & Mermaid DFDs (SECURITY_THREAT_MODEL.md)
  • torusguard_benchmark: Runs SecurityReviewBench self-evaluating precision & recall suite
  • torusguard_status: Workspace posture and tech stack inspection
  • torusguard://security_report: MCP Resource reading the living security report
  • torusguard://rules_catalog: MCP Resource exploring verified rules catalog & Golden Fix patterns

🧪 Verified Test Suite & Mass Benchmarks

TorusGuard undergoes rigorous automated multi-tier testing across polyglot stacks, multi-modal vision assets, and agent communication protocols:

Testing Tier Scope & Target Stacks Pass Rate Verified Capabilities
Go Engine & Unit Tests cmd/torusguard, internal/scanner, internal/* 100% Passing Deterministic AST matching, 88 canonical rule patterns, JSON-RPC 2.0 MCP protocol (133/133 harness tests passing).
Mass Polyglot Benchmarks 20 Enterprise Tech Stacks (Go, Python, Java, Node, Rust, PHP, C#, Ruby, Svelte, Vue, Angular) 20/20 Passed Framework auto-profiling, heuristic AST analysis, finding deduplication.
Unseen Tri-Mode Validation 6 Unseen Framework Ecosystems (SvelteKit 2 + Bun, FastAPI AI RAG, DevOps Git Mine, OCR Asset Suite, Kotlin Ktor, Laravel 11) 6/6 Passed (100%) Mode A (CLI) + Mode B (Slash Commands) + Mode C (Native MCP Tools) across 18/18 canonical skills with automated sandbox cleanup.
Tri-Mode & Vision E2E 16 Diverse Framework Repos (React, Next.js, Express, Django, FastAPI, Spring Boot, etc.) 16/16 Passed Mode A (CLI) + Mode B (Slash Commands) + Mode C (Native MCP Tools) + Multi-Modal Vision OCR.
Multi-Modal Vision OCR Diagram & Image assets (.png, .jpg, .webp) via Tesseract v5.4.0 100% Recall Secrets detection (TG-SEC-001 - TG-SEC-007), 10MB DoS bounding, OCR character substitution tolerance.
Ponytail Churn Limits Surgical patch validation across all 88 rules Bounded Line bounds (≤35 additions, ≤25 deletions), zero-bypass verification (TG-DIFF-001).

All test environments are completely sandboxed, verified with byte-for-byte assertions, and cleaned up automatically.


🛡️ Non-Negotiable Invariants

  1. Browser-Code Truth: Never expose secrets in frontend bundles.
  2. Multi-Tenant Isolation: Always scope DB lookups by tenant/user ownership.
  3. Ponytail Churn Bounds: Patches ≤35 additions, ≤25 deletions. No full-file rewrites.
  4. Zero Security Bypasses: Never insert # nosec, verify=False, InsecureSkipVerify: true.
  5. Snapshots Before Edits: Mandatory .bak backup before every modification.
  6. Fail-Closed Cryptography: Panic on entropy failure. No fallback tokens.
  7. SSRF Boundary Enforcement: Block private IPs and cloud metadata before probing.
  8. DoS Resilience: 10,000-file max, 5-minute timeout.

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feat/your-feature
  3. Commit changes: git commit -m "feat: add your feature"
  4. Push to branch: git push origin feat/your-feature
  5. Open a Pull Request

See CONTRIBUTING.md for detailed guidelines and CODE_OF_CONDUCT.md for community standards.


📄 License

MIT © 2026 Jenish Lad


📚 Documentation

Document Description
Architecture System design and module relationships
Security Architecture Threat model and security design
Detection Engine Scanner internals and rule matching
API Specification CLI argument specification
Security Philosophy Core design principles
Testing Playbook Testing guide and CI integration
Demo Guide Quick start and full lifecycle demo
Roadmap Feature roadmap and release planning
Unseen Stacks Validation Report Tri-mode validation across 6 unseen ecosystems & vision OCR
SECURITY.md Vulnerability disclosure policy
CHANGELOG.md Version history and release notes

About

Autonomous Security Guardrails & Governed Remediation for AI-Built Apps. Tri-Mode Parity (CLI, Chat Slash Commands, Native MCP Server), First-Principles Security Suite, Multi-Modal Vision OCR, 86 Rules across 22 Families & Ponytail Patch Bounds.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages