torusguard 2.0.0-alpha → 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 (136) hide show
  1. package/.torusguard/.manifest.json +50 -28
  2. package/.torusguard/rules/container/TG-CONT-001-root-user-execution.md +50 -0
  3. package/.torusguard/rules/container/TG-CONT-002-docker-socket-mount.md +47 -0
  4. package/.torusguard/rules/container/TG-CONT-003-privileged-container-mode.md +53 -0
  5. package/.torusguard/rules/container/TG-CONT-004-build-arg-secret-exposure.md +43 -0
  6. package/.torusguard/rules/git/TG-GIT-001-historical-secret-in-git-commit.md +44 -0
  7. package/.torusguard/rules/git/TG-GIT-002-plaintext-credentials-in-git-config.md +41 -0
  8. package/.torusguard/rules/git/TG-GIT-003-sensitive-tracked-file-gitignore-breach.md +40 -0
  9. package/.torusguard/rules/rag/TG-RAG-001-untrusted-rag-context-injection.md +72 -0
  10. package/.torusguard/rules/rag/TG-RAG-002-autonomous-llm-tool-unsandboxed-call.md +51 -0
  11. package/.torusguard/rules/rag/TG-RAG-003-unpartitioned-vector-tenant-lookup.md +51 -0
  12. package/.torusguard/rules/redos/TG-REDOS-001-catastrophic-exponential-backtracking.md +46 -0
  13. package/.torusguard/rules/redos/TG-REDOS-002-unbounded-nested-quantifier.md +43 -0
  14. package/.torusguard/rules_catalog.json +96 -0
  15. package/.torusguard/scripts/__pycache__/manifest_builder.cpython-314.pyc +0 -0
  16. package/.torusguard/scripts/manifest_builder.py +1 -1
  17. package/.torusguard/skills/torusguard/SKILL.md +69 -24
  18. package/.torusguard/skills/torusguard/bootstrap.py +57 -24
  19. package/.torusguard/skills/torusguard-ai-guard/SKILL.md +95 -0
  20. package/.torusguard/skills/torusguard-apply/SKILL.md +60 -34
  21. package/.torusguard/skills/torusguard-audit/SKILL.md +73 -24
  22. package/.torusguard/skills/torusguard-authorize/SKILL.md +48 -6
  23. package/.torusguard/skills/torusguard-container/SKILL.md +94 -0
  24. package/.torusguard/skills/torusguard-exploit-check/SKILL.md +50 -6
  25. package/.torusguard/skills/torusguard-full/SKILL.md +62 -19
  26. package/.torusguard/skills/torusguard-git-mine/SKILL.md +92 -0
  27. package/.torusguard/skills/torusguard-harden/SKILL.md +81 -50
  28. package/.torusguard/skills/torusguard-init/SKILL.md +61 -14
  29. package/.torusguard/skills/torusguard-ocr-scan/SKILL.md +94 -0
  30. package/.torusguard/skills/torusguard-recheck/SKILL.md +71 -18
  31. package/.torusguard/skills/torusguard-redos/SKILL.md +91 -0
  32. package/.torusguard/skills/torusguard-report/SKILL.md +50 -9
  33. package/.torusguard/skills/torusguard-status/SKILL.md +63 -10
  34. package/.torusguard/skills/torusguard-verify/SKILL.md +52 -10
  35. package/.torusguard/skills/torusguard-web-validate/SKILL.md +53 -8
  36. package/.torusguard/workflows/ai-guard.md +31 -0
  37. package/.torusguard/workflows/apply.md +32 -55
  38. package/.torusguard/workflows/audit.md +28 -46
  39. package/.torusguard/workflows/authorize.md +27 -50
  40. package/.torusguard/workflows/container.md +29 -0
  41. package/.torusguard/workflows/exploit-check.md +28 -50
  42. package/.torusguard/workflows/git-mine.md +25 -0
  43. package/.torusguard/workflows/harden.md +29 -48
  44. package/.torusguard/workflows/init.md +27 -50
  45. package/.torusguard/workflows/memory.md +18 -23
  46. package/.torusguard/workflows/ocr-scan.md +25 -0
  47. package/.torusguard/workflows/recheck.md +28 -46
  48. package/.torusguard/workflows/redos.md +27 -0
  49. package/.torusguard/workflows/report.md +33 -52
  50. package/.torusguard/workflows/status.md +31 -52
  51. package/.torusguard/workflows/verify.md +29 -49
  52. package/.torusguard/workflows/web-validate.md +22 -45
  53. package/README.md +84 -56
  54. package/package.json +1 -1
  55. package/skills/torusguard/SKILL.md +71 -24
  56. package/skills/torusguard/__pycache__/bootstrap.cpython-314.pyc +0 -0
  57. package/skills/torusguard/bootstrap.py +60 -71
  58. package/skills/torusguard/payload/.manifest.json +50 -28
  59. package/skills/torusguard/payload/rules/container/TG-CONT-001-root-user-execution.md +50 -0
  60. package/skills/torusguard/payload/rules/container/TG-CONT-002-docker-socket-mount.md +47 -0
  61. package/skills/torusguard/payload/rules/container/TG-CONT-003-privileged-container-mode.md +53 -0
  62. package/skills/torusguard/payload/rules/container/TG-CONT-004-build-arg-secret-exposure.md +43 -0
  63. package/skills/torusguard/payload/rules/git/TG-GIT-001-historical-secret-in-git-commit.md +44 -0
  64. package/skills/torusguard/payload/rules/git/TG-GIT-002-plaintext-credentials-in-git-config.md +41 -0
  65. package/skills/torusguard/payload/rules/git/TG-GIT-003-sensitive-tracked-file-gitignore-breach.md +40 -0
  66. package/skills/torusguard/payload/rules/rag/TG-RAG-001-untrusted-rag-context-injection.md +72 -0
  67. package/skills/torusguard/payload/rules/rag/TG-RAG-002-autonomous-llm-tool-unsandboxed-call.md +51 -0
  68. package/skills/torusguard/payload/rules/rag/TG-RAG-003-unpartitioned-vector-tenant-lookup.md +51 -0
  69. package/skills/torusguard/payload/rules/redos/TG-REDOS-001-catastrophic-exponential-backtracking.md +46 -0
  70. package/skills/torusguard/payload/rules/redos/TG-REDOS-002-unbounded-nested-quantifier.md +43 -0
  71. package/skills/torusguard/payload/rules_catalog.json +338 -518
  72. package/skills/torusguard/payload/scripts/__pycache__/term_ui.cpython-314.pyc +0 -0
  73. package/skills/torusguard/payload/scripts/manifest_builder.py +1 -1
  74. package/skills/torusguard/payload/skills/torusguard/SKILL.md +69 -24
  75. package/skills/torusguard/payload/skills/torusguard/bootstrap.py +57 -24
  76. package/skills/torusguard/payload/skills/torusguard/references/csharp-security.md +41 -41
  77. package/skills/torusguard/payload/skills/torusguard/references/go-security.md +41 -41
  78. package/skills/torusguard/payload/skills/torusguard/references/java-security.md +40 -40
  79. package/skills/torusguard/payload/skills/torusguard/references/polyglot-security-matrix.md +25 -25
  80. package/skills/torusguard/payload/skills/torusguard/references/rust-security.md +40 -40
  81. package/skills/torusguard/payload/skills/torusguard-ai-guard/SKILL.md +95 -0
  82. package/skills/torusguard/payload/skills/torusguard-apply/SKILL.md +60 -34
  83. package/skills/torusguard/payload/skills/torusguard-audit/SKILL.md +73 -24
  84. package/skills/torusguard/payload/skills/torusguard-authorize/SKILL.md +48 -6
  85. package/skills/torusguard/payload/skills/torusguard-container/SKILL.md +94 -0
  86. package/skills/torusguard/payload/skills/torusguard-exploit-check/SKILL.md +50 -6
  87. package/skills/torusguard/payload/skills/torusguard-full/SKILL.md +62 -19
  88. package/skills/torusguard/payload/skills/torusguard-git-mine/SKILL.md +92 -0
  89. package/skills/torusguard/payload/skills/torusguard-harden/SKILL.md +81 -50
  90. package/skills/torusguard/payload/skills/torusguard-init/SKILL.md +61 -14
  91. package/skills/torusguard/payload/skills/torusguard-ocr-scan/SKILL.md +94 -0
  92. package/skills/torusguard/payload/skills/torusguard-recheck/SKILL.md +71 -18
  93. package/skills/torusguard/payload/skills/torusguard-redos/SKILL.md +91 -0
  94. package/skills/torusguard/payload/skills/torusguard-report/SKILL.md +50 -9
  95. package/skills/torusguard/payload/skills/torusguard-status/SKILL.md +63 -10
  96. package/skills/torusguard/payload/skills/torusguard-verify/SKILL.md +52 -10
  97. package/skills/torusguard/payload/skills/torusguard-web-validate/SKILL.md +53 -8
  98. package/skills/torusguard/payload/workflows/ai-guard.md +31 -0
  99. package/skills/torusguard/payload/workflows/apply.md +31 -62
  100. package/skills/torusguard/payload/workflows/audit.md +27 -51
  101. package/skills/torusguard/payload/workflows/authorize.md +27 -50
  102. package/skills/torusguard/payload/workflows/container.md +29 -0
  103. package/skills/torusguard/payload/workflows/exploit-check.md +28 -50
  104. package/skills/torusguard/payload/workflows/git-mine.md +25 -0
  105. package/skills/torusguard/payload/workflows/harden.md +28 -52
  106. package/skills/torusguard/payload/workflows/init.md +27 -56
  107. package/skills/torusguard/payload/workflows/memory.md +18 -23
  108. package/skills/torusguard/payload/workflows/ocr-scan.md +25 -0
  109. package/skills/torusguard/payload/workflows/recheck.md +28 -46
  110. package/skills/torusguard/payload/workflows/redos.md +27 -0
  111. package/skills/torusguard/payload/workflows/report.md +39 -62
  112. package/skills/torusguard/payload/workflows/status.md +31 -55
  113. package/skills/torusguard/payload/workflows/verify.md +29 -49
  114. package/skills/torusguard/payload/workflows/web-validate.md +22 -45
  115. package/skills/torusguard/references/csharp-security.md +41 -0
  116. package/skills/torusguard/references/go-security.md +41 -0
  117. package/skills/torusguard/references/java-security.md +40 -0
  118. package/skills/torusguard/references/polyglot-security-matrix.md +25 -0
  119. package/skills/torusguard/references/rust-security.md +40 -0
  120. package/skills/torusguard-ai-guard/SKILL.md +95 -0
  121. package/skills/torusguard-apply/SKILL.md +60 -34
  122. package/skills/torusguard-audit/SKILL.md +73 -24
  123. package/skills/torusguard-authorize/SKILL.md +48 -6
  124. package/skills/torusguard-container/SKILL.md +94 -0
  125. package/skills/torusguard-exploit-check/SKILL.md +50 -6
  126. package/skills/torusguard-full/SKILL.md +62 -19
  127. package/skills/torusguard-git-mine/SKILL.md +92 -0
  128. package/skills/torusguard-harden/SKILL.md +81 -50
  129. package/skills/torusguard-init/SKILL.md +61 -14
  130. package/skills/torusguard-ocr-scan/SKILL.md +94 -0
  131. package/skills/torusguard-recheck/SKILL.md +71 -18
  132. package/skills/torusguard-redos/SKILL.md +91 -0
  133. package/skills/torusguard-report/SKILL.md +50 -9
  134. package/skills/torusguard-status/SKILL.md +63 -10
  135. package/skills/torusguard-verify/SKILL.md +52 -10
  136. package/skills/torusguard-web-validate/SKILL.md +53 -8
