- Add Next.js app structure with base configs, linting, and formatting - Implement LiveKit Meet page, types, and utility functions - Add Docker, Compose, and deployment scripts for backend and token server - Provide E2E and smoke test scaffolding with Puppeteer and Playwright helpers - Include CSS modules and global styles for UI - Add postMessage and studio integration utilities - Update package.json with dependencies and scripts for development and testing
124 lines
6.0 KiB
Markdown
124 lines
6.0 KiB
Markdown
# AvanzaCast — backend-api
|
|
|
|
Este servicio expone las APIs de backend para AvanzaCast: generación de tokens para LiveKit, gestión de sesiones para el Studio, registro de tokens provenientes de un token-server, gestión de usuarios y broadcasts.
|
|
|
|
## Endpoints principales
|
|
|
|
- `GET /health` — healthcheck.
|
|
- `POST /api/session` — generar sesión (token) para un `room` y `username`.
|
|
- Body: { room: string, username: string, ttl?: number }
|
|
- Respuesta: { id, studioUrl, redirectUrl, ttlSeconds }
|
|
- `GET /api/session/:id` — obtener sesión por id (token, url, room, username, ttlSeconds).
|
|
- `POST /api/session/:id/consume` — marcar sesión consumida (single-use).
|
|
- `POST /api/tokens` — registro de tokens generados por un token-server externo.
|
|
- Body: { sessionId: string, token: string, room?: string, username?: string, ttl?: number, createdBy?: number }
|
|
- (El token-server puede llamar este endpoint para persistir tokens con el usuario asociado.)
|
|
- `GET /api/token?room=<>&username=<>` — (legacy) generar token sin crear sesión almacenada (usa `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` si están configuradas).
|
|
- `POST /api/session/validate` — proxy para validar un token contra LiveKit.
|
|
|
|
- User & Broadcasts management (pueden usar Prisma o fallback en memoria):
|
|
- `POST /api/users` — crear usuario { email, username, displayName?, isAdmin? }
|
|
- `GET /api/users/:id` — obtener usuario
|
|
- `POST /api/broadcasts` — crear broadcast { title, description?, ownerId? }
|
|
- `GET /api/broadcasts` — listar broadcasts
|
|
- `POST /api/broadcasts/:id/session` — crear sesión vinculada a un broadcast (genera token y guarda session)
|
|
|
|
## Variables de entorno (más relevantes)
|
|
|
|
- `PORT` — puerto de escucha (default 4000)
|
|
- `DATABASE_URL` — cadena de conexión PostgreSQL (opcional, para Prisma)
|
|
- `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET` — credenciales LiveKit para generar AccessTokens reales
|
|
- `LIVEKIT_WS_URL` o `LIVEKIT_URL` — URL del servidor LiveKit (ws/wss o http(s))
|
|
- `VITE_BROADCASTPANEL_URL`, `VITE_STUDIO_URL` — URLs del frontend para construir redirect/studioUrl
|
|
- `VITE_TOKEN_SERVER_URL` — token-server host (para CORS/allowed origins)
|
|
- `REDIS_URL` — Redis si lo quieres usar
|
|
- `ALLOW_ALL_CORS` — si se quiere permitir cualquier origen (debug only)
|
|
- `SESSION_TTL_SECONDS` — TTL por defecto para sesiones (300s por defecto)
|
|
|
|
## Integración con token-server
|
|
|
|
- Un token-server puede generar tokens y llamar `POST /api/tokens` para registrar la sesión/token en el backend.
|
|
- El `POST /api/tokens` persiste la sesión en la base de datos (Prisma) o en Redis/memoria si Prisma no está disponible.
|
|
- Para mayor seguridad puedes proteger `POST /api/tokens` con un secreto compartido. Recomendación: añadir `BACKEND_REGISTER_SECRET` y que el token-server envíe `X-BACKEND-SECRET`.
|
|
|
|
## Cómo ejecutar localmente (quick start)
|
|
|
|
En el monorepo, desde la raíz:
|
|
|
|
1. Backend API (dev)
|
|
|
|
```bash
|
|
cd packages/backend-api
|
|
npm install
|
|
# Arrancar en dev (usa tsx)
|
|
npm run dev
|
|
```
|
|
|
|
2. Generar tokens / registrar sesiones
|
|
|
|
- Puedes usar la propia ruta `POST /api/session` del `backend-api` para crear una sesión y obtener un token si `LIVEKIT_API_KEY`/`LIVEKIT_API_SECRET` están configuradas. De lo contrario el backend devolverá un token "dev" (mock) para pruebas.
|
|
|
|
3. Probar generación y registro
|
|
|
|
```bash
|
|
# crea session/token
|
|
curl -sS -X POST http://localhost:4000/api/session -H 'Content-Type: application/json' -d '{"room":"test-room","username":"e2e","ttl":300}' | jq .
|
|
# verifica que la sesión se puede obtener por id (usar id devuelto)
|
|
curl -sS http://localhost:4000/api/session/<id> | jq .
|
|
```
|
|
|
|
### Generar sesión internamente (server-to-server)
|
|
|
|
Puedes pedir al `backend-api` que genere la sesión de forma segura usando el endpoint interno protegido `POST /api/internal/session`. Esto requiere que en tu `.env` configures `BACKEND_REGISTER_SECRET` y que la petición incluya el header `X-BACKEND-SECRET`.
|
|
|
|
Para pruebas locales hay un script incluido:
|
|
|
|
```bash
|
|
# establece el secreto en la misma sesión o en el .env
|
|
export BACKEND_REGISTER_SECRET=devregistersecret
|
|
npm run internal:request --workspace packages/backend-api
|
|
# o desde el package folder
|
|
cd packages/backend-api && npm run internal:request
|
|
|
|
# el script usa por defecto room=test-room y username=e2e
|
|
```
|
|
|
|
El resultado incluirá `id`, `studioUrl`, `redirectUrl`, `ttlSeconds` y `token`.
|
|
|
|
4. Probar desde el frontend `broadcast-panel`
|
|
|
|
- Asegúrate `packages/broadcast-panel/.env` apunta a la URL correcta del backend (p. ej. `VITE_BACKEND_API_URL=http://localhost:4000`).
|
|
- Arranca `broadcast-panel` e intenta crear una transmisión y click en "Entrar al estudio". El flujo intentará obtener una session desde `/api/session` y el `StudioPortal` recoge la sesión desde `sessionStorage` o por evento.
|
|
|
|
## Notas de seguridad y producción
|
|
|
|
- No uses credenciales dev en producción. Protege el endpoint `/api/tokens` con autenticación (token mutual, HMAC o IP allowlist).
|
|
- Si usas Prisma, ejecuta `npm run prisma:migrate` y `npm run prisma:generate` antes de arrancar el servicio.
|
|
|
|
## API examples (curl)
|
|
|
|
Generate session (backend-api):
|
|
```bash
|
|
curl -sS -X POST http://localhost:4000/api/session -H 'Content-Type: application/json' -d '{"room":"room1","username":"cesar","ttl":300}' | jq .
|
|
```
|
|
|
|
Register token (token-server -> backend-api):
|
|
```bash
|
|
curl -sS -X POST http://localhost:4000/api/tokens -H 'Content-Type: application/json' -d '{"sessionId":"abcd123","token":"jwt..","room":"room1","username":"cesar","ttl":300}' | jq .
|
|
```
|
|
|
|
Get session by id:
|
|
```bash
|
|
curl -sS http://localhost:4000/api/session/abcd123 | jq .
|
|
```
|
|
|
|
## Next steps / mejoras
|
|
|
|
- Añadir protección a `/api/tokens` (header secreto o auth) y actualizar el token-server para enviarlo.
|
|
- Añadir pruebas e2e que cubran el flujo completo (token-server -> backend-api -> broadcast-panel -> studio).
|
|
- Si quieres, implemento la protección con `BACKEND_REGISTER_SECRET` y actualizaré la documentación.
|
|
|
|
---
|
|
|
|
Si quieres que implemente la protección `BACKEND_REGISTER_SECRET` ahora, lo hago y detallo cómo configurar ambas partes.
|