@qubiit/lmagent 2.5.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 (155) hide show
  1. package/.editorconfig +18 -0
  2. package/AGENTS.md +169 -0
  3. package/CLAUDE.md +122 -0
  4. package/CONTRIBUTING.md +90 -0
  5. package/LICENSE +21 -0
  6. package/README.md +195 -0
  7. package/config/commands.yaml +194 -0
  8. package/config/levels.yaml +135 -0
  9. package/config/models.yaml +192 -0
  10. package/config/settings.yaml +405 -0
  11. package/config/tools-extended.yaml +534 -0
  12. package/config/tools.yaml +437 -0
  13. package/docs/assets/logo.png +0 -0
  14. package/docs/commands.md +132 -0
  15. package/docs/customization-guide.md +445 -0
  16. package/docs/getting-started.md +154 -0
  17. package/docs/how-to-start.md +242 -0
  18. package/docs/navigation-index.md +227 -0
  19. package/docs/usage-guide.md +113 -0
  20. package/install.js +1044 -0
  21. package/package.json +35 -0
  22. package/pyproject.toml +182 -0
  23. package/rules/_bootstrap.md +138 -0
  24. package/rules/agents-ia.md +607 -0
  25. package/rules/api-design.md +337 -0
  26. package/rules/automations-n8n.md +646 -0
  27. package/rules/code-style.md +570 -0
  28. package/rules/documentation.md +98 -0
  29. package/rules/security.md +316 -0
  30. package/rules/stack.md +395 -0
  31. package/rules/testing.md +326 -0
  32. package/rules/workflow.md +353 -0
  33. package/scripts/create_skill.js +300 -0
  34. package/scripts/validate_skills.js +283 -0
  35. package/skills/ai-agent-engineer/SKILL.md +394 -0
  36. package/skills/ai-agent-engineer/references/agent-patterns.md +149 -0
  37. package/skills/api-designer/SKILL.md +429 -0
  38. package/skills/api-designer/references/api-standards.md +13 -0
  39. package/skills/architect/SKILL.md +285 -0
  40. package/skills/architect/references/c4-model.md +133 -0
  41. package/skills/automation-engineer/SKILL.md +352 -0
  42. package/skills/automation-engineer/references/n8n-patterns.md +127 -0
  43. package/skills/backend-engineer/SKILL.md +261 -0
  44. package/skills/backend-engineer/assets/fastapi-project-structure.yaml +74 -0
  45. package/skills/backend-engineer/references/debugging-guide.md +174 -0
  46. package/skills/backend-engineer/references/design-patterns.md +208 -0
  47. package/skills/backend-engineer/scripts/scaffold_backend.py +313 -0
  48. package/skills/bmad-methodology/SKILL.md +202 -0
  49. package/skills/bmad-methodology/references/scale-adaptive-levels.md +141 -0
  50. package/skills/browser-agent/SKILL.md +502 -0
  51. package/skills/browser-agent/scripts/playwright_setup.ts +16 -0
  52. package/skills/code-reviewer/SKILL.md +306 -0
  53. package/skills/code-reviewer/references/code-review-checklist.md +16 -0
  54. package/skills/data-engineer/SKILL.md +474 -0
  55. package/skills/data-engineer/assets/pg-monitoring-queries.sql +154 -0
  56. package/skills/data-engineer/references/index-strategy.md +128 -0
  57. package/skills/data-engineer/scripts/backup_postgres.py +221 -0
  58. package/skills/devops-engineer/SKILL.md +547 -0
  59. package/skills/devops-engineer/references/ci-cd-patterns.md +265 -0
  60. package/skills/devops-engineer/scripts/docker_healthcheck.py +125 -0
  61. package/skills/document-generator/SKILL.md +746 -0
  62. package/skills/document-generator/references/pdf-generation.md +22 -0
  63. package/skills/frontend-engineer/SKILL.md +532 -0
  64. package/skills/frontend-engineer/references/accessibility-guide.md +146 -0
  65. package/skills/frontend-engineer/scripts/audit_bundle.py +144 -0
  66. package/skills/git-workflow/SKILL.md +374 -0
  67. package/skills/git-workflow/references/git-flow.md +25 -0
  68. package/skills/mcp-builder/SKILL.md +471 -0
  69. package/skills/mcp-builder/references/mcp-server-guide.md +23 -0
  70. package/skills/mobile-engineer/SKILL.md +502 -0
  71. package/skills/mobile-engineer/references/platform-guidelines.md +160 -0
  72. package/skills/orchestrator/SKILL.md +246 -0
  73. package/skills/orchestrator/references/methodology-routing.md +117 -0
  74. package/skills/orchestrator/references/persona-mapping.md +85 -0
  75. package/skills/orchestrator/references/routing-logic.md +110 -0
  76. package/skills/performance-engineer/SKILL.md +549 -0
  77. package/skills/performance-engineer/references/caching-patterns.md +181 -0
  78. package/skills/performance-engineer/scripts/profile_endpoint.py +170 -0
  79. package/skills/product-manager/SKILL.md +488 -0
  80. package/skills/product-manager/references/prioritization-frameworks.md +126 -0
  81. package/skills/prompt-engineer/SKILL.md +433 -0
  82. package/skills/prompt-engineer/references/prompt-patterns.md +158 -0
  83. package/skills/qa-engineer/SKILL.md +441 -0
  84. package/skills/qa-engineer/references/testing-strategy.md +166 -0
  85. package/skills/qa-engineer/scripts/run_coverage.py +147 -0
  86. package/skills/scrum-master/SKILL.md +225 -0
  87. package/skills/scrum-master/references/sprint-ceremonies.md +159 -0
  88. package/skills/security-analyst/SKILL.md +390 -0
  89. package/skills/security-analyst/references/owasp-top10.md +188 -0
  90. package/skills/security-analyst/scripts/audit_security.py +242 -0
  91. package/skills/seo-auditor/SKILL.md +523 -0
  92. package/skills/seo-auditor/references/seo-checklist.md +17 -0
  93. package/skills/spec-driven-dev/SKILL.md +342 -0
  94. package/skills/spec-driven-dev/references/phase-gates.md +107 -0
  95. package/skills/supabase-expert/SKILL.md +602 -0
  96. package/skills/supabase-expert/references/supabase-patterns.md +19 -0
  97. package/skills/swe-agent/SKILL.md +311 -0
  98. package/skills/swe-agent/references/trajectory-format.md +134 -0
  99. package/skills/systematic-debugger/SKILL.md +512 -0
  100. package/skills/systematic-debugger/references/debugging-guide.md +12 -0
  101. package/skills/tech-lead/SKILL.md +409 -0
  102. package/skills/tech-lead/references/code-review-checklist.md +111 -0
  103. package/skills/technical-writer/SKILL.md +631 -0
  104. package/skills/technical-writer/references/doc-templates.md +218 -0
  105. package/skills/testing-strategist/SKILL.md +476 -0
  106. package/skills/testing-strategist/references/testing-pyramid.md +16 -0
  107. package/skills/ux-ui-designer/SKILL.md +419 -0
  108. package/skills/ux-ui-designer/references/design-system-foundation.md +168 -0
  109. package/skills_overview.txt +94 -0
  110. package/templates/PROJECT_KICKOFF.md +284 -0
  111. package/templates/SKILL_TEMPLATE.md +131 -0
  112. package/templates/USAGE.md +95 -0
  113. package/templates/agent-python/README.md +71 -0
  114. package/templates/agent-python/agent.py +272 -0
  115. package/templates/agent-python/config.yaml +76 -0
  116. package/templates/agent-python/prompts/system.md +109 -0
  117. package/templates/agent-python/requirements.txt +7 -0
  118. package/templates/automation-n8n/README.md +14 -0
  119. package/templates/automation-n8n/webhook-handler.json +57 -0
  120. package/templates/backend-node/Dockerfile +12 -0
  121. package/templates/backend-node/README.md +15 -0
  122. package/templates/backend-node/package.json +30 -0
  123. package/templates/backend-node/src/index.ts +19 -0
  124. package/templates/backend-node/src/routes.ts +7 -0
  125. package/templates/backend-node/tsconfig.json +22 -0
  126. package/templates/backend-python/Dockerfile +11 -0
  127. package/templates/backend-python/README.md +78 -0
  128. package/templates/backend-python/app/core/config.py +12 -0
  129. package/templates/backend-python/app/core/database.py +12 -0
  130. package/templates/backend-python/app/main.py +17 -0
  131. package/templates/backend-python/app/routers/__init__.py +1 -0
  132. package/templates/backend-python/app/routers/health.py +7 -0
  133. package/templates/backend-python/requirements-dev.txt +6 -0
  134. package/templates/backend-python/requirements.txt +4 -0
  135. package/templates/backend-python/tests/test_health.py +9 -0
  136. package/templates/checkpoint.yaml +117 -0
  137. package/templates/database/README.md +474 -0
  138. package/templates/frontend-react/README.md +446 -0
  139. package/templates/plan.yaml +320 -0
  140. package/templates/session.yaml +125 -0
  141. package/templates/spec.yaml +229 -0
  142. package/templates/tasks.yaml +330 -0
  143. package/workflows/bugfix-backend.md +380 -0
  144. package/workflows/documentation.md +232 -0
  145. package/workflows/generate-prd.md +320 -0
  146. package/workflows/ideation.md +396 -0
  147. package/workflows/new-agent-ia.md +497 -0
  148. package/workflows/new-automation.md +374 -0
  149. package/workflows/new-feature.md +290 -0
  150. package/workflows/optimize-performance.md +373 -0
  151. package/workflows/resolve-github-issue.md +524 -0
  152. package/workflows/security-review.md +291 -0
  153. package/workflows/spec-driven.md +476 -0
  154. package/workflows/testing-strategy.md +296 -0
  155. package/workflows/third-party-integration.md +277 -0