@@ -39,7 +39,7 @@ def scan_workspace_files(base_dir):
39
39
  dirs.remove("__pycache__")
40
40
 
41
41
  for f in sorted(files):
42
- if f in [".manifest.json", ".gitkeep"] or f.endswith(".pyc"):
42
+ if f in [".manifest.json", ".gitkeep", "auth.json"] or f.endswith(".pyc"):
43
43
  continue
44
44
  full_path = Path(root) / f
45
45
  rel_path = full_path.relative_to(base_dir).as_posix()
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: torusguard
3
3
  description: Universal autonomous security engine: 74 canonical rules across 18 families, polyglot stack detection across 16+ languages, Ponytail remediation bounds (<=35 add, <=25 del), standardized 75-column terminal UI, SARIF v2.1.0 exports, and persistent security memory context.
4
- version: 1.3.6
4
+ version: 2.0.0
5
5
  ---
6
6
 
7
7
  # TorusGuard Master Security Engine & Command Router
@@ -10,38 +10,50 @@ version: 1.3.6
10
10
 
11
11
  ---
12
12
 
13
- ## Command Catalog: Terminal CLI & AI Chat Parity
13
+ ## Tri-Mode Execution & Command Catalog
14
14
 
15
- TorusGuard operates with 100% feature parity across both the terminal CLI and AI chat slash commands:
15
+ TorusGuard operates with 100% feature parity across the compiled terminal CLI, AI chat slash commands, and Model Context Protocol (MCP) tools:
16
16
 
