@girardelli/architect 2.2.0 → 4.0.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 (296) hide show
  1. package/README.md +105 -116
  2. package/__test_agent_output__/INDEX.md +1 -0
  3. package/__test_agent_output__/agents/AGENT-ORCHESTRATOR.md +1 -0
  4. package/__test_agent_output__/agents/DATABASE-ENGINEER.md +174 -0
  5. package/__test_agent_output__/agents/QA-TEST-ENGINEER.md +138 -0
  6. package/__test_agent_output__/agents/SECURITY-AUDITOR.md +106 -0
  7. package/__test_agent_output__/agents/TECH-DEBT-CONTROLLER.md +104 -0
  8. package/__test_agent_output__/agents/TYPESCRIPT-BACKEND-DEVELOPER.md +135 -0
  9. package/__test_agent_output__/guards/CODE-REVIEW-CHECKLIST.md +95 -0
  10. package/__test_agent_output__/guards/PREFLIGHT.md +200 -0
  11. package/__test_agent_output__/guards/QUALITY-GATES.md +1 -0
  12. package/__test_agent_output__/rules/00-general.md +229 -0
  13. package/__test_agent_output__/rules/01-architecture.md +191 -0
  14. package/__test_agent_output__/rules/02-security.md +402 -0
  15. package/__test_agent_output__/rules/03-nestjs.md +124 -0
  16. package/__test_agent_output__/templates/ADR.md +95 -0
  17. package/__test_agent_output__/templates/BDD.md +58 -0
  18. package/__test_agent_output__/templates/C4.md +68 -0
  19. package/__test_agent_output__/templates/TDD.md +86 -0
  20. package/__test_agent_output__/templates/THREAT-MODEL.md +82 -0
  21. package/__test_agent_output__/workflows/fix-bug.md +228 -0
  22. package/__test_agent_output__/workflows/new-feature.md +311 -0
  23. package/__test_agent_output__/workflows/review.md +95 -0
  24. package/__test_context_7RvUrO/src/modules/empty/empty.ts +0 -0
  25. package/__test_context_Rf5fNJ/src/modules/mixed/mixed.ts +5 -0
  26. package/__test_context_WRCnYH/src/modules/test/test.ts +10 -0
  27. package/__test_context_YsnVS3/src/modules/test/test.ts +10 -0
  28. package/__test_context_w7XZeH/src/modules/mixed/mixed.ts +5 -0
  29. package/__test_context_y5noh6/src/modules/empty/empty.ts +0 -0
  30. package/__test_framework__24OjAu/package.json +1 -0
  31. package/__test_framework__3ZDZsx/pyproject.toml +8 -0
  32. package/__test_framework__4T54Jn/package.json +1 -0
  33. package/__test_framework__4tlXu9/pyproject.toml +8 -0
  34. package/__test_framework__6boWqQ/Pipfile +6 -0
  35. package/__test_framework__6gygMU/pom.xml +10 -0
  36. package/__test_framework__6kxj0N/go.mod +8 -0
  37. package/__test_framework__7CEoXw/pom.xml +10 -0
  38. package/__test_framework__85DDz0/Pipfile +6 -0
  39. package/__test_framework__9WrRIr/pom.xml +7 -0
  40. package/__test_framework__ANqGKl/Gemfile +5 -0
  41. package/__test_framework__BCXTEM/go.mod +3 -0
  42. package/__test_framework__BHiPNq/setup.py +2 -0
  43. package/__test_framework__BqkiKv/package.json +1 -0
  44. package/__test_framework__C5yd8X/Pipfile.lock +1 -0
  45. package/__test_framework__C5yd8X/requirements.txt +1 -0
  46. package/__test_framework__C87d3a/manage.py +1 -0
  47. package/__test_framework__C87d3a/requirements.txt +2 -0
  48. package/__test_framework__DXNwc5/build.gradle +7 -0
  49. package/__test_framework__GhHSt3/build.gradle.kts +4 -0
  50. package/__test_framework__GzklJP/Cargo.toml +7 -0
  51. package/__test_framework__H4hd13/go.mod +8 -0
  52. package/__test_framework__HKjOXO/composer.json +1 -0
  53. package/__test_framework__HaDN45/Gemfile +3 -0
  54. package/__test_framework__IBO7YG/pyproject.toml +9 -0
  55. package/__test_framework__JwSOyF/pyproject.toml +6 -0
  56. package/__test_framework__K6HrCr/build.gradle +2 -0
  57. package/__test_framework__KzRPlh/pubspec.yaml +9 -0
  58. package/__test_framework__L6uIym/pyproject.toml +6 -0
  59. package/__test_framework__LOdoGK/requirements.txt +4 -0
  60. package/__test_framework__LgHzss/package.json +1 -0
  61. package/__test_framework__M76M6q/Gemfile +5 -0
  62. package/__test_framework__Mr9vWW/composer.json +1 -0
  63. package/__test_framework__N03Gnv/package.json +1 -0
  64. package/__test_framework__Num4UE/requirements +1 -0
  65. package/__test_framework__OAGw3Y/build.gradle +7 -0
  66. package/__test_framework__OQc8yG/pubspec.yaml +9 -0
  67. package/__test_framework__OwKZcd/requirements.txt +3 -0
  68. package/__test_framework__P0gFv7/requirements +1 -0
  69. package/__test_framework__PN55Rq/package.json +1 -0
  70. package/__test_framework__PQiqX8/pubspec.yaml +3 -0
  71. package/__test_framework__RBHsg7/composer.json +1 -0
  72. package/__test_framework__RHxif4/Cargo.toml +7 -0
  73. package/__test_framework__T0v0p1/Cargo.toml +4 -0
  74. package/__test_framework__Tu0clt/Pipfile.lock +1 -0
  75. package/__test_framework__Tu0clt/requirements.txt +1 -0
  76. package/__test_framework__TwDj9P/Cargo.toml +4 -0
  77. package/__test_framework__VQJNC4/pom.xml +7 -0
  78. package/__test_framework__W6sm05/package.json +1 -0
  79. package/__test_framework__W7vBLy/pyproject.toml +4 -0
  80. package/__test_framework__WNJOWT/setup.py +2 -0
  81. package/__test_framework__WSJs7U/package.json +1 -0
  82. package/__test_framework__YQ5VpA/build.gradle.kts +4 -0
  83. package/__test_framework__ZNEUEs/package.json +1 -0
  84. package/__test_framework__Znt922/pom.xml +7 -0
  85. package/__test_framework__azyg0h/pom.xml +7 -0
  86. package/__test_framework__c6otLr/package.json +1 -0
  87. package/__test_framework__cl9S9G/build.gradle +2 -0
  88. package/__test_framework__eilvV4/composer.json +1 -0
  89. package/__test_framework__gQZxXO/manage.py +1 -0
  90. package/__test_framework__gQZxXO/requirements.txt +2 -0
  91. package/__test_framework__ghvl26/poetry.lock +1 -0
  92. package/__test_framework__ghvl26/pyproject.toml +2 -0
  93. package/__test_framework__hR7b9U/Makefile +11 -0
  94. package/__test_framework__iESVsi/composer.json +1 -0
  95. package/__test_framework__jm6TJy/package.json +1 -0
  96. package/__test_framework__kBUpjs/pyproject.toml +9 -0
  97. package/__test_framework__kqoZrw/requirements.txt +4 -0
  98. package/__test_framework__lWkoyO/pyproject.toml +4 -0
  99. package/__test_framework__mTKnUO/package.json +1 -0
  100. package/__test_framework__nCeZwe/Makefile +11 -0
  101. package/__test_framework__oljsU0/package.json +1 -0
  102. package/__test_framework__osRG4q/go.mod +3 -0
  103. package/__test_framework__pCHH4F/package.json +1 -0
  104. package/__test_framework__pExx6E/Gemfile +3 -0
  105. package/__test_framework__pyBoGd/pyproject.toml +5 -0
  106. package/__test_framework__qw16VQ/package.json +1 -0
  107. package/__test_framework__rRayrG/package.json +1 -0
  108. package/__test_framework__s82zO5/package.json +1 -0
  109. package/__test_framework__tp8MFK/pyproject.toml +5 -0
  110. package/__test_framework__w44k4w/composer.json +1 -0
  111. package/__test_framework__yefPZY/poetry.lock +1 -0
  112. package/__test_framework__yefPZY/pyproject.toml +2 -0
  113. package/__test_framework__zCiyDT/requirements.txt +3 -0
  114. package/__test_framework__zGZN3j/pubspec.yaml +3 -0
  115. package/__test_framework__zXpnxL/package.json +1 -0
  116. package/architect-run.sh +431 -0
  117. package/assets/banner-v3.html +561 -0
  118. package/dist/agent-generator/context-enricher.d.ts +58 -0
  119. package/dist/agent-generator/context-enricher.d.ts.map +1 -0
  120. package/dist/agent-generator/context-enricher.js +581 -0
  121. package/dist/agent-generator/context-enricher.js.map +1 -0
  122. package/dist/agent-generator/domain-inferrer.d.ts +52 -0
  123. package/dist/agent-generator/domain-inferrer.d.ts.map +1 -0
  124. package/dist/agent-generator/domain-inferrer.js +575 -0
  125. package/dist/agent-generator/domain-inferrer.js.map +1 -0
  126. package/dist/agent-generator/framework-detector.d.ts +40 -0
  127. package/dist/agent-generator/framework-detector.d.ts.map +1 -0
  128. package/dist/agent-generator/framework-detector.js +611 -0
  129. package/dist/agent-generator/framework-detector.js.map +1 -0
  130. package/dist/agent-generator/index.d.ts +33 -0
  131. package/dist/agent-generator/index.d.ts.map +1 -0
  132. package/dist/agent-generator/index.js +477 -0
  133. package/dist/agent-generator/index.js.map +1 -0
  134. package/dist/agent-generator/stack-detector.d.ts +12 -0
  135. package/dist/agent-generator/stack-detector.d.ts.map +1 -0
  136. package/dist/agent-generator/stack-detector.js +128 -0
  137. package/dist/agent-generator/stack-detector.js.map +1 -0
  138. package/dist/agent-generator/templates/core/agents.d.ts +17 -0
  139. package/dist/agent-generator/templates/core/agents.d.ts.map +1 -0
  140. package/dist/agent-generator/templates/core/agents.js +1252 -0
  141. package/dist/agent-generator/templates/core/agents.js.map +1 -0
  142. package/dist/agent-generator/templates/core/architecture-rules.d.ts +7 -0
  143. package/dist/agent-generator/templates/core/architecture-rules.d.ts.map +1 -0
  144. package/dist/agent-generator/templates/core/architecture-rules.js +274 -0
  145. package/dist/agent-generator/templates/core/architecture-rules.js.map +1 -0
  146. package/dist/agent-generator/templates/core/general-rules.d.ts +8 -0
  147. package/dist/agent-generator/templates/core/general-rules.d.ts.map +1 -0
  148. package/dist/agent-generator/templates/core/general-rules.js +301 -0
  149. package/dist/agent-generator/templates/core/general-rules.js.map +1 -0
  150. package/dist/agent-generator/templates/core/index-md.d.ts +7 -0
  151. package/dist/agent-generator/templates/core/index-md.d.ts.map +1 -0
  152. package/dist/agent-generator/templates/core/index-md.js +246 -0
  153. package/dist/agent-generator/templates/core/index-md.js.map +1 -0
  154. package/dist/agent-generator/templates/core/orchestrator.d.ts +8 -0
  155. package/dist/agent-generator/templates/core/orchestrator.d.ts.map +1 -0
  156. package/dist/agent-generator/templates/core/orchestrator.js +422 -0
  157. package/dist/agent-generator/templates/core/orchestrator.js.map +1 -0
  158. package/dist/agent-generator/templates/core/preflight.d.ts +8 -0
  159. package/dist/agent-generator/templates/core/preflight.d.ts.map +1 -0
  160. package/dist/agent-generator/templates/core/preflight.js +213 -0
  161. package/dist/agent-generator/templates/core/preflight.js.map +1 -0
  162. package/dist/agent-generator/templates/core/quality-gates.d.ts +11 -0
  163. package/dist/agent-generator/templates/core/quality-gates.d.ts.map +1 -0
  164. package/dist/agent-generator/templates/core/quality-gates.js +254 -0
  165. package/dist/agent-generator/templates/core/quality-gates.js.map +1 -0
  166. package/dist/agent-generator/templates/core/security-rules.d.ts +7 -0
  167. package/dist/agent-generator/templates/core/security-rules.d.ts.map +1 -0
  168. package/dist/agent-generator/templates/core/security-rules.js +528 -0
  169. package/dist/agent-generator/templates/core/security-rules.js.map +1 -0
  170. package/dist/agent-generator/templates/core/skills-generator.d.ts +6 -0
  171. package/dist/agent-generator/templates/core/skills-generator.d.ts.map +1 -0
  172. package/dist/agent-generator/templates/core/skills-generator.js +207 -0
  173. package/dist/agent-generator/templates/core/skills-generator.js.map +1 -0
  174. package/dist/agent-generator/templates/core/workflow-fix-bug.d.ts +7 -0
  175. package/dist/agent-generator/templates/core/workflow-fix-bug.d.ts.map +1 -0
  176. package/dist/agent-generator/templates/core/workflow-fix-bug.js +237 -0
  177. package/dist/agent-generator/templates/core/workflow-fix-bug.js.map +1 -0
  178. package/dist/agent-generator/templates/core/workflow-new-feature.d.ts +8 -0
  179. package/dist/agent-generator/templates/core/workflow-new-feature.d.ts.map +1 -0
  180. package/dist/agent-generator/templates/core/workflow-new-feature.js +321 -0
  181. package/dist/agent-generator/templates/core/workflow-new-feature.js.map +1 -0
  182. package/dist/agent-generator/templates/core/workflow-review.d.ts +7 -0
  183. package/dist/agent-generator/templates/core/workflow-review.d.ts.map +1 -0
  184. package/dist/agent-generator/templates/core/workflow-review.js +104 -0
  185. package/dist/agent-generator/templates/core/workflow-review.js.map +1 -0
  186. package/dist/agent-generator/templates/domain/index.d.ts +22 -0
  187. package/dist/agent-generator/templates/domain/index.d.ts.map +1 -0
  188. package/dist/agent-generator/templates/domain/index.js +1176 -0
  189. package/dist/agent-generator/templates/domain/index.js.map +1 -0
  190. package/dist/agent-generator/templates/stack/index.d.ts +8 -0
  191. package/dist/agent-generator/templates/stack/index.d.ts.map +1 -0
  192. package/dist/agent-generator/templates/stack/index.js +695 -0
  193. package/dist/agent-generator/templates/stack/index.js.map +1 -0
  194. package/dist/agent-generator/templates/template-helpers.d.ts +75 -0
  195. package/dist/agent-generator/templates/template-helpers.d.ts.map +1 -0
  196. package/dist/agent-generator/templates/template-helpers.js +726 -0
  197. package/dist/agent-generator/templates/template-helpers.js.map +1 -0
  198. package/dist/agent-generator/types.d.ts +196 -0
  199. package/dist/agent-generator/types.d.ts.map +1 -0
  200. package/dist/agent-generator/types.js +27 -0
  201. package/dist/agent-generator/types.js.map +1 -0
  202. package/dist/analyzer.d.ts +5 -0
  203. package/dist/analyzer.d.ts.map +1 -1
  204. package/dist/analyzer.js +35 -4
  205. package/dist/analyzer.js.map +1 -1
  206. package/dist/analyzers/forecast.d.ts +85 -0
  207. package/dist/analyzers/forecast.d.ts.map +1 -0
  208. package/dist/analyzers/forecast.js +337 -0
  209. package/dist/analyzers/forecast.js.map +1 -0
  210. package/dist/analyzers/git-cache.d.ts +7 -0
  211. package/dist/analyzers/git-cache.d.ts.map +1 -0
  212. package/dist/analyzers/git-cache.js +41 -0
  213. package/dist/analyzers/git-cache.js.map +1 -0
  214. package/dist/analyzers/git-history.d.ts +113 -0
  215. package/dist/analyzers/git-history.d.ts.map +1 -0
  216. package/dist/analyzers/git-history.js +333 -0
  217. package/dist/analyzers/git-history.js.map +1 -0
  218. package/dist/analyzers/index.d.ts +10 -0
  219. package/dist/analyzers/index.d.ts.map +1 -0
  220. package/dist/analyzers/index.js +7 -0
  221. package/dist/analyzers/index.js.map +1 -0
  222. package/dist/analyzers/temporal-scorer.d.ts +72 -0
  223. package/dist/analyzers/temporal-scorer.d.ts.map +1 -0
  224. package/dist/analyzers/temporal-scorer.js +140 -0
  225. package/dist/analyzers/temporal-scorer.js.map +1 -0
  226. package/dist/cli.d.ts +2 -3
  227. package/dist/cli.d.ts.map +1 -1
  228. package/dist/cli.js +275 -113
  229. package/dist/cli.js.map +1 -1
  230. package/dist/html-reporter.d.ts +3 -1
  231. package/dist/html-reporter.d.ts.map +1 -1
  232. package/dist/html-reporter.js +248 -12
  233. package/dist/html-reporter.js.map +1 -1
  234. package/dist/index.d.ts +16 -3
  235. package/dist/index.d.ts.map +1 -1
  236. package/dist/index.js +63 -4
  237. package/dist/index.js.map +1 -1
  238. package/dist/project-summarizer.d.ts +18 -0
  239. package/dist/project-summarizer.d.ts.map +1 -0
  240. package/dist/project-summarizer.js +306 -0
  241. package/dist/project-summarizer.js.map +1 -0
  242. package/dist/refactor-reporter.js +1 -1
  243. package/dist/types.d.ts +13 -0
  244. package/dist/types.d.ts.map +1 -1
  245. package/package.json +12 -3
  246. package/src/agent-generator/context-enricher.ts +643 -0
  247. package/src/agent-generator/domain-inferrer.ts +625 -0
  248. package/src/agent-generator/framework-detector.ts +669 -0
  249. package/src/agent-generator/index.ts +555 -0
  250. package/src/agent-generator/stack-detector.ts +103 -0
  251. package/src/agent-generator/templates/core/agents.ts +1293 -0
  252. package/src/agent-generator/templates/core/architecture-rules.ts +287 -0
  253. package/src/agent-generator/templates/core/general-rules.ts +306 -0
  254. package/src/agent-generator/templates/core/index-md.ts +260 -0
  255. package/src/agent-generator/templates/core/orchestrator.ts +459 -0
  256. package/src/agent-generator/templates/core/preflight.ts +215 -0
  257. package/src/agent-generator/templates/core/quality-gates.ts +256 -0
  258. package/src/agent-generator/templates/core/security-rules.ts +543 -0
  259. package/src/agent-generator/templates/core/skills-generator.ts +236 -0
  260. package/src/agent-generator/templates/core/workflow-fix-bug.ts +239 -0
  261. package/src/agent-generator/templates/core/workflow-new-feature.ts +323 -0
  262. package/src/agent-generator/templates/core/workflow-review.ts +106 -0
  263. package/src/agent-generator/templates/domain/index.ts +1201 -0
  264. package/src/agent-generator/templates/stack/index.ts +705 -0
  265. package/src/agent-generator/templates/template-helpers.ts +776 -0
  266. package/src/agent-generator/types.ts +232 -0
  267. package/src/analyzer.ts +38 -4
  268. package/src/analyzers/forecast.ts +496 -0
  269. package/src/analyzers/git-cache.ts +52 -0
  270. package/src/analyzers/git-history.ts +488 -0
  271. package/src/analyzers/index.ts +33 -0
  272. package/src/analyzers/temporal-scorer.ts +227 -0
  273. package/src/cli.ts +316 -117
  274. package/src/html-reporter.ts +263 -13
  275. package/src/index.ts +92 -9
  276. package/src/project-summarizer.ts +347 -0
  277. package/src/refactor-reporter.ts +1 -1
  278. package/src/types.ts +10 -0
  279. package/tests/agent-generator.test.ts +411 -0
  280. package/tests/analyzers-integration.test.ts +174 -0
  281. package/tests/architect-adapter-enrichment.test.ts +9 -0
  282. package/tests/context-enricher.test.ts +971 -0
  283. package/tests/forecast.test.ts +509 -0
  284. package/tests/framework-detector.test.ts +1172 -0
  285. package/tests/git-history.test.ts +254 -0
  286. package/tests/scanner.test.ts +7 -8
  287. package/tests/scorer.test.ts +588 -0
  288. package/tests/stack-detector.test.ts +241 -0
  289. package/tests/template-generation.test.ts +706 -0
  290. package/tests/template-helpers.test.ts +1152 -0
  291. package/tests/temporal-scorer.test.ts +307 -0
  292. package/dist/agent-generator.d.ts +0 -106
  293. package/dist/agent-generator.d.ts.map +0 -1
  294. package/dist/agent-generator.js +0 -1398
  295. package/dist/agent-generator.js.map +0 -1
  296. package/src/agent-generator.ts +0 -1526
