4
0

server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. "github.com/gnacho/netpulse/server-go/internal/auth"
  19. "github.com/gnacho/netpulse/server-go/internal/config"
  20. "github.com/gnacho/netpulse/server-go/internal/db"
  21. "github.com/gnacho/netpulse/server-go/internal/security"
  22. "github.com/gnacho/netpulse/server-go/internal/sse"
  23. "github.com/gnacho/netpulse/server-go/internal/staticspa"
  24. "github.com/gnacho/netpulse/server-go/internal/updater"
  25. )
  26. // Version es la versión del backend (app.js:18).
  27. const Version = "2.0.0"
  28. // Deps son las dependencias del servidor API (como createApp de app.js).
  29. type Deps struct {
  30. Config *config.Config
  31. DB *db.DB
  32. Adapter adapters.Snapshotter
  33. Hub *sse.Hub
  34. Secret string
  35. Static *staticspa.Handler
  36. Updater *updater.Updater // nil → sin rutas /api/update/*
  37. // LastOverview devuelve el último overview del poller (nil si aún no hay).
  38. LastOverview func() *adapters.Overview
  39. Started time.Time
  40. }
  41. type server struct {
  42. cfg *config.Config
  43. db *db.DB
  44. adapter adapters.Snapshotter
  45. hub *sse.Hub
  46. secret string
  47. lastOv func() *adapters.Overview
  48. started time.Time
  49. }
  50. // NewHandler ensambla el handler HTTP completo (API + estáticos + SPA).
  51. func NewHandler(d Deps) http.Handler {
  52. s := &server{
  53. cfg: d.Config, db: d.DB, adapter: d.Adapter, hub: d.Hub,
  54. secret: d.Secret, lastOv: d.LastOverview, started: d.Started,
  55. }
  56. mode := d.Adapter.Mode()
  57. mux := http.NewServeMux()
  58. // --- Health (público; SIN no-store) ---
  59. mux.HandleFunc("GET /api/health", s.handleAPIHealth(mode))
  60. mux.HandleFunc("GET /health", s.handleHealth)
  61. // --- Auth (público login; SIN no-store) ---
  62. mux.HandleFunc("POST /api/auth/login", s.handleLogin)
  63. mux.HandleFunc("POST /api/auth/logout", s.handleLogout)
  64. mux.HandleFunc("GET /api/auth/me", s.handleMe(mode))
  65. // --- Datos (sesión; con no-store) ---
  66. mux.HandleFunc("GET /api/overview", s.handleOverview)
  67. mux.HandleFunc("GET /api/routers", s.handleRouters)
  68. mux.HandleFunc("GET /api/routers/{id}", s.handleRouterDetail)
  69. mux.HandleFunc("GET /api/devices", s.handleDevices)
  70. mux.HandleFunc("GET /api/alerts", s.handleAlerts)
  71. mux.HandleFunc("GET /api/topology", s.handleTopology)
  72. mux.HandleFunc("GET /api/dawn", s.handleDawn)
  73. mux.HandleFunc("GET /api/adguard/clients", s.handleAdguardClients)
  74. // --- Users ---
  75. // Idioma propio: FUERA del gate admin (se registra antes en Node).
  76. mux.HandleFunc("PUT /api/users/me/language", s.handleMyLanguage)
  77. // Resto: solo admin.
  78. mux.Handle("GET /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleListUsers)))
  79. mux.Handle("POST /api/users", auth.RequireAdmin(http.HandlerFunc(s.handleCreateUser)))
  80. mux.Handle("PUT /api/users/{id}/password", auth.RequireAdmin(http.HandlerFunc(s.handleSetPassword)))
  81. mux.Handle("PUT /api/users/{id}/role", auth.RequireAdmin(http.HandlerFunc(s.handleSetRole)))
  82. mux.Handle("DELETE /api/users/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteUser)))
  83. // --- Config (sesión; /api/config/adguard solo admin) ---
  84. s.registerConfigRoutes(mux)
  85. // --- Update (solo admin; ausente si no hay updater, p.ej. en tests) ---
  86. if d.Updater != nil {
  87. s.registerUpdateRoutes(mux, d.Updater)
  88. }
  89. // --- SSE ---
  90. mux.HandleFunc("GET /api/stream", s.hub.HandleStream)
  91. // --- 404 JSON para cualquier /api/* no registrado (cualquier método) ---
  92. mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
  93. writeError(w, http.StatusNotFound, "not_found")
  94. })
  95. // --- Estáticos + SPA fallback ---
  96. static := d.Static
  97. if static != nil {
  98. mux.Handle("/", static)
  99. }
  100. return security.Middleware(auth.RequireAuth(s.db, s.secret, noStoreMux(mux)))
  101. }
  102. // noStoreMux replica el middleware noStore() de routes/data.js: aplica
  103. // Cache-Control: no-store a /api/* EXCEPTO /api/health y /api/auth/*
  104. // (/health no es /api/*). /api/stream sobrescribe con no-cache después.
  105. func noStoreMux(next http.Handler) http.Handler {
  106. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  107. p := r.URL.Path
  108. if strings.HasPrefix(p, "/api/") && p != "/api/health" && !strings.HasPrefix(p, "/api/auth/") {
  109. w.Header().Set("Cache-Control", "no-store")
  110. }
  111. next.ServeHTTP(w, r)
  112. })
  113. }
  114. // writeJSON serializa como JSON.stringify: compacto, SIN escapar HTML
  115. // (SetEscapeHTML(false)) y SIN el '\n' final que añade Encoder.Encode
  116. // (consistencia con D5 WriteError / paridad Hono: marshal + write).
  117. func writeJSON(w http.ResponseWriter, status int, v any) {
  118. var buf bytes.Buffer
  119. enc := json.NewEncoder(&buf)
  120. enc.SetEscapeHTML(false)
  121. _ = enc.Encode(v)
  122. w.Header().Set("Content-Type", "application/json")
  123. w.WriteHeader(status)
  124. _, _ = w.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
  125. }
  126. // writeError escribe el envelope {error, message?}.
  127. func writeError(w http.ResponseWriter, status int, code string, message ...string) {
  128. if len(message) > 0 {
  129. writeJSON(w, status, map[string]any{"error": code, "message": message[0]})
  130. return
  131. }
  132. writeJSON(w, status, map[string]any{"error": code})
  133. }
  134. // readJSONBody parsea el body JSON; devuelve false si no es JSON válido
  135. // (equivalente a c.req.json().catch(() => null)).
  136. func readJSONBody(r *http.Request, dst any) bool {
  137. dec := json.NewDecoder(r.Body)
  138. if err := dec.Decode(dst); err != nil {
  139. return false
  140. }
  141. return true
  142. }