Saltearse al contenido

Contratos API y Tiempo Real (REST + WebSocket)

  • Base URL en producción: https://api.42.salado.me
  • Versionado público: /api/v1/* para clientes externos (con API Key + rate limit) y /api/{servicio}/* tras el proxy inverso.
  • Formato: JSON UTF-8 (Content-Type: application/json). Fechas en ISO-8601 UTC (2026-11-28T18:00:00Z).
  • Paginación: por cursor (?cursor=<opaque>&limit=25, máximo 100) para evitar saltos o duplicados cuando entran registros nuevos.
{
"error": {
"code": "campus_pending",
"message": "Tu cuenta aún necesita verificación de campus para esta acción.",
"details": {}
}
}
Código HTTP Cuándo se devuelve
400 Bad Request JSON malformado o parámetros inválidos
401 Unauthorized Sin sesión, JWT caducado o API Key inválida
403 Forbidden Rol insuficiente, cuenta suspendida o campus_pending
404 Not Found Recurso inexistente o ruta /internal/* bloqueada en edge
409 Conflict Duplicado (email/login existente) o transición de estado inválida (CAS)
422 Unprocessable Entity Error de validación semántica de campos de formulario
423 Locked Cuenta bloqueada temporalmente (5 fallos consecutivos de login)
429 Too Many Requests Rate limit superado (incluye cabecera Retry-After)

Endpoints activos actualmente en api.42.salado.me

Sección titulada «Endpoints activos actualmente en api.42.salado.me»
Método Ruta Descripción Respuesta ejemplo
GET / Estado y mensaje de bienvenida del servicio {"service":"awesome42-core","message":"...","status":"coming_soon"}
GET /health Healthcheck de servicio y conexión a PostgreSQL {"ok":true,"db":"ok","service":"awesome42-core","version":"dev"}
GET /random Devuelve una frase aleatoria real de 42 (1..42) desde Postgres {"number":20,"total":42,"code":"definitely-lost","phrase":"...","meaning":"..."}

Catálogo de endpoints por servicio (plan objetivo)

Sección titulada «Catálogo de endpoints por servicio (plan objetivo)»
Dominio Rutas principales
Auth (/api/auth) POST /signup, POST /login, POST /login/totp, POST /magic, GET /magic/callback, GET /oauth/42/start, GET /oauth/42/callback, POST /refresh, POST /logout, POST /2fa/setup|enable|disable, GET /me, GET /me/export, POST /me/delete
Social y Perfil (/api/core) GET/PATCH /me/profile, PUT /me/avatar, GET /u/:login, POST /friends/:id, POST /friends/:id/accept|decline, DELETE /friends/:id
Campus y Estudio (/api/core) GET/POST /news, GET/POST /events, POST /events/:id/register, GET/POST /leagues, GET/POST /resources, GET/POST /flashcards/decks, POST /cards/:id/review, GET/POST /qa, GET /search
API Pública (/api/v1) GET /me, GET /users/:login, GET /events, GET/POST/PUT/DELETE /resources, GET /leaderboard (requiere cabecera X-API-Key, rate limit 60 req/min)
Mensajería (/api/realtime) GET /channels, GET/POST /channels/:id/messages, GET/POST /dm/:userId, GET /notifications, POST /blocks/:userId, WS /ws
Juegos (/api/games) POST /matches, POST /matches/:id/accept|decline, GET /matches/:id/replay, GET/POST /tournaments, GET /leaderboard, WS /ws

Protocolo WebSocket: Chat y Presencia (/api/realtime/ws)

Sección titulada «Protocolo WebSocket: Chat y Presencia (/api/realtime/ws)»
sequenceDiagram
  autonumber
  participant C as Cliente Web
  participant RT as realtime (WS Hub)
  participant RD as Redis Pub/Sub
  participant DB as PostgreSQL

  C->>RT: Upgrade WSS (cookie a42_access)
  RT->>RT: Valida JWT + campus_verified
  RT-->>C: {"type":"hello","online":[...]}
  RT->>RD: PUBLISH presence {userId, status:"online"}
  C->>RT: {"type":"subscribe","channelId":"..."}
  C->>RT: {"type":"typing","channelId":"..."}
  RT->>RD: PUBLISH channel:id {type:"typing"}
  C->>RT: POST /channels/:id/messages (HTTP)
  RT->>DB: INSERT channel_messages
  RT->>RD: PUBLISH channel:id {type:"channel_message"}
  RD-->>RT: Broadcast a instancias suscritas
  RT-->>C: {"type":"channel_message","data":{...}}
Dirección Eventos clave
Cliente → Servidor subscribe, unsubscribe, typing, ping, board_stroke, board_focus
Servidor → Cliente hello, presence, channel_message, channel_message_hidden, dm, dm_read, notification, typing, pong

Protocolo WebSocket: Juegos en Vivo (/api/games/ws)

Sección titulada «Protocolo WebSocket: Juegos en Vivo (/api/games/ws)»
sequenceDiagram
  autonumber
  participant P1 as Jugador 1
  participant G as games (Room 60Hz)
  participant P2 as Jugador 2
  participant C as core (/internal/xp)

  P1->>G: {"type":"join","matchId":"..."}
  P2->>G: {"type":"join","matchId":"..."}
  G-->>P1: {"type":"start","seed":982134,"rules":{...}}
  G-->>P2: {"type":"start","seed":982134,"rules":{...}}
  loop Cada 16.6 ms (60 Hz)
    P1->>G: {"type":"input","dir":-1,"seq":42}
    P2->>G: {"type":"input","dir":1,"seq":41}
    G->>G: stepPhysicsDeterministic()
    G-->>P1: {"type":"state","ball":[x,y],"paddles":[y1,y2],"score":[s1,s2]}
    G-->>P2: {"type":"state","ball":[x,y],"paddles":[y1,y2],"score":[s1,s2]}
  end
  G->>G: Fin de partida -> guarda Replay + Elo + Outbox
  G-->>P1: {"type":"finish","winner":P1,"eloDelta":+16}
  G-->>P2: {"type":"finish","winner":P1,"eloDelta":-16}
  G->>C: Outbox POST /internal/xp (idempotency_key)

Autoridad del servidor: los clientes solo envían intención de movimiento (-1, 0, 1). La posición de la bola, colisiones, puntuación y condición de victoria se calculan exclusivamente en el servidor para impedir trampas desde DevTools.