17
- | Capability | Terminal CLI Command | AI Chat Slash Command | Specialist Skill | Purpose |
17
+ | Capability | Terminal CLI Command | AI Chat Slash Command | Specialist Skill | Governed Purpose |
18
18
  | :--- | :--- | :--- | :--- | :--- |
19
- | **Init** | `npx torusguard init` | `/torusguard init` | `skills/torusguard-init` | Stack discovery, rule activation, workspace scaffolding |
20
- | **Status** | `npx torusguard status` | `/torusguard status` | `skills/torusguard-status` | Posture score, active rules, run history, scope check |
21
- | **Audit** | `npx torusguard audit` | `/torusguard audit` | `skills/torusguard-audit` | Static AST scan, invariant fingerprinting, confidence scoring |
22
- | **Verify** | `npx torusguard verify` | `/torusguard verify` | `skills/torusguard-verify` | Evidence sufficiency audit & line match calibration |
23
- | **Harden** | `npx torusguard harden` | `/torusguard harden` | `skills/torusguard-harden` | Ponytail patch formulation ($\le 35$ add, $\le 25$ del) |
24
- | **Apply** | `npx torusguard apply [--yes]` | `/torusguard apply` | `skills/torusguard-apply` | Human Gate review, `.bak` snapshots, patch application |
25
- | **Rollback** | `npx torusguard rollback` | `/torusguard rollback` | `skills/torusguard-apply` | Instant 1-step rollback from pre-apply snapshots |
26
- | **Recheck** | `npx torusguard recheck` | `/torusguard recheck` | `skills/torusguard-recheck` | Targeted differential AST scan, fix closure verification |
27
- | **Recipes** | `npx torusguard recipes` | `/torusguard recipes` | `skills/torusguard-harden` | Explore verified Golden Fix Recipes from persistent memory |
28
- | **Report** | `npx torusguard report --html` | `/torusguard report` | `skills/torusguard-report` | Executive posture reporting, SARIF v2.1.0 & visual HTML |
29
- | **Authorize** | `npx torusguard authorize` | `/torusguard authorize` | `skills/torusguard-authorize`| Legal scope definition & safety boundaries |
30
- | **Validate** | `npx torusguard web-validate` | `/torusguard web-validate` | `skills/torusguard-web-validate`| Authorized non-destructive HTTP probing |
31
- | **Exploit** | `npx torusguard exploit-check` | `/torusguard exploit-check`| `skills/torusguard-exploit-check`| Bounded single-step exploitability confirmation |
32
- | **Full** | `npx torusguard full` | `/torusguard full` | `skills/torusguard-full` | End-to-end 7-stage closed-loop execution |
33
- | **Sync** | `npx torusguard rules sync` | `/torusguard rules sync` | `skills/torusguard-init` | Synchronize rules across AI editors (Cursor, Claude, Antigravity) |
19
+ | **Init** | `torusguard init` | `/torusguard init` | `.torusguard/skills/torusguard-init` | Stack discovery, rule activation, workspace scaffolding |
20
+ | **Status** | `torusguard status` | `/torusguard status` | `.torusguard/skills/torusguard-status` | Posture score, active rules, run history, scope check |
21
+ | **Audit** | `torusguard audit` | `/torusguard audit` | `.torusguard/skills/torusguard-audit` | Static AST scan, invariant fingerprinting, confidence scoring |
22
+ | **OCR Vision**| `torusguard ocr-scan <path>` | `/torusguard ocr-scan` | `.torusguard/skills/torusguard-ocr-scan` | Tesseract OCR secret scan on images/diagrams |
23
+ | **Verify** | `torusguard verify` | `/torusguard verify` | `.torusguard/skills/torusguard-verify` | Evidence sufficiency audit & line match calibration |
24
+ | **Harden** | `torusguard harden <patch>` | `/torusguard harden` | `.torusguard/skills/torusguard-harden` | Ponytail patch formulation ($\le 35$ add, $\le 25$ del) & reflection validation |
25
+ | **Apply** | `torusguard apply [--yes]` | `/torusguard apply` | `.torusguard/skills/torusguard-apply` | Human Gate review, `.bak` snapshots, patch application |
26
+ | **Rollback** | `torusguard rollback` | `/torusguard rollback` | `.torusguard/skills/torusguard-apply` | Instant 1-step rollback from pre-apply snapshots |
27
+ | **Recheck** | `torusguard recheck` | `/torusguard recheck` | `.torusguard/skills/torusguard-recheck` | Targeted differential AST scan, fix closure verification |
28
+ | **Recipes** | `torusguard recipes` | `/torusguard recipes` | `.torusguard/skills/torusguard-harden` | Explore verified Golden Fix Recipes from persistent memory |
29
+ | **Report** | `torusguard report --html` | `/torusguard report` | `.torusguard/skills/torusguard-report` | Executive posture reporting, SARIF v2.1.0 & visual HTML |
30
+ | **Authorize** | `torusguard authorize` | `/torusguard authorize` | `.torusguard/skills/torusguard-authorize`| Legal scope definition & safety boundaries |
31
+ | **Validate** | `torusguard web-validate` | `/torusguard web-validate` | `.torusguard/skills/torusguard-web-validate`| Authorized non-destructive HTTP probing |
32
+ | **Exploit** | `torusguard exploit-check` | `/torusguard exploit-check`| `.torusguard/skills/torusguard-exploit-check`| Bounded single-step exploitability confirmation |
33
+ | **Full** | `torusguard full` | `/torusguard full` | `.torusguard/skills/torusguard-full` | End-to-end 7-stage closed-loop execution |
34
+ | **MCP Server**| `torusguard mcp` | — | Native Stdio JSON-RPC 2.0 | Serves native Model Context Protocol tools to AI coding agents |
35
+ | **Update** | `torusguard update` | `/torusguard update` | `.torusguard/skills/torusguard-init` | Self-update TorusGuard engine binary |
36
+ | **Help** | `torusguard help` | `/torusguard help` | — | Interactive command guide |
34
37
 
35
38
  ---
36
39
 
37
40
  ## Non-Negotiable Invariants
38
41
 
39
- 1. **Browser-Code Truth:** If the client receives it, it is public. Zero hardcoded secrets (`SUPABASE_SERVICE_ROLE_KEY`, private tokens, live API keys) in frontend code.
40
- 2. **Multi-Tenant Isolation:** All database lookups must be scoped by organization or user ownership (`tenant_id`, `organization_id`, `where: { tenantId }`).
42
+ 1. **Browser-Code Truth:** If the client receives it, it is public. Zero hardcoded secrets (`SUPABASE_SERVICE_ROLE_KEY`, private tokens, live API keys) in frontend code (`TG-CLIENT-001`).
43
+ 2. **Multi-Tenant Isolation:** All database lookups must be scoped by organization or user ownership (`tenant_id`, `organization_id`, `where: { tenantId }`) (`TG-DB-001`).
41
44
  3. **Ponytail Churn Bounds:** Patches must be minimal and surgical ($\le 35$ additions, $\le 25$ deletions). Never perform full-file rewrites.