@@ -0,0 +1,543 @@
1
+ import { TemplateContext } from '../../types.js';
2
+
3
+ /**
4
+ * Generates 02-security.md — OWASP rules, input validation, secrets management,
5
+ * auth/authz patterns, and security anti-patterns.
6
+ */
7
+ export function generateSecurityRules(ctx: TemplateContext): string {
8
+ const { stack, projectName, report, config } = ctx;
9
+ const validationPatterns = buildValidationPatterns(ctx);
10
+ const authPatterns = buildAuthPatterns(ctx);
11
+ const secretsRules = buildSecretsRules(ctx);
12
+
13
+ return `---
14
+ antigravity:
15
+ trigger: 'always_on'
16
+ globs: ['**/*']
17
+ description: 'Regras de segurança para ${projectName}'
18
+ priority: CRITICAL
19
+ ---
20
+
21
+ # 🛡️ Regras de Segurança — ${projectName}
22
+
23
+ > **Segurança NÃO é feature — é requisito. Toda linha de código é superfície de ataque.**
24
+
25
+ ---
26
+
27
+ ## ⚠️ REGRA ZERO DE SEGURANÇA
28
+
29
+ \`\`\`
30
+ ╔══════════════════════════════════════════════════════════════╗
31
+ ║ NUNCA confiar em input do usuário. ║
32
+ ║ NUNCA expor detalhes internos em respostas de erro. ║
33
+ ║ NUNCA armazenar secrets em código. ║
34
+ ║ NUNCA desabilitar validação "temporariamente". ║
35
+ ║ NUNCA commitar com security warnings ignorados. ║
36
+ ╚══════════════════════════════════════════════════════════════╝
37
+ \`\`\`
38
+
39
+ ---
40
+
41
+ ## 🔐 OWASP Top 10 — Checklist Obrigatório
42
+
43
+ ### A01: Broken Access Control
44
+ \`\`\`
45
+ ❌ PROIBIDO: Endpoint sem verificação de autorização
46
+ ❌ PROIBIDO: IDOR (Insecure Direct Object Reference) — acessar recurso de outro usuário via ID
47
+ ✅ CORRETO: RBAC (Role-Based Access Control) em TODOS os endpoints
48
+ ✅ CORRETO: Verificar ownership do recurso antes de retornar
49
+
50
+ Padrão:
51
+ 1. Autenticar (quem é?)
52
+ 2. Autorizar (pode fazer isso?)
53
+ 3. Verificar ownership (esse recurso é dele?)
54
+ 4. Executar ação
55
+ \`\`\`
56
+
57
+ ### A02: Cryptographic Failures
58
+ \`\`\`
59
+ ❌ PROIBIDO: Senhas em plain text
60
+ ❌ PROIBIDO: HTTP para dados sensíveis
61
+ ❌ PROIBIDO: Algoritmos fracos (MD5, SHA1 para passwords)
62
+ ✅ CORRETO: bcrypt/argon2 para passwords (cost ≥ 12)
63
+ ✅ CORRETO: HTTPS everywhere (HSTS)
64
+ ✅ CORRETO: AES-256-GCM para dados em repouso
65
+ ✅ CORRETO: TLS 1.2+ para dados em trânsito
66
+ \`\`\`
67
+
68
+ ### A03: Injection
69
+ \`\`\`
70
+ ❌ PROIBIDO: Concatenação de strings em queries SQL
71
+ ❌ PROIBIDO: Template strings com input de usuário
72
+ ❌ PROIBIDO: eval(), exec(), Function() com input externo
73
+ ✅ CORRETO: Queries parametrizadas SEMPRE
74
+ ✅ CORRETO: ORM com bindings
75
+ ✅ CORRETO: Input sanitization na borda (controller/pipe)
76
+
77
+ Exemplos:
78
+ ❌ \`SELECT * FROM users WHERE id = '\${userId}'\`
79
+ ✅ \`SELECT * FROM users WHERE id = $1\` + [userId]
80
+ ❌ \`db.query(\`...WHERE name = '\${name}'\`)\`
81
+ ✅ \`db.query('...WHERE name = ?', [name])\`
82
+ \`\`\`
83
+
84
+ ### A04: Insecure Design
85
+ \`\`\`
86
+ ❌ PROIBIDO: Endpoints sem rate limiting
87
+ ❌ PROIBIDO: Reset de senha via link sem expiração
88
+ ❌ PROIBIDO: Lógica de negócio sem threat model
89
+ ✅ CORRETO: STRIDE analysis antes de implementar features sensíveis
90
+ ✅ CORRETO: Rate limiting em auth endpoints (≤ 5 tentativas/minuto)
91
+ ✅ CORRETO: Tokens com expiração curta (15min access, 7d refresh)
92
+ \`\`\`
93
+
94
+ ### A05: Security Misconfiguration
95
+ \`\`\`
96
+ ❌ PROIBIDO: CORS com origin: '*' em produção
97
+ ❌ PROIBIDO: Debug mode em produção
98
+ ❌ PROIBIDO: Default credentials
99
+ ❌ PROIBIDO: Stack traces em respostas de erro
100
+ ✅ CORRETO: CORS restritivo (origins explícitos)
101
+ ✅ CORRETO: Headers de segurança (X-Frame-Options, CSP, X-Content-Type-Options)
102
+ ✅ CORRETO: Error handling que retorna apenas mensagem genérica ao usuário
103
+
104
+ Headers obrigatórios:
105
+ X-Content-Type-Options: nosniff
106
+ X-Frame-Options: DENY
107
+ X-XSS-Protection: 0 (CSP substitui)
108
+ Content-Security-Policy: default-src 'self'
109
+ Strict-Transport-Security: max-age=31536000; includeSubDomains
110
+ Referrer-Policy: strict-origin-when-cross-origin
111
+ \`\`\`
112
+
113
+ ### A06: Vulnerable and Outdated Components
114
+ \`\`\`
115
+ ❌ PROIBIDO: Dependências com vulnerabilidades conhecidas
116
+ ❌ PROIBIDO: Ignorar security advisories
117
+ ✅ CORRETO: Audit regular (npm audit / pip audit / safety check)
118
+ ✅ CORRETO: Renovate/Dependabot configurado
119
+ ✅ CORRETO: Lock files commitados (package-lock.json, poetry.lock)
120
+
121
+ Comandos de verificação:
122
+ ${stack.primary === 'Python'
123
+ ? ' $ pip audit\n $ safety check\n $ bandit -r src/'
124
+ : stack.primary === 'Dart'
125
+ ? ' $ flutter pub outdated\n $ dart analyze --fatal-warnings'
126
+ : ' $ npm audit\n $ npx audit-ci --critical\n $ npx snyk test'}
127
+ \`\`\`
128
+
129
+ ### A07: Identification and Authentication Failures
130
+ \`\`\`
131
+ ❌ PROIBIDO: Sessions sem expiração
132
+ ❌ PROIBIDO: Tokens previsíveis
133
+ ❌ PROIBIDO: Brute force sem proteção
134
+ ✅ CORRETO: JWT com algoritmo explícito (RS256 ou ES256)
135
+ ✅ CORRETO: Refresh token rotation
136
+ ✅ CORRETO: Account lockout após N tentativas
137
+ ✅ CORRETO: MFA para operações sensíveis
138
+
139
+ JWT Checklist:
140
+ □ Algoritmo explícito (nunca 'none')
141
+ □ Audience (aud) verificado
142
+ □ Issuer (iss) verificado
143
+ □ Expiração (exp) curta
144
+ □ Secret key ≥ 256 bits
145
+ □ Stored em httpOnly cookie (não localStorage)
146
+ \`\`\`
147
+
148
+ ### A08: Software and Data Integrity Failures
149
+ \`\`\`
150
+ ❌ PROIBIDO: CI/CD sem verificação de integridade
151
+ ❌ PROIBIDO: Deserialização de dados não confiáveis
152
+ ✅ CORRETO: Subresource Integrity (SRI) para CDN scripts
153
+ ✅ CORRETO: Signed commits
154
+ ✅ CORRETO: Pipeline protegido (branch protection rules)
155
+ \`\`\`
156
+
157
+ ### A09: Security Logging and Monitoring Failures
158
+ \`\`\`
159
+ ❌ PROIBIDO: Ações sensíveis sem log
160
+ ❌ PROIBIDO: Logs com dados sensíveis (passwords, tokens, PII)
161
+ ✅ CORRETO: Audit log para: login, logout, password change, permission change
162
+ ✅ CORRETO: Log level adequado (WARN/ERROR para falhas de auth)
163
+ ✅ CORRETO: Alertas para atividades anômalas
164
+
165
+ O que logar:
166
+ ✅ Quem (user ID)
167
+ ✅ O quê (ação)
168
+ ✅ Quando (timestamp UTC)
169
+ ✅ Onde (IP, user-agent)
170
+ ✅ Resultado (sucesso/falha)
171
+
172
+ O que NUNCA logar:
173
+ ❌ Passwords (nem em debug)
174
+ ❌ Tokens de autenticação
175
+ ❌ Dados de cartão de crédito
176
+ ❌ PII sem necessidade
177
+ \`\`\`
178
+
179
+ ### A10: Server-Side Request Forgery (SSRF)
180
+ \`\`\`
181
+ ❌ PROIBIDO: Fetch de URL fornecida pelo usuário sem validação
182
+ ❌ PROIBIDO: Acesso a metadata endpoints (169.254.169.254)
183
+ ✅ CORRETO: Allowlist de domínios para requests externos
184
+ ✅ CORRETO: Validação de schema (https only)
185
+ ✅ CORRETO: Block de IPs internos/privados
186
+ \`\`\`
187
+
188
+ ---
189
+
190
+ ## 🔑 Validação de Input
191
+
192
+ ${validationPatterns}
193
+
194
+ ---
195
+
196
+ ## 🔒 Autenticação & Autorização
197
+
198
+ ${authPatterns}
199
+
200
+ ---
201
+
202
+ ## 🗝️ Gestão de Secrets
203
+
204
+ ${secretsRules}
205
+
206
+ ---
207
+
208
+ ## 🚨 Security Anti-Patterns Detectados
209
+
210
+ ${report.antiPatterns.filter(a =>
211
+ a.name.toLowerCase().includes('security') ||
212
+ a.name.toLowerCase().includes('secret') ||
213
+ a.name.toLowerCase().includes('hardcoded') ||
214
+ a.name.toLowerCase().includes('injection') ||
215
+ a.name.toLowerCase().includes('validation')
216
+ ).length > 0
217
+ ? report.antiPatterns
218
+ .filter(a =>
219
+ a.name.toLowerCase().includes('security') ||
220
+ a.name.toLowerCase().includes('secret') ||
221
+ a.name.toLowerCase().includes('hardcoded') ||
222
+ a.name.toLowerCase().includes('injection') ||
223
+ a.name.toLowerCase().includes('validation')
224
+ )
225
+ .map(a => `- **${a.name}** (${a.severity}) em \`${a.location}\` — ${a.suggestion}`)
226
+ .join('\\n')
227
+ : '✅ Nenhum anti-pattern de segurança detectado no scan automático.\\n> ⚠️ Isso NÃO significa que o projeto está seguro. Análise manual é necessária.'}
228
+
229
+ ---
230
+
231
+ ## ✅ Checklist de Segurança por Camada
232
+
233
+ ### Controller / API Layer
234
+ \`\`\`
235
+ □ Input validado com DTO/Schema
236
+ □ Rate limiting configurado
237
+ □ Auth guard aplicado
238
+ □ CORS configurado corretamente
239
+ □ Response não expõe dados internos
240
+ □ Error handling sem stack trace
241
+ \`\`\`
242
+
243
+ ### Service / Business Layer
244
+ \`\`\`
245
+ □ Autorização verificada (ownership)
246
+ □ Dados sensíveis criptografados
247
+ □ Lógica de negócio com audit log
248
+ □ Sem eval/exec com input externo
249
+ □ Timeout em operações externas
250
+ \`\`\`
251
+
252
+ ### Data / Repository Layer
253
+ \`\`\`
254
+ □ Queries parametrizadas (NUNCA concatenação)
255
+ □ Connection pooling com limits
256
+ □ Migrations reversíveis
257
+ □ Dados sensíveis com encryption at rest
258
+ □ Backup policy definida
259
+ \`\`\`
260
+
261
+ ### Frontend / Mobile Layer
262
+ \`\`\`
263
+ □ XSS prevenido (sanitization)
264
+ □ CSRF token em formulários
265
+ □ Tokens em httpOnly cookies (não localStorage)
266
+ □ Content Security Policy
267
+ □ Sem secrets no bundle (NUNCA)
268
+ □ Validação client-side + server-side
269
+ \`\`\`
270
+
271
+ ---
272
+
273
+ ## 🛡️ Threat Model (STRIDE)
274
+
275
+ Antes de implementar features sensíveis, usar template STRIDE:
276
+
277
+ \`\`\`
278
+ | Ameaça | Descrição | Mitigação |
279
+ |---------------------|------------------------------------|-----------|
280
+ | Spoofing | Alguém se passando por outro | Auth forte, MFA |
281
+ | Tampering | Dados alterados em trânsito | TLS, HMAC, checksums |
282
+ | Repudiation | Negar ação realizada | Audit logs |
283
+ | Info Disclosure | Vazamento de dados | Encryption, access control |
284
+ | Denial of Service | Indisponibilidade | Rate limiting, CDN, autoscaling |
285
+ | Elevation of Priv. | Escalar permissões | Least privilege, RBAC |
286
+ \`\`\`
287
+
288
+ > Template completo disponível em: \`templates/THREAT-MODEL.md\`
289
+
290
+ ---
291
+
292
+ ## 📊 Verificação Automatizada
293
+
294
+ \`\`\`bash
295
+ # Scan de vulnerabilidades em dependências
296
+ ${stack.primary === 'Python'
297
+ ? 'pip audit\nsafety check\nbandit -r src/'
298
+ : stack.primary === 'Dart'
299
+ ? 'dart analyze --fatal-warnings'
300
+ : 'npm audit\nnpx audit-ci --critical'}
301
+
302
+ # Scan de secrets no código
303
+ # (configure pre-commit hook)
304
+ git secrets --scan
305
+ gitleaks detect
306
+
307
+ # Score de arquitetura (inclui métricas de segurança)
308
+ architect score ./src
309
+ architect anti-patterns ./src
310
+ \`\`\`
311
+
312
+ ---
313
+
314
+ **Gerado por Architect v3.1 · Score: ${report.score.overall}/100**
315
+ `;
316
+ }
317
+
318
+ function buildValidationPatterns(ctx: TemplateContext): string {
319
+ const { stack } = ctx;
320
+
321
+ if (stack.frameworks.includes('NestJS')) {
322
+ return `### NestJS — class-validator + class-transformer
323
+
324
+ \`\`\`typescript
325
+ // ✅ CORRETO: DTO com validação
326
+ import { IsString, IsEmail, MinLength, MaxLength, IsOptional } from 'class-validator';
327
+
328
+ export class CreateUserDto {
329
+ @IsString()
330
+ @MinLength(2)
331
+ @MaxLength(100)
332
+ name: string;
333
+
334
+ @IsEmail()
335
+ email: string;
336
+
337
+ @IsString()
338
+ @MinLength(8)
339
+ @MaxLength(128)
340
+ password: string;
341
+ }
342
+
343
+ // Controller com ValidationPipe
344
+ @Post()
345
+ @UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
346
+ async create(@Body() dto: CreateUserDto) { ... }
347
+ \`\`\`
348
+
349
+ **Regras:**
350
+ - \`whitelist: true\` — remove campos não declarados no DTO
351
+ - \`forbidNonWhitelisted: true\` — retorna 400 se campo extra enviado
352
+ - \`transform: true\` — converte tipos automaticamente
353
+ - NUNCA usar \`@Body()\` sem DTO validado`;
354
+ }
355
+
356
+ if (stack.primary === 'Python') {
357
+ return `### Python — Pydantic / marshmallow
358
+
359
+ \`\`\`python
360
+ # ✅ CORRETO: Schema com validação
361
+ from pydantic import BaseModel, EmailStr, Field, validator
362
+
363
+ class CreateUserSchema(BaseModel):
364
+ name: str = Field(min_length=2, max_length=100)
365
+ email: EmailStr
366
+ password: str = Field(min_length=8, max_length=128)
367
+
368
+ @validator('name')
369
+ def name_must_be_alphanumeric(cls, v):
370
+ if not v.replace(' ', '').isalnum():
371
+ raise ValueError('Name must be alphanumeric')
372
+ return v.strip()
373
+ \`\`\`
374
+
375
+ **Regras:**
376
+ - Pydantic \`BaseModel\` ou marshmallow \`Schema\` para TODOS os inputs
377
+ - \`Field()\` com min/max constraints
378
+ - Custom validators para regras de negócio
379
+ - NUNCA usar \`request.json\` diretamente sem validação`;
380
+ }
381
+
382
+ // Generic
383
+ return `### Validação de Input — Padrão Geral
384
+
385
+ \`\`\`
386
+ Regras de validação:
387
+ 1. TODOS os inputs passam por schema validation
388
+ 2. Tipos verificados (string, number, email, etc.)
389
+ 3. Limites definidos (min/max length, ranges)
390
+ 4. Whitelist de campos aceitos
391
+ 5. Sanitização de caracteres especiais
392
+ 6. Encoding correto (UTF-8)
393
+
394
+ Pipeline:
395
+ Request → Schema Validation → Sanitization → Business Logic
396
+
397
+ NUNCA:
398
+ ❌ request.body direto na lógica
399
+ ❌ Confiar em validação client-side apenas
400
+ ❌ Aceitar campos não declarados
401
+ \`\`\``;
402
+ }
403
+
404
+ function buildAuthPatterns(ctx: TemplateContext): string {
405
+ const { stack } = ctx;
406
+
407
+ if (stack.frameworks.includes('NestJS')) {
408
+ return `### NestJS Auth Pattern
409
+
410
+ \`\`\`
411
+ Implementação padrão:
412
+ 1. AuthGuard global para rotas protegidas
413
+ 2. @Public() decorator para rotas abertas
414
+ 3. RolesGuard para autorização
415
+ 4. CurrentUser decorator para extrair user do token
416
+
417
+ Hierarquia:
418
+ @Public() → Sem autenticação
419
+ @UseGuards(AuthGuard) → Autenticado
420
+ @Roles('admin') → Autenticado + Role específica
421
+ @OwnerGuard() → Autenticado + Dono do recurso
422
+
423
+ Fluxo de token:
424
+ Login → Access Token (15min) + Refresh Token (7d, httpOnly cookie)
425
+ Request → AuthGuard verifica Access Token
426
+ Expired → Refresh endpoint gera novo par
427
+ Logout → Invalidar Refresh Token no banco
428
+ \`\`\``;
429
+ }
430
+
431
+ // Generic
432
+ return `### Padrão de Autenticação/Autorização
433
+
434
+ \`\`\`
435
+ Fluxo obrigatório:
436
+ 1. Autenticar: Verificar identidade (JWT/session)
437
+ 2. Autorizar: Verificar permissões (roles/policies)
438
+ 3. Ownership: Verificar se recurso pertence ao usuário
439
+ 4. Executar: Somente após passos 1-3
440
+
441
+ Token management:
442
+ - Access Token: curta duração (15min)
443
+ - Refresh Token: longa duração (7d), httpOnly, secure
444
+ - Rotation: novo refresh token a cada uso
445
+ - Blacklist: invalidar tokens no logout
446
+
447
+ RBAC mínimo:
448
+ - admin: tudo
449
+ - user: próprios recursos
450
+ - public: endpoints marcados explicitamente
451
+ \`\`\``;
452
+ }
453
+
454
+ function buildSecretsRules(ctx: TemplateContext): string {
455
+ const { stack } = ctx;
456
+
457
+ return `### Regras de Secrets
458
+
459
+ \`\`\`
460
+ ╔══════════════════════════════════════════════════════════════╗
461
+ ║ SECRETS NUNCA NO CÓDIGO. NUNCA. SEM EXCEÇÃO. ║
462
+ ╚══════════════════════════════════════════════════════════════╝
463
+
464
+ ❌ PROIBIDO:
465
+ - API keys hardcoded
466
+ - Passwords em arquivos de config
467
+ - Tokens em constantes
468
+ - Connection strings com credenciais no código
469
+ - .env commitado no repositório
470
+
471
+ ✅ CORRETO:
472
+ - Environment variables
473
+ - Secret manager (AWS SSM, Vault, GCP Secret Manager)
474
+ - .env.example com placeholders (sem valores reais)
475
+ - .gitignore com: .env, .env.local, .env.*.local
476
+ \`\`\`
477
+
478
+ ### .gitignore obrigatório
479
+
480
+ \`\`\`
481
+ # Secrets — NUNCA commitar
482
+ .env
483
+ .env.local
484
+ .env.*.local
485
+ *.pem
486
+ *.key
487
+ *.p12
488
+ credentials.json
489
+ service-account.json
490
+ \`\`\`
491
+
492
+ ### Detecção de secrets no CI
493
+
494
+ \`\`\`bash
495
+ # Pre-commit hook (recomendado)
496
+ # .pre-commit-config.yaml
497
+ repos:
498
+ - repo: https://github.com/gitleaks/gitleaks
499
+ rev: v8.18.0
500
+ hooks:
501
+ - id: gitleaks
502
+
503
+ # Ou manualmente:
504
+ gitleaks detect --source . --verbose
505
+ git secrets --scan
506
+ \`\`\`
507
+
508
+ ### Padrão de configuração
509
+
510
+ \`\`\`${stack.primary === 'Python' ? 'python' : 'typescript'}
511
+ ${stack.primary === 'Python'
512
+ ? `# ✅ CORRETO
513
+ import os
514
+ from pydantic_settings import BaseSettings
515
+
516
+ class Settings(BaseSettings):
517
+ database_url: str
518
+ jwt_secret: str
519
+ redis_url: str = "redis://localhost:6379"
520
+
521
+ class Config:
522
+ env_file = ".env"
523
+
524
+ settings = Settings() # Carrega de environment variables`
525
+ : `// ✅ CORRETO
526
+ const config = {
527
+ database: {
528
+ url: process.env.DATABASE_URL, // De environment variable
529
+ ssl: process.env.DB_SSL === 'true',
530
+ },
531
+ jwt: {
532
+ secret: process.env.JWT_SECRET, // NUNCA hardcoded
533
+ expiresIn: '15m',
534
+ },
535
+ };
536
+
537
+ // Validação no startup — falha rápido se falta secret
538
+ const required = ['DATABASE_URL', 'JWT_SECRET'];
539
+ for (const key of required) {
540
+ if (!process.env[key]) throw new Error(\\\`Missing env: \\\${key}\\\`);
541
+ }`}
542
+ \`\`\``;
543
+ }