torusguard 1.4.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/.torusguard/.manifest.json +50 -28
  2. package/.torusguard/auth.json +5 -0
  3. package/.torusguard/rules/container/TG-CONT-001-root-user-execution.md +50 -0
  4. package/.torusguard/rules/container/TG-CONT-002-docker-socket-mount.md +47 -0
  5. package/.torusguard/rules/container/TG-CONT-003-privileged-container-mode.md +53 -0
  6. package/.torusguard/rules/container/TG-CONT-004-build-arg-secret-exposure.md +43 -0
  7. package/.torusguard/rules/git/TG-GIT-001-historical-secret-in-git-commit.md +44 -0
  8. package/.torusguard/rules/git/TG-GIT-002-plaintext-credentials-in-git-config.md +41 -0
  9. package/.torusguard/rules/git/TG-GIT-003-sensitive-tracked-file-gitignore-breach.md +40 -0
  10. package/.torusguard/rules/rag/TG-RAG-001-untrusted-rag-context-injection.md +72 -0
  11. package/.torusguard/rules/rag/TG-RAG-002-autonomous-llm-tool-unsandboxed-call.md +51 -0
  12. package/.torusguard/rules/rag/TG-RAG-003-unpartitioned-vector-tenant-lookup.md +51 -0
  13. package/.torusguard/rules/redos/TG-REDOS-001-catastrophic-exponential-backtracking.md +46 -0
  14. package/.torusguard/rules/redos/TG-REDOS-002-unbounded-nested-quantifier.md +43 -0
  15. package/.torusguard/rules_catalog.json +338 -518
  16. package/.torusguard/scripts/__pycache__/apply_runner.cpython-314.pyc +0 -0
  17. package/.torusguard/scripts/__pycache__/audit_runner.cpython-314.pyc +0 -0
  18. package/.torusguard/scripts/__pycache__/harden_runner.cpython-314.pyc +0 -0
  19. package/.torusguard/scripts/__pycache__/html_reporter.cpython-314.pyc +0 -0
  20. package/.torusguard/scripts/__pycache__/manifest_builder.cpython-314.pyc +0 -0
  21. package/.torusguard/scripts/__pycache__/recipes_runner.cpython-314.pyc +0 -0
  22. package/.torusguard/scripts/__pycache__/report_sync.cpython-314.pyc +0 -0
  23. package/.torusguard/scripts/manifest_builder.py +1 -1
  24. package/.torusguard/skills/torusguard/SKILL.md +69 -24
  25. package/.torusguard/skills/torusguard/bootstrap.py +57 -24
  26. package/.torusguard/skills/torusguard-ai-guard/SKILL.md +95 -0
  27. package/.torusguard/skills/torusguard-apply/SKILL.md +60 -34
  28. package/.torusguard/skills/torusguard-audit/SKILL.md +73 -24
  29. package/.torusguard/skills/torusguard-authorize/SKILL.md +48 -6
  30. package/.torusguard/skills/torusguard-container/SKILL.md +94 -0
  31. package/.torusguard/skills/torusguard-exploit-check/SKILL.md +50 -6
  32. package/.torusguard/skills/torusguard-full/SKILL.md +62 -19
  33. package/.torusguard/skills/torusguard-git-mine/SKILL.md +92 -0
  34. package/.torusguard/skills/torusguard-harden/SKILL.md +81 -50
  35. package/.torusguard/skills/torusguard-init/SKILL.md +61 -14
  36. package/.torusguard/skills/torusguard-ocr-scan/SKILL.md +94 -0
  37. package/.torusguard/skills/torusguard-recheck/SKILL.md +71 -18
  38. package/.torusguard/skills/torusguard-redos/SKILL.md +91 -0
  39. package/.torusguard/skills/torusguard-report/SKILL.md +50 -9
  40. package/.torusguard/skills/torusguard-status/SKILL.md +63 -10
  41. package/.torusguard/skills/torusguard-verify/SKILL.md +52 -10
  42. package/.torusguard/skills/torusguard-web-validate/SKILL.md +53 -8
  43. package/.torusguard/snapshots/20260921-182638/go.mod.bak +11 -0
  44. package/.torusguard/snapshots/20260921-185213/file.go.bak +5 -0
  45. package/.torusguard/workflows/ai-guard.md +31 -0
  46. package/.torusguard/workflows/apply.md +32 -55
  47. package/.torusguard/workflows/audit.md +28 -46
  48. package/.torusguard/workflows/authorize.md +27 -50
  49. package/.torusguard/workflows/container.md +29 -0
  50. package/.torusguard/workflows/exploit-check.md +28 -50
  51. package/.torusguard/workflows/git-mine.md +25 -0
  52. package/.torusguard/workflows/harden.md +29 -48
  53. package/.torusguard/workflows/init.md +27 -50
  54. package/.torusguard/workflows/memory.md +18 -23
  55. package/.torusguard/workflows/ocr-scan.md +25 -0
  56. package/.torusguard/workflows/recheck.md +28 -46
  57. package/.torusguard/workflows/redos.md +27 -0
  58. package/.torusguard/workflows/report.md +33 -52
  59. package/.torusguard/workflows/status.md +31 -52
  60. package/.torusguard/workflows/verify.md +29 -49
  61. package/.torusguard/workflows/web-validate.md +22 -45
  62. package/README.md +336 -386
  63. package/package.json +1 -1
  64. package/skills/torusguard/SKILL.md +71 -24
  65. package/skills/torusguard/__pycache__/bootstrap.cpython-314.pyc +0 -0
  66. package/skills/torusguard/bootstrap.py +60 -71
  67. package/skills/torusguard/payload/.manifest.json +50 -28
  68. package/skills/torusguard/payload/TORUSGUARD.md +145 -145
  69. package/skills/torusguard/payload/agents/auditor.md +41 -41
  70. package/skills/torusguard/payload/agents/profiler.md +49 -49
  71. package/skills/torusguard/payload/agents/remediator.md +41 -41
  72. package/skills/torusguard/payload/agents/reviewer.md +39 -39
  73. package/skills/torusguard/payload/agents/validator.md +46 -46
  74. package/skills/torusguard/payload/config/scope.json +24 -24
  75. package/skills/torusguard/payload/references/csharp-security.md +41 -41
  76. package/skills/torusguard/payload/references/go-security.md +41 -41
  77. package/skills/torusguard/payload/references/java-security.md +40 -40
  78. package/skills/torusguard/payload/references/polyglot-security-matrix.md +25 -25
  79. package/skills/torusguard/payload/references/rust-security.md +40 -40
  80. package/skills/torusguard/payload/rules/container/TG-CONT-001-root-user-execution.md +50 -0
  81. package/skills/torusguard/payload/rules/container/TG-CONT-002-docker-socket-mount.md +47 -0
  82. package/skills/torusguard/payload/rules/container/TG-CONT-003-privileged-container-mode.md +53 -0
  83. package/skills/torusguard/payload/rules/container/TG-CONT-004-build-arg-secret-exposure.md +43 -0
  84. package/skills/torusguard/payload/rules/custom/.gitkeep +1 -1
  85. package/skills/torusguard/payload/rules/custom/README.md +30 -30
  86. package/skills/torusguard/payload/rules/git/TG-GIT-001-historical-secret-in-git-commit.md +44 -0
  87. package/skills/torusguard/payload/rules/git/TG-GIT-002-plaintext-credentials-in-git-config.md +41 -0
  88. package/skills/torusguard/payload/rules/git/TG-GIT-003-sensitive-tracked-file-gitignore-breach.md +40 -0
  89. package/skills/torusguard/payload/rules/rag/TG-RAG-001-untrusted-rag-context-injection.md +72 -0
  90. package/skills/torusguard/payload/rules/rag/TG-RAG-002-autonomous-llm-tool-unsandboxed-call.md +51 -0
  91. package/skills/torusguard/payload/rules/rag/TG-RAG-003-unpartitioned-vector-tenant-lookup.md +51 -0
  92. package/skills/torusguard/payload/rules/redos/TG-REDOS-001-catastrophic-exponential-backtracking.md +46 -0
  93. package/skills/torusguard/payload/rules/redos/TG-REDOS-002-unbounded-nested-quantifier.md +43 -0
  94. package/skills/torusguard/payload/rules_catalog.json +338 -518
  95. package/skills/torusguard/payload/scripts/__pycache__/term_ui.cpython-314.pyc +0 -0
  96. package/skills/torusguard/payload/scripts/manifest_builder.py +1 -1
  97. package/skills/torusguard/payload/scripts/rules_sync.py +321 -321
  98. package/skills/torusguard/payload/scripts/safety_gate.py +64 -64
  99. package/skills/torusguard/payload/skills/torusguard/SKILL.md +69 -24
  100. package/skills/torusguard/payload/skills/torusguard/bootstrap.py +57 -24
  101. package/skills/torusguard/payload/skills/torusguard-ai-guard/SKILL.md +95 -0
  102. package/skills/torusguard/payload/skills/torusguard-apply/SKILL.md +60 -34
  103. package/skills/torusguard/payload/skills/torusguard-audit/SKILL.md +73 -24
  104. package/skills/torusguard/payload/skills/torusguard-authorize/SKILL.md +48 -6
  105. package/skills/torusguard/payload/skills/torusguard-container/SKILL.md +94 -0
  106. package/skills/torusguard/payload/skills/torusguard-exploit-check/SKILL.md +50 -6
  107. package/skills/torusguard/payload/skills/torusguard-full/SKILL.md +62 -19
  108. package/skills/torusguard/payload/skills/torusguard-git-mine/SKILL.md +92 -0
  109. package/skills/torusguard/payload/skills/torusguard-harden/SKILL.md +81 -50
  110. package/skills/torusguard/payload/skills/torusguard-init/SKILL.md +61 -14
  111. package/skills/torusguard/payload/skills/torusguard-ocr-scan/SKILL.md +94 -0
  112. package/skills/torusguard/payload/skills/torusguard-recheck/SKILL.md +71 -18
  113. package/skills/torusguard/payload/skills/torusguard-redos/SKILL.md +91 -0
  114. package/skills/torusguard/payload/skills/torusguard-report/SKILL.md +50 -9
  115. package/skills/torusguard/payload/skills/torusguard-status/SKILL.md +63 -10
  116. package/skills/torusguard/payload/skills/torusguard-verify/SKILL.md +52 -10
  117. package/skills/torusguard/payload/skills/torusguard-web-validate/SKILL.md +53 -8
  118. package/skills/torusguard/payload/templates/audit-report.template.md +54 -54
  119. package/skills/torusguard/payload/templates/authorization.template.md +34 -34
  120. package/skills/torusguard/payload/templates/finding-card.template.md +32 -32
  121. package/skills/torusguard/payload/templates/remediation-bundle.template.md +35 -35
  122. package/skills/torusguard/payload/workflows/ai-guard.md +31 -0
  123. package/skills/torusguard/payload/workflows/apply.md +31 -62
  124. package/skills/torusguard/payload/workflows/audit.md +27 -51
  125. package/skills/torusguard/payload/workflows/authorize.md +27 -50
  126. package/skills/torusguard/payload/workflows/container.md +29 -0
  127. package/skills/torusguard/payload/workflows/exploit-check.md +28 -50
  128. package/skills/torusguard/payload/workflows/git-mine.md +25 -0
  129. package/skills/torusguard/payload/workflows/harden.md +28 -52
  130. package/skills/torusguard/payload/workflows/init.md +27 -56
  131. package/skills/torusguard/payload/workflows/memory.md +18 -23
  132. package/skills/torusguard/payload/workflows/ocr-scan.md +25 -0
  133. package/skills/torusguard/payload/workflows/recheck.md +28 -46
  134. package/skills/torusguard/payload/workflows/redos.md +27 -0
  135. package/skills/torusguard/payload/workflows/report.md +39 -62
  136. package/skills/torusguard/payload/workflows/status.md +31 -55
  137. package/skills/torusguard/payload/workflows/verify.md +29 -49
  138. package/skills/torusguard/payload/workflows/web-validate.md +22 -45
  139. package/skills/torusguard/references/csharp-security.md +41 -0
  140. package/skills/torusguard/references/go-security.md +41 -0
  141. package/skills/torusguard/references/java-security.md +40 -0
  142. package/skills/torusguard/references/polyglot-security-matrix.md +25 -0
  143. package/skills/torusguard/references/rust-security.md +40 -0
  144. package/skills/torusguard-ai-guard/SKILL.md +95 -0
  145. package/skills/torusguard-apply/SKILL.md +60 -34
  146. package/skills/torusguard-audit/SKILL.md +73 -24
  147. package/skills/torusguard-authorize/SKILL.md +48 -6
  148. package/skills/torusguard-container/SKILL.md +94 -0
  149. package/skills/torusguard-exploit-check/SKILL.md +50 -6
  150. package/skills/torusguard-full/SKILL.md +62 -19
  151. package/skills/torusguard-git-mine/SKILL.md +92 -0
  152. package/skills/torusguard-harden/SKILL.md +81 -50
  153. package/skills/torusguard-init/SKILL.md +61 -14
  154. package/skills/torusguard-ocr-scan/SKILL.md +94 -0
  155. package/skills/torusguard-recheck/SKILL.md +71 -18
  156. package/skills/torusguard-redos/SKILL.md +91 -0
  157. package/skills/torusguard-report/SKILL.md +50 -9
  158. package/skills/torusguard-status/SKILL.md +63 -10
  159. package/skills/torusguard-verify/SKILL.md +52 -10
  160. package/skills/torusguard-web-validate/SKILL.md +53 -8