42
45
  4. **Standardized 75-Column Terminal:** All CLI terminal output is strictly normalized to 75 visual columns with Unicode emoji width calculation, ANSI escape handling, and visual truncation with ellipsis (`...`).
43
- 5. **Zero Security Bypasses:** Never insert `# nosec`, `verify=False`, `InsecureSkipVerify: true`, `[AllowAnonymous]`, or `csrf().disable()`.
46
+ 5. **Zero Security Bypasses:** Never insert `# nosec`, `verify=False`, `InsecureSkipVerify: true`, `[AllowAnonymous]`, or `csrf().disable()` (`TG-DIFF-001`).
44
47
  6. **Snapshots Before Edits:** Every code modification must capture a byte-for-byte pre-apply backup in `.torusguard/snapshots/<run_id>/` before touching disk code.
48
+ 7. **Living Report Ground Truth:** All findings synchronize directly with `security_report.md` at workspace root.
49
+
50
+ ---
51
+
52
+ ## 🏛️ Alibaba OpenCodeReview Hybrid Architecture Integration
53
+ TorusGuard employs the dual-track hybrid architecture battle-tested at Alibaba Group scale:
54
+ 1. **Deterministic Engineering Pipeline (Go CLI Engine):** Mechanical tasks (file traversal, whitespace tolerance, exact AST matching, Ponytail churn bounds calculation, pre-apply snapshot capture, and OCR extraction) are strictly executed by the compiled Go binary.
55
+ 2. **Context Minimization (1/9th Token Strategy):** Agents never dump full files into prompt context. Bounded AST windows ($\pm 3$ lines) are extracted via `ExtractContext` to keep review tokens hyper-dense.
56
+ 3. **Line-Level Reflection:** In remediation, the agent provides semantic intent (`find_snippet` + `replace_snippet`). The Go CLI reflection module pins and verifies line bounds deterministically, preventing line-number drift.
45
57
 
46
58
  ---
47
59
 
@@ -67,9 +79,42 @@ TorusGuard operates with 100% feature parity across both the terminal CLI and AI
67
79
  │ ├── report.html # Single-file visual dark-mode HTML report
68
80
  │ ├── results.sarif # OASIS SARIF v2.1.0 log
69
81
  │ └── bundles/ # Formulated Ponytail remediation bundles
82
+ ├── skills/ # Canonical distribution skills for end-user AI agents
83
+ ├── workflows/ # Operational step-by-step workflow guides
70
84
  └── snapshots/
71
85
  └── run-YYYYMMDD-HHMMSS-audit/ # Pre-apply .bak files for instant rollback
72
86
  ```
73
87
 
74
- ## Living Report Ground Truth
75
- - Read `security_report.md` in the workspace root before taking any action. Update the relevant finding card after completing remediation.
88
+ ---
89
+
90
+ ## 🚨 LLM Trap Table
91
+
92
+ | Pattern | What AI Does Wrong | What Is Actually Correct |
93
+ | :--- | :--- | :--- |
94
+ | **Line-Number Diff Hallucination** | Guesses line numbers in unified diff headers (`@@ -42,5 +42,7 @@`) causing patch rejection. | Use the Line-Level Reflection Module (`SemanticPatch` with `find_snippet` and `replace_snippet`) to let Go resolve exact lines. |
95
+ | **Context Window Bloating** | Dumps entire 1,000-line source files into conversation when diagnosing a single finding. | Use bounded AST context extraction ($\pm 3$ lines) matching OpenCodeReview's 1/9th token efficiency. |
96
+ | **Full-File Rewrites** | Rewrites the entire file or surrounding business logic when fixing a vulnerability. | Strictly conform to Ponytail bounds ($\le 35$ additions, $\le 25$ deletions per bundle). |
97
+ | **Security Bypass Insertion** | Introduces `# nosec`, `verify=False`, or `[AllowAnonymous]` to make tests pass. | Strictly forbidden (`TG-DIFF-001`). Rejections are enforced fail-closed by the Go engine. |
98
+ | **Missing Multi-Tenant Scope** | Modifies queries to filter only by record `id`. | Always scope database lookups by tenant or user ownership (`tenantId: user.tenantId`). |
99
+
100
+ ---
101
+
102
+ ## ✅ Pre-Flight Self-Audit
103
+
104
+ Before producing any security remediation or analysis, verify:
105
+ - [ ] Did I read `security_report.md` at workspace root before proposing changes?
106
+ - [ ] Did I inspect only the bounded AST context window ($\pm 3$ lines) rather than the entire file?
107
+ - [ ] Does my proposed remediation stay strictly within Ponytail bounds ($\le 35$ additions, $\le 25$ deletions)?
108
+ - [ ] Is the fix free of any `# nosec`, `verify=False`, or bypass flags?
109
+ - [ ] Did I verify multi-tenant isolation on all database and model queries?
110
+ - [ ] Can this patch be applied via deterministic reflection (`find_snippet` -> `replace_snippet`)?
111
+
112
+ ---
113
+
114
+ ## 🔁 VBC Protocol (Verify → Build → Confirm)
115
+
116
+ ```
117
+ VERIFY: Inspect living security_report.md and bounded AST context snippet.
118
+ BUILD: Formulate surgical SemanticPatch (find_snippet + replace_snippet within <=35 add / <=25 del).
119
+ CONFIRM: Validate via torusguard harden, apply snapshot, and execute differential torusguard recheck.
120
+ ```
@@ -63,14 +63,15 @@ import unicodedata
63
63
  ANSI_REGEX = re.compile(r'\033\[[0-9;]*m')
64
64
 
65
65
  def get_visual_width(text: str) -> int:
66
- """Calculate the printable display width of a string (ANSI and emoji aware)."""
66
+ """Calculate the printable display width of a string (ANSI, emoji and variation selector aware)."""
67
67
  clean = ANSI_REGEX.sub('', text)
68
68
  width = 0
69
69
  for ch in clean:
70
+ cp = ord(ch)
71
+ if (0xFE00 <= cp <= 0xFE0F) or (0xE0100 <= cp <= 0xE01EF) or cp in (0x200B, 0x200C, 0x200D, 0x00AD):
72
+ continue
70
73
  ea = unicodedata.east_asian_width(ch)
71
- if ea in ('W', 'F'):
72
- width += 2
73
- elif ord(ch) >= 0x1F300:
74
+ if ea in ('W', 'F') or cp >= 0x1F300:
74
75
  width += 2
