device_overrides.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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, "speaker": true,
  47. "router": true, "server": true, "watch": true, "car": true,
  48. "home": true, "printer": true, "plug": true, "shield": true,
  49. "help-circle": true, "wifi": true, "ethernet": true,
  50. }
  51. return allowed[icon]
  52. }
  53. // deviceNameMax cota el nombre visible personalizado (#797).
  54. const deviceNameMax = 64
  55. // handleDeviceOverridePut: campos opcionales {"icon","name","type"}; vacío
  56. // limpia, ausente no toca. Si los tres quedan vacíos la fila se borra.
  57. func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) {
  58. mac := normalizeMAC(r.PathValue("mac"))
  59. if mac == "" || len(mac) != 17 {
  60. writeError(w, http.StatusBadRequest, "invalid_mac")
  61. return
  62. }
  63. var body struct {
  64. Icon *string `json:"icon"`
  65. Name *string `json:"name"`
  66. Type *string `json:"type"`
  67. }
  68. if st := readJSONBody(w, r, &body); st != 0 {
  69. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  70. return
  71. }
  72. if body.Icon != nil && !validateIcon(*body.Icon) {
  73. writeError(w, http.StatusBadRequest, "invalid_icon")
  74. return
  75. }
  76. if body.Type != nil && *body.Type != "" && !adapters.ValidDeviceTypes[*body.Type] {
  77. writeError(w, http.StatusBadRequest, "invalid_type")
  78. return
  79. }
  80. name := ""
  81. if body.Name != nil {
  82. name = strings.TrimSpace(*body.Name)
  83. if strings.ContainsAny(name, "\r\n") {
  84. writeError(w, http.StatusBadRequest, "invalid_name")
  85. return
  86. }
  87. if len(name) > deviceNameMax {
  88. name = name[:deviceNameMax]
  89. }
  90. }
  91. // Valores actuales (los campos ausentes conservan lo persistido).
  92. var curIcon sql.NullString
  93. var curName, curType string
  94. row := s.db.QueryRow("SELECT icon, name, device_type FROM device_overrides WHERE mac = ?", mac)
  95. switch err := row.Scan(&curIcon, &curName, &curType); err {
  96. case nil:
  97. case sql.ErrNoRows:
  98. default:
  99. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  100. return
  101. }
  102. nextIcon := curIcon.String
  103. nextName, nextType := curName, curType
  104. if body.Icon != nil {
  105. nextIcon = *body.Icon
  106. }
  107. if body.Name != nil {
  108. nextName = name
  109. }
  110. if body.Type != nil {
  111. nextType = *body.Type
  112. }
  113. now := time.Now().UnixMilli()
  114. if nextIcon == "" && nextName == "" && nextType == "" {
  115. _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
  116. } else {
  117. _, err := s.db.Exec(
  118. `INSERT INTO device_overrides (mac, icon, name, device_type, banned_bands, created_at, updated_at)
  119. VALUES (?, ?, ?, ?, '', ?, ?)
  120. ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, name=excluded.name,
  121. device_type=excluded.device_type, updated_at=excluded.updated_at`,
  122. mac, nextIcon, nextName, nextType, now, now,
  123. )
  124. if err != nil {
  125. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  126. return
  127. }
  128. }
  129. // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices.
  130. if s.pollNow != nil {
  131. s.pollNow()
  132. }
  133. writeJSON(w, http.StatusOK, map[string]any{
  134. "ok": true, "mac": mac, "icon": nextIcon, "name": nextName, "type": nextType,
  135. })
  136. }
  137. // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
  138. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
  139. mac := normalizeMAC(r.PathValue("mac"))
  140. if mac == "" || len(mac) != 17 {
  141. writeError(w, http.StatusBadRequest, "invalid_mac")
  142. return
  143. }
  144. var icon, name, deviceType, banned sql.NullString
  145. row := s.db.QueryRow("SELECT icon, name, device_type, banned_bands FROM device_overrides WHERE mac = ?", mac)
  146. if err := row.Scan(&icon, &name, &deviceType, &banned); err != nil && err != sql.ErrNoRows {
  147. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  148. return
  149. }
  150. writeJSON(w, http.StatusOK, map[string]any{
  151. "mac": mac,
  152. "icon": icon.String,
  153. "name": name.String,
  154. "type": deviceType.String,
  155. "bannedBands": banned.String,
  156. })
  157. }
  158. // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}.
  159. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437).
  160. func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
  161. var body struct {
  162. Bands []string `json:"bands"`
  163. }
  164. if st := readJSONBody(w, r, &body); st != 0 {
  165. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  166. return
  167. }
  168. _ = body
  169. writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
  170. }