@@ -1,78 +1,80 @@
1
1
  ---
2
2
  name: torusguard-harden
3
3
  description: Package surgical remediation bundles conforming to the Ponytail Protocol (<= 35 additions, <= 25 deletions) via CLI or AI Agent.
4
- version: 1.3.6
4
+ version: 2.0.0
5
5
  workflow: .torusguard/workflows/harden.md
6
6
  tools: Read, Grep, Glob, Write, run_command
7
7
  scripts-binding:
8
- - .torusguard/scripts/report_sync.py
9
- - .torusguard/scripts/harden_runner.py
10
- - .torusguard/scripts/diff_guard.py
11
- - .torusguard/scripts/term_ui.py
8
+ - internal/harden/harden.go
9
+ - internal/harden/patch.go
10
+ - internal/harden/reflection.go
11
+ - cmd/torusguard/main.go
12
12
  ---
13
13
 
14
14
  # TorusGuard Harden — Governed Remediation & Bundle Packaging
15
15
 
16
16
  ## Objective
17
- Formulate minimal, surgical code fixes bound by the Ponytail Protocol ($\le 35$ additions, $\le 25$ deletions), packaging unified diffs into auditable remediation bundles ready for review.
17
+ Formulate minimal, surgical code fixes bound by the Ponytail Protocol ($\le 35$ additions, $\le 25$ deletions), packaging unified diffs or semantic reflection patches into auditable remediation bundles ready for review.
18
18
 