75
76
  else:
76
77
  width += 1
@@ -82,7 +83,7 @@ def truncate_visual(text: str, max_w: int = 67) -> str:
82
83
  return text
83
84
  out, curr_w, in_ansi, ansi_buf = [], 0, False, ''
84
85
  for ch in text:
85
- if ch == '\033':
86
+ if ch in ('\033', '\x1b'):
86
87
  in_ansi = True
87
88
  ansi_buf = ch
88
89
  continue
@@ -92,13 +93,19 @@ def truncate_visual(text: str, max_w: int = 67) -> str:
92
93
  in_ansi = False
93
94
  out.append(ansi_buf)
94
95
  continue
96
+ cp = ord(ch)
97
+ if (0xFE00 <= cp <= 0xFE0F) or (0xE0100 <= cp <= 0xE01EF) or cp in (0x200B, 0x200C, 0x200D, 0x00AD):
98
+ out.append(ch)
99
+ continue
95
100
  ea = unicodedata.east_asian_width(ch)
96
- cw = 2 if ea in ('W', 'F') or ord(ch) >= 0x1F300 else 1
101
+ cw = 2 if (ea in ('W', 'F') or cp >= 0x1F300) else 1
97
102
  if curr_w + cw > max_w - 3:
98
- out.append('...')
103
+ out.append(RESET + '...')
104
+ curr_w += 3
99
105
  break
100
106
  out.append(ch)
101
107
  curr_w += cw
108
+ out.append(RESET)
102
109
  return ''.join(out)
103
110
 
104
111
  def card_line(content: str, max_w: int = 67, border: str = "│", border_color: str = CYAN) -> str:
