Claude/push agent code otcaa#7
Open
Jon-human-in-the-loop wants to merge 12 commits into
Open
Conversation
…CRITICAL) Cambios en los templates de CLAUDE.md que generan agentes nuevos: 1. agent/providers/meta.py — validación HMAC-SHA256 de X-Hub-Signature-256 con META_APP_SECRET. Sin esto cualquiera podía POSTear al webhook y hacerse pasar por Meta. 2. agent/providers/twilio.py — validación HMAC-SHA1 de X-Twilio-Signature. Mismo problema: webhook abierto sin verificar origen. Flag TWILIO_VALIDATE_SIGNATURE=false disponible para tests locales. 3. agent/main.py — cache de mensajes_id procesados (OrderedDict, TTL 1h, max 10k entradas). Meta reenvía el webhook si no respondemos en <20s, sin idempotencia el mensaje se procesaba 2x: 2 llamadas a Claude, 2 respuestas al usuario. 4. agent/brain.py — timeout=30s y max_retries=2 en AsyncAnthropic. Antes una API colgada bloqueaba el webhook indefinidamente. Acompañando: - .env.example: agregadas META_APP_SECRET y TWILIO_VALIDATE_SIGNATURE, removido valor predecible "agentkit-verify" del verify_token. - CLAUDE.md PREGUNTA 10 (entrevista): pide App Secret y genera verify_token aleatorio con secrets.token_urlsafe(32). - CLAUDE.md FASE 5 (Railway) y secciones 3.9/7: variables actualizadas. https://claude.ai/code/session_012XK7WbAqcrbMUjNy6du5xi
…ction (MEDIUM) Cambios en los templates de CLAUDE.md: 1. agent/main.py — validar_configuracion() falla rápido al arrancar si faltan variables del proveedor elegido. Detecta META_VERIFY_TOKEN débil (predecible o <16 chars) y avisa cómo regenerarlo. 2. agent/main.py — rate limiting por número (10 msgs/60s en memoria). Evita abuso del agente y costos descontrolados de la API. Nota documentada: con --workers >1 hace falta Redis. 3. agent/main.py — sanitizar_mensaje() trunca a 4000 chars y normaliza Unicode con NFKC. Elimina caracteres de control que podrían usarse para prompt injection con caracteres invisibles. 4. agent/tools.py — buscar_en_knowledge() con límite de 5 MB por archivo, máximo 5 resultados, y verificación de symlinks que apunten fuera de knowledge/ (defensa en profundidad contra path traversal via symlink). 5. config/prompts.yaml — sección "Reglas de seguridad (inviolables)" en el system prompt. Indica al modelo que el mensaje del cliente es CONTENIDO, no instrucciones, y le da una respuesta canónica frente a intentos comunes de manipulación. https://claude.ai/code/session_012XK7WbAqcrbMUjNy6du5xi
Cambios en los templates de CLAUDE.md: 1. agent/providers/meta.py — httpx.Timeout(10s, connect=5s) al enviar mensajes. try/except httpx.HTTPError. Sin esto, una API lenta de Meta colgaba el webhook mucho más allá del timeout de 30s de Claude. 2. agent/providers/twilio.py — mismo timeout y manejo de errores HTTP. 3. Dockerfile — usuario no-root (uid 1000), COPY --chown, HEALTHCHECK sobre /. Reduce el blast radius si alguien escapa del contenedor y permite que Railway detecte cuelgues del servidor. 4. requirements.txt — todas las deps pineadas con upper bound (<X.0.0). Una rebuild en Railway no traerá un major release con breaking changes que rompa el agente en producción. https://claude.ai/code/session_012XK7WbAqcrbMUjNy6du5xi
…ts heredables Los agentes generados por AgentKit ahora incluyen dos archivos nuevos que cada usuario recibe automáticamente al correr /build-agent: agent/security.py Módulo con todas las funciones puras extraídas de main.py: validar_configuracion, sanitizar_mensaje, ya_procesado, marcar_procesado, rate_limit_excedido + sus constantes y estado. Al vivir separado de main.py (que tiene side effects al importarse), es directamente testeable sin mockear env vars ni la BD. tests/test_security.py 27 tests pytest que cada agente generado hereda: - TestFirmaMeta (5): HMAC-SHA256, firma vacía, sin secret, tampering - TestFirmaTwilio (5): HMAC-SHA1, URL modificada, param modificado - TestIdempotencia (5): nuevo/marcado/vacío, cache acotado, TTL - TestSanitizacion (7): control chars, zero-width, NFKC, truncado - TestRateLimit (4): límite, superación, aislamiento por teléfono agent/main.py Simplificado: importa las funciones de agent.security en vez de tenerlas inline. Más fácil de leer — main.py solo define la app. FASE 4 del onboarding actualizada: Nuevo paso 1: pip install pytest Nuevo paso 2: pytest tests/test_security.py -v Si los tests fallan → no continuar hasta arreglar. Si pasan → continuar con el chat interactivo de prueba. https://claude.ai/code/session_012XK7WbAqcrbMUjNy6du5xi
En producción, el handler de error 500 devolvía str(e) como detalle
HTTP — Meta/Twilio recibía stack traces o mensajes internos del servidor.
Ahora: development → detalle completo (útil para debuggear)
production → "Error interno" (sin información sensible)
https://claude.ai/code/session_012XK7WbAqcrbMUjNy6du5xi
…vulnerabilities-IM5nO fix(security): remediación completa de vulnerabilidades en templates
…-jonathan docs: agregar créditos del fork y mejoras de seguridad de Jonathan Flores
- FastAPI webhook server with Twilio WhatsApp provider - Claude claude-sonnet-4-6 brain with HELIX · AI custom system prompt - SQLite conversation memory per phone number - Security: HMAC-SHA1 signature validation, rate limiting, idempotency cache, input sanitization - Business config for HELIX · AI (4 service pillars, lead qualification, scheduling) - Docker + docker-compose for production deploy - 20/20 security tests passing
- System prompt: prohibir markdown, bullets y firmas; estilo conversacional informal - Delay humano antes de enviar (2-8s según largo del mensaje) - Respuestas largas se parten en múltiples mensajes con pausa entre bloques
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.