19
19
  ---
20
20
 
21
- ## Two Execution Modes
21
+ ## Tri-Mode Execution
22
22
 
23
23
  ### Mode A: Automated CLI Execution (Recommended First Step)
24
24
  Run the autonomous remediation engine via the terminal:
25
25
  ```bash
26
- # Harden latest audit run
27
- npx torusguard harden
26
+ # Validate candidate patch or semantic patch against Ponytail bounds
27
+ torusguard harden candidate.patch
28
28
 
29
- # Harden specific project directory
30
- npx torusguard harden ./my-project
31
-
32
- # Harden specific run ID
33
- npx torusguard harden --run run-20260910-121618-audit
34
-
35
- # Machine-readable JSON output
36
- npx torusguard harden --json
29
+ # Validate semantic JSON patch
30
+ torusguard harden patch.json
37
31
  ```
38
- **Under the Hood:** Executes `python .torusguard/scripts/harden_runner.py`.
39
- - Discovers findings in `.torusguard/runs/<run_id>/findings.json`.
40
- - Matches findings against canonical AST patch templates (`TG-SEC-*`, `TG-INPUT-*`, `TG-DB-*`, `TG-PLATFORM-*`, `TG-AUTH-*`, `TG-DIFF-*`).
41
- - Validates that every candidate patch strictly satisfies Ponytail bounds ($\le 35$ additions, $\le 25$ deletions).
42
- - Packages candidate bundles into `.torusguard/runs/<run_id>/bundles/<bundle_id>/` containing `patch.diff`, `minimal_patch_plan.md`, and `metadata.json`.
43
- - Emits run-level summary `remediation.md`.
32
+ **Under the Hood:** Executes compiled Go hardening engine (`internal/harden`).
33
+ - Evaluates patch churn strictly against Ponytail bounds ($\le 35$ additions, $\le 25$ deletions).
34
+ - Scans replacement code for security bypasses (`# nosec`, `verify=False`, `InsecureSkipVerify: true`).
35
+ - Supports both unified diff files (`.diff`, `.patch`) and Semantic Reflection JSON files.
44
36
  - Renders pixel-perfect 75-column terminal cards.
45
37
 
46
38
  ### Mode B: In-Session AI Chat Agent Remediation
47
- When findings require complex architectural changes, or when the automated CLI cannot formulate a template match:
48
- 1. **Locate Target Finding:** Inspect `.torusguard/runs/<run_id>/findings.md` or `findings.json`.
49
- 2. **Inspect AST Context:** Read surrounding lines ($\pm 15$) of the vulnerable sink using `view_file`.
50
- 3. **Formulate Minimal Fix:** Craft a surgical code modification:
39
+ When findings require complex architectural changes, or when formulating fixes:
40
+ 1. **Locate Target Finding:** Inspect `security_report.md` at workspace root.
41
+ 2. **Inspect AST Context (1/9th Token Strategy):** Inspect only surrounding lines ($\pm 3$ lines) via `ExtractContext` rather than ingesting entire files.
42
+ 3. **Formulate Minimal Semantic Patch:** Formulate a surgical code modification using the Line-Level Reflection Module:
43
+ - Provide `target_file`, `find_snippet`, and `replace_snippet`.
51
44
  - Parameterize SQL queries (replace concatenation with `?` or `$1` or `%s`).
52
- - Add tenant isolation (`where: { tenantId }`, `organization_id=...`).
53
- - Replace unsafe HTML injection (`dangerouslySetInnerHTML`, `.innerHTML = ...`) with safe text rendering (`textContent`, React elements).
54
- - Sanitize path traversal using `path.basename()` or `os.path.basename()`.
55
- - Constrain wildcard CORS headers to verified origin environment variables.
56
- - Restore TLS verification flags (`verify=True`, `rejectUnauthorized: true`).
45
+ - Add tenant isolation (`where: { tenantId: user.tenantId }`).
46
+ - Replace unsafe HTML injection with safe text rendering (`textContent`).
47
+ - Sanitize path traversal using `filepath.Base()` or `path.basename()`.
48
+ - Restore TLS verification flags.
57
49
  4. **Validate Ponytail Bounds:** Count additions ($\le 35$) and deletions ($\le 25$). Never perform full-file rewrites.
