server.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Package httpapi — handlers de la API (paridad con server/src/routes/* +
  2. // app.js + health.js). Ensamblado equivalente a createApp:
  3. //
  4. // security headers (global) → requireAuth (global) → rutas API →
  5. // 404 JSON /api/* → estáticos + SPA fallback → onError 500.
  6. //
  7. // El middleware noStore (Cache-Control: no-store) se aplica a /api/* salvo
  8. // /api/health, /health y /api/auth/* (paridad con el orden de registro de
  9. // Hono, SPEC §1); /api/stream lo sobrescribe con no-cache.
  10. package httpapi
  11. import (
  12. "bytes"
  13. "encoding/json"
  14. "net/http"
  15. "strings"
  16. "sync"
  17. "time"
  18. "github.com/gnacho/netpulse/server-go/internal/adapters"
  19. "github.com/gnacho/netpulse/server-go/internal/auth"
  20. "github.com/gnacho/netpulse/server-go/internal/config"
  21. "github.com/gnacho/netpulse/server-go/internal/db"
  22. "github.com/gnacho/netpulse/server-go/internal/security"
  23. "github.com/gnacho/netpulse/server-go/internal/sse"
  24. "github.com/gnacho/netpulse/server-go/internal/staticspa"
  25. "github.com/gnacho/netpulse/server-go/internal/updater"
  26. )
  27. // Version es la versión del backend (app.js:18).
  28. const Version = "2.0.0"
  29. // Deps son las dependencias del servidor API (como createApp de app.js).
  30. type Deps struct {
  31. Config *config.Config
  32. DB *db.DB
  33. Adapter adapters.Snapshotter
  34. Hub *sse.Hub
  35. Secret string
  36. Static *staticspa.Handler
  37. Updater *updater.Updater // nil → sin rutas /api/update/*
  38. // Agents: registry de agentes nativos (ingesta POST /api/ingest/agent y
  39. // last_seen/versión de GET /api/agents). nil → ingesta 503.
  40. Agents *adapters.AgentRegistry
  41. // LastOverview devuelve el último overview del poller (nil si aún no hay).
  42. LastOverview func() *adapters.Overview
  43. // PollNow dispara un ciclo de sondeo inmediato (POST /api/refresh);
  44. // nil → el refresh manual es no-op (tests sin poller).
  45. PollNow func()
  46. Started time.Time
  47. }
  48. type server struct {
  49. cfg *config.Config
  50. db *db.DB
  51. adapter adapters.Snapshotter
  52. hub *sse.Hub
  53. secret string
  54. agents *adapters.AgentRegistry
  55. lastOv func() *adapters.Overview
  56. pollNow func()
  57. started time.Time
  58. // Anti-martilleo de POST /api/refresh (global, min 5 s entre sondeos).
  59. refreshMu sync.Mutex
  60. lastRefresh time.Time
  61. // Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
  62. ingestLimit *ipRateLimit
  63. }
  64. // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
  65. func NewHandler(d Deps) http.Handler {
  66. s := &server{
  67. cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
  68. secret: d.Secret, agents: d.Agents, lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
  69. ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
  70. }
  71. mode := d.Adapter.Mode()
  72. mux := http.NewServeMux()
  73. // --- Health (público; SIN no-store) ---
  74. mux.HandleFunc("GET /api/health", s.handleAPIHealth(mode))
  75. mux.HandleFunc("GET /health", s.handleHealth)
  76. // --- Auth (público login; SIN no-store) ---
  77. mux.HandleFunc("POST /api/auth/login", s.handleLogin)
  78. mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
  79. mux.HandleFunc("GET /api/auth/me", s.handleMe(mode))
  80. // --- Datos (sesión; con no-store) ---
  81. mux.HandleFunc("GET /api/overview", s.handleOverview)
  82. mux.HandleFunc("GET /api/routers", s.handleRouters)
  83. mux.HandleFunc("GET /api/routers/{id}", s.handleRouterDetail)
  84. mux.HandleFunc("GET /api/devices", s.handleDevices)
  85. mux.HandleFunc("GET /api/alerts", s.handleAlerts)
  86. mux.HandleFunc("GET /api/alerts/config", s.handleAlertsConfigGet)
  87. mux.HandleFunc("PUT /api/alerts/config", s.handleAlertsConfigPut)
  88. mux.HandleFunc("POST /api/alerts/read", s.handleAlertsRead)
  89. mux.HandleFunc("POST /api/alerts/read-all", s.handleAlertsReadAll)
  90. mux.HandleFunc("GET /api/topology", s.handleTopology)
  91. mux.HandleFunc("GET /api/dawn", s.handleDawn)
  92. mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
  93. // --- Sondeo manual (botón "Refrescar" de Topología; 202 + SSE empuja) ---
  94. mux.HandleFunc("POST /api/refresh", s.handleRefresh)
  95. // --- Agentes nativos (Fase 6) ---
  96. // Ingesta: SIN sesión (auth Bearer propia; exenta en RequireAuth).
  97. mux.HandleFunc("POST /api/ingest/agent", s.handleIngestAgent)
  98. // Gestión de tokens: tras sesión como el resto del API.
  99. mux.HandleFunc("POST /api/agents", s.handleAgentsCreate)
  100. mux.HandleFunc("GET /api/agents", s.handleAgentsList)
  101. mux.HandleFunc("DELETE /api/agents/{slug}", s.handleAgentsDelete)
  102. // --- Web Push (Fase 6 Bloque C; tras sesión como el resto del API) ---
  103. mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)
  104. mux.HandleFunc("POST /api/push/subscribe", s.handlePushSubscribe)
  105. mux.HandleFunc("POST /api/push/unsubscribe", s.handlePushUnsubscribe)
  106. // --- Users ---
  107. // Idioma propio: FUERA del gate admin (se registra antes en Node).
  108. mux.HandleFunc("PUT /api/users/me/language", s.handleMyLanguage)
  109. // Resto: solo admin.
  110. mux.Handle("GET /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleListUsers)))
  111. mux.Handle("POST /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleCreateUser)))
  112. mux.Handle("PUT /api/users/{id}/password", auth.RequireAdmin(http.HandlerFunc(s.handleSetPassword)))
  113. mux.Handle("PUT /api/users/{id}/role", auth.RequireAdmin(http.HandlerFunc(s.handleSetRole)))
  114. mux.Handle("DELETE /api/users/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteUser)))
  115. // --- Config (sesión; /api/config/adguard solo admin) ---
  116. s.registerConfigRoutes(mux)
  117. // --- Update (solo admin; ausente si no hay updater, p.ej. en tests) ---
  118. if d.Updater != nil {
  119. s.registerUpdateRoutes(mux, d.Updater)
  120. }
  121. // --- SSE ---
  122. mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
  123. // --- 404 JSON para cualquier /api/* no registrado (cualquier método) ---
  124. mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
  125. writeError(w, http.StatusNotFound, "not_found")
  126. })
  127. // --- Estáticos + SPA fallback ---
  128. static := d.Static
  129. if static != nil {
  130. mux.Handle("/", static)
  131. }
  132. return security.Middleware(auth.RequireAuth(s.db, s.secret, noStoreMux(mux)))
  133. }
  134. // noStoreMux replica el middleware noStore() de routes/data.js: aplica
  135. // Cache-Control: no-store a /api/* EXCEPTO /api/health y /api/auth/*
  136. // (/health no es /api/*). /api/stream sobrescribe con no-cache después.
  137. func noStoreMux(next http.Handler) http.Handler {
  138. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  139. p := r.URL.Path
  140. if strings.HasPrefix(p, "/api/") && p != "/api/health" && !strings.HasPrefix(p, "/api/auth/") {
  141. w.Header().Set("Cache-Control", "no-store")
  142. }
  143. next.ServeHTTP(w, r)
  144. })
  145. }
  146. // writeJSON serializa como JSON.stringify: compacto, SIN escapar HTML
  147. // (SetEscapeHTML(false)) y SIN el '\n' final que añade Encoder.Encode
  148. // (consistencia con D5 WriteError / paridad Hono: marshal + write).
  149. func writeJSON(w http.ResponseWriter, status int, v any) {
  150. var buf bytes.Buffer
  151. enc := json.NewEncoder(&buf)
  152. enc.SetEscapeHTML(false)
  153. _ = enc.Encode(v)
  154. w.Header().Set("Content-Type", "application/json")
  155. w.WriteHeader(status)
  156. _, _ = w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
  157. }
  158. // writeError escribe el envelope {error, message?}.
  159. func writeError(w http.ResponseWriter, status int, code string, message ...string) {
  160. if len(message) > 0 {
  161. writeJSON(w, status, map[string]any{"error": code, "message": message[0]})
  162. return
  163. }
  164. writeJSON(w, status, map[string]any{"error": code})
  165. }
  166. // readJSONBody parsea el body JSON; devuelve false si no es JSON válido
  167. // (equivalente a c.req.json().catch(() => null)).
  168. func readJSONBody(r *http.Request, dst any) bool {
  169. dec := json.NewDecoder(r.Body)
  170. if err := dec.Decode(dst); err != nil {
  171. return false
  172. }
  173. return true
  174. }