CSRF_FIX.md•3.99 kB
# Solución al Error de CSRF Token
## Problema
Al ejecutar `npm test` obtienes el error:
```
❌ Test failed with error:
E_BAD_CSRF_TOKEN: Invalid CSRF Token
```
## Causa
Superprecio usa AdonisJS Shield que protege las rutas con tokens CSRF por defecto. El servidor MCP necesita acceso a las rutas de API sin validación CSRF.
## Solución Aplicada
Ya he actualizado el archivo `/Users/diegopacheco/Development/superprecio/config/shield.ts` para excluir las rutas de API de la validación CSRF.
### Cambios Realizados
En el archivo `config/shield.ts` línea 95, se cambió:
**Antes:**
```typescript
exceptRoutes: ['/devices/suscribe'],
```
**Después:**
```typescript
exceptRoutes: [
'/devices/suscribe',
'/api/products',
'/api/productsByCode',
'/notifications/send',
'/notifications/broadcast',
],
```
## Pasos para Aplicar la Solución
### 1. Reiniciar Superprecio
El servidor Superprecio debe reiniciarse para tomar los cambios:
```bash
# Ve al directorio de Superprecio
cd /Users/diegopacheco/Development/superprecio
# Si está corriendo en una terminal, presiona Ctrl+C para detenerlo
# Reinicia el servidor
npm run dev
```
### 2. Verificar que Superprecio esté corriendo
```bash
# Prueba que responde
curl http://localhost:3000
```
Deberías ver HTML de la página de inicio.
### 3. Probar el MCP Server
```bash
# Vuelve al directorio del MCP
cd /Users/diegopacheco/Development/superprecio_mcp
# Ejecuta el test
npm test
```
## Resultado Esperado
```bash
🧪 Testing Superprecio MCP Server Connection...
📡 API URL: http://localhost:3000
1️⃣ Testing health check...
✅ Health check passed
2️⃣ Testing search products...
✅ Search successful
📊 Found products in X supermarkets
🏪 Supermarkets: [Lista de supermercados]
3️⃣ Testing supermarket list...
✅ Supermarket list retrieved
1. [Supermercado 1]
2. [Supermercado 2]
...
✅ All tests passed!
🚀 The MCP server is ready to use!
```
## Alternativa: Deshabilitar CSRF Completamente (No Recomendado)
Si NO quieres modificar Superprecio, puedes deshabilitar CSRF completamente (solo para desarrollo):
```typescript
// En config/shield.ts línea 76
export const csrf: ShieldConfig['csrf'] = {
enabled: false, // Cambiar de true a false
// ... resto de configuración
}
```
**⚠️ ADVERTENCIA**: No hagas esto en producción. Solo deshabilita las rutas específicas como se muestra arriba.
## Verificar Cambios
Para confirmar que los cambios se aplicaron:
```bash
# En el directorio de Superprecio
cat config/shield.ts | grep -A 5 "exceptRoutes"
```
Deberías ver:
```typescript
exceptRoutes: [
'/devices/suscribe',
'/api/products',
'/api/productsByCode',
'/notifications/send',
'/notifications/broadcast',
],
```
## Problemas Comunes
### "Still getting CSRF error"
1. **¿Reiniciaste Superprecio?** El servidor debe reiniciarse para cargar la nueva configuración
2. **¿Estás usando el puerto correcto?** Verifica que sea `http://localhost:3000`
3. **¿Hay errores en la consola de Superprecio?** Revisa la terminal donde corre
### "Connection refused"
Superprecio no está corriendo:
```bash
cd /Users/diegopacheco/Development/superprecio
npm run dev
```
### "Timeout"
La API está tardando mucho. Aumenta el timeout en `.env`:
```env
REQUEST_TIMEOUT=60000
```
## Seguridad
Esta configuración es **segura** porque:
1. ✅ Solo deshabilita CSRF en rutas de API específicas
2. ✅ Las rutas web (formularios) siguen protegidas
3. ✅ Las APIs REST generalmente no necesitan CSRF (son stateless)
4. ✅ Sigues teniendo protección contra XSS, clickjacking, etc.
## Más Información
- [AdonisJS Shield Documentation](https://docs.adonisjs.com/guides/security/web-security)
- [CSRF Protection Best Practices](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)
---
**Resumen**: Reinicia Superprecio y vuelve a ejecutar `npm test` en el directorio del MCP.