58
- 5. **Package Bundle Artifacts:** Write bundle under `.torusguard/runs/<run_id>/bundles/<bundle_id>/`:
59
- - `patch.diff`: Standard unified diff.
60
- - `minimal_patch_plan.md`: Context, rationale, and diff preview.
61
- - `metadata.json`: Bundle metadata.
62
- 6. **Report to Operator:** Present proposed diff card and recommend running `/torusguard apply` or `npx torusguard apply`.
50
+ 5. **Report to Operator:** Present proposed diff card and recommend running `/torusguard apply` or `torusguard apply`.
51
+
52
+ ### Mode C: Native MCP Tool Execution
53
+ For autonomous AI coding agents (Antigravity, Cursor, Windsurf, Claude Code):
54
+ - **Tool Invocation:** Call `torusguard_harden` with semantic reflection arguments:
55
+ ```json
56
+ {
57
+ "target_file": "src/controllers/userController.js",
58
+ "find_snippet": "const query = `SELECT * FROM users WHERE id = ${req.params.id}`;",
59
+ "replace_snippet": "const query = 'SELECT * FROM users WHERE id = ? AND tenant_id = ?';\nconst params = [req.params.id, req.user.tenantId];"
60
+ }
61
+ ```
62
+ - **Programmatic Return:** Receives exact line ranges matched by Go AST, calculated additions/deletions, and verification that no `# nosec` or security bypasses exist.
63
63
 
64
64
  ---
65
65
 
66
- ## Remediation Bundle Structure
67
- ```
68
- .torusguard/runs/<run_id>/
69
- ├── remediation.md # Run-level catalog of formulated candidate patches
70
- └── bundles/
71
- └── bnd-<rule_id>-<line>-<hash>/
72
- ├── patch.diff # Unified diff preview
73
- ├── minimal_patch_plan.md # Detailed explanation, rationale, and churn stats
74
- └── metadata.json # Machine-readable bundle metadata
66
+ ## 🏛️ Line-Level Reflection Module (OpenCodeReview Hybrid Engine)
67
+ Instead of forcing the LLM to guess error-prone unified diff line offsets (`@@ -14,6 +14,8 @@`), TorusGuard allows formulating **Semantic Patches**:
68
+ ```json
69
+ {
70
+ "target_file": "server/index.js",
71
+ "rule_id": "TG-SEC-001",
72
+ "find_snippet": "const jwtSecret = 'hardcoded-dev-secret-key-12345';",
73
+ "replace_snippet": "const jwtSecret = process.env.JWT_SECRET;",
74
+ "rationale": "Extracted hardcoded JWT secret to environment variable"
75
+ }
75
76
  ```
77
+ The Go engine deterministically matches `find_snippet` against the target file, counts additions/deletions, verifies Ponytail bounds, and guarantees zero line-number drift.
76
78
 
77
79
  ---
78
80
 
@@ -90,9 +92,38 @@ When findings require complex architectural changes, or when the automated CLI c
90
92
  - **Target Finding:** `[TG-SEC-001]` at `server/index.js:9`
91
93
  - **Ponytail Churn:** +1 / -1 (Compliant <= 35 add, <= 25 del)
92
94
  - **Strategy:** Migrated hardcoded JWT secret to environment variable process.env.JWT_SECRET
93
- - **Bundle Directory:** `.torusguard/runs/<run_id>/bundles/bnd-tg-sec-001-9-a8310c/`
94
- - **Next Step:** Run `npx torusguard apply` or `/torusguard apply` to review and apply
95
+ - **Mode:** Line-Level Reflection Match (Semantic Patch)
96
+ - **Next Step:** Run `torusguard apply` or `/torusguard apply` to review and apply
95
97
  ```
96
98
 
97
- ## Living Report Ground Truth
98
- - Read `security_report.md` in the workspace root before taking any action. Update the relevant finding card after completing remediation.
99
+ ---
100
+
101
+ ## 🚨 LLM Trap Table
102
+
103
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
104
+ | :--- | :--- | :--- |
105
+ | **Line-Number Drift** | Formulates diff headers with estimated line numbers that fail `git apply`. | Use semantic patches (`find_snippet` -> `replace_snippet`) so Go reflection pins line bounds. |
106
+ | **Exceeding Ponytail Budget** | Produces patches with +50 additions or +40 deletions rewriting surrounding logic. | Split complex remediations or keep changes surgical ($\le 35$ additions, $\le 25$ deletions). |
107
+ | **Introducing Bypass Flags** | Inserts `# nosec`, `verify=False`, or `@csrf_exempt` to quickly silence warnings. | Fix the root cause without disabling security invariants. Bypasses trigger immediate error. |
108
+ | **Formatting Unrelated Lines** | Re-indents or cleans up imports in unrelated sections of the target file. | Zero unrelated churn. Touch only the lines required for vulnerability remediation. |
109
+
110
+ ---
111
+
112
+ ## ✅ Pre-Flight Self-Audit
113
+
114
+ Before formulating a remediation bundle, verify:
115
+ - [ ] Did I read only the bounded AST context window ($\pm 3$ lines) to keep tokens minimal?
116
+ - [ ] Is `find_snippet` an exact, verbatim substring of the target file?
117
+ - [ ] Are total additions $\le 35$ and deletions $\le 25$?
118
+ - [ ] Does `replace_snippet` strictly avoid any bypass flags (`# nosec`, `verify=False`)?
119
+ - [ ] Does the fix preserve existing application behavior and business contracts?
120
+
121
+ ---
122
+
123
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
124
+
125
+ ```
126
+ VERIFY: Inspect target finding context and verify verbatim match of find_snippet in source code.
127
+ BUILD: Formulate minimal SemanticPatch or unified diff conforming to Ponytail budget (<=35 add, <=25 del).
128
+ CONFIRM: Validate via torusguard harden or torusguard_harden MCP tool; verify zero bypass rejections.
129
+ ```
@@ -1,13 +1,13 @@
1
1
  ---
2
2
  name: torusguard-init
3
3
  description: Initialize TorusGuard workspace — detect project stack, activate tailored TG-* security rules, and generate SECURITY.md baseline via CLI or AI Agent.
4
- version: 1.3.6
4
+ version: 2.0.0
5
5
  workflow: .torusguard/workflows/init.md
6
6
  tools: Read, Grep, Glob, Write, run_command
7
7
  scripts-binding:
8
+ - internal/scanner/scanner.go
8
9
  - .torusguard/scripts/report_sync.py
9
10
  - .torusguard/scripts/stack_detect.py
10
- - .torusguard/scripts/term_ui.py
11
11
  ---
12
12
 
13
13
  # TorusGuard Init — Project Stack Discovery & Rule Activation
@@ -17,26 +17,37 @@ Auto-detect repository technology stack across 16+ languages and frameworks, pro
17
17
 
18
18
  ---
19
19
 
