device_overrides.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // device_overrides.go — mutaciones manuales de dispositivo (issue #437):
  2. //
  3. // PUT /api/devices/{mac}/override → icono.
  4. // PUT /api/devices/{mac}/ban → bandas a bloquear/desbloquear (Fase 2).
  5. package httpapi
  6. import (
  7. "database/sql"
  8. "net/http"
  9. "regexp"
  10. "strings"
  11. "time"
  12. )
  13. var macNormalizeRe = regexp.MustCompile(`[^0-9a-fA-F]`)
  14. // normalizeMAC devuelve MAC en minúsculas con ':' (la forma canónica del
  15. // server y de device_overrides).
  16. func normalizeMAC(mac string) string {
  17. hex := macNormalizeRe.ReplaceAllString(mac, "")
  18. hex = strings.ToLower(hex)
  19. var out strings.Builder
  20. for i := 0; i < len(hex); i += 2 {
  21. if i > 0 {
  22. out.WriteByte(':')
  23. }
  24. if i+2 <= len(hex) {
  25. out.WriteString(hex[i : i+2])
  26. } else {
  27. out.WriteString(hex[i:])
  28. }
  29. }
  30. return out.String()
  31. }
  32. // validateIcon comprueba que el icono enviado es uno de los permitidos por
  33. // DEVICE_ICONS del frontend. Lista cerrada para evitar inyección de clases.
  34. func validateIcon(icon string) bool {
  35. if icon == "" {
  36. return true
  37. }
  38. allowed := map[string]bool{
  39. "monitor": true, "laptop": true, "smartphone": true, "tablet": true,
  40. "tv": true, "gamepad": true, "camera": true, "speaker": true,
  41. "router": true, "server": true, "watch": true, "car": true,
  42. "home": true, "printer": true, "plug": true, "shield": true,
  43. "help-circle": true, "wifi": true, "ethernet": true,
  44. }
  45. return allowed[icon]
  46. }
  47. // handleDeviceOverridePut: body {"icon":"..."}. Vacío borra.
  48. func (s *server) handleDeviceOverridePut(w http.ResponseWriter, r *http.Request) {
  49. mac := normalizeMAC(r.PathValue("mac"))
  50. if mac == "" || len(mac) != 17 {
  51. writeError(w, http.StatusBadRequest, "invalid_mac")
  52. return
  53. }
  54. var body struct {
  55. Icon string `json:"icon"`
  56. }
  57. if st := readJSONBody(w, r, &body); st != 0 {
  58. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  59. return
  60. }
  61. if !validateIcon(body.Icon) {
  62. writeError(w, http.StatusBadRequest, "invalid_icon")
  63. return
  64. }
  65. now := time.Now().UnixMilli()
  66. if body.Icon == "" {
  67. _, _ = s.db.Exec("DELETE FROM device_overrides WHERE mac = ?", mac)
  68. } else {
  69. _, err := s.db.Exec(
  70. `INSERT INTO device_overrides (mac, icon, banned_bands, created_at, updated_at)
  71. VALUES (?, ?, '', ?, ?)
  72. ON CONFLICT(mac) DO UPDATE SET icon=excluded.icon, updated_at=excluded.updated_at`,
  73. mac, body.Icon, now, now,
  74. )
  75. if err != nil {
  76. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  77. return
  78. }
  79. }
  80. // Dispara un sondeo para que el cambio se refleje en el próximo buildDevices.
  81. if s.pollNow != nil {
  82. s.pollNow()
  83. }
  84. writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mac": mac})
  85. }
  86. // handleDeviceOverrideGet: devuelve el override actual de un dispositivo.
  87. func (s *server) handleDeviceOverrideGet(w http.ResponseWriter, r *http.Request) {
  88. mac := normalizeMAC(r.PathValue("mac"))
  89. if mac == "" || len(mac) != 17 {
  90. writeError(w, http.StatusBadRequest, "invalid_mac")
  91. return
  92. }
  93. var icon, banned sql.NullString
  94. row := s.db.QueryRow("SELECT icon, banned_bands FROM device_overrides WHERE mac = ?", mac)
  95. if err := row.Scan(&icon, &banned); err != nil && err != sql.ErrNoRows {
  96. writeError(w, http.StatusInternalServerError, "db_error", err.Error())
  97. return
  98. }
  99. writeJSON(w, http.StatusOK, map[string]any{
  100. "mac": mac,
  101. "icon": icon.String,
  102. "bannedBands": banned.String,
  103. })
  104. }
  105. // handleDeviceBanPut: body {"bands":["2.4","5","6","all"]} o {"bands":[]}.
  106. // Aplica la política de MAC filter en el router asociado (Fase 2 del issue #437).
  107. func (s *server) handleDeviceBanPut(w http.ResponseWriter, r *http.Request) {
  108. var body struct {
  109. Bands []string `json:"bands"`
  110. }
  111. if st := readJSONBody(w, r, &body); st != 0 {
  112. writeBodyError(w, st, "invalid_body", "body JSON inválido")
  113. return
  114. }
  115. _ = body
  116. writeError(w, http.StatusNotImplemented, "not_implemented", "baneo por banda: Fase 2 del issue #437")
  117. }