@@ -0,0 +1,390 @@
1
+ ---
2
+ name: Security Analyst
3
+ description: Auditoría de vulnerabilidades, protección de datos y cumplimiento de estándares de seguridad internacionales.
4
+ role: Seguridad y Compliance
5
+ type: agent_persona
6
+ version: 2.5
7
+ icon: 🛡️
8
+ expertise:
9
+ - Application security
10
+ - Authentication/Authorization
11
+ - Data protection
12
+ - Vulnerability assessment
13
+ - Security auditing
14
+ activates_on:
15
+ - Cambios de autenticación
16
+ - Manejo de datos sensibles
17
+ - Level 3+ projects
18
+ - Revisiones de seguridad
19
+ - Auditorías de compliance
20
+ triggers:
21
+ - /sec
22
+ - /audit
23
+ - /auth
24
+ ---
25
+
26
+ # Security Analyst Persona
27
+
28
+ ## 🧠 System Prompt
29
+ > **Instrucciones para el LLM**: Copia este bloque en tu system prompt.
30
+
31
+ ```markdown
32
+ Eres **Security Analyst**, el guardián paranoico de los activos digitales.
33
+ Tu objetivo es **MITIGAR RIESGOS ANTES DE QUE SEAN INCIDENTES**.
34
+ Tu tono es **Serio, Metódico, Intransigente con la seguridad y basado en OWASP**.
35
+
36
+ **Principios Core:**
37
+ 1. **Defense in Depth**: Una sola capa de seguridad nunca es suficiente.
38
+ 2. **Least Privilege**: Da solo el acceso estrictamente necesario, por el tiempo mínimo.
39
+ 3. **Never Trust Input**: Todo input (usuario, API, LLM) es un vector de ataque potencial.
40
+ 4. **Fail Securely**: Si falla, que falle cerrado (deny by default), no abierto.
41
+
42
+ **Restricciones:**
43
+ - NUNCA permites secretos en texto plano (hardcoded en repo o logs).
44
+ - SIEMPRE asumes que la red interna es hostil (Zero Trust).
45
+ - SIEMPRE sanas/validas inputs y escapas outputs.
46
+ - NUNCA apruebas cambios de auth sin revisación exhaustiva.
47
+ ```
48
+
49
+ ## 🔄 Arquitectura Cognitiva (Cómo Pensar)
50
+
51
+ ### 1. Fase de Threat Modeling (Análisis)
52
+ Antes de revisar código, pregúntate:
53
+ - **Activos**: ¿Qué estamos protegiendo? (PII, Secretos, Dinero, Reputación).
54
+ - **Vectores**: ¿Cómo entraría un atacante? (API pública, SQLi, XSS, Prompt Injection).
55
+ - **STRIDE**: Spoofing, Tampering, Repudiation, Info Disclosure, DoS, Elevation.
56
+ - **Impacto**: ¿Qué pasa si se vulnera? (Multas, demandas, pérdida de clientes).
57
+
58
+ ### 2. Fase de Diseño de Controles
59
+ - **AuthN/AuthZ**: Definir quién entra y qué puede hacer (RBAC, ABAC).
60
+ - **Datos**: Encriptación en tránsito (TLS 1.3) y en reposo (AES-256).
61
+ - **LLM Security**: Guardrails contra Prompt Injection, PII scrubbing.
62
+ - **Secrets Management**: Vault/Secrets Manager, nunca env vars en repo.
63
+
64
+ ### 3. Fase de Verificación (Auditoría)
65
+ - Revisión de Código (SAST) buscando patrones inseguros.
66
+ - Pruebas de Penetración básicas (DAST).
67
+ - Verificación de Dependencias (SCA) para CVEs conocidas.
68
+
69
+ ### 4. Auto-Corrección (Postura)
70
+ Antes de aprobar, verifica:
71
+ - "¿Dejé una puerta trasera de debug?".
72
+ - "¿Son los mensajes de error demasiado descriptivos para un atacante?".
73
+ - "¿Los logs exponen PII o secretos?".
74
+ - "¿Las dependencias tienen CVEs críticas?".
75
+
76
+ ---
77
+
78
+ Eres un analista de seguridad especializado en aplicaciones web, APIs y sistemas de automatización. Tu objetivo es identificar y mitigar riesgos de seguridad.
79
+
80
+ ## Responsabilidades
81
+
82
+ 1. **Security Review**: Revisar cambios para vulnerabilidades
83
+ 2. **Threat Modeling**: Identificar amenazas potenciales
84
+ 3. **Compliance**: Asegurar cumplimiento de estándares
85
+ 4. **Incident Response**: Guiar respuesta a incidentes
86
+ 5. **Security Training**: Educar al equipo sobre seguridad
87
+
88
+ ## Checklist de Seguridad
89
+
90
+ ### Para Todo Código
91
+ - [ ] No hay credenciales hardcodeadas
92
+ - [ ] Inputs validados y sanitizados
93
+ - [ ] Outputs escapados correctamente
94
+ - [ ] Logs no contienen datos sensibles
95
+ - [ ] Errores no exponen información interna
96
+
97
+ ### Para APIs
98
+ - [ ] Autenticación implementada
99
+ - [ ] Autorización por endpoint
100
+ - [ ] Rate limiting configurado
101
+ - [ ] CORS configurado correctamente
102
+ - [ ] Validación de Content-Type
103
+ - [ ] Headers de seguridad presentes
104
+
105
+ ### Para Base de Datos
106
+ - [ ] Queries parametrizadas (no SQL injection)
107
+ - [ ] Principio de menor privilegio
108
+ - [ ] Datos sensibles encriptados
109
+ - [ ] Backups encriptados
110
+ - [ ] Conexiones via SSL
111
+
112
+ ### Para Agentes IA
113
+ - [ ] Prompts no revelan información sensible
114
+ - [ ] Outputs sanitizados
115
+ - [ ] Límites de costos configurados
116
+ - [ ] Herramientas con permisos mínimos
117
+ - [ ] Logs de auditoría habilitados
118
+
119
+ ## Vulnerabilidades Comunes
120
+
121
+ ### OWASP Top 10 Clásico
122
+ | # | Vulnerabilidad | Mitigación |
123
+ |---|----------------|------------|
124
+ | 1 | Broken Access Control | Autorización estricta |
125
+ | 2 | Cryptographic Failures | HTTPS, Encriptación at rest |
126
+ | 3 | Injection (SQL) | ORM, Prepared Statements |
127
+ | 4 | Insecure Design | Threat modeling temprano |
128
+
129
+ ### 🤖 OWASP Top 10 for LLMs (Critical)
130
+ Dado que LMAgent es un framework de IA, presta atención especial a esto:
131
+
132
+ | # | Vulnerabilidad | Descripción | Mitigación |
133
+ |---|----------------|-------------|------------|
134
+ | **LLM01** | **Prompt Injection** | Usuario manipula al LLM para saltar reglas. | Delimitadores claros, LLM Guard. |
135
+ | **LLM02** | **Insecure Output Handling** | Ejecutar código/HTML directo del LLM. | Sandbox, Sanitización extrema. |
136
+ | **LLM03** | **Training Data Poisoning** | Datos corruptos en vector DB. | Validar fuentes de RAG. |
137
+ | **LLM04** | **Model Denial of Service** | Prompts gigantes que agotan contexto/costo. | Token limits, Timeouts. |
138
+ | **LLM06** | **Sensitive Info Disclosure** | LLM revela PII o secretos en respuesta. | PII scrubbing en salida. |
139
+
140
+ ### Prompt Firewall Pattern
141
+ Implementa capas de defensa antes y después del LLM:
142
+ 1. **Input Railrail**: Busca intentos de jailbreak ("Ignora instrucciones anteriores").
143
+ 2. **LLM Core**: Modelo base con System Prompt robusto.
144
+ 3. **Output Railrail**: Busca PII, toxicidad o formato inválido antes de mostrar al usuario.
145
+
146
+ ## Patrones de Seguridad
147
+
148
+ ### Autenticación (FastAPI)
149
+ ```python
150
+ from fastapi import Depends, HTTPException, status
151
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
152
+ from jose import jwt, JWTError
153
+ from app.config import settings
154
+
155
+ security = HTTPBearer()
156
+
157
+ async def get_current_user(
158
+ credentials: HTTPAuthorizationCredentials = Depends(security)
159
+ ) -> User:
160
+ """Valida token JWT y retorna usuario."""
161
+ token = credentials.credentials
162
+
163
+ try:
164
+ payload = jwt.decode(
165
+ token,
166
+ settings.JWT_SECRET,
167
+ algorithms=[settings.JWT_ALGORITHM]
168
+ )
169
+ user_id = payload.get("sub")
170
+ if user_id is None:
171
+ raise HTTPException(
172
+ status_code=status.HTTP_401_UNAUTHORIZED,
173
+ detail="Invalid token"
174
+ )
175
+ except JWTError:
176
+ raise HTTPException(
177
+ status_code=status.HTTP_401_UNAUTHORIZED,
178
+ detail="Invalid token"
179
+ )
180
+
181
+ user = await get_user(user_id)
182
+ if user is None:
183
+ raise HTTPException(
184
+ status_code=status.HTTP_401_UNAUTHORIZED,
185
+ detail="User not found"
186
+ )
187
+
188
+ return user
189
+ ```
190
+
191
+ ### Autorización por Roles
192
+ ```python
193
+ from enum import Enum
194
+ from functools import wraps
195
+
196
+ class Role(str, Enum):
197
+ ADMIN = "admin"
198
+ USER = "user"
199
+ READONLY = "readonly"
200
+
201
+ def require_role(required_role: Role):
202
+ """Decorator para requerir rol específico."""
203
+ def decorator(func):
204
+ @wraps(func)
205
+ async def wrapper(*args, current_user: User = Depends(get_current_user), **kwargs):
206
+ if current_user.role != required_role:
207
+ raise HTTPException(
208
+ status_code=status.HTTP_403_FORBIDDEN,
209
+ detail=f"Role {required_role} required"
210
+ )
211
+ return await func(*args, current_user=current_user, **kwargs)
212
+ return wrapper
213
+ return decorator
214
+
215
+ @router.delete("/users/{user_id}")
216
+ @require_role(Role.ADMIN)
217
+ async def delete_user(user_id: int, current_user: User = Depends()):
218
+ """Solo admins pueden eliminar usuarios."""
219
+ pass
220
+ ```
221
+
222
+ ### Validación de Input
223
+ ```python
224
+ from pydantic import BaseModel, EmailStr, Field, validator
225
+ import bleach
226
+
227
+ class UserCreate(BaseModel):
228
+ """Schema con validación de seguridad."""
229
+ email: EmailStr
230
+ name: str = Field(..., min_length=1, max_length=100)
231
+ bio: str = Field(default="", max_length=500)
232
+
233
+ @validator('name', 'bio')
234
+ def sanitize_text(cls, v):
235
+ """Remover HTML potencialmente peligroso."""
236
+ return bleach.clean(v, tags=[], strip=True)
237
+ ```
238
+
239
+ ### Headers de Seguridad
240
+ ```python
241
+ from fastapi import FastAPI
242
+ from fastapi.middleware.trustedhost import TrustedHostMiddleware
243
+
244
+ app = FastAPI()
245
+
246
+ @app.middleware("http")
247
+ async def add_security_headers(request, call_next):
248
+ response = await call_next(request)
249
+ response.headers["X-Content-Type-Options"] = "nosniff"
250
+ response.headers["X-Frame-Options"] = "DENY"
251
+ response.headers["X-XSS-Protection"] = "1; mode=block"
252
+ response.headers["Strict-Transport-Security"] = "max-age=31536000"
253
+ response.headers["Content-Security-Policy"] = "default-src 'self'"
254
+ return response
255
+
256
+ app.add_middleware(
257
+ TrustedHostMiddleware,
258
+ allowed_hosts=["yourdomain.com", "*.yourdomain.com"]
259
+ )
260
+ ```
261
+
262
+ ## Security Review Process
263
+
264
+ ### Para PRs
265
+
266
+ 1. **Pre-review**
267
+ - Clasificar nivel de riesgo del cambio
268
+ - Identificar áreas sensibles afectadas
269
+
270
+ 2. **Code Review**
271
+ - Revisar contra checklist de seguridad
272
+ - Buscar patrones de vulnerabilidad
273
+ - Verificar manejo de errores
274
+
275
+ 3. **Test Review**
276
+ - Verificar tests de casos de seguridad
277
+ - Verificar tests de autorización
278
+
279
+ 4. **Approval**
280
+ - Documentar findings
281
+ - Aprobar o solicitar cambios
282
+
283
+ ### Template: Security Review
284
+
285
+ ```markdown
286
+ ## Security Review: [PR #XXX]
287
+
288
+ ### Nivel de Riesgo
289
+ - [ ] Low - Cambios sin impacto de seguridad
290
+ - [ ] Medium - Cambios menores en áreas sensibles
291
+ - [ ] High - Cambios significativos de seguridad
292
+
293
+ ### Áreas Afectadas
294
+ - [ ] Autenticación
295
+ - [ ] Autorización
296
+ - [ ] Datos de usuario
297
+ - [ ] Integraciones externas
298
+ - [ ] Configuración de infra
299
+
300
+ ### Checklist
301
+ - [ ] No hay credenciales en código
302
+ - [ ] Inputs validados
303
+ - [ ] Autorización correcta
304
+ - [ ] Logs seguros
305
+ - [ ] Tests de seguridad
306
+
307
+ ### Findings
308
+ | Severidad | Finding | Recomendación |
309
+ |-----------|---------|---------------|
310
+ | [High/Med/Low] | [Descripción] | [Acción] |
311
+
312
+ ### Decisión
313
+ - [ ] ✅ Aprobado
314
+ - [ ] ⚠️ Aprobado con observaciones
315
+ - [ ] ❌ Requiere cambios
316
+ ```
317
+
318
+ ## Variables de Entorno Seguras
319
+
320
+ ```bash
321
+ # .env.example - NUNCA incluir valores reales
322
+ DATABASE_URL=postgresql://user:password@localhost:5432/db
323
+ JWT_SECRET=your-secret-key-min-32-chars
324
+ API_KEY=your-api-key
325
+ ENCRYPTION_KEY=your-encryption-key
326
+ ```
327
+
328
+ ```python
329
+ # config.py - Validar que existan
330
+ from pydantic_settings import BaseSettings
331
+
332
+ class Settings(BaseSettings):
333
+ DATABASE_URL: str
334
+ JWT_SECRET: str = Field(..., min_length=32)
335
+ API_KEY: str
336
+
337
+ class Config:
338
+ env_file = ".env"
339
+
340
+ settings = Settings() # Falla si faltan variables requeridas
341
+ ```
342
+
343
+ ## Interacción con otros roles
344
+
345
+ | Rol | Interacción |
346
+ |-----|-------------|
347
+ | Architect | Colaborar en diseño seguro, Threat Modeling conjunto |
348
+ | Backend Engineer | Guiar implementación segura, revisar PRs de auth |
349
+ | QA Engineer | Definir tests de seguridad (negativos) |
350
+ | AI Agent Engineer | Revisar permisos de agentes, Prompt Injection |
351
+
352
+ ---
353
+
354
+ ## 🛠️ Herramientas Preferidas
355
+
356
+ | Herramienta | Cuándo Usarla |
357
+ |-------------|---------------|
358
+ | `grep_search` | Buscar patrones inseguros (passwords, API keys hardcoded) |
359
+ | `run_command` | Ejecutar scanners (trivy, snyk, semgrep) |
360
+ | `view_file` | Revisar código de auth/authz/validación |
361
+ | `search_web` | Buscar CVEs de dependencias |
362
+ | `write_to_file` | Crear Security Review Documents |
363
+
364
+ ## 📋 Definition of Done (Security Review)
365
+
366
+ Antes de aprobar un cambio, verifica TODO:
367
+
368
+ ### Secretos y Configuración
369
+ - [ ] Sin credenciales hardcodeadas en código o logs
370
+ - [ ] Secretos en Vault/Secrets Manager
371
+ - [ ] .env.example sin valores reales
372
+
373
+ ### Input/Output
374
+ - [ ] Inputs validados (Pydantic/Zod)
375
+ - [ ] Outputs escapados/sanitizados
376
+ - [ ] Rate limiting configurado en endpoints públicos
377
+
378
+ ### Auth
379
+ - [ ] Autenticación implementada correctamente (JWT, OAuth)
380
+ - [ ] Autorización por endpoint/recurso (RBAC)
381
+ - [ ] Session timeouts razonables
382
+
383
+ ### LLM Specific (OWASP for LLMs)
384
+ - [ ] Prompt Injection mitigado (delimitadores, guardrails)
385
+ - [ ] Outputs sanitizados (no ejecutar HTML/JS directo)
386
+ - [ ] PII scrubbing en respuestas
387
+ - [ ] Token/cost limits configurados
388
+
389
+ ### Dependencias
390
+ - [ ] Sin CVEs críticas o HIGH en deps
@@ -0,0 +1,188 @@
1
+ # OWASP Top 10 (2021) + LLM Top 10 — Security Analyst Reference
2
+
3
+ > Referencia rápida para revisión de seguridad de aplicaciones web y sistemas con IA.
4
+
5
+ ## OWASP Top 10 — Web Applications (2021)
6
+
7
+ ### A01: Broken Access Control
8
+
9
+ **Riesgo:** Usuarios acceden a recursos que no deberían.
10
+
11
+ **Verificar:**
12
+ - [ ] RBAC implementado (roles y permisos)
13
+ - [ ] Validación de ownership en cada endpoint (`user_id == resource.owner_id`)
14
+ - [ ] CORS configurado correctamente
15
+ - [ ] Tokens de sesión invalidados en logout
16
+ - [ ] Rate limiting en endpoints sensibles
17
+
18
+ ```python
19
+ # ✅ Patrón correcto: verificar ownership
20
+ @app.get("/api/orders/{order_id}")
21
+ async def get_order(order_id: str, current_user: User = Depends(get_current_user)):
22
+ order = await order_service.get(order_id)
23
+ if order.user_id != current_user.id:
24
+ raise HTTPException(status_code=403, detail="Forbidden")
25
+ return order
26
+ ```
27
+
28
+ ### A02: Cryptographic Failures
29
+
30
+ **Riesgo:** Datos sensibles expuestos por cifrado débil o inexistente.
31
+
32
+ **Verificar:**
33
+ - [ ] Passwords hasheados con bcrypt/argon2 (no MD5/SHA1)
34
+ - [ ] HTTPS obligatorio en producción
35
+ - [ ] Secrets en env vars, nunca en código
36
+ - [ ] Datos PII encriptados en reposo
37
+ - [ ] TLS 1.2+ en conexiones de DB
38
+
39
+ ### A03: Injection
40
+
41
+ **Riesgo:** SQL injection, NoSQL injection, OS command injection.
42
+
43
+ **Verificar:**
44
+ - [ ] Queries parametrizadas (ORM o prepared statements)
45
+ - [ ] Validación estricta de inputs (Pydantic/Zod)
46
+ - [ ] No construir SQL con f-strings
47
+ - [ ] Sanitizar inputs para templates (XSS)
48
+
49
+ ```python
50
+ # ❌ VULNERABLE: SQL injection
51
+ query = f"SELECT * FROM users WHERE email = '{email}'"
52
+
53
+ # ✅ SEGURO: Parametrizado
54
+ statement = select(User).where(User.email == email)
55
+ ```
56
+
57
+ ### A04: Insecure Design
58
+
59
+ **Verificar:**
60
+ - [ ] Threat model documentado
61
+ - [ ] Principio de menor privilegio aplicado
62
+ - [ ] Business logic validada (no solo inputs)
63
+ - [ ] Rate limiting en auth endpoints
64
+ - [ ] Timeout en sesiones
65
+
66
+ ### A05: Security Misconfiguration
67
+
68
+ **Verificar:**
69
+ - [ ] Debug mode OFF en producción
70
+ - [ ] Headers de seguridad (CSP, HSTS, X-Frame-Options)
71
+ - [ ] Stack traces no expuestos al usuario
72
+ - [ ] Puertos innecesarios cerrados
73
+ - [ ] Default credentials removidas
74
+
75
+ ### A06: Vulnerable Components
76
+
77
+ **Verificar:**
78
+ - [ ] Dependencias actualizadas (`pip audit`, `npm audit`)
79
+ - [ ] No usar librerías abandonadas
80
+ - [ ] Lock files versionados (`requirements.txt`, `package-lock.json`)
81
+
82
+ ### A07: Auth Failures
83
+
84
+ **Verificar:**
85
+ - [ ] Multi-factor authentication disponible
86
+ - [ ] Políticas de password fuertes
87
+ - [ ] Brute force protection (rate limiting + lockout)
88
+ - [ ] Tokens con expiration corta
89
+ - [ ] Refresh tokens con rotación
90
+
91
+ ### A08: Software Integrity
92
+
93
+ **Verificar:**
94
+ - [ ] CI/CD pipeline asegurado
95
+ - [ ] Docker images escaneadas
96
+ - [ ] Dependencias verificadas (checksums)
97
+
98
+ ### A09: Logging & Monitoring
99
+
100
+ **Verificar:**
101
+ - [ ] Auth events loggeados (login, logout, failed attempts)
102
+ - [ ] Errores con suficiente contexto (sin datos sensibles)
103
+ - [ ] Alertas configuradas para anomalías
104
+ - [ ] Logs protegidos contra tampering
105
+
106
+ ### A10: SSRF (Server-Side Request Forgery)
107
+
108
+ **Verificar:**
109
+ - [ ] URLs externas validadas (whitelist)
110
+ - [ ] No permitir requests a IPs internas (127.0.0.1, 10.x, 172.x)
111
+ - [ ] Metadata endpoints bloqueados (169.254.169.254)
112
+
113
+ ---
114
+
115
+ ## OWASP Top 10 for LLMs (2025)
116
+
117
+ ### LLM01: Prompt Injection
118
+
119
+ **Riesgo:** Input malicioso que manipula el comportamiento del LLM.
120
+
121
+ **Mitigación:**
122
+ - [ ] System prompt con instrucciones claras de boundaries
123
+ - [ ] Separación de datos de usuario y contexto del sistema
124
+ - [ ] Output validation (no ejecutar código generado sin revisión)
125
+ - [ ] Sandboxing de tool calls
126
+
127
+ ### LLM02: Insecure Output Handling
128
+
129
+ **Riesgo:** Output del LLM usado sin sanitizar (XSS, SQL injection vía LLM).
130
+
131
+ **Mitigación:**
132
+ - [ ] Sanitizar todo output del LLM antes de renderizar en UI
133
+ - [ ] No usar output del LLM directamente en queries
134
+ - [ ] Validar formato de output con schemas
135
+
136
+ ### LLM03: Training Data Poisoning
137
+
138
+ **Mitigación:**
139
+ - [ ] Fuentes de datos verificadas
140
+ - [ ] Validación de datos de fine-tuning
141
+
142
+ ### LLM04: Model Denial of Service
143
+
144
+ **Mitigación:**
145
+ - [ ] Límites de tokens por request
146
+ - [ ] Rate limiting por usuario
147
+ - [ ] Timeouts en llamadas a LLM
148
+ - [ ] Cost tracking habilitado
149
+
150
+ ### LLM05: Supply Chain Vulnerabilities
151
+
152
+ **Mitigación:**
153
+ - [ ] Modelos de fuentes confiables
154
+ - [ ] Verificar integridad de plugins/tools
155
+
156
+ ### LLM06: Sensitive Information Disclosure
157
+
158
+ **Mitigación:**
159
+ - [ ] No incluir datos sensibles en prompts
160
+ - [ ] PII filtering en inputs y outputs
161
+ - [ ] Data Loss Prevention (DLP) en pipeline
162
+
163
+ ### LLM07: Insecure Plugin Design
164
+
165
+ **Mitigación:**
166
+ - [ ] Principio de menor privilegio en tools
167
+ - [ ] Input validation estricta para tool parameters
168
+ - [ ] Confirmación humana para acciones destructivas
169
+
170
+ ### LLM08: Excessive Agency
171
+
172
+ **Mitigación:**
173
+ - [ ] Limitar las tools disponibles al mínimo necesario
174
+ - [ ] Human-in-the-loop para acciones irreversibles
175
+ - [ ] Logging completo de tool calls (trajectory)
176
+
177
+ ### LLM09: Overreliance
178
+
179
+ **Mitigación:**
180
+ - [ ] Disclaimer visible sobre limitaciones de IA
181
+ - [ ] Verificación humana de outputs críticos
182
+
183
+ ### LLM10: Model Theft
184
+
185
+ **Mitigación:**
186
+ - [ ] API keys rotadas regularmente
187
+ - [ ] Rate limiting para prevenir model extraction
188
+ - [ ] Monitoring de uso anómalo