20
- ## Two Execution Modes
20
+ ## Tri-Mode Parity
21
+
22
+ | Mode | Command / Tool | Governed Behavior |
23
+ | :--- | :--- | :--- |
24
+ | **Mode A: CLI Terminal** | `torusguard init` | Profiles workspace, provisions directories, activates tailored rules. |
25
+ | **Mode B: AI Chat Slash** | `/torusguard init` | Inspects workspace dependencies and guides baseline rule activation. |
26
+ | **Mode C: Native MCP Tool**| — | Workspace initialization is an administrative setup command. |
27
+
28
+ ---
29
+
30
+ ## Tri-Mode Execution
21
31
 
22
32
  ### Mode A: Automated CLI Execution
23
33
  Run the workspace initializer from your terminal:
24
34
  ```bash
25
35
  # Initialize current repository
26
- npx torusguard init
36
+ torusguard init
27
37
 
28
38
  # Initialize specific directory
29
- npx torusguard init ./my-app
39
+ torusguard init ./my-app
30
40
 
31
41
  # Force re-initialization (overwriting existing configuration)
32
- npx torusguard init --force
42
+ torusguard init --force
33
43
 
34
- # Explicitly specify stack (e.g. react, nextjs, django, fastapi, express)
35
- npx torusguard init --stack express
44
+ # Explicitly specify stack (e.g. react, nextjs, django, fastapi, express, go)
45
+ torusguard init --stack express
36
46
  ```
47
+
37
48
  **Under the Hood:**
38
- - Runs `stack_detect.py` to inspect package files (`package.json`, `pyproject.toml`, `requirements.txt`, `go.mod`, `Cargo.toml`, `Gemfile`, `composer.json`, `*.csproj`).
39
- - Detects backend frameworks, frontend libraries, ORMs (Prisma, Mongoose, SQLAlchemy, Django ORM), and authentication systems.
49
+ - Inspects package files (`package.json`, `pyproject.toml`, `requirements.txt`, `go.mod`, `Cargo.toml`, `Gemfile`, `composer.json`, `*.csproj`).
50
+ - Detects backend frameworks, frontend libraries, ORMs (Prisma, Mongoose, SQLAlchemy, Django ORM, GORM), and authentication systems.
40
51
  - Scaffolds `.torusguard/` directory tree: `config/`, `rules/active/`, `runs/`, `scripts/`, `workflows/`, `templates/`, `schemas/`, `memory/`, `snapshots/`.
41
52
  - Copies tailored rule definitions into `.torusguard/rules/active/`.
42
53
  - Provisions `SECURITY.md` with standard responsible disclosure contacts.
@@ -45,12 +56,17 @@ npx torusguard init --stack express
45
56
 
46
57
  ### Mode B: In-Session AI Chat Agent Initialization
47
58
  When initializing a workspace directly in AI chat:
48
- 1. **Detect Stack:** Inspect root files (`package.json`, `requirements.txt`, etc.) to determine languages and frameworks.
49
- 2. **Bootstrap Structure:** Ensure `.torusguard/` structure exists. If missing, run `python skills/torusguard/bootstrap.py --target .`.
59
+ 1. **Detect Stack:** Inspect root files (`package.json`, `go.mod`, `requirements.txt`, etc.) to determine languages and frameworks.
60
+ 2. **Bootstrap Structure:** Ensure `.torusguard/` structure exists.
50
61
  3. **Activate Rules:** Populate `.torusguard/rules/active/` with applicable rule files from `rules/`.
51
62
  4. **Provision Policy:** Create `SECURITY.md` if not already present.
52
63
  5. **Write Configuration:** Persist settings into `.torusguard/config/torusguard.json`.
53
- 6. **Prompt Audit:** Advise the user to run `npx torusguard audit` or `/torusguard audit`.
64
+ 6. **Prompt Audit:** Advise the user to run `torusguard audit` or `/torusguard audit`.
65
+
66
+ ### Mode C: Native MCP Tool Integration
67
+ For autonomous AI coding agents (Antigravity, Cursor, Windsurf, Claude Code):
68
+ - **Administrative Provisioning:** Agents prompt or invoke `torusguard init` to scaffold workspace boundaries.
69
+ - **Posture Verification:** Once initialized, agents query `torusguard_status` via MCP to inspect active rules and verify initialization state.
54
70
 
55
71
  ---
56
72
 
@@ -61,8 +77,39 @@ When initializing a workspace directly in AI chat:
61
77
  - **Active Rules:** 74 canonical security rules enabled in `.torusguard/rules/active/`
62
78
  - **Configuration:** Written to `.torusguard/config/torusguard.json`
63
79
  - **Security Policy:** Baseline `SECURITY.md` generated
