ML Engine Updates: - Updated BTCUSD with Polygon API data (2024-2025): 215,699 new records - Re-trained all ML models: Attention (R²: 0.223), Base, Metamodel (87.3% confidence) - Backtest results: +176.71R profit with aggressive_filter strategy Documentation Consolidation: - Created docs/99-analisis/_MAP.md index with 13 new analysis documents - Consolidated inventories: removed duplicates from orchestration/inventarios/ - Updated ML_INVENTORY.yml with BTCUSD metrics and training results - Added execution reports: FASE11-BTCUSD, correction issues, alignment validation Architecture & Integration: - Updated all module documentation with NEXUS v3.4 frontmatter - Fixed _MAP.md indexes across all folders - Updated orchestration plans and traces Files: 229 changed, 5064 insertions(+), 1872 deletions(-) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
219 lines
10 KiB
Markdown
219 lines
10 KiB
Markdown
---
|
|
id: "ADR-003-autenticacion-multiproveedor"
|
|
title: "Autenticacion Multi-proveedor"
|
|
type: "Documentation"
|
|
project: "trading-platform"
|
|
version: "1.0.0"
|
|
updated_date: "2026-01-04"
|
|
---
|
|
|
|
# ADR-003: Autenticacion Multi-proveedor
|
|
|
|
**Fecha:** 2025-12-05
|
|
**Estado:** ✅ Aceptado
|
|
**Deciders:** Tech Lead, Security Lead
|
|
**Épica:** [OQI-001](../01-fase-mvp/OQI-001-fundamentos-auth/_MAP.md)
|
|
|
|
---
|
|
|
|
## Contexto
|
|
|
|
Trading Platform necesita un sistema de autenticacion que:
|
|
1. Reduzca friccion en el registro (aumentar conversion)
|
|
2. Soporte multiples metodos de acceso para diferentes usuarios
|
|
3. Cumpla con estandares de seguridad para plataforma financiera
|
|
4. Sea extensible para futuros proveedores
|
|
5. Funcione en mercado LATAM (WhatsApp tiene alta penetracion)
|
|
|
|
---
|
|
|
|
## Decision
|
|
|
|
Implementar autenticacion multi-proveedor con los siguientes metodos:
|
|
|
|
### Proveedores OAuth 2.0
|
|
1. **Google** - Mayor adopcion global
|
|
2. **Facebook** - Popular en LATAM
|
|
3. **X/Twitter** - Comunidad de traders/crypto
|
|
4. **Apple Sign In** - Usuarios iOS premium
|
|
5. **GitHub** - Desarrolladores, early adopters
|
|
|
|
### Autenticacion Tradicional
|
|
6. **Email/Password** - Metodo clasico con verificacion
|
|
7. **Telefono (SMS/WhatsApp)** - Via Twilio, popular en LATAM
|
|
|
|
### Seguridad Adicional
|
|
8. **2FA con TOTP** - Google Authenticator compatible
|
|
9. **Backup codes** - Recuperacion de cuenta
|
|
|
|
### Tokens
|
|
- **JWT RS256** para access tokens (15 min)
|
|
- **Refresh token rotation** (7 dias)
|
|
- **Session management** con revocacion
|
|
|
|
---
|
|
|
|
## Alternativas Consideradas
|
|
|
|
### Servicios de Auth Gestionados
|
|
|
|
| Opcion | Pros | Contras | Decision |
|
|
|--------|------|---------|----------|
|
|
| **Implementacion propia** | Control total, sin vendor lock-in | Mas trabajo, responsabilidad seguridad | ✅ Elegido |
|
|
| Auth0 | Feature completo, seguro | Costo alto en escala, vendor lock-in | ❌ |
|
|
| Firebase Auth | Gratis hasta cierto punto | Lock-in Google, menos control | ❌ |
|
|
| Clerk | UI bonita, facil | Nuevo, menos features | ❌ |
|
|
| Supabase Auth | Postgres nativo | Menos proveedores OAuth | ❌ |
|
|
|
|
**Justificacion**: Para una plataforma financiera, el control total sobre autenticacion es critico. Ademas, el costo de Auth0 a escala seria significativo.
|
|
|
|
### Estrategia de Tokens
|
|
|
|
| Opcion | Pros | Contras | Decision |
|
|
|--------|------|---------|----------|
|
|
| **JWT + Refresh rotation** | Stateless, seguro con rotation | Complejidad de implementacion | ✅ Elegido |
|
|
| Sessions en DB | Simple, revocacion facil | Stateful, mas queries | ❌ |
|
|
| JWT sin refresh | Simple | Inseguro (tokens largos) | ❌ |
|
|
| Opaque tokens | Mas seguro | Requiere lookup en cada request | ❌ |
|
|
|
|
### Algoritmo JWT
|
|
|
|
| Opcion | Pros | Contras | Decision |
|
|
|--------|------|---------|----------|
|
|
| **RS256** | Verificacion sin secreto | Keys mas grandes | ✅ Elegido |
|
|
| HS256 | Simple, rapido | Secreto compartido | ❌ |
|
|
| ES256 | Keys pequeñas | Menos soporte en librerias | ❌ |
|
|
|
|
### Servicio SMS/WhatsApp
|
|
|
|
| Opcion | Pros | Contras | Decision |
|
|
|--------|------|---------|----------|
|
|
| **Twilio** | Confiable, WhatsApp API | Costo por mensaje | ✅ Elegido |
|
|
| AWS SNS | Economico | Sin WhatsApp | ❌ |
|
|
| MessageBird | Bueno para Europa | Menos soporte LATAM | ❌ |
|
|
|
|
---
|
|
|
|
## Diseño de la Solucion
|
|
|
|
### Flujo de Autenticacion
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────────────────┐
|
|
│ AUTHENTICATION FLOW │
|
|
├─────────────────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ Usuario elige metodo de autenticacion │
|
|
│ │
|
|
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
|
│ │ OAuth │ │ Email/ │ │ Phone │ │ 2FA │ │
|
|
│ │ Providers │ │ Password │ │ OTP │ │ TOTP │ │
|
|
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
|
|
│ │ │ │ │ │
|
|
│ ▼ ▼ ▼ ▼ │
|
|
│ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
│ │ AUTHENTICATION LAYER │ │
|
|
│ │ │ │
|
|
│ │ • Validar credenciales │ │
|
|
│ │ • Verificar estado de cuenta │ │
|
|
│ │ • Verificar 2FA si esta habilitado │ │
|
|
│ │ • Rate limiting │ │
|
|
│ └─────────────────────────────────────────────────────────────────┘ │
|
|
│ │ │
|
|
│ ▼ │
|
|
│ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
│ │ TOKEN SERVICE │ │
|
|
│ │ │ │
|
|
│ │ • Generar Access Token (JWT RS256, 15min) │ │
|
|
│ │ • Generar Refresh Token (JWT RS256, 7d) │ │
|
|
│ │ • Crear sesion en DB │ │
|
|
│ └─────────────────────────────────────────────────────────────────┘ │
|
|
│ │ │
|
|
│ ▼ │
|
|
│ ┌─────────────────────────────────────────────────────────────────┐ │
|
|
│ │ SESSION MANAGEMENT │ │
|
|
│ │ │ │
|
|
│ │ • Almacenar device info │ │
|
|
│ │ • Tracking de IP/ubicacion │ │
|
|
│ │ • Deteccion de anomalias │ │
|
|
│ └─────────────────────────────────────────────────────────────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
### Modelo de Datos
|
|
|
|
```sql
|
|
-- Usuario puede tener multiples metodos de auth
|
|
users (1) ─────┬───── (N) oauth_accounts
|
|
│
|
|
├───── (N) sessions
|
|
│
|
|
├───── (N) email_verifications
|
|
│
|
|
└───── (N) phone_verifications
|
|
```
|
|
|
|
### Seguridad Implementada
|
|
|
|
| Medida | Implementacion |
|
|
|--------|----------------|
|
|
| Password hashing | bcrypt cost 12 |
|
|
| Token encryption | AES-256-GCM para OAuth tokens |
|
|
| Rate limiting | 5 intentos / 15 min en login |
|
|
| Account lockout | Progresivo (15min, 1h, 24h) |
|
|
| Refresh rotation | Nuevo token en cada refresh |
|
|
| Token reuse detection | Invalida todas las sesiones |
|
|
| PKCE | Para OAuth providers que lo soportan |
|
|
| State validation | Redis con TTL 10 min |
|
|
|
|
---
|
|
|
|
## Consecuencias
|
|
|
|
### Positivas
|
|
|
|
1. **Mayor conversion**: Usuarios pueden registrarse con un click
|
|
2. **Seguridad robusta**: 2FA, rotation, rate limiting
|
|
3. **Flexibilidad**: Multiples metodos para diferentes segmentos
|
|
4. **Control total**: Sin dependencia de servicios externos (excepto OAuth providers)
|
|
5. **Escalable**: Facil agregar nuevos proveedores
|
|
|
|
### Negativas
|
|
|
|
1. **Complejidad**: Mas codigo que usar Auth0
|
|
2. **Mantenimiento**: Actualizar integraciones OAuth cuando cambien
|
|
3. **Costo Twilio**: SMS/WhatsApp tienen costo por mensaje
|
|
4. **Responsabilidad**: Seguridad es nuestra responsabilidad
|
|
|
|
### Riesgos y Mitigaciones
|
|
|
|
| Riesgo | Probabilidad | Impacto | Mitigacion |
|
|
|--------|--------------|---------|------------|
|
|
| Breach de tokens | Baja | Alto | Rotation, encryption, short TTL |
|
|
| Cambios en OAuth APIs | Media | Medio | Abstraer en servicio, monitorear cambios |
|
|
| Abuso de OTP | Media | Medio | Rate limiting agresivo |
|
|
| Perdida de 2FA | Baja | Alto | Backup codes, recovery flow |
|
|
|
|
---
|
|
|
|
## Metricas de Exito
|
|
|
|
| Metrica | Target |
|
|
|---------|--------|
|
|
| Conversion registro OAuth | >40% de registros |
|
|
| Tiempo de login (p95) | <2 segundos |
|
|
| Tasa de abandono en registro | <30% |
|
|
| Adopcion de 2FA | >20% usuarios activos |
|
|
| Intentos de login fallidos | <5% del total |
|
|
|
|
---
|
|
|
|
## Referencias
|
|
|
|
- [OAuth 2.0 RFC 6749](https://tools.ietf.org/html/rfc6749)
|
|
- [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
|
|
- [JWT Best Practices](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-jwt-bcp)
|
|
- [NIST Digital Identity Guidelines](https://pages.nist.gov/800-63-3/)
|
|
- [Sign in with Apple Guidelines](https://developer.apple.com/sign-in-with-apple/get-started/)
|