@@ -109,37 +116,56 @@ def card_line(content: str, max_w: int = 67, border: str = "│", border_color:
109
116
  return f" {border_color}{border}{RESET} {trunc}{pad} {border_color}{border}{RESET}"
110
117
 
111
118
  def card_border_top(title: str = "", border_color: str = CYAN, double: bool = False) -> str:
119
+ """Generate 75-column top border (single ┌ or double ╔) with optional title."""
112
120
  left = "╔" if double else "┌"
113
121
  right = "╗" if double else "┐"
114
122
  h = "═" if double else "─"
115
123
  if title:
116
124
  vis = get_visual_width(title)
117
- rem = max(0, 71 - 3 - vis - 1)
125
+ rem = max(0, 68 - vis)
118
126
  return f" {border_color}{left}{h} {BOLD}{WHITE}{title}{RESET}{border_color} {h * rem}{right}{RESET}"
119
127
  return f" {border_color}{left}{h * 71}{right}{RESET}"
120
128
 
121
129
  def card_border_bottom(border_color: str = CYAN, double: bool = False) -> str:
130
+ """Generate 75-column bottom border (single └ or double ╚)."""
122
131
  left = "╚" if double else "└"
123
132
  right = "╝" if double else "┘"
124
133
  h = "═" if double else "─"
125
134
  return f" {border_color}{left}{h * 71}{right}{RESET}"
126
135
 
127
- def card_divider(border_color: str = CYAN, double: bool = False) -> str:
136
+ def card_divider(title: str = "", border_color: str = CYAN, double: bool = False) -> str:
137
+ """Generate 75-column divider (single ├ or double ╠) with optional title."""
128
138
  left = "╠" if double else "├"
129
139
  right = "╣" if double else "┤"
130
140
  h = "═" if double else "─"
141
+ if title:
142
+ vis = get_visual_width(title)
143
+ rem = max(0, 68 - vis)
144
+ return f" {border_color}{left}{h} {BOLD}{WHITE}{title}{RESET}{border_color} {h * rem}{right}{RESET}"
131
145
  return f" {border_color}{left}{h * 71}{right}{RESET}"
132
146
 
147
+ def card_header(title: str, subtitle: str = "", version: str = "v2.1.0", border_color: str = CYAN) -> str:
148
+ """Generate standardized 75-column curved header box."""
149
+ top = f" {border_color}╭{'─' * 71}╮{RESET}"
150
+ bottom = f" {border_color}╰{'─' * 71}╯{RESET}"
151
+ empty = f" {border_color}│{' ' * 71}│{RESET}"
152
+
153
+ title_vis = get_visual_width(title)
154
+ ver_vis = get_visual_width(version)
155
+ space_count = max(1, 67 - title_vis - ver_vis)
156
+ title_str = f"{BOLD}{WHITE}{title}{RESET}{' ' * space_count}{GRAY}{version}{RESET}"
157
+
158
+ lines = [top, empty, card_line(title_str, max_w=67, border_color=border_color)]
159
+ if subtitle:
160
+ lines.append(card_line(f"{DIM}{subtitle}{RESET}", max_w=67, border_color=border_color))
161
+ lines.extend([empty, bottom])
162
+ return "\n".join(lines)
163
+
133
164
  def print_header():
134
165
  """Print the branded TorusGuard header card."""
135
- print(f"""
136
- {CYAN}╭─────────────────────────────────────────────────────────────────────────╮{RESET}
137
- {CYAN}│{RESET} {CYAN}│{RESET}
138
- {CYAN}│{RESET} {BOLD}{WHITE}🛡️ T O R U S G U A R D{RESET} {GRAY}v1.3.0{RESET} {CYAN}│{RESET}
139
- {CYAN}│{RESET} {DIM}Autonomous Security Engine for AI-Built Applications{RESET} {CYAN}│{RESET}
140
- {CYAN}│{RESET} {CYAN}│{RESET}
141
- {CYAN}╰─────────────────────────────────────────────────────────────────────────╯{RESET}
142
- """)
166
+ print()
167
+ print(card_header("🛡️ T O R U S G U A R D", "Autonomous Security Engine for AI-Built Applications", version="v2.1.0"))
168
+ print()
143
169
 
144
170
 
145
171
  def print_step_1_assets(file_count):
@@ -213,14 +239,15 @@ def print_success_card():
213
239
 
214
240
  def print_already_initialized(target_root, cfg):
215
241
  """Print the already-initialized status card."""
242
+ print()
243
+ top = f" {CYAN}╭{'─' * 71}╮{RESET}"
244
+ bottom = f" {CYAN}╰{'─' * 71}╯{RESET}"
245
+ title_line = card_line(f"{BOLD}{WHITE}🛡️ TORUSGUARD WORKSPACE{RESET}{' ' * 28}{GREEN}[Active]{RESET}")
246
+ print(f"{top}\n{title_line}\n{bottom}")
216
247
  print(f"""
217
- {CYAN}╭─────────────────────────────────────────────────────────────────────────╮{RESET}
218
- {CYAN}│{RESET} {BOLD}{WHITE}🛡️ TORUSGUARD WORKSPACE{RESET} {GREEN}[Active]{RESET} {CYAN}│{RESET}
219
- {CYAN}╰─────────────────────────────────────────────────────────────────────────╯{RESET}
220
-
221
248
  {BOLD}▸ Project Root:{RESET} {GREEN}{target_root}{RESET}
222
249
  {BOLD}▸ Workspace:{RESET} {GREEN}.torusguard/{RESET} {DIM}(Already Initialized){RESET}
223
- {BOLD}▸ Version:{RESET} {CYAN}{cfg.get('version', '1.3.0')}{RESET}
250
+ {BOLD}▸ Version:{RESET} {CYAN}{cfg.get('version', '2.1.0')}{RESET}
224
251
  {BOLD}▸ Severity Floor:{RESET} {YELLOW}{cfg.get('severity_threshold', 'medium')}{RESET}
225
252
 
226
253
  {DIM}To refresh templates or re-scaffold, run:{RESET}
@@ -228,7 +255,7 @@ def print_already_initialized(target_root, cfg):
228
255
  """)
229
256
 
230
257
 
231
- def scaffold_workspace(target_root=None, force=False, full_commands=False):
258
+ def scaffold_workspace(target_root=None, force=False, full_commands=False, template=None, **kwargs):
232
259
  """Scaffold the .torusguard workspace into the target project root."""
233
260
  target_root = Path(target_root or find_project_root()).resolve()
234
261
  torusguard_target = target_root / ".torusguard"
@@ -379,7 +406,13 @@ def scaffold_workspace(target_root=None, force=False, full_commands=False):
379
406
  try:
380
407
  with open(config_file, "r", encoding="utf-8") as f:
381
408
  cfg = json.load(f)
382
- if detected_stack and detected_stack.get("framework") != "None":
409
+ if template and template.lower() in ("golang", "go"):
410
+ cfg["detected_stack"] = {
411
+ "language": "Go",
412
+ "framework": "Gin",
413
+ "data_layer": "None"
414
+ }
415
+ elif detected_stack and detected_stack.get("framework") != "None":
383
416
  cfg["detected_stack"] = {
384
417
  "language": detected_stack.get("language"),
385
418
  "framework": detected_stack.get("framework"),
@@ -1,41 +1,41 @@
1
- # TorusGuard Skill Reference: C# & ASP.NET Core Security
2
-
3
- > **Loaded When:** A project is identified as a C# / .NET application (`*.csproj`, `*.sln`, ASP.NET Core detected).
4
-
5
- ---
6
-
7
- ## 🛡️ Key Inspection Areas & Rules
8
-
9
- ### 1. Authentication & Authorization
10
- * `TG-AUTH-001`: Ensure controllers and endpoints have `[Authorize]` attributes.
11
- * Prohibit unvetted `[AllowAnonymous]` on sensitive business logic or user data endpoints.
12
-
13
- ### 2. Entity Framework Core & SQL Injection
14
- * `TG-INPUT-002`: Use LINQ expressions or `FromSqlInterpolated` with interpolated string syntax (EF Core converts parameters automatically).
15
- * Prohibit raw `FromSqlRaw` with un-parameterized string concatenations.
16
- * `TG-DB-004`: Configure Global Query Filters (`HasQueryFilter(e => e.TenantId == _currentTenant)`) for multi-tenant safety.
17
-
18
- ### 3. Anti-Forgery & TLS
19
- * `TG-CSRF-001`: Ensure `[ValidateAntiForgeryToken]` or `[AutoValidateAntiforgeryToken]` is applied to POST/PUT/DELETE actions.
20
- * Prohibit `DangerousAcceptAnyServerCertificateValidator`.
21
-
22
- ---
23
-
24
- ## 🛠️ Safe Patterns Summary
25
-
26
- ```csharp
27
- // Safe Entity Framework Parameterized Query
28
- var user = await context.Users
29
- .Where(u => u.Id == userId && u.TenantId == currentTenantId)
30
- .FirstOrDefaultAsync();
31
-
32
- // Safe Global Query Filter in DbContext
33
- modelBuilder.Entity<Invoice>()
34
- .HasQueryFilter(i => i.TenantId == _tenantProvider.GetTenantId());
35
-
36
- // Safe Controller Security
37
- [Authorize]
38
- [ApiController]
39
- [Route("api/[controller]")]
40
- public class InvoicesController : ControllerBase { ... }
41
- ```
1
+ # TorusGuard Skill Reference: C# & ASP.NET Core Security
2
+
3
+ > **Loaded When:** A project is identified as a C# / .NET application (`*.csproj`, `*.sln`, ASP.NET Core detected).
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Authentication & Authorization
10
+ * `TG-AUTH-001`: Ensure controllers and endpoints have `[Authorize]` attributes.
11
+ * Prohibit unvetted `[AllowAnonymous]` on sensitive business logic or user data endpoints.
12
+
13
+ ### 2. Entity Framework Core & SQL Injection
14
+ * `TG-INPUT-002`: Use LINQ expressions or `FromSqlInterpolated` with interpolated string syntax (EF Core converts parameters automatically).
15
+ * Prohibit raw `FromSqlRaw` with un-parameterized string concatenations.
16
+ * `TG-DB-004`: Configure Global Query Filters (`HasQueryFilter(e => e.TenantId == _currentTenant)`) for multi-tenant safety.
17
+
18
+ ### 3. Anti-Forgery & TLS
19
+ * `TG-CSRF-001`: Ensure `[ValidateAntiForgeryToken]` or `[AutoValidateAntiforgeryToken]` is applied to POST/PUT/DELETE actions.
20
+ * Prohibit `DangerousAcceptAnyServerCertificateValidator`.
21
+
22
+ ---
23
+
24
+ ## 🛠️ Safe Patterns Summary
25
+
26
+ ```csharp
27
+ // Safe Entity Framework Parameterized Query
28
+ var user = await context.Users
29
+ .Where(u => u.Id == userId && u.TenantId == currentTenantId)
30
+ .FirstOrDefaultAsync();
31
+
32
+ // Safe Global Query Filter in DbContext
33
+ modelBuilder.Entity<Invoice>()
34
+ .HasQueryFilter(i => i.TenantId == _tenantProvider.GetTenantId());
35
+
36
+ // Safe Controller Security
37
+ [Authorize]
38
+ [ApiController]
39
+ [Route("api/[controller]")]
40
+ public class InvoicesController : ControllerBase { ... }
41
+ ```
@@ -1,41 +1,41 @@
1
- # TorusGuard Skill Reference: Go Security
2
-
3
- > **Loaded When:** A project is identified as a Go application (`go.mod`, `go.sum`, or Go source files detected).
4
-
5
- ---
6
-
7
- ## 🛡️ Key Inspection Areas & Rules
8
-
9
- ### 1. Database & SQL Injection
10
- * `TG-INPUT-002`: Ensure raw queries use parameterized placeholders (`?`, `$1`), never `fmt.Sprintf` or string concatenation.
11
- * `TG-DB-004`: Enforce tenant isolation in GORM queries (`db.Where("tenant_id = ?", tenantID)`).
12
-
13
- ### 2. TLS & Network Security
14
- * `TG-DIFF-001`: Prohibit `InsecureSkipVerify: true` in `tls.Config`. Always use valid root CA pools.
15
- * `TG-SSRF-001`: Validate outbound URLs before issuing `http.Get` or `http.Post`.
16
-
17
- ### 3. Concurrency & Goroutine Safety
18
- * `TG-BIZ-001`: Ensure context cancellation propagation (`ctx.Done()`) to prevent goroutine leaks.
19
- * Use mutexes or channels to prevent data races on shared state.
20
-
21
- ### 4. Input Validation & Path Traversal
22
- * `TG-INPUT-006`: Sanitize file paths with `filepath.Clean` and check `strings.HasPrefix(cleanPath, baseDir)`.
23
-
24
- ---
25
-
26
- ## 🛠️ Safe Patterns Summary
27
-
28
- ```go
29
- // Safe Parameterized Query
30
- row := db.QueryRowContext(ctx, "SELECT id, email FROM users WHERE id = ? AND tenant_id = ?", userID, tenantID)
31
-
32
- // Safe GORM Scoping
33
- var invoice Invoice
34
- result := db.Where("id = ? AND tenant_id = ?", invoiceID, currentTenantID).First(&invoice)
35
-
36
- // Safe TLS Client
37
- tlsConfig := &tls.Config{
38
- MinVersion: tls.VersionTLS13,
39
- }
40
- client := &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}
41
- ```
1
+ # TorusGuard Skill Reference: Go Security
2
+
3
+ > **Loaded When:** A project is identified as a Go application (`go.mod`, `go.sum`, or Go source files detected).
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Database & SQL Injection
10
+ * `TG-INPUT-002`: Ensure raw queries use parameterized placeholders (`?`, `$1`), never `fmt.Sprintf` or string concatenation.
11
+ * `TG-DB-004`: Enforce tenant isolation in GORM queries (`db.Where("tenant_id = ?", tenantID)`).
12
+
13
+ ### 2. TLS & Network Security
14
+ * `TG-DIFF-001`: Prohibit `InsecureSkipVerify: true` in `tls.Config`. Always use valid root CA pools.
15
+ * `TG-SSRF-001`: Validate outbound URLs before issuing `http.Get` or `http.Post`.
16
+
17
+ ### 3. Concurrency & Goroutine Safety
18
+ * `TG-BIZ-001`: Ensure context cancellation propagation (`ctx.Done()`) to prevent goroutine leaks.
19
+ * Use mutexes or channels to prevent data races on shared state.
20
+
21
+ ### 4. Input Validation & Path Traversal
22
+ * `TG-INPUT-006`: Sanitize file paths with `filepath.Clean` and check `strings.HasPrefix(cleanPath, baseDir)`.
23
+
24
+ ---
25
+
26
+ ## 🛠️ Safe Patterns Summary
27
+
28
+ ```go
29
+ // Safe Parameterized Query
30
+ row := db.QueryRowContext(ctx, "SELECT id, email FROM users WHERE id = ? AND tenant_id = ?", userID, tenantID)
31
+
32
+ // Safe GORM Scoping
33
+ var invoice Invoice
34
+ result := db.Where("id = ? AND tenant_id = ?", invoiceID, currentTenantID).First(&invoice)
35
+
36
+ // Safe TLS Client
37
+ tlsConfig := &tls.Config{
38
+ MinVersion: tls.VersionTLS13,
39
+ }
40
+ client := &http.Client{Transport: &http.Transport{TLSClientConfig: tlsConfig}}
41
+ ```
@@ -1,40 +1,40 @@
1
- # TorusGuard Skill Reference: Java & Spring Security
2
-
3
- > **Loaded When:** A project is identified as a Java/Kotlin application (`pom.xml`, `build.gradle`, Spring Boot detected).
4
-
5
- ---
6
-
7
- ## 🛡️ Key Inspection Areas & Rules
8
-
9
- ### 1. Spring Security & CSRF
10
- * `TG-CSRF-001`: Prohibit `.csrf().disable()` or `AbstractHttpConfigurer::disable` on state-changing browser routes.
11
- * `TG-PLATFORM-001`: Avoid `@CrossOrigin(origins = "*")` with `allowCredentials = "true"`.
12
-
13
- ### 2. JPA & Hibernate SQL Injection
14
- * `TG-INPUT-002`: Use named parameters (`:param`) or `CriteriaBuilder`. Never concatenate strings into JPQL queries.
15
- * `TG-DB-004`: Enforce tenant isolation via `@Filter` or explicit where clauses.
16
-
17
- ### 3. Insecure Deserialization & XML
18
- * Prohibit `ObjectInputStream.readObject()` on untrusted input without look-ahead verification.
19
- * Disable external entity resolution (`setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)`).
20
-
21
- ---
22
-
23
- ## 🛠️ Safe Patterns Summary
24
-
25
- ```java
26
- // Safe JPA Query
27
- @Query("SELECT u FROM User u WHERE u.id = :id AND u.tenantId = :tenantId")
28
- Optional<User> findByIdAndTenantId(@Param("id") Long id, @Param("tenantId") String tenantId);
29
-
30
- // Safe Spring Security Configuration
31
- @Bean
32
- public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
33
- http
34
- .authorizeHttpRequests(auth -> auth
35
- .requestMatchers("/public/**").permitAll()
36
- .anyRequest().authenticated()
37
- );
38
- return http.build();
39
- }
40
- ```
1
+ # TorusGuard Skill Reference: Java & Spring Security
2
+
3
+ > **Loaded When:** A project is identified as a Java/Kotlin application (`pom.xml`, `build.gradle`, Spring Boot detected).
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Spring Security & CSRF
10
+ * `TG-CSRF-001`: Prohibit `.csrf().disable()` or `AbstractHttpConfigurer::disable` on state-changing browser routes.
11
+ * `TG-PLATFORM-001`: Avoid `@CrossOrigin(origins = "*")` with `allowCredentials = "true"`.
12
+
13
+ ### 2. JPA & Hibernate SQL Injection
14
+ * `TG-INPUT-002`: Use named parameters (`:param`) or `CriteriaBuilder`. Never concatenate strings into JPQL queries.
15
+ * `TG-DB-004`: Enforce tenant isolation via `@Filter` or explicit where clauses.
16
+
17
+ ### 3. Insecure Deserialization & XML
18
+ * Prohibit `ObjectInputStream.readObject()` on untrusted input without look-ahead verification.
19
+ * Disable external entity resolution (`setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)`).
20
+
21
+ ---
22
+
23
+ ## 🛠️ Safe Patterns Summary
24
+
25
+ ```java
26
+ // Safe JPA Query
27
+ @Query("SELECT u FROM User u WHERE u.id = :id AND u.tenantId = :tenantId")
28
+ Optional<User> findByIdAndTenantId(@Param("id") Long id, @Param("tenantId") String tenantId);
29
+
30
+ // Safe Spring Security Configuration
31
+ @Bean
32
+ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
33
+ http
34
+ .authorizeHttpRequests(auth -> auth
35
+ .requestMatchers("/public/**").permitAll()
36
+ .anyRequest().authenticated()
37
+ );
38
+ return http.build();
39
+ }
40
+ ```
@@ -1,25 +1,25 @@
1
- # TorusGuard Universal Polyglot Security Matrix
2
-
3
- > **Loaded When:** Any language or framework is detected. Maps universal security invariants across major programming language ecosystems.
4
-
5
- ---
6
-
7
- ## 🛡️ Cross-Language Invariant Mappings
8
-
9
- | Rule Family | Python | TypeScript / Node.js | Go | Rust | Java / Kotlin | C# / .NET |
10
- |---|---|---|---|---|---|---|
11
- | **TG-SEC (Secrets)** | `os.environ["KEY"]` | `process.env.KEY` | `os.Getenv("KEY")` | `std::env::var("KEY")` | `System.getenv("KEY")` | `Environment.GetEnvironmentVariable()` |
12
- | **TG-DB (SQL Injection)** | `%s` / ORM bound | `$1` / Prisma / Drizzle | `?` / `$1` / GORM `?` | `sqlx::query!` / Diesel | Named parameters `:param` | `@p0` / `FromSqlInterpolated` |
13
- | **TG-DB-004 (Tenant Scope)** | `.filter(tenant=...)` | `where: { tenantId }` | `.Where("tenant_id = ?", tid)` | `filter(tenant_id.eq(tid))` | `WHERE e.tenantId = :tid` | `.Where(x => x.TenantId == tid)` |
14
- | **TG-AUTH (Access Control)** | `@login_required` / Depends | Middleware auth / Guards | Middleware handlers | Tower layer / extractors | `@PreAuthorize` / Spring Sec | `[Authorize]` attributes |
15
- | **TG-CSRF (Request Forgery)** | CSRF Middleware | SameSite / csurf | Gorilla CSRF | Anti-CSRF token middleware | Spring Security CSRF | `[ValidateAntiForgeryToken]` |
16
- | **TG-DIFF (Bypass Comments)** | No `# nosec` | No `// nosec` | No `/* nosec */` | No `#![allow(unsafe)]` | No `@SuppressWarnings` | No pragma disable |
17
- | **TG-DIFF (TLS Verification)** | No `verify=False` | No `rejectUnauthorized:false` | No `InsecureSkipVerify: true` | No `danger_accept_invalid_certs`| No `TrustAllStrategy` | No `DangerousAcceptAny...` |
18
-
19
- ---
20
-
21
- ## 🚀 Polyglot Hardening Rules of Thumb
22
-
23
- 1. **Parameterize Everything:** Never concatenate raw user input into SQL, shell commands, LDAP filters, or template strings, regardless of language.
24
- 2. **Fail Closed on Auth:** Default all endpoints to authenticated; explicitly mark public routes rather than remembering to protect private ones.
25
- 3. **Strict Bounds:** Keep remediation diffs minimal ($\le 35$ additions, $\le 25$ deletions) to ensure auditability across all codebases.
1
+ # TorusGuard Universal Polyglot Security Matrix
2
+
3
+ > **Loaded When:** Any language or framework is detected. Maps universal security invariants across major programming language ecosystems.
4
+
5
+ ---
6
+
7
+ ## 🛡️ Cross-Language Invariant Mappings
8
+
9
+ | Rule Family | Python | TypeScript / Node.js | Go | Rust | Java / Kotlin | C# / .NET |
10
+ |---|---|---|---|---|---|---|
11
+ | **TG-SEC (Secrets)** | `os.environ["KEY"]` | `process.env.KEY` | `os.Getenv("KEY")` | `std::env::var("KEY")` | `System.getenv("KEY")` | `Environment.GetEnvironmentVariable()` |
12
+ | **TG-DB (SQL Injection)** | `%s` / ORM bound | `$1` / Prisma / Drizzle | `?` / `$1` / GORM `?` | `sqlx::query!` / Diesel | Named parameters `:param` | `@p0` / `FromSqlInterpolated` |
13
+ | **TG-DB-004 (Tenant Scope)** | `.filter(tenant=...)` | `where: { tenantId }` | `.Where("tenant_id = ?", tid)` | `filter(tenant_id.eq(tid))` | `WHERE e.tenantId = :tid` | `.Where(x => x.TenantId == tid)` |
14
+ | **TG-AUTH (Access Control)** | `@login_required` / Depends | Middleware auth / Guards | Middleware handlers | Tower layer / extractors | `@PreAuthorize` / Spring Sec | `[Authorize]` attributes |
15
+ | **TG-CSRF (Request Forgery)** | CSRF Middleware | SameSite / csurf | Gorilla CSRF | Anti-CSRF token middleware | Spring Security CSRF | `[ValidateAntiForgeryToken]` |
16
+ | **TG-DIFF (Bypass Comments)** | No `# nosec` | No `// nosec` | No `/* nosec */` | No `#![allow(unsafe)]` | No `@SuppressWarnings` | No pragma disable |
17
+ | **TG-DIFF (TLS Verification)** | No `verify=False` | No `rejectUnauthorized:false` | No `InsecureSkipVerify: true` | No `danger_accept_invalid_certs`| No `TrustAllStrategy` | No `DangerousAcceptAny...` |
18
+
19
+ ---
20
+
21
+ ## 🚀 Polyglot Hardening Rules of Thumb
22
+
23
+ 1. **Parameterize Everything:** Never concatenate raw user input into SQL, shell commands, LDAP filters, or template strings, regardless of language.
24
+ 2. **Fail Closed on Auth:** Default all endpoints to authenticated; explicitly mark public routes rather than remembering to protect private ones.
25
+ 3. **Strict Bounds:** Keep remediation diffs minimal ($\le 35$ additions, $\le 25$ deletions) to ensure auditability across all codebases.