64
- - **Next Step:** Run `npx torusguard audit` or `/torusguard audit` to scan for flaws
80
+ - **Next Step:** Run `torusguard audit` or `/torusguard audit` to scan for flaws
65
81
  ```
66
82
 
67
83
  ## Living Report Ground Truth
68
84
  - Read `security_report.md` in the workspace root before taking any action. Update the relevant finding card after completing remediation.
85
+
86
+ ---
87
+
88
+ ## 🚨 LLM Trap Table
89
+
90
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
91
+ | :--- | :--- | :--- |
92
+ | **Destructive Overwrite** | Overwrites user-customized `.torusguard/rules/active/` without checking `--force`. | Preserve existing customized rules unless `--force` is explicitly provided. |
93
+ | **Generic Stack Guess** | Guesses Node.js without reading `go.mod`, `pyproject.toml`, or `Cargo.toml` in the repository. | Check actual package manifests to detect real multi-language frameworks. |
94
+ | **Root Directory Clutter** | Spills temporary configuration files across root instead of isolating inside `.torusguard/config/`. | Confine all configuration, snapshots, and run artifacts strictly within `.torusguard/`. |
95
+ | **Missing SECURITY.md** | Fails to verify whether responsible disclosure policy already exists before creating a new one. | Check for existing `SECURITY.md` at workspace root; avoid clobbering existing policies. |
96
+
97
+ ---
98
+
99
+ ## ✅ Pre-Flight Self-Audit
100
+
101
+ Before initializing a workspace:
102
+ - [ ] Did I inspect root manifests (`go.mod`, `package.json`, etc.) to identify the true technology stack?
103
+ - [ ] Did I verify whether `.torusguard/` is already initialized?
104
+ - [ ] Did I check if `SECURITY.md` already exists before writing?
105
+ - [ ] Are all directories properly scoped to `.torusguard/`?
106
+
107
+ ---
108
+
109
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
110
+
111
+ ```
112
+ VERIFY: Check workspace root for manifest files and existing .torusguard configuration.
113
+ BUILD: Generate directory tree, configure tailored TG-* rules, and draft SECURITY.md.
114
+ CONFIRM: Verify .torusguard/config/torusguard.json is valid JSON and notify user of readiness.
115
+ ```
@@ -0,0 +1,94 @@
1
+ ---
2
+ name: torusguard-ocr-scan
3
+ description: Scans images, architecture diagrams, and screenshots via Tesseract OCR for leaked API keys, tokens, and credentials via CLI or AI Agent.
4
+ version: 2.0.0
5
+ workflow: .torusguard/workflows/ocr-scan.md
6
+ tools: Read, Grep, Glob, Write, run_command
7
+ scripts-binding:
8
+ - internal/scanner/ocr.go
9
+ - cmd/torusguard/main.go
10
+ ---
11
+
12
+ # TorusGuard OCR Vision Scan — Multi-Modal Secret Extraction
13
+
14
+ ## Objective
15
+ Detect optical leaks of private API keys, AWS credentials, database URIs, GitHub personal access tokens, and private certificates embedded inside visual artifacts (PNG, JPG, WebP, BMP, TIFF) up to 10MB using Tesseract OCR and deterministic regex signatures.
16
+
17
+ ---
18
+
19
+ ## Tri-Mode Execution
20
+
21
+ ### Mode A: Automated CLI Execution
22
+ Run OCR scanning against a single diagram file or an entire directory of visual assets:
23
+ ```bash
24
+ # Scan a specific architecture diagram or screenshot
25
+ torusguard ocr-scan docs/architecture/diagram.png
26
+
27
+ # Scan an entire directory of media assets
28
+ torusguard ocr-scan ./assets/images/
29
+ ```
30
+
31
+ ### Mode B: In-Session AI Chat Slash Command
32
+ Run `/torusguard ocr-scan <path>` in chat.
33
+ The agent invokes the native Go scanner or MCP tool to extract optical text, analyze credential patterns, and report leaked keys.
34
+
35
+ ### Mode C: Native MCP Tool Call
36
+ MCP-enabled coding agents (Antigravity, Cursor, Windsurf, Claude Code) call:
37
+ ```json
38
+ {
39
+ "tool": "torusguard_ocr_scan",
40
+ "arguments": {
41
+ "target": "docs/architecture/cloud-architecture.png",
42
+ "max_image_mb": 10
43
+ }
44
+ }
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Supported Patterns & Invariants
50
+ - **TG-SEC-001:** Hardcoded API Keys / Tokens / OpenAI & Stripe Keys (`sk-live-...`, `sk-...`).
51
+ - **TG-SEC-002:** AWS Access Key IDs (`AKIA[0-9A-Z]{16}`).
52
+ - **TG-SEC-003:** GitHub Personal Access Tokens (`ghp_...`, `github_pat_...`).
53
+ - **TG-SEC-004:** Database Connection URIs (`postgres://user:pass@host:5432/db`).
54
+ - **TG-SEC-005:** Private Key Headers (`-----BEGIN RSA PRIVATE KEY-----`).
55
+ - **TG-SEC-007:** Password assignments (`password = "..."`).
56
+ - **10MB DoS Guard:** Files exceeding 10MB are rejected fail-closed to prevent resource exhaustion attacks.
57
+
58
+ ---
59
+
60
+ ## 🏛️ OpenCodeReview Hybrid Architecture Integration
61
+ - **Deterministic OCR Preprocessing:** Optical extraction and regex pattern matching run entirely in compiled Go code without LLM hallucination.
62
+ - **Token Efficiency:** Only the extracted text and detected secret matches are emitted to the agent context (zero token waste on binary image blobs).
63
+
64
+ ---
65
+
66
+ ## 🚨 LLM Trap Table
67
+
68
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
69
+ | :--- | :--- | :--- |
70
+ | **Reading Binary Images as Text** | Attempts to read raw `.png` or `.jpg` with `view_file` as utf-8 text. | Invoke `torusguard ocr-scan` or `torusguard_ocr_scan` to perform OCR. |
71
+ | **Ignoring Image File Size Bounds** | Tries to OCR multi-hundred megabyte video files or giant raw images. | Adhere to the 10MB DoS boundary (`DefaultMaxImageSize`). |
72
+ | **Echoing Full Leaked Secrets in Logs** | Prints live production credentials unredacted in terminal output or reports. | Partially redact sensitive tokens (e.g. `sk-live-****3211`). |
73
+ | **Assuming Images Don't Contain Secrets** | Audits only `.go` or `.js` code and ignores cloud diagrams or screenshots. | Always run OCR vision scan across image directories during full audits. |
74
+
75
+ ---
76
+
77
+ ## ✅ Pre-Flight Self-Audit
78
+
79
+ Before concluding an OCR inspection, verify:
80
+ - [ ] Is Tesseract installed and discoverable on PATH?
81
+ - [ ] Are all target files valid image formats (`.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`, `.tiff`)?
82
+ - [ ] Are target image file sizes strictly $\le 10$ MB?
83
+ - [ ] Did I check against all 7 canonical secret signatures (`TG-SEC-001` through `TG-SEC-007`)?
84
+ - [ ] Are confirmed leaks documented in `security_report.md` with remediation steps?
85
+
86
+ ---
87
+
88
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
89
+
90
+ ```
91
+ VERIFY: Confirm target image existence and size <= 10MB.
92
+ BUILD: Execute torusguard ocr-scan or torusguard_ocr_scan to extract optical text.
93
+ CONFIRM: Match text against OCRSecretPattern signatures, redact sensitive tokens, and record in security_report.md.
94
+ ```
@@ -1,15 +1,13 @@
1
1
  ---
2
2
  name: torusguard-recheck
3
3
  description: Execute targeted differential AST re-scan against modified files, verify fix closure, and assert zero regressions via CLI or AI Agent.
4
- version: 1.3.6
4
+ version: 2.0.0
5
5
  workflow: .torusguard/workflows/recheck.md
6
6
  tools: Read, Grep, Glob, Write, run_command
7
7
  scripts-binding:
8
+ - internal/scanner/scanner.go
9
+ - internal/harden/patch.go
8
10
  - .torusguard/scripts/report_sync.py
9
- - .torusguard/scripts/recheck_runner.py
10
- - .torusguard/scripts/audit_runner.py
11
- - .torusguard/scripts/memory_engine.py
12
- - .torusguard/scripts/term_ui.py
13
11
  ---
14
12
 
15
13
  # TorusGuard Recheck — Targeted Differential Audit & Fix Closure
