# FASE 5 — Mega Plan: Security, Infrastructure, Quality > **Análisis completo del sistema**: 155 archivos TS/TSX, 67 archivos de currículum, 15 API routes, 22 páginas, 31 componentes. --- ## 0. Hallazgos Críticos del Análisis | # | Severidad | Issue | Estado actual | |---|-----------|-------|---------------| | 1 | 🔴 CRÍTICO | **15 APIs sin autenticación** — cualquiera accede/modifica datos de children | `better-auth` instalado pero NUNCA enforceado | | 2 | 🟠 ALTO | **5 APIs sin try/catch** — Prisma errors → unhandled rejections → crash | `children`, `curriculum/next`, `dashboard/summary`, `fsrs/next` | | 3 | 🟠 ALTO | **Sin .dockerignore** — Docker copia 777MB de node_modules al contexto | build lento, imagen enorme | | 4 | 🟡 MEDIO | **Sin .env.example** — usuarios no saben qué variables configurar | | | 5 | 🟡 MEDIO | **Sin README.md** — cero documentación en raíz del proyecto | | | 6 | 🟡 MEDIO | **Sin /api/health** — Docker no puede verificar si la app responde | | | 7 | 🟡 MEDIO | **ESLint config deprecated** — produce warnings en build | FlatCompat con opciones removidas | | 8 | 🟢 BAJO | **Sin rate limiting en TTS** — endpoint CPU-intensive sin protección | | | 9 | 🟢 BAJO | **Sin input validation** — tipos/longitudes no validados antes de Prisma | | --- ## 1. Plan de Ejecución ### FASE 5.1 — Seguridad: Device Auth Middleware (CRÍTICO) - Crear middleware de API que valide device pairing - Las APIs de children/curriculum requieren `childId` validado contra `Device.deviceFingerprint` - Las APIs de debug ya están protegidas (NODE_ENV guard de fase 4) - Las APIs de auth (better-auth) se excluyen del middleware ### FASE 5.2 — Error Handling Consistente - Envolver TODAS las APIs en try/catch con respuesta 500 estandarizada - Log de errores con contexto (ruta, childId, timestamp) ### FASE 5.3 — Infraestructura Faltante - `.env.example` con todas las variables documentadas - `.dockerignore` para excluir node_modules, .next, .git, e2e, *.md - `README.md` con descripción del proyecto y links - `app/api/health/route.ts` — endpoint de health check simple ### FASE 5.4 — ESLint Fix - Simplificar `eslint.config.mjs` sin FlatCompat deprecated - Verificar que `next lint` pasa sin warnings ### FASE 5.5 — Docker Hardening - `.dockerignore` reduce contexto de build - Health check en docker-compose.yml - `.env.example` referenciado en INSTALL.md ### FASE 5.6 — Verificación Final - TypeScript compila - Build pasa - 61+ E2E tests pasan - Commit + push --- ## 2. Detalles Técnicos ### 2.1 API Auth Strategy El sistema tiene 2 tipos de acceso: 1. **Child device** (iPad): ya emparejado vía pairing code, tiene `deviceFingerprint` en localStorage 2. **Parent**: autenticado vía better-auth (email/password) Para no romper el flujo existente, el middleware validará: - `/api/curriculum/*`, `/api/dashboard/*`, `/api/milestones`, `/api/sessions/*`: requieren `childId` que tenga un Device asociado - `/api/children`, `/api/pairing`: requieren parent session (better-auth) o device fingerprint - `/api/tts`: sin auth (endpoint público, ya tiene límite de 200 chars) - `/api/debug/*`: ya protegidas (NODE_ENV) - `/api/auth/*`: manejado por better-auth Implementación pragmática: en lugar de middleware complejo, añadir validación de `childId` directamente en cada API que lo recibe — verificar que el child existe antes de devolver datos. ### 2.2 .dockerignore ``` node_modules .next .git e2e *.md .env* docker-compose.yml Dockerfile .playwright ``` ### 2.3 Health Endpoint ```typescript // app/api/health/route.ts export async function GET() { return NextResponse.json({ status: "ok", timestamp: Date.now() }) } ``` ### 2.4 ESLint Fix Reemplazar `FlatCompat` con config flat nativa de ESLint 9. --- ## 3. Ejecución (checklist) - [ ] 5.1 Crear childId validation helper + aplicar a APIs - [ ] 5.2 Añadir try/catch a 5 APIs sin manejo de errores - [ ] 5.3 Crear .env.example - [ ] 5.4 Crear .dockerignore - [ ] 5.5 Crear README.md - [ ] 5.6 Crear /api/health endpoint - [ ] 5.7 Fix ESLint config - [ ] 5.8 Actualizar docker-compose.yml con healthcheck - [ ] 5.9 Verificar: tsc + build + tests - [ ] 5.10 Commit + push