device_overrides.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // device_overrides.go — mutaciones manuales de dispositivo (issue #437,
  2. // #797):
  3. //
  4. // PUT /api/devices/{mac}/override → icono, nombre visible y/o tipo.
  5. // PUT /api/devices/{mac}/ban → bandas a bloquear/desbloquear (Fase 2).
  6. //
  7. // Semántica del PUT: cada campo es opcional; ausente = no tocar, vacío =
  8. // limpiar ese override. Así los clientes antiguos que solo envían {icon}
  9. // (p. ej. el alta rápida de desconocidos, #772) no borran nombre/tipo.
  10. package httpapi
  11. import (
  12. "database/sql"
  13. "net/http"
  14. "regexp"
  15. "strings"
  16. "time"
  17. "github.com/gnacho/netpulse/server-go/internal/adapters"
  18. )
  19. var macNormalizeRe = regexp.MustCompile(`[^0-9a-fA-F]`)
  20. // normalizeMAC devuelve MAC en minúsculas con ':' (la forma canónica del
  21. // server y de device_overrides).
  22. func normalizeMAC(mac string) string {
  23. hex := macNormalizeRe.ReplaceAllString(mac, "")
  24. hex = strings.ToLower(hex)
  25. var out strings.Builder
  26. for i := 0; i < len(hex); i += 2 {
  27. if i > 0 {
  28. out.WriteByte(':')
  29. }
  30. if i+2 <= len(hex) {
  31. out.WriteString(hex[i : i+2])
  32. } else {
  33. out.WriteString(hex[i:])
  34. }
  35. }
  36. return out.String()
  37. }
  38. // validateIcon comprueba que el icono enviado es uno de los permitidos por
  39. // DEVICE_ICONS del frontend. Lista cerrada para evitar inyección de clases.
  40. func validateIcon(icon string) bool {
  41. if icon == "" {
  42. return true
  43. }
  44. allowed := map[string]bool{
  45. "monitor": true, "laptop": true, "smartphone": true, "tablet": true,
  46. "tv": true, "gamepad": true, "camera": true, "cctv": true,
  47. "vacuum": true, "doorbell": true, "air-vent": true, "heater": true,
  48. "circuit-board": true, "speaker": true,
  49. "router": true, "server": true, "watch": true, "car": true,
  50. "home": true, "printer": true, "plug": true, "shield": true,
  51. "help-circle": true, "wifi": true, "ethernet": true,
  52. }
  53. return allowed[icon]
  54. }
  55. // deviceNameMax cota el nombre visible personalizado (#797).
  56. const deviceNameMax = 64
  57. // handleDeviceOverridePut: campos opcionales {"icon","name","type"}; vacío
  58. // limpia, ausente no toca. Si los tres quedan vacíos la fila se borra.
  59. func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) {
  60. mac := normalizeMAC(r.PathValue("mac"))
  61. if mac == "" || len(mac) != 17 {
  62. writeError(w, http.StatusBadRequest, "invalid_mac")
  63. return
  64. }
  65. var body struct {
  66. Icon *string `json:"icon"`
  67. Name *string `json:"name"`
  68. Type *string `json:"type"`
  69. NotifyOffline *bool `json:"notifyOffline"`
  70. }
  71. if st := readJSONBody(w, r, &body); st != 0 {
  72. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  73. return
  74. }
  75. if body.Icon != nil && !validateIcon(*body.Icon) {
  76. writeError(w, http.StatusBadRequest, "invalid_icon")
  77. return
  78. }
  79. if body.Type != nil && *body.Type != "" && !adapters.ValidDeviceTypes[*body.Type] {
  80. writeError(w, http.StatusBadRequest, "invalid_type")
  81. return
  82. }
  83. name := ""
  84. if body.Name != nil {
  85. name = strings.TrimSpace(*body.Name)
  86. if strings.ContainsAny(name, "\r\n") {
  87. writeError(w, http.StatusBadRequest, "invalid_name")
  88. return
  89. }
  90. if len(name) > deviceNameMax {
  91. name = name[:deviceNameMax]
  92. }
  93. }
  94. // Valores actuales (los campos ausentes conservan lo persistido).
  95. var curIcon sql.NullString
  96. var curName, curType string
  97. var curNotifyOffline bool
  98. row := s.db.QueryRow("SELECT icon, name, device_type, notify_offline FROM device_overrides WHERE mac = ?", mac)
  99. switch err := row.Scan(&curIcon, &curName, &curType, &curNotifyOffline); err {
  100. case nil:
  101. case sql.ErrNoRows:
  102. default:
  103. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  104. return
  105. }
  106. nextIcon := curIcon.String
  107. nextName, nextType := curName, curType
  108. nextNotifyOffline := curNotifyOffline
  109. if body.Icon != nil {
  110. nextIcon = *body.Icon
  111. }
  112. if body.Name != nil {
  113. nextName = name
  114. }
  115. if body.Type != nil {
  116. nextType = *body.Type
  117. }
  118. if body.NotifyOffline != nil {
  119. nextNotifyOffline = *body.NotifyOffline
  120. }
  121. now := time.Now().UnixMilli()
  122. if nextIcon == "" && nextName == "" && nextType == "" && !nextNotifyOffline {
  123. _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
  124. } else {
  125. _, err := s.db.Exec(
  126. `INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, notify_offline, created_at, updated_at)
  127. VALUES (?, ?, ?, ?, '', ?, ?, ?)
  128. ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
  129. device_type=excluded.device_type, notify_offline=excluded.notify_offline,
  130. updated_at=excluded.updated_at`,
  131. mac, nextIcon, nextName, nextType, nextNotifyOffline, now, now,
  132. )
  133. if err != nil {
  134. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  135. return
  136. }
  137. }
  138. // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices.
  139. if s.pollNow != nil {
  140. s.pollNow()
  141. }
  142. writeJSON(w, http.StatusOK, map[string]any{
  143. "ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
  144. "notifyOffline": nextNotifyOffline,
  145. })
  146. }
  147. // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
  148. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
  149. mac := normalizeMAC(r.PathValue("mac"))
  150. if mac == "" || len(mac) != 17 {
  151. writeError(w, http.StatusBadRequest, "invalid_mac")
  152. return
  153. }
  154. var icon, name, deviceType, banned sql.NullString
  155. var notifyOffline bool
  156. row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands, notify_offline FROM device_overrides WHERE mac = ?", mac)
  157. if err := row.Scan(&icon, &name, &deviceType, &banned, &notifyOffline); err != nil && err != sql.ErrNoRows {
  158. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  159. return
  160. }
  161. writeJSON(w, http.StatusOK, map[string]any{
  162. "mac": mac,
  163. "icon": icon.String,
  164. "name": name.String,
  165. "type": deviceType.String,
  166. "bannedBands": banned.String,
  167. "notifyOffline": notifyOffline,
  168. })
  169. }
  170. // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}.
  171. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437).
  172. func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
  173. var body struct {
  174. Bands []string `json:"bands"`
  175. }
  176. if st := readJSONBody(w, r, &body); st != 0 {
  177. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  178. return
  179. }
  180. _ = body
  181. writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
  182. }
  183. // handleDeviceDelete: borra un cliente del registro device_seen (#1145,
  184. // retención indefinida con control explícito). Si el cliente sigue viéndose
  185. // en vivo, el siguiente ciclo del poller lo vuelve a dar de alta: borrar
  186. // elimina el recuerdo, no el equipo físico (la UI lo documenta en el
  187. // diálogo de confirmación).
  188. func (s *server) handleDeviceDelete(w http.ResponseWriter, r *http.Request) {
  189. raw := strings.TrimSpace(r.PathValue("mac"))
  190. mac := strings.ToUpper(strings.ReplaceAll(raw, "-", ":"))
  191. if mac == "" {
  192. writeError(w, http.StatusBadRequest, "invalid_input", "missing mac")
  193. return
  194. }
  195. // BDs legadas pueden guardar la MAC sin normalizar (con guiones): se
  196. // borran ambas formas (#1145).
  197. res, err := s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?", mac, raw)
  198. if err != nil {
  199. writeError(w, http.StatusInternalServerError, "storage_error", "")
  200. return
  201. }
  202. // #1278: lápida. Sin ella, la siguiente fuente que reporte la MAC como
  203. // online (una entrada cacheada del AP, un colector) la re-daba de alta y
  204. // el borrado "no funcionaba".
  205. if err := s.db.AddDeletedClient(mac); err != nil {
  206. writeError(w, http.StatusInternalServerError, "storage_error", "")
  207. return
  208. }
  209. if n, _ := res.RowsAffected(); n == 0 {
  210. writeError(w, http.StatusNotFound, "not_found", "")
  211. return
  212. }
  213. w.WriteHeader(http.StatusNoContent)
  214. }