@@ -19,26 +17,37 @@ Execute differential security re-scans strictly scoped to modified files and adj
19
17
 
20
18
  ---
21
19
 
22
- ## Two Execution Modes
20
+ ## Tri-Mode Parity
21
+
22
+ | Mode | Command / Tool | Governed Behavior |
23
+ | :--- | :--- | :--- |
24
+ | **Mode A: CLI Terminal** | `torusguard recheck` | Scans modified files, verifies fix closure, and updates run artifacts. |
25
+ | **Mode B: AI Chat Slash** | `/torusguard recheck` | Guides interactive differential review and records fix events. |
26
+ | **Mode C: Native MCP Tool**| `torusguard_recheck` | Machine-to-machine differential AST re-scan for AI coding agents. |
27
+
28
+ ---
29
+
30
+ ## Tri-Mode Execution
23
31
 
24
32
  ### Mode A: Automated CLI Execution
25
33
  Run the differential recheck engine from the terminal:
26
34
  ```bash
27
35
  # Recheck the latest applied run
28
- npx torusguard recheck
36
+ torusguard recheck
29
37
 
30
38
  # Recheck a specific project directory
31
- npx torusguard recheck ./my-project
39
+ torusguard recheck ./my-project
32
40
 
33
41
  # Recheck a specific run ID
34
- npx torusguard recheck --run run-20260910-121618-audit
42
+ torusguard recheck --run run-20260910-121618-audit
35
43
 
36
44
  # Machine-readable JSON output
37
- npx torusguard recheck --json
45
+ torusguard recheck --json
38
46
  ```
39
- **Under the Hood:** Executes `python .torusguard/scripts/recheck_runner.py`.
47
+
48
+ **Under the Hood:**
40
49
  - Evaluates applied candidate bundles from `.torusguard/runs/<run_id>/bundles/`.
41
- - Executes single-file targeted differential AST scans via `audit_runner.scan_file()`.
50
+ - Executes single-file targeted differential AST scans via `internal/scanner` and `internal/recheck`.
42
51
  - Calculates formal status transitions:
43
52
  - `✔ [Confirmed Fixed]`: Vulnerable pattern absent, zero regressions.
44
53
  - `✖ [Regressed]`: New security finding introduced by patch.
@@ -50,10 +59,22 @@ npx torusguard recheck --json
50
59
  ### Mode B: In-Session AI Chat Agent Differential Scan
51
60
  When evaluating patches directly in AI chat:
52
61
  1. **Identify Modified Files:** Read `diff_summary.md` or git status for files modified in the active run.
53
- 2. **Re-Scan Sinks:** View the target file and verify that the specific rule violation (e.g. `TG-INPUT-003`, `TG-PLATFORM-001`) is no longer triggered.
54
- 3. **Assert Zero Regressions:** Verify that no new vulnerabilities (like raw concatenation or unvalidated input) were introduced by the fix.
55
- 4. **Update Status:** Log outcome in `.torusguard/runs/<run_id>/recheck.md`.
56
- 5. **Memory Telemetry:** Record verification event with `memory_engine.record_event("fix_verified", ...)`.
62
+ 2. **Re-Scan Sinks:** View the target file and verify that the specific rule violation (e.g. `TG-INPUT-003`, `TG-PLATFORM-001`, `TG-NPE-001`) is no longer triggered.
63
+ 3. **Assert Zero Regressions:** Verify that no new vulnerabilities (like raw concatenation, missing null checks, or unvalidated inputs) were introduced by the fix.
64
+ 4. **Update Status:** Log outcome in `.torusguard/runs/<run_id>/recheck.md` and transition status in `security_report.md`.
65
+ 5. **Memory Telemetry:** Record verification event in persistent memory.
66
+
67
+ ### Mode C: Native MCP Tool Execution
68
+ For autonomous AI coding agents (Antigravity, Cursor, Windsurf, Claude Code):
69
+ - **Tool Invocation:** Call `torusguard_recheck` with target workspace:
70
+ ```json
71
+ {
72
+ "target": "."
73
+ }
74
+ ```
75
+ - **Programmatic Return:** Receives differential AST re-scan results, baseline comparison, and confirms zero regressions.
76
+
77
+ ---
57
78
 
58
79
  ---
59
80
 
@@ -62,7 +83,7 @@ When evaluating patches directly in AI chat:
62
83
  | :--- | :--- | :--- | :--- |
63
84
  | **Confirmed Fixed** | `✔ [Confirmed Fixed]` | Sink eliminated, zero regressions | Proceed to Posture Report |
64
85
  | **Unresolved** | `⚠ [Unresolved]` | Flaw still present in file | Re-harden with alternative pattern |
65
- | **Regressed** | `✖ [Regressed]` | New security flaw introduced | Instant `npx torusguard rollback` |
86
+ | **Regressed** | `✖ [Regressed]` | New security flaw introduced | Instant `torusguard rollback` |
66
87
 
67
88
  ---
68
89
 
@@ -74,8 +95,40 @@ When evaluating patches directly in AI chat:
74
95
  - **Regressions:** 0 detected
75
96
  - **Unresolved:** 0
76
97
  - **Artifact:** `.torusguard/runs/<run_id>/recheck.md`
77
- - **Next Step:** Run `npx torusguard report --html` for visual dashboard
98
+ - **Next Step:** Run `torusguard report --html` for visual dashboard
78
99
  ```
79
100
 
80
101
  ## Living Report Ground Truth
81
102
  - Read `security_report.md` in the workspace root before taking any action. Update the relevant finding card after completing remediation.
103
+
104
+ ---
105
+
106
+ ## 🚨 LLM Trap Table
107
+
108
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
109
+ | :--- | :--- | :--- |
110
+ | **Premature Closure** | Marks finding "Fixed" merely because code was written, without differential AST re-scan. | Must execute `torusguard recheck` or differential scan to verify the AST sink is genuinely absent. |
111
+ | **Line-Shift Drift** | Relies on original finding line numbers after patches shifted line offsets. | Use semantic snippet matching or recalculate line numbers from fresh AST scan. |
112
+ | **Regression Blindness** | Checks only the original sink and ignores new flaws introduced in surrounding lines (e.g., introducing an unhandled null pointer or SQL concatenation). | Scan entire changed block and adjacent context ($\pm 3$ lines) for zero newly introduced `TG-*` violations. |
113
+ | **Bypass Disguise** | Accepts `# nosec`, `// eslint-disable`, or `InsecureSkipVerify` as a valid "fix". | Strictly flag security bypasses as `✖ [Regressed]` under rule `TG-DIFF-001`. |
114
+
115
+ ---
116
+
117
+ ## ✅ Pre-Flight Self-Audit
118
+
119
+ Before declaring any finding resolved:
120
+ - [ ] Did I read the modified file from disk after applying the patch?
121
+ - [ ] Did I verify the exact AST sink is absent and unreachable?
122
+ - [ ] Did I verify no new vulnerabilities were introduced in surrounding code ($\pm 3$ lines)?
123
+ - [ ] Did I verify zero security suppression comments or bypasses (`# nosec`, `verify=False`, etc.) exist?
124
+ - [ ] Is the finding status updated in `security_report.md`?
125
+
126
+ ---
127
+
128
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
129
+
130
+ ```
131
+ VERIFY: Inspect disk content of modified files to confirm patch application.
132
+ BUILD: Execute differential re-scan against modified files using scanner rules.
133
+ CONFIRM: Assert finding transition to Confirmed Fixed and verify zero regressions.
134
+ ```
@@ -0,0 +1,91 @@
1
+ ---
2
+ name: torusguard-redos
3
+ description: Analyzes regular expressions across JavaScript, TypeScript, Python, and Go for catastrophic exponential backtracking and ReDoS vulnerabilities via CLI, Chat, or MCP.
4
+ version: 2.0.0
5
+ workflow: .torusguard/workflows/redos.md
6
+ tools: Read, Grep, Glob, Write, run_command
7
+ scripts-binding:
8
+ - internal/scanner/redos.go
9
+ - cmd/torusguard/main.go
10
+ - cmd/torusguard/mcp.go
11
+ ---
12
+
13
+ # TorusGuard ReDoS Complexity Scanner
14
+
15
+ ## Objective
16
+ Detect and remediate catastrophic exponential ($O(2^n)$) and polynomial ($O(n^k)$) backtracking regular expressions in web applications. Prevents thread starvation, CPU exhaustion, and availability denial of service attacks caused by untrusted user input matching evil regex patterns.
17
+
18
+ ---
19
+
20
+ ## Tri-Mode Execution
21
+
22
+ ### Mode A: Automated CLI Execution
23
+ Run ReDoS scanning against source code files:
24
+ ```bash
25
+ # Scan current workspace for catastrophic regex backtracking
26
+ torusguard redos
27
+
28
+ # Scan specific directory or source tree
29
+ torusguard redos --target ./src
30
+ ```
31
+
32
+ ### Mode B: In-Session AI Chat Slash Command
33
+ Run `/torusguard redos` in chat.
34
+ The agent executes the compiled Go ReDoS analyzer or MCP tool to locate dangerous nested quantifiers, overlapping alternations, and unanchored expressions.
35
+
36
+ ### Mode C: Native MCP Tool Call
37
+ MCP-enabled coding agents (Antigravity, Cursor, Windsurf, Claude Code) call:
38
+ ```json
39
+ {
40
+ "tool": "torusguard_redos",
41
+ "arguments": {
42
+ "target": "."
43
+ }
44
+ }
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Supported Patterns & Invariants
50
+ - **TG-REDOS-001 (Nested Quantifier Catastrophic Backtracking):** Detects nested repetitions such as `(a+)+`, `([a-zA-Z0-9]+)*`, or `((foo)*)+` that cause exponential evaluation time $O(2^n)$ when matching non-matching suffixes (e.g. `aaaaaaaaaaaaaaaa!`).
51
+ - **TG-REDOS-002 (Overlapping Alternation with Outer Repetition):** Detects patterns like `(a|ab)+` or `(user|username)*` where multiple branches match identical prefixes, causing exponential branch exploration.
52
+
53
+ ---
54
+
55
+ ## 🏛️ OpenCodeReview Hybrid Architecture Integration
56
+ - **First-Principles NFA/DFA Complexity Analysis:** Scans regex literals and constructor invocations across JS, TS, Python, and Go.
57
+ - **Engine-Aware Triage:** Flags backtracking engines (V8, Node.js, Python `re`, PCRE) as high risk while noting linear-time DFA engines (Go `regexp`/RE2, Rust `regex`).
58
+ - **Surgical Patching:** Replaces evil regexes with bounded, non-overlapping expressions or length pre-checks (≤35 additions, ≤25 deletions).
59
+
60
+ ---
61
+
62
+ ## 🚨 LLM Trap Table
63
+
64
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
65
+ | :--- | :--- | :--- |
66
+ | **Nested Quantifiers** | Writes `([a-zA-Z0-9_]+)*` or `(https?://.+)*`, causing $O(2^n)$ catastrophic backtracking on malicious input. | Flatten expressions: `[a-zA-Z0-9_]*` or use non-overlapping delimiters like `[^/\s]+`. |
67
+ | **Overlapping Alternation** | Combines overlapping options inside repetition: `(a\|aa)+` or `(\w+\|\d+)+`. | Disjoint branch design: ensure alternatives cannot consume the same character prefix. |
68
+ | **Missing Input Length Guards** | Evaluates complex regexes against arbitrarily long input strings from untrusted HTTP bodies. | Impose input bounds (`if (input.length > 256) return false`) before regex evaluation. |
69
+ | **Unanchored Wildcards** | Writes `.*foo.*` without anchors, leading to quadratic scan across long documents. | Anchor patterns with `^` and `$` whenever full string matching is intended. |
70
+ | **Engine Indifference** | Assumes all regex engines backtrack identically; doesn't know Go RE2 is linear $O(n)$ while Node V8 is vulnerable. | Tailor remediation to target runtime: use atomic groups/lookahead in V8/Python or switch to parser combinators. |
71
+
72
+ ---
73
+
74
+ ## ✅ Pre-Flight Self-Audit
75
+
76
+ Before concluding a ReDoS complexity audit, verify:
77
+ - [ ] Were all regex literals and `RegExp` / `re.compile` declarations inspected?
78
+ - [ ] Are any nested quantifiers (`(x+)+`, `(x*)*`) present in the codebase?
79
+ - [ ] Are alternatives in grouped alternations strictly mutually exclusive?
80
+ - [ ] Is untrusted input strictly bounded in length before regex execution?
81
+ - [ ] Are remediations validated within Ponytail diff bounds?
82
+
83
+ ---
84
+
85
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
86
+
87
+ ```
88
+ VERIFY: Identify regex patterns evaluated on untrusted user inputs.
89
+ BUILD: Execute torusguard redos or torusguard_redos to detect exponential backtracking structures.
90
+ CONFIRM: Refactor pattern into deterministic, non-overlapping tokens, adding length guards and testing with evil payloads.
91
+ ```