server.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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.2.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. // Pool: ejecutor de comandos SSH del sondeo. nil (demo / sin clave) → el
  42. // rearme de agentes responde 503 (POST /api/agents/{slug}/rearm, Fase 6.1).
  43. // Es una interfaz para poder inyectar un fake en los tests.
  44. Pool SSHRunner
  45. // RearmPollWait: cuánto esperar el push de vuelta tras rearmar (default
  46. // 30 s; los tests lo bajan). <= 0 → rearmPollWait.
  47. RearmPollWait time.Duration
  48. // LastOverview devuelve el último overview del poller (nil si aún no hay).
  49. LastOverview func() *adapters.Overview
  50. // PollNow dispara un ciclo de sondeo inmediato (POST /api/refresh);
  51. // nil → el refresh manual es no-op (tests sin poller).
  52. PollNow func()
  53. Started time.Time
  54. }
  55. type server struct {
  56. cfg *config.Config
  57. db *db.DB
  58. adapter adapters.Snapshotter
  59. hub *sse.Hub
  60. secret string
  61. agents *adapters.AgentRegistry
  62. pool SSHRunner
  63. rearmPollWait time.Duration
  64. lastOv func() *adapters.Overview
  65. pollNow func()
  66. started time.Time
  67. // Anti-martilleo de POST /api/refresh (global, min 5 s entre sondeos).
  68. refreshMu sync.Mutex
  69. lastRefresh time.Time
  70. // Rate limit por IP de POST /api/ingest/agent (30/min, SPEC-AGENTE §1).
  71. ingestLimit *ipRateLimit
  72. // Anti-martilleo del rearme de agentes (60 s por slug, Fase 6.1).
  73. rearmMu sync.Mutex
  74. lastRearm map[string]time.Time
  75. }
  76. // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
  77. func NewHandler(d Deps) http.Handler {
  78. s := &server{
  79. cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
  80. secret: d.Secret, agents: d.Agents, pool: d.Pool,
  81. rearmPollWait: d.RearmPollWait,
  82. lastOv: d.LastOverview, pollNow: d.PollNow, started: d.Started,
  83. ingestLimit: newIPRateLimit(ingestRateLimit, ingestRateWindow),
  84. }
  85. if s.rearmPollWait <= 0 {
  86. s.rearmPollWait = rearmPollWait
  87. }
  88. mode := d.Adapter.Mode()
  89. mux := http.NewServeMux()
  90. // --- Health (público; SIN no-store) ---
  91. mux.HandleFunc("GET /api/health", s.handleAPIHealth(mode))
  92. mux.HandleFunc("GET /health", s.handleHealth)
  93. // --- Auth (público login; SIN no-store) ---
  94. mux.HandleFunc("POST /api/auth/login", s.handleLogin)
  95. mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
  96. mux.HandleFunc("GET /api/auth/me", s.handleMe(mode))
  97. // --- Datos (sesión; con no-store) ---
  98. mux.HandleFunc("GET /api/overview", s.handleOverview)
  99. mux.HandleFunc("GET /api/routers", s.handleRouters)
  100. mux.HandleFunc("GET /api/routers/{id}", s.handleRouterDetail)
  101. mux.HandleFunc("GET /api/devices", s.handleDevices)
  102. mux.HandleFunc("GET /api/alerts", s.handleAlerts)
  103. mux.HandleFunc("GET /api/alerts/config", s.handleAlertsConfigGet)
  104. mux.HandleFunc("PUT /api/alerts/config", s.handleAlertsConfigPut)
  105. mux.HandleFunc("POST /api/alerts/read", s.handleAlertsRead)
  106. mux.HandleFunc("POST /api/alerts/read-all", s.handleAlertsReadAll)
  107. mux.HandleFunc("GET /api/topology", s.handleTopology)
  108. mux.HandleFunc("GET /api/dawn", s.handleDawn)
  109. mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
  110. mux.HandleFunc("GET /api/system/info", s.handleSystemInfo)
  111. // --- Sondeo manual (botón "Refrescar" de Topología; 202 + SSE empuja) ---
  112. mux.HandleFunc("POST /api/refresh", s.handleRefresh)
  113. // --- Agentes nativos (Fase 6) ---
  114. // Ingesta: SIN sesión (auth Bearer propia; exenta en RequireAuth).
  115. mux.HandleFunc("POST /api/ingest/agent", s.handleIngestAgent)
  116. // Gestión de tokens: tras sesión como el resto del API.
  117. mux.HandleFunc("POST /api/agents", s.handleAgentsCreate)
  118. mux.HandleFunc("GET /api/agents", s.handleAgentsList)
  119. mux.HandleFunc("DELETE /api/agents/{slug}", s.handleAgentsDelete)
  120. // Fase 6.1 (Plan B): rearme del servicio procd del agente vía SSH.
  121. mux.HandleFunc("POST /api/agents/{slug}/rearm", s.handleAgentRearm)
  122. // --- Web Push (Fase 6 Bloque C; tras sesión como el resto del API) ---
  123. mux.HandleFunc("GET /api/push/vapid-key", s.handlePushVapidKey)
  124. mux.HandleFunc("POST /api/push/subscribe", s.handlePushSubscribe)
  125. mux.HandleFunc("POST /api/push/unsubscribe", s.handlePushUnsubscribe)
  126. // --- Users ---
  127. // Idioma y nombre propios: FUERA del gate admin (se registran antes en Node).
  128. mux.HandleFunc("PUT /api/users/me/language", s.handleMyLanguage)
  129. mux.HandleFunc("PUT /api/users/me/display-name", s.handleMyDisplayName)
  130. // Resto: solo admin.
  131. mux.Handle("GET /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleListUsers)))
  132. mux.Handle("POST /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleCreateUser)))
  133. mux.Handle("PUT /api/users/{id}/password", auth.RequireAdmin(http.HandlerFunc(s.handleSetPassword)))
  134. mux.Handle("PUT /api/users/{id}/role", auth.RequireAdmin(http.HandlerFunc(s.handleSetRole)))
  135. mux.Handle("DELETE /api/users/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteUser)))
  136. // --- Config (sesión; /api/config/adguard solo admin) ---
  137. s.registerConfigRoutes(mux)
  138. // --- Update (solo admin; ausente si no hay updater, p.ej. en tests) ---
  139. if d.Updater != nil {
  140. s.registerUpdateRoutes(mux, d.Updater)
  141. }
  142. // --- SSE ---
  143. mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
  144. // --- 404 JSON para cualquier /api/* no registrado (cualquier método) ---
  145. mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
  146. writeError(w, http.StatusNotFound, "not_found")
  147. })
  148. // --- Estáticos + SPA fallback ---
  149. static := d.Static
  150. if static != nil {
  151. mux.Handle("/", static)
  152. }
  153. return security.Middleware(auth.RequireAuth(s.db, s.secret, noStoreMux(mux)))
  154. }
  155. // noStoreMux replica el middleware noStore() de routes/data.js: aplica
  156. // Cache-Control: no-store a /api/* EXCEPTO /api/health y /api/auth/*
  157. // (/health no es /api/*). /api/stream sobrescribe con no-cache después.
  158. func noStoreMux(next http.Handler) http.Handler {
  159. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  160. p := r.URL.Path
  161. if strings.HasPrefix(p, "/api/") && p != "/api/health" && !strings.HasPrefix(p, "/api/auth/") {
  162. w.Header().Set("Cache-Control", "no-store")
  163. }
  164. next.ServeHTTP(w, r)
  165. })
  166. }
  167. // writeJSON serializa como JSON.stringify: compacto, SIN escapar HTML
  168. // (SetEscapeHTML(false)) y SIN el '\n' final que añade Encoder.Encode
  169. // (consistencia con D5 WriteError / paridad Hono: marshal + write).
  170. func writeJSON(w http.ResponseWriter, status int, v any) {
  171. var buf bytes.Buffer
  172. enc := json.NewEncoder(&buf)
  173. enc.SetEscapeHTML(false)
  174. _ = enc.Encode(v)
  175. w.Header().Set("Content-Type", "application/json")
  176. w.WriteHeader(status)
  177. _, _ = w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
  178. }
  179. // writeError escribe el envelope {error, message?}.
  180. func writeError(w http.ResponseWriter, status int, code string, message ...string) {
  181. if len(message) > 0 {
  182. writeJSON(w, status, map[string]any{"error": code, "message": message[0]})
  183. return
  184. }
  185. writeJSON(w, status, map[string]any{"error": code})
  186. }
  187. // readJSONBody parsea el body JSON; devuelve false si no es JSON válido
  188. // (equivalente a c.req.json().catch(() => null)).
  189. func readJSONBody(r *http.Request, dst any) bool {
  190. dec := json.NewDecoder(r.Body)
  191. if err := dec.Decode(dst); err != nil {
  192. return false
  193. }
  194. return true
  195. }