torusguard 0.9.2

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 (236) hide show
  1. package/.torusguard/.manifest.json +95 -0
  2. package/.torusguard/ARCHITECTURE.md +168 -0
  3. package/.torusguard/TORUSGUARD.md +145 -0
  4. package/.torusguard/agents/auditor.md +41 -0
  5. package/.torusguard/agents/profiler.md +49 -0
  6. package/.torusguard/agents/remediator.md +41 -0
  7. package/.torusguard/agents/reviewer.md +39 -0
  8. package/.torusguard/agents/validator.md +46 -0
  9. package/.torusguard/config/scope.json +24 -0
  10. package/.torusguard/config/slash-commands.json +102 -0
  11. package/.torusguard/config/torusguard.json +30 -0
  12. package/.torusguard/references/django-security.md +43 -0
  13. package/.torusguard/references/drf-security.md +20 -0
  14. package/.torusguard/references/express-security.md +103 -0
  15. package/.torusguard/references/fastapi-security.md +20 -0
  16. package/.torusguard/references/firebase-security.md +78 -0
  17. package/.torusguard/references/flask-security.md +20 -0
  18. package/.torusguard/references/nextjs-security.md +96 -0
  19. package/.torusguard/references/react-vite-security.md +97 -0
  20. package/.torusguard/references/sqlalchemy-security.md +16 -0
  21. package/.torusguard/references/supabase-security.md +84 -0
  22. package/.torusguard/rules/README.md +62 -0
  23. package/.torusguard/rules/TORUSGUARD.md +145 -0
  24. package/.torusguard/rules/active/.gitkeep +0 -0
  25. package/.torusguard/rules/active/TG-DIFF-001.md +20 -0
  26. package/.torusguard/rules/active/TG-DIFF-002.md +20 -0
  27. package/.torusguard/rules/active/TG-DIFF-003.md +19 -0
  28. package/.torusguard/runs/.gitkeep +0 -0
  29. package/.torusguard/schemas/authorization.schema.json +81 -0
  30. package/.torusguard/schemas/confidence.schema.json +72 -0
  31. package/.torusguard/schemas/evidence.schema.json +66 -0
  32. package/.torusguard/schemas/finding.schema.json +164 -0
  33. package/.torusguard/schemas/provenance.schema.json +46 -0
  34. package/.torusguard/schemas/remediation.schema.json +59 -0
  35. package/.torusguard/schemas/retest.schema.json +53 -0
  36. package/.torusguard/schemas/runtime-evidence.schema.json +72 -0
  37. package/.torusguard/scripts/__pycache__/diff_guard.cpython-311.pyc +0 -0
  38. package/.torusguard/scripts/__pycache__/monorepo_detector.cpython-311.pyc +0 -0
  39. package/.torusguard/scripts/diff_guard.py +171 -0
  40. package/.torusguard/scripts/finding_scorer.py +86 -0
  41. package/.torusguard/scripts/manifest_builder.py +130 -0
  42. package/.torusguard/scripts/monorepo_detector.py +164 -0
  43. package/.torusguard/scripts/run_manager.py +89 -0
  44. package/.torusguard/scripts/safety_gate.py +64 -0
  45. package/.torusguard/scripts/sarif_exporter.py +116 -0
  46. package/.torusguard/scripts/stack_detect.py +152 -0
  47. package/.torusguard/skills/torusguard/SKILL.md +37 -0
  48. package/.torusguard/skills/torusguard/bootstrap.py +158 -0
  49. package/.torusguard/skills/torusguard/references/auth-and-sessions.md +56 -0
  50. package/.torusguard/skills/torusguard/references/business-logic-and-abuse.md +23 -0
  51. package/.torusguard/skills/torusguard/references/cache-and-sensitive-responses.md +10 -0
  52. package/.torusguard/skills/torusguard/references/client-code-exposure.md +55 -0
  53. package/.torusguard/skills/torusguard/references/csrf-and-cross-origin.md +11 -0
  54. package/.torusguard/skills/torusguard/references/dependency-and-supply-chain.md +22 -0
  55. package/.torusguard/skills/torusguard/references/django-security.md +43 -0
  56. package/.torusguard/skills/torusguard/references/drf-security.md +20 -0
  57. package/.torusguard/skills/torusguard/references/fastapi-security.md +20 -0
  58. package/.torusguard/skills/torusguard/references/flask-security.md +20 -0
  59. package/.torusguard/skills/torusguard/references/frontend-no-db.md +53 -0
  60. package/.torusguard/skills/torusguard/references/graphql-security.md +12 -0
  61. package/.torusguard/skills/torusguard/references/input-and-injection.md +51 -0
  62. package/.torusguard/skills/torusguard/references/mass-assignment-and-property-auth.md +22 -0
  63. package/.torusguard/skills/torusguard/references/platform-hardening.md +56 -0
  64. package/.torusguard/skills/torusguard/references/python-dependencies.md +16 -0
  65. package/.torusguard/skills/torusguard/references/python-security-overview.md +12 -0
  66. package/.torusguard/skills/torusguard/references/rate-limit-and-abuse.md +57 -0
  67. package/.torusguard/skills/torusguard/references/secrets-and-config.md +64 -0
  68. package/.torusguard/skills/torusguard/references/sqlalchemy-security.md +16 -0
  69. package/.torusguard/skills/torusguard/references/ssrf-and-outbound-requests.md +46 -0
  70. package/.torusguard/skills/torusguard/references/webhook-security.md +15 -0
  71. package/.torusguard/skills/torusguard/references/websocket-security.md +12 -0
  72. package/.torusguard/skills/torusguard-apply/SKILL.md +46 -0
  73. package/.torusguard/skills/torusguard-audit/SKILL.md +70 -0
  74. package/.torusguard/skills/torusguard-authorize/SKILL.md +47 -0
  75. package/.torusguard/skills/torusguard-exploit-check/SKILL.md +64 -0
  76. package/.torusguard/skills/torusguard-full/SKILL.md +70 -0
  77. package/.torusguard/skills/torusguard-harden/SKILL.md +63 -0
  78. package/.torusguard/skills/torusguard-init/SKILL.md +52 -0
  79. package/.torusguard/skills/torusguard-recheck/SKILL.md +53 -0
  80. package/.torusguard/skills/torusguard-report/SKILL.md +54 -0
  81. package/.torusguard/skills/torusguard-status/SKILL.md +42 -0
  82. package/.torusguard/skills/torusguard-verify/SKILL.md +55 -0
  83. package/.torusguard/skills/torusguard-web-validate/SKILL.md +64 -0
  84. package/.torusguard/templates/audit-report.template.md +54 -0
  85. package/.torusguard/templates/authorization.template.md +34 -0
  86. package/.torusguard/templates/finding-card.template.md +32 -0
  87. package/.torusguard/templates/remediation-bundle.template.md +35 -0
  88. package/.torusguard/workflows/apply.md +95 -0
  89. package/.torusguard/workflows/audit.md +93 -0
  90. package/.torusguard/workflows/authorize.md +95 -0
  91. package/.torusguard/workflows/exploit-check.md +97 -0
  92. package/.torusguard/workflows/harden.md +93 -0
  93. package/.torusguard/workflows/init.md +95 -0
  94. package/.torusguard/workflows/recheck.md +95 -0
  95. package/.torusguard/workflows/report.md +95 -0
  96. package/.torusguard/workflows/status.md +95 -0
  97. package/.torusguard/workflows/verify.md +95 -0
  98. package/.torusguard/workflows/web-validate.md +95 -0
  99. package/LICENSE +21 -0
  100. package/README.md +319 -0
  101. package/bin/torusguard.js +110 -0
  102. package/install.py +98 -0
  103. package/package.json +48 -0
  104. package/skills/torusguard/SKILL.md +41 -0
  105. package/skills/torusguard/__pycache__/bootstrap.cpython-311.pyc +0 -0
  106. package/skills/torusguard/bootstrap.py +256 -0
  107. package/skills/torusguard/payload/.manifest.json +95 -0
  108. package/skills/torusguard/payload/ARCHITECTURE.md +168 -0
  109. package/skills/torusguard/payload/TORUSGUARD.md +145 -0
  110. package/skills/torusguard/payload/agents/auditor.md +41 -0
  111. package/skills/torusguard/payload/agents/profiler.md +49 -0
  112. package/skills/torusguard/payload/agents/remediator.md +41 -0
  113. package/skills/torusguard/payload/agents/reviewer.md +39 -0
  114. package/skills/torusguard/payload/agents/validator.md +46 -0
  115. package/skills/torusguard/payload/config/scope.json +24 -0
  116. package/skills/torusguard/payload/config/slash-commands.json +102 -0
  117. package/skills/torusguard/payload/config/torusguard.json +30 -0
  118. package/skills/torusguard/payload/references/django-security.md +43 -0
  119. package/skills/torusguard/payload/references/drf-security.md +20 -0
  120. package/skills/torusguard/payload/references/express-security.md +103 -0
  121. package/skills/torusguard/payload/references/fastapi-security.md +20 -0
  122. package/skills/torusguard/payload/references/firebase-security.md +78 -0
  123. package/skills/torusguard/payload/references/flask-security.md +20 -0
  124. package/skills/torusguard/payload/references/nextjs-security.md +96 -0
  125. package/skills/torusguard/payload/references/react-vite-security.md +97 -0
  126. package/skills/torusguard/payload/references/sqlalchemy-security.md +16 -0
  127. package/skills/torusguard/payload/references/supabase-security.md +84 -0
  128. package/skills/torusguard/payload/rules/README.md +62 -0
  129. package/skills/torusguard/payload/rules/TORUSGUARD.md +145 -0
  130. package/skills/torusguard/payload/rules/active/.gitkeep +0 -0
  131. package/skills/torusguard/payload/rules/active/TG-DIFF-001.md +20 -0
  132. package/skills/torusguard/payload/rules/active/TG-DIFF-002.md +20 -0
  133. package/skills/torusguard/payload/rules/active/TG-DIFF-003.md +19 -0
  134. package/skills/torusguard/payload/schemas/authorization.schema.json +81 -0
  135. package/skills/torusguard/payload/schemas/confidence.schema.json +72 -0
  136. package/skills/torusguard/payload/schemas/evidence.schema.json +66 -0
  137. package/skills/torusguard/payload/schemas/finding.schema.json +164 -0
  138. package/skills/torusguard/payload/schemas/provenance.schema.json +46 -0
  139. package/skills/torusguard/payload/schemas/remediation.schema.json +59 -0
  140. package/skills/torusguard/payload/schemas/retest.schema.json +53 -0
  141. package/skills/torusguard/payload/schemas/runtime-evidence.schema.json +72 -0
  142. package/skills/torusguard/payload/scripts/diff_guard.py +171 -0
  143. package/skills/torusguard/payload/scripts/finding_scorer.py +86 -0
  144. package/skills/torusguard/payload/scripts/manifest_builder.py +130 -0
  145. package/skills/torusguard/payload/scripts/monorepo_detector.py +164 -0
  146. package/skills/torusguard/payload/scripts/run_manager.py +89 -0
  147. package/skills/torusguard/payload/scripts/safety_gate.py +64 -0
  148. package/skills/torusguard/payload/scripts/sarif_exporter.py +116 -0
  149. package/skills/torusguard/payload/scripts/stack_detect.py +152 -0
  150. package/skills/torusguard/payload/skills/torusguard/SKILL.md +37 -0
  151. package/skills/torusguard/payload/skills/torusguard/bootstrap.py +158 -0
  152. package/skills/torusguard/payload/skills/torusguard/references/auth-and-sessions.md +56 -0
  153. package/skills/torusguard/payload/skills/torusguard/references/business-logic-and-abuse.md +23 -0
  154. package/skills/torusguard/payload/skills/torusguard/references/cache-and-sensitive-responses.md +10 -0
  155. package/skills/torusguard/payload/skills/torusguard/references/client-code-exposure.md +55 -0
  156. package/skills/torusguard/payload/skills/torusguard/references/csrf-and-cross-origin.md +11 -0
  157. package/skills/torusguard/payload/skills/torusguard/references/dependency-and-supply-chain.md +22 -0
  158. package/skills/torusguard/payload/skills/torusguard/references/django-security.md +43 -0
  159. package/skills/torusguard/payload/skills/torusguard/references/drf-security.md +20 -0
  160. package/skills/torusguard/payload/skills/torusguard/references/fastapi-security.md +20 -0
  161. package/skills/torusguard/payload/skills/torusguard/references/flask-security.md +20 -0
  162. package/skills/torusguard/payload/skills/torusguard/references/frontend-no-db.md +53 -0
  163. package/skills/torusguard/payload/skills/torusguard/references/graphql-security.md +12 -0
  164. package/skills/torusguard/payload/skills/torusguard/references/input-and-injection.md +51 -0
  165. package/skills/torusguard/payload/skills/torusguard/references/mass-assignment-and-property-auth.md +22 -0
  166. package/skills/torusguard/payload/skills/torusguard/references/platform-hardening.md +56 -0
  167. package/skills/torusguard/payload/skills/torusguard/references/python-dependencies.md +16 -0
  168. package/skills/torusguard/payload/skills/torusguard/references/python-security-overview.md +12 -0
  169. package/skills/torusguard/payload/skills/torusguard/references/rate-limit-and-abuse.md +57 -0
  170. package/skills/torusguard/payload/skills/torusguard/references/secrets-and-config.md +64 -0
  171. package/skills/torusguard/payload/skills/torusguard/references/sqlalchemy-security.md +16 -0
  172. package/skills/torusguard/payload/skills/torusguard/references/ssrf-and-outbound-requests.md +46 -0
  173. package/skills/torusguard/payload/skills/torusguard/references/webhook-security.md +15 -0
  174. package/skills/torusguard/payload/skills/torusguard/references/websocket-security.md +12 -0
  175. package/skills/torusguard/payload/skills/torusguard-apply/SKILL.md +46 -0
  176. package/skills/torusguard/payload/skills/torusguard-audit/SKILL.md +70 -0
  177. package/skills/torusguard/payload/skills/torusguard-authorize/SKILL.md +47 -0
  178. package/skills/torusguard/payload/skills/torusguard-exploit-check/SKILL.md +64 -0
  179. package/skills/torusguard/payload/skills/torusguard-full/SKILL.md +70 -0
  180. package/skills/torusguard/payload/skills/torusguard-harden/SKILL.md +63 -0
  181. package/skills/torusguard/payload/skills/torusguard-init/SKILL.md +52 -0
  182. package/skills/torusguard/payload/skills/torusguard-recheck/SKILL.md +53 -0
  183. package/skills/torusguard/payload/skills/torusguard-report/SKILL.md +54 -0
  184. package/skills/torusguard/payload/skills/torusguard-status/SKILL.md +42 -0
  185. package/skills/torusguard/payload/skills/torusguard-verify/SKILL.md +55 -0
  186. package/skills/torusguard/payload/skills/torusguard-web-validate/SKILL.md +64 -0
  187. package/skills/torusguard/payload/templates/audit-report.template.md +54 -0
  188. package/skills/torusguard/payload/templates/authorization.template.md +34 -0
  189. package/skills/torusguard/payload/templates/finding-card.template.md +32 -0
  190. package/skills/torusguard/payload/templates/remediation-bundle.template.md +35 -0
  191. package/skills/torusguard/payload/workflows/apply.md +95 -0
  192. package/skills/torusguard/payload/workflows/audit.md +93 -0
  193. package/skills/torusguard/payload/workflows/authorize.md +95 -0
  194. package/skills/torusguard/payload/workflows/exploit-check.md +97 -0
  195. package/skills/torusguard/payload/workflows/harden.md +93 -0
  196. package/skills/torusguard/payload/workflows/init.md +95 -0
  197. package/skills/torusguard/payload/workflows/recheck.md +95 -0
  198. package/skills/torusguard/payload/workflows/report.md +95 -0
  199. package/skills/torusguard/payload/workflows/status.md +95 -0
  200. package/skills/torusguard/payload/workflows/verify.md +95 -0
  201. package/skills/torusguard/payload/workflows/web-validate.md +95 -0
  202. package/skills/torusguard/references/auth-and-sessions.md +56 -0
  203. package/skills/torusguard/references/business-logic-and-abuse.md +23 -0
  204. package/skills/torusguard/references/cache-and-sensitive-responses.md +10 -0
  205. package/skills/torusguard/references/client-code-exposure.md +55 -0
  206. package/skills/torusguard/references/csrf-and-cross-origin.md +11 -0
  207. package/skills/torusguard/references/dependency-and-supply-chain.md +22 -0
  208. package/skills/torusguard/references/django-security.md +43 -0
  209. package/skills/torusguard/references/drf-security.md +20 -0
  210. package/skills/torusguard/references/fastapi-security.md +20 -0
  211. package/skills/torusguard/references/flask-security.md +20 -0
  212. package/skills/torusguard/references/frontend-no-db.md +53 -0
  213. package/skills/torusguard/references/graphql-security.md +12 -0
  214. package/skills/torusguard/references/input-and-injection.md +51 -0
  215. package/skills/torusguard/references/mass-assignment-and-property-auth.md +22 -0
  216. package/skills/torusguard/references/platform-hardening.md +56 -0
  217. package/skills/torusguard/references/python-dependencies.md +16 -0
  218. package/skills/torusguard/references/python-security-overview.md +12 -0
  219. package/skills/torusguard/references/rate-limit-and-abuse.md +57 -0
  220. package/skills/torusguard/references/secrets-and-config.md +64 -0
  221. package/skills/torusguard/references/sqlalchemy-security.md +16 -0
  222. package/skills/torusguard/references/ssrf-and-outbound-requests.md +46 -0
  223. package/skills/torusguard/references/webhook-security.md +15 -0
  224. package/skills/torusguard/references/websocket-security.md +12 -0
  225. package/skills/torusguard-apply/SKILL.md +46 -0
  226. package/skills/torusguard-audit/SKILL.md +70 -0
  227. package/skills/torusguard-authorize/SKILL.md +47 -0
  228. package/skills/torusguard-exploit-check/SKILL.md +64 -0
  229. package/skills/torusguard-full/SKILL.md +70 -0
  230. package/skills/torusguard-harden/SKILL.md +63 -0
  231. package/skills/torusguard-init/SKILL.md +52 -0
  232. package/skills/torusguard-recheck/SKILL.md +53 -0
  233. package/skills/torusguard-report/SKILL.md +54 -0
  234. package/skills/torusguard-status/SKILL.md +42 -0
  235. package/skills/torusguard-verify/SKILL.md +55 -0
  236. package/skills/torusguard-web-validate/SKILL.md +64 -0
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TorusGuard Stack Detector Utility
4
+ Inspects project directory to detect programming language, frameworks, ORM/data layer,
5
+ and dependency manifests. Outputs canonical stack block and structured JSON.
6
+ """
7
+
8
+ import sys
9
+ import json
10
+ import argparse
11
+ from pathlib import Path
12
+ from typing import Dict, Any, List
13
+
14
+ def detect_stack(project_root: Path) -> Dict[str, Any]:
15
+ profile = {
16
+ "language": "Unknown",
17
+ "framework": "None",
18
+ "data_layer": "None",
19
+ "dependency_files": [],
20
+ "detection_evidence": [],
21
+ "confidence": "Needs Review",
22
+ "recommended_rules": [
23
+ "TG-SEC-*",
24
+ "TG-INPUT-*",
25
+ "TG-AUTH-*"
26
+ ],
27
+ "recommended_references": []
28
+ }
29
+
30
+ # 1. Inspect dependency manifests
31
+ dep_candidates = ["pyproject.toml", "requirements.txt", "Pipfile", "package.json", "package-lock.json", "pnpm-lock.yaml"]
32
+ for dc in dep_candidates:
33
+ if (project_root / dc).is_file():
34
+ profile["dependency_files"].append(dc)
35
+
36
+ # 2. Check Python ecosystem
37
+ manage_py = project_root / "manage.py"
38
+ settings_py = list(project_root.glob("**/settings.py"))
39
+
40
+ if manage_py.is_file() or settings_py:
41
+ profile["language"] = "Python"
42
+ profile["framework"] = "Django"
43
+ profile["data_layer"] = "Django ORM"
44
+ profile["confidence"] = "Confirmed"
45
+ profile["detection_evidence"].append({
46
+ "file": "manage.py" if manage_py.is_file() else str(settings_py[0].relative_to(project_root)),
47
+ "indicator": "Django management or settings configuration"
48
+ })
49
+ profile["recommended_rules"].extend(["TG-DB-004", "TG-RATE-001", "TG-PLATFORM-*"])
50
+ profile["recommended_references"].extend(["django-security.md", "python-security-overview.md"])
51
+
52
+ # Check for DRF
53
+ for py_file in project_root.glob("**/*.py"):
54
+ try:
55
+ content = py_file.read_text(encoding="utf-8", errors="ignore")
56
+ if "rest_framework" in content:
57
+ profile["framework"] = "Django / DRF"
58
+ profile["recommended_references"].append("drf-security.md")
59
+ break
60
+ except Exception:
61
+ continue
62
+
63
+ # Check for FastAPI / Flask if not Django
64
+ if profile["framework"] == "None":
65
+ for py_file in list(project_root.glob("*.py")) + list(project_root.glob("app/**/*.py")) + list(project_root.glob("src/**/*.py")):
66
+ try:
67
+ content = py_file.read_text(encoding="utf-8", errors="ignore")
68
+ if "FastAPI(" in content or "from fastapi" in content:
69
+ profile["language"] = "Python"
70
+ profile["framework"] = "FastAPI"
71
+ profile["confidence"] = "Confirmed"
72
+ profile["detection_evidence"].append({
73
+ "file": str(py_file.relative_to(project_root)),
74
+ "indicator": "FastAPI application instantiation"
75
+ })
76
+ profile["recommended_references"].append("fastapi-security.md")
77
+ elif "Flask(__name__)" in content or "from flask" in content:
78
+ profile["language"] = "Python"
79
+ profile["framework"] = "Flask"
80
+ profile["confidence"] = "Confirmed"
81
+ profile["detection_evidence"].append({
82
+ "file": str(py_file.relative_to(project_root)),
83
+ "indicator": "Flask application instantiation"
84
+ })
85
+ profile["recommended_references"].append("flask-security.md")
86
+
87
+ if "sqlalchemy" in content:
88
+ profile["data_layer"] = "SQLAlchemy"
89
+ profile["recommended_references"].append("sqlalchemy-security.md")
90
+ except Exception:
91
+ continue
92
+
93
+ # 3. Check JavaScript / TypeScript ecosystem
94
+ pkg_json_path = project_root / "package.json"
95
+ if pkg_json_path.is_file():
96
+ profile["language"] = "TypeScript" if list(project_root.glob("**/*.ts*")) else "JavaScript"
97
+ try:
98
+ with open(pkg_json_path, "r", encoding="utf-8") as f:
99
+ pkg = json.load(f)
100
+ deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
101
+
102
+ if "next" in deps:
103
+ profile["framework"] = "Next.js"
104
+ profile["confidence"] = "Confirmed"
105
+ profile["detection_evidence"].append({"file": "package.json", "indicator": "next dependency"})
106
+ profile["recommended_references"].append("nextjs-security.md")
107
+ profile["recommended_rules"].extend(["TG-CLIENT-*", "TG-PLATFORM-001"])
108
+ elif "express" in deps:
109
+ profile["framework"] = "Express"
110
+ profile["confidence"] = "Confirmed"
111
+ profile["detection_evidence"].append({"file": "package.json", "indicator": "express dependency"})
112
+ profile["recommended_references"].append("express-security.md")
113
+ elif "react" in deps:
114
+ profile["framework"] = "React / Vite"
115
+ profile["confidence"] = "Confirmed"
116
+ profile["detection_evidence"].append({"file": "package.json", "indicator": "react dependency"})
117
+ profile["recommended_references"].append("react-vite-security.md")
118
+
119
+ if "@supabase/supabase-js" in deps:
120
+ profile["data_layer"] = "Supabase"
121
+ profile["recommended_references"].append("supabase-security.md")
122
+ elif "firebase" in deps or "firebase-admin" in deps:
123
+ profile["data_layer"] = "Firebase"
124
+ profile["recommended_references"].append("firebase-security.md")
125
+ except Exception:
126
+ pass
127
+
128
+ return profile
129
+
130
+
131
+ def main():
132
+ parser = argparse.ArgumentParser(description="TorusGuard Stack Detector")
133
+ parser.add_argument("path", nargs="?", default=".", help="Target project root directory")
134
+ parser.add_argument("--json", action="store_true", help="Output raw JSON")
135
+ args = parser.parse_args()
136
+
137
+ project_root = Path(args.path).resolve()
138
+ profile = detect_stack(project_root)
139
+
140
+ if args.json:
141
+ print(json.dumps(profile, indent=2))
142
+ else:
143
+ evidence = profile["detection_evidence"][0]["file"] if profile["detection_evidence"] else "heuristic"
144
+ print(f"## Detected Stack")
145
+ print(f"- Language: {profile['language']}")
146
+ print(f"- Framework: {profile['framework']}")
147
+ print(f"- Data layer: {profile['data_layer']}")
148
+ print(f"- Dependency files: {', '.join(profile['dependency_files']) if profile['dependency_files'] else 'None'}")
149
+ print(f"- Detection confidence: {profile['confidence']} ({evidence})")
150
+
151
+ if __name__ == "__main__":
152
+ main()
@@ -0,0 +1,37 @@
1
+ ---
2
+ name: torusguard
3
+ description: Security guardrails, governed remediation, and authorized runtime validation for AI-built web applications across Python and TypeScript.
4
+ version: 0.9.2
5
+ ---
6
+
7
+ # TorusGuard Master Router
8
+
9
+ **Principle:** If the browser receives it, users can inspect it. Keep secrets, direct database access, and authorization on trusted server-side code.
10
+
11
+ ---
12
+
13
+ ## ⚡ Workspace Bootstrap Check
14
+ 1. **If `.torusguard/` exists:** Load matching specialist skill on demand per command.
15
+ 2. **If `.torusguard/` is missing:** Run `python skills/torusguard/bootstrap.py --target .` or `/torusguard init`.
16
+
17
+ ---
18
+
19
+ ## Specialist Skill Routing (Lazy Loading)
20
+ Load **only** the designated sub-skill when a slash command is executed to maintain strict 1,000–1,500 token budget:
21
+
22
+ | Command | Specialist Skill | Agent |
23
+ | :--- | :--- | :--- |
24
+ | `/torusguard init` | `skills/torusguard-init/SKILL.md` | `profiler` |
25
+ | `/torusguard authorize` | `skills/torusguard-authorize/SKILL.md` | `reviewer` |
26
+ | `/torusguard audit` | `skills/torusguard-audit/SKILL.md` | `auditor` |
27
+ | `/torusguard verify` | `skills/torusguard-verify/SKILL.md` | `validator` |
28
+ | `/torusguard web-validate` | `skills/torusguard-web-validate/SKILL.md` | `validator` |
29
+ | `/torusguard exploit-check` | `skills/torusguard-exploit-check/SKILL.md` | `validator` |
30
+ | `/torusguard harden` | `skills/torusguard-harden/SKILL.md` | `remediator` |
31
+ | `/torusguard apply` | `skills/torusguard-apply/SKILL.md` | `remediator` |
32
+ | `/torusguard recheck` | `skills/torusguard-recheck/SKILL.md` | `reviewer` |
33
+ | `/torusguard report` | `skills/torusguard-report/SKILL.md` | `reviewer` |
34
+ | `/torusguard status` | `skills/torusguard-status/SKILL.md` | `reviewer` |
35
+ | `/torusguard full` | `skills/torusguard-full/SKILL.md` | *All* |
36
+
37
+ *Note: Never load all skills simultaneously. Lazy-load strictly on demand.*
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TorusGuard Autonomous Workspace Bootstrapper
4
+ Scaffolds the complete .torusguard/ directory into any user project when
5
+ /torusguard init is executed or when npx skills add installs the skill kit.
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import shutil
11
+ import json
12
+ import argparse
13
+ import subprocess
14
+ from pathlib import Path
15
+
16
+
17
+ def find_project_root(start_dir=None):
18
+ """Detect project root directory by searching for standard repo root markers."""
19
+ current = Path(start_dir or os.getcwd()).resolve()
20
+ markers = [".git", "package.json", "pyproject.toml", "manage.py", "Pipfile", "requirements.txt"]
21
+
22
+ # First check current directory
23
+ for m in markers:
24
+ if (current / m).exists():
25
+ return current
26
+
27
+ # Search upwards
28
+ for parent in current.parents:
29
+ for m in markers:
30
+ if (parent / m).exists():
31
+ return parent
32
+
33
+ return current
34
+
35
+
36
+ def scaffold_workspace(target_root=None, force=False):
37
+ """Scaffold the .torusguard workspace into the target project root."""
38
+ target_root = Path(target_root or find_project_root()).resolve()
39
+ torusguard_target = target_root / ".torusguard"
40
+ script_dir = Path(__file__).resolve().parent
41
+ payload_dir = script_dir / "payload"
42
+
43
+ print("================================================================================")
44
+ print("TORUSGUARD WORKSPACE BOOTSTRAPPER")
45
+ print("================================================================================")
46
+ print(f"Target Directory: {target_root}")
47
+ print(f"Destination: {torusguard_target}")
48
+
49
+ if torusguard_target.exists() and not force:
50
+ print(f"\n[INFO] Workspace already exists at {torusguard_target}")
51
+ config_file = torusguard_target / "config" / "torusguard.json"
52
+ if config_file.exists():
53
+ try:
54
+ with open(config_file, "r", encoding="utf-8") as f:
55
+ cfg = json.load(f)
56
+ print(f"Current Version: {cfg.get('version', 'unknown')}")
57
+ print(f"Severity Minimum: {cfg.get('severity_threshold', 'medium')}")
58
+ except Exception:
59
+ pass
60
+ print("\nUse --force to re-scaffold or refresh templates.")
61
+ return True
62
+
63
+ # 1. Unpack Payload Template
64
+ if payload_dir.is_dir():
65
+ print("\n1. Unpacking bundled offline workspace payload...")
66
+ try:
67
+ if torusguard_target.exists() and force:
68
+ shutil.rmtree(torusguard_target)
69
+ shutil.copytree(
70
+ payload_dir,
71
+ torusguard_target,
72
+ ignore=shutil.ignore_patterns("runs", "*.pyc", "__pycache__", ".git*")
73
+ )
74
+ print(" [SUCCESS] Copied template tree from local skill payload.")
75
+ except Exception as e:
76
+ print(f" [ERROR] Failed to unpack payload: {e}")
77
+ return False
78
+ else:
79
+ # Fallback: create base structure
80
+ print("\n1. Bundled payload not found. Creating core skeleton...")
81
+ subdirs = [
82
+ "config", "agents", "workflows", "scripts", "templates",
83
+ "schemas", "references", "rules/active", "runs"
84
+ ]
85
+ for s in subdirs:
86
+ (torusguard_target / s).mkdir(parents=True, exist_ok=True)
87
+ print(" [WARN] Bare skeleton created; full assets should be pulled from repository.")
88
+
89
+ # 2. Ensure runs and rules/active directories exist
90
+ runs_dir = torusguard_target / "runs"
91
+ runs_dir.mkdir(parents=True, exist_ok=True)
92
+ gitkeep_runs = runs_dir / ".gitkeep"
93
+ if not gitkeep_runs.exists():
94
+ gitkeep_runs.write_text("", encoding="utf-8")
95
+
96
+ active_rules_dir = torusguard_target / "rules" / "active"
97
+ active_rules_dir.mkdir(parents=True, exist_ok=True)
98
+ gitkeep_rules = active_rules_dir / ".gitkeep"
99
+ if not gitkeep_rules.exists():
100
+ gitkeep_rules.write_text("", encoding="utf-8")
101
+
102
+ # 3. Stack Detection & Tailoring
103
+ print("\n2. Executing stack detection on target project...")
104
+ stack_detect_script = torusguard_target / "scripts" / "stack_detect.py"
105
+ detected_stack = {"language": "Unknown", "framework": "None", "data_layer": "None", "confidence": "Uncertain"}
106
+
107
+ if stack_detect_script.exists():
108
+ try:
109
+ res = subprocess.run(
110
+ [sys.executable, str(stack_detect_script), str(target_root), "--json"],
111
+ capture_output=True,
112
+ text=True,
113
+ timeout=10
114
+ )
115
+ if res.returncode == 0 and res.stdout.strip():
116
+ detected_stack = json.loads(res.stdout)
117
+ print(f" [DETECTED] Language: {detected_stack.get('language')}")
118
+ print(f" [DETECTED] Framework: {detected_stack.get('framework')}")
119
+ print(f" [DETECTED] Data Layer: {detected_stack.get('data_layer')}")
120
+ except Exception as e:
121
+ print(f" [WARN] Stack detection encountered error: {e}")
122
+
123
+ # 4. Update torusguard.json configuration
124
+ config_file = torusguard_target / "config" / "torusguard.json"
125
+ if config_file.exists():
126
+ try:
127
+ with open(config_file, "r", encoding="utf-8") as f:
128
+ cfg = json.load(f)
129
+ cfg["detected_stack"] = {
130
+ "language": detected_stack.get("language"),
131
+ "framework": detected_stack.get("framework"),
132
+ "data_layer": detected_stack.get("data_layer")
133
+ }
134
+ with open(config_file, "w", encoding="utf-8") as f:
135
+ json.dump(cfg, f, indent=2)
136
+ print(" [SUCCESS] Configured .torusguard/config/torusguard.json")
137
+ except Exception as e:
138
+ print(f" [WARN] Failed to write stack details to config: {e}")
139
+
140
+ print("\n================================================================================")
141
+ print("[SUCCESS] TORUSGUARD WORKSPACE SCAFFOLDED SUCCESSFULLY!")
142
+ print("================================================================================")
143
+ print(f"Workspace Path: {torusguard_target}")
144
+ print("\nNext Steps:")
145
+ print(" 1. Run `/torusguard audit` in your AI IDE to scan the project.")
146
+ print(" 2. Run `/torusguard status` to verify active security posture.")
147
+ print("================================================================================")
148
+ return True
149
+
150
+
151
+ if __name__ == "__main__":
152
+ parser = argparse.ArgumentParser(description="TorusGuard Autonomous Workspace Bootstrapper")
153
+ parser.add_argument("--target", type=str, help="Target project root directory")
154
+ parser.add_argument("--force", action="store_true", help="Force overwrite existing workspace")
155
+ args = parser.parse_args()
156
+
157
+ success = scaffold_workspace(target_root=args.target, force=args.force)
158
+ sys.exit(0 if success else 1)
@@ -0,0 +1,56 @@
1
+ # Authentication, Sessions, and Authorization
2
+
3
+ ## When to load
4
+
5
+ Load during `/TorusGuard check auth`, login/signup/reset implementation, or resource route reviews.
6
+
7
+ ## Linked rules
8
+
9
+ - [TG-AUTH-001](../../rules/TG-AUTH-001-weak-password-storage.md) — Weak Password Storage (Critical)
10
+ - [TG-AUTH-002](../../rules/TG-AUTH-002-client-only-authorization.md) — Client-Only Authorization (High)
11
+ - [TG-AUTH-003](../../rules/TG-AUTH-003-missing-object-authorization.md) — IDOR/BOLA (High)
12
+ - [TG-AUTH-004](../../rules/TG-AUTH-004-insecure-session-cookie.md) — Insecure Session Cookie (High)
13
+ - [TG-AUTH-005](../../rules/TG-AUTH-005-unsafe-password-reset.md) — Unsafe Password Reset (High)
14
+
15
+ ## Hard bans
16
+
17
+ - No plaintext, MD5, or SHA1 password storage
18
+ - No authorization enforced only in frontend routing
19
+ - No trust in client-supplied user IDs or roles
20
+ - No session cookies missing httpOnly/Secure/SameSite in production
21
+ - No predictable or reusable password reset tokens
22
+
23
+ ## Safe defaults
24
+
25
+ - Argon2id or bcrypt (cost ≥ 12) for passwords
26
+ - httpOnly, Secure, SameSite cookies for browser sessions
27
+ - Server-side role and ownership checks on every sensitive route
28
+ - Neutral login/reset responses (no account enumeration)
29
+ - CSRF protection for cookie-authenticated state changes
30
+ - Reset tokens: random, single-use, expiring
31
+
32
+ ## IDOR test procedure
33
+
34
+ For each route with a resource ID (`/api/users/:id`, `/api/orders/:orderId`):
35
+
36
+ > Can User A change the ID and access User B's resource?
37
+
38
+ If yes → fails TG-AUTH-003.
39
+
40
+ ## Audit checklist
41
+
42
+ - [ ] Strong password hashing (TG-AUTH-001)
43
+ - [ ] Server enforces authZ (TG-AUTH-002)
44
+ - [ ] Object ownership verified (TG-AUTH-003)
45
+ - [ ] Secure cookie flags (TG-AUTH-004)
46
+ - [ ] Safe reset flow + rate limits (TG-AUTH-005)
47
+
48
+ ## Manual review
49
+
50
+ - Organization/tenant-scoped authorization
51
+ - Privilege escalation via mass assignment
52
+ - Session fixation and logout invalidation
53
+
54
+ ## Related rules
55
+
56
+ TG-RATE-001, TG-SEC-004, TG-INPUT-001
@@ -0,0 +1,23 @@
1
+ # Business Logic and Abuse
2
+
3
+ ## Topics
4
+ - Coupon and discount abuse.
5
+ - Trial and referral abuse.
6
+ - Payment amount tampering.
7
+ - Inventory manipulation.
8
+ - OTP and verification workflow bypass.
9
+ - Vote and rating manipulation.
10
+ - Repeated one-time operations.
11
+ - AI or third-party API cost abuse.
12
+ - Replay and idempotency.
13
+ - Per-user and per-account velocity.
14
+ - Server-side state transitions.
15
+
16
+ ## Review Table
17
+ | Flow | Value protected | Abuse action | Existing control | Missing control |
18
+ |---|---|---|---|---|
19
+ | Apply coupon | Discount amount | Reuse coupon | Database flag | Atomic update |
20
+ | Send OTP | SMS cost | Repeated requests | IP limiter | Account limiter |
21
+ | Create order | Inventory/payment | Modify quantity/price | Auth only | Server-side pricing |
22
+
23
+ The agent must ask whether a user can execute a technically valid operation too many times. OWASP identifies sensitive business-flow abuse separately from ordinary authentication and resource-exhaustion concerns.
@@ -0,0 +1,10 @@
1
+ # Cache and Sensitive Responses
2
+
3
+ - Cache-Control: private, no-store for sensitive responses where appropriate.
4
+ - CDN cache-key isolation.
5
+ - User-specific response separation.
6
+ - Sensitive query parameters and tokens.
7
+ - Referrer leakage.
8
+ - Authenticated API responses.
9
+ - Export/download URLs.
10
+ - Signed URL expiry.
@@ -0,0 +1,55 @@
1
+ # Client Code Exposure and Source Maps
2
+
3
+ ## When to load
4
+
5
+ Load during `/TorusGuard check client`, production build review, or frontend bundle audits.
6
+
7
+ ## Linked rules
8
+
9
+ - [TG-CLIENT-001](../../rules/TG-CLIENT-001-public-production-source-maps.md) — Public Production Source Maps (Medium)
10
+ - [TG-CLIENT-002](../../rules/TG-CLIENT-002-sensitive-client-bundle-content.md) — Sensitive Bundle Content (High)
11
+
12
+ ## Important truth
13
+
14
+ **Inspect Element and DevTools cannot be prevented.** Browser-delivered JavaScript is public. TorusGuard must never claim client code can be hidden. Security comes from server-side enforcement, not obfuscation.
15
+
16
+ Obfuscation is a minor deterrent only — never a security control.
17
+
18
+ ## Hard bans
19
+
20
+ - No secrets, privileged routes, or auth decisions only in client code
21
+ - No production `console.log` of tokens, users, or config
22
+ - No public `.map` files unless explicitly required
23
+
24
+ ## Safe defaults
25
+
26
+ | Framework | Production setting |
27
+ |-----------|-------------------|
28
+ | Vite | `build.sourcemap: false` |
29
+ | Next.js | `productionBrowserSourceMaps: false` |
30
+ | CRA | `GENERATE_SOURCEMAP=false` |
31
+
32
+ - Upload source maps privately to Sentry/monitoring — do not serve publicly
33
+ - Verify public `.map` URLs return 404 when disabled
34
+ - Add CSP where practical
35
+ - Move authorization and secrets server-side
36
+
37
+ ## Audit checklist
38
+
39
+ - [ ] Production source maps disabled or private (TG-CLIENT-001)
40
+ - [ ] No secrets or privileged logic in bundle (TG-CLIENT-002)
41
+ - [ ] No sensitive console logging
42
+ - [ ] CSP configured appropriately
43
+
44
+ ## Manual review
45
+
46
+ - Third-party script dependencies
47
+ - Comments revealing internal routes or admin endpoints
48
+
49
+ ## Related rules
50
+
51
+ TG-SEC-002, TG-AUTH-002, TG-PLATFORM-002
52
+
53
+ ## Framework guide
54
+
55
+ [React/Vite Security](../../guides/react-vite-security.md)
@@ -0,0 +1,11 @@
1
+ # CSRF and Cross-Origin
2
+
3
+ - Cookie-authenticated state changes.
4
+ - Synchronizer tokens.
5
+ - Double-submit cookies.
6
+ - SameSite behavior and limitations.
7
+ - CORS and credentials.
8
+ - Origin and Referer validation where appropriate.
9
+ - JSON content-type restrictions.
10
+ - Framework-native CSRF protections.
11
+ - SPA/API architecture differences.
@@ -0,0 +1,22 @@
1
+ # Dependency and Supply Chain
2
+
3
+ - Lockfiles.
4
+ - Dependency update policy.
5
+ - Vulnerability audit commands by ecosystem.
6
+ - Dependabot/Renovate.
7
+ - GitHub Actions pinning.
8
+ - CI secret exposure.
9
+ - Pull-request workflow trust.
10
+ - Install scripts.
11
+ - Dependency provenance.
12
+ - Review of new packages.
13
+
14
+ ## Audit Commands
15
+ ```bash
16
+ npm audit
17
+ pip-audit
18
+ osv-scanner --lockfile=package-lock.json
19
+ dotnet list package --vulnerable
20
+ bundle audit
21
+ govulncheck ./...
22
+ ```
@@ -0,0 +1,43 @@
1
+ # TorusGuard Skill Reference: Django Security
2
+
3
+ > **Loaded When:** A project is identified as a Django application (`manage.py`, `settings.py`, or `django` dependency detected).
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Secrets & Production Configuration
10
+ * `TG-SEC-001`: Verify `SECRET_KEY` is loaded via `os.environ` or a secrets manager, not hardcoded.
11
+ * `TG-PLATFORM-003`: Verify `DEBUG = False` in production configs.
12
+ * `TG-PLATFORM-001`: Ensure `ALLOWED_HOSTS` is restricted to legitimate hostnames.
13
+
14
+ ### 2. Authentication & Authorization
15
+ * `TG-AUTH-001`: Ensure protected views use `@login_required` or `LoginRequiredMixin`.
16
+ * `TG-AUTH-007`: Enforce object-level ownership checks (e.g. `get_object_or_404(Model, id=id, user=request.user)`). Avoid unrestricted numeric ID lookups.
17
+
18
+ ### 3. Mass Assignment
19
+ * `TG-AUTH-006`: Ensure `ModelForm` definitions specify explicit `fields = [...]` lists instead of `fields = '__all__'`.
20
+
21
+ ### 4. Injection & Database Security
22
+ * `TG-INPUT-003`: Ensure `Model.objects.raw()` or `cursor.execute()` uses parameterized inputs (`%s`), never f-strings or `.format()`.
23
+
24
+ ### 5. CSRF & Request Security
25
+ * `TG-CSRF-001`: Verify `django.middleware.csrf.CsrfViewMiddleware` is active in `MIDDLEWARE`. Avoid indiscriminate `@csrf_exempt`.
26
+ * `TG-CACHE-001`: Verify sensitive authenticated endpoints use `@never_cache`.
27
+
28
+ ---
29
+
30
+ ## 🛠️ Safe Patterns Summary
31
+ ```python
32
+ # Safe Object Lookup
33
+ item = get_object_or_404(Invoice, id=invoice_id, account=request.user.account)
34
+
35
+ # Safe Form
36
+ class ProfileForm(forms.ModelForm):
37
+ class Meta:
38
+ model = Profile
39
+ fields = ['bio', 'website_url', 'avatar']
40
+
41
+ # Safe Raw SQL (if mandatory)
42
+ cursor.execute("SELECT * FROM reports WHERE account_id = %s", [request.user.account_id])
43
+ ```
@@ -0,0 +1,20 @@
1
+ # TorusGuard Skill Reference: Django REST Framework (DRF)
2
+
3
+ > **Loaded When:** Project uses `rest_framework` dependencies or imports.
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Permissions & Endpoint Exposure
10
+ * `TG-AUTH-001`: Inspect `settings.py` for `REST_FRAMEWORK['DEFAULT_PERMISSION_CLASSES']`. If missing or set to `AllowAny`, verify that individual views specify explicit `permission_classes`.
11
+ * `TG-AUTH-007`: In `ModelViewSet` and API views, check if `get_queryset()` returns `Model.objects.all()` without filtering by `request.user` or tenant context.
12
+
13
+ ### 2. Serializer Field Whitelists & Mass Assignment
14
+ * `TG-AUTH-006`: Inspect Serializer classes. Flag serializers where `fields = '__all__'` or where administrative/financial fields are not in `read_only_fields`.
15
+
16
+ ### 3. Throttling & Rate Limits
17
+ * `TG-RATE-001`: Check authentication endpoints (login, password reset, register, OTP) for throttle classes (`UserRateThrottle`, `ScopedRateThrottle`).
18
+
19
+ ### 4. Pagination Caps
20
+ * `TG-RATE-002`: Check custom pagination classes for `max_page_size`. If client-controlled `page_size_query_param` is enabled without a ceiling, flag as unbound resource risk.
@@ -0,0 +1,20 @@
1
+ # TorusGuard Skill Reference: FastAPI Security
2
+
3
+ > **Loaded When:** Project uses `fastapi` dependencies or imports.
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Route Authorization & Dependencies
10
+ * `TG-AUTH-001` / `TG-AUTH-003`: Verify protected routes include security dependencies (`Depends(get_current_user)`).
11
+ * `TG-AUTH-007`: In route handlers taking numeric/UUID path parameters (e.g. `profile_id`, `invoice_id`), verify that database queries filter by the authenticated user's ID.
12
+
13
+ ### 2. Request Models & Mass Assignment
14
+ * `TG-AUTH-006`: Check that endpoints accept structured Pydantic `BaseModel` classes rather than raw `dict`, `Body(...)`, or unpacking `**payload` directly into ORM entities.
15
+
16
+ ### 3. Outbound Requests & SSRF
17
+ * `TG-SSRF-001`: Inspect endpoints that fetch external URLs via `httpx` or `requests`. Verify scheme validation and private IP address filtering.
18
+
19
+ ### 4. Webhook Integrity
20
+ * `TG-WEBHOOK-001`: In webhook endpoints, verify HMAC signature validation using `await request.body()` (raw bytes) before JSON parsing.
@@ -0,0 +1,20 @@
1
+ # TorusGuard Skill Reference: Flask Security
2
+
3
+ > **Loaded When:** Project uses `flask` dependencies or imports.
4
+
5
+ ---
6
+
7
+ ## 🛡️ Key Inspection Areas & Rules
8
+
9
+ ### 1. Secret Key & Cookie Configuration
10
+ * `TG-SEC-001`: Inspect `app.config['SECRET_KEY']`. Flag hardcoded string literals.
11
+ * `TG-PLATFORM-003`: Verify `app.debug = False` in production configs.
12
+
13
+ ### 2. Authorization & Ownership (IDOR)
14
+ * `TG-AUTH-007`: In route handlers querying database models by route variables (e.g. `<int:id>`), verify that the query filters by `current_user.id`.
15
+
16
+ ### 3. CSRF Protection
17
+ * `TG-CSRF-001`: Verify that cookie-authenticated web forms initialize `flask_wtf.CSRFProtect`.
18
+
19
+ ### 4. File Uploads
20
+ * `TG-INPUT-004`: Ensure uploaded filenames are filtered using `secure_filename()` and validate against an extension whitelist.