config.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. // config.go — rutas /api/config/* (paridad src/routes/config.js, SPEC §2.17):
  2. // CRUD de routers (tabla `routers`), clave SSH propia del servidor,
  3. // descubrimiento de la LAN y credenciales AdGuard GL.iNet (kv; la contraseña
  4. // NUNCA se devuelve). Tras cada mutación se sincroniza el adapter
  5. // (SetRouters) sin reiniciar.
  6. package httpapi
  7. import (
  8. "database/sql"
  9. "net/http"
  10. urlpkg "net/url"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "github.com/gnacho/netpulse/server-go/internal/auth"
  15. "github.com/gnacho/netpulse/server-go/internal/discover"
  16. "github.com/gnacho/netpulse/server-go/internal/pve"
  17. "github.com/gnacho/netpulse/server-go/internal/routerstore"
  18. "github.com/gnacho/netpulse/server-go/internal/sshkey"
  19. )
  20. var (
  21. hostRe = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
  22. hostPortRe = regexp.MustCompile(`^([a-zA-Z0-9._-]+)(:[0-9]{1,5})?$`)
  23. )
  24. // registerConfigRoutes registra las rutas /api/config/* en el mux.
  25. // Las mutaciones (añadir/borrar routers) y las que exponen credenciales o
  26. // escanean la red (sshkey, discover) exigen rol admin (auditoría v2.4.0 §2,
  27. // issue #7); la lista de routers es de lectura y queda tras RequireAuth.
  28. func (s *server) registerConfigRoutes(mux *http.ServeMux) {
  29. mux.Handle("GET /api/config/sshkey", auth.RequireAdmin(http.HandlerFunc(s.handleGetSSHKey)))
  30. mux.Handle("POST /api/config/sshkey/rotate", auth.RequireAdmin(http.HandlerFunc(s.handleRotateSSHKey)))
  31. mux.Handle("GET /api/config/discover", auth.RequireAdmin(http.HandlerFunc(s.handleDiscover)))
  32. mux.HandleFunc("GET /api/config/routers", s.handleListConfigRouters)
  33. mux.Handle("POST /api/config/routers", auth.RequireAdmin(http.HandlerFunc(s.handleAddConfigRouter)))
  34. mux.Handle("PUT /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleUpdateConfigRouter)))
  35. mux.Handle("DELETE /api/config/routers/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteConfigRouter)))
  36. mux.Handle("GET /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleGetAdguardConfig)))
  37. mux.Handle("PUT /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handlePutAdguardConfig)))
  38. mux.Handle("DELETE /api/config/adguard", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteAdguardConfig)))
  39. mux.Handle("POST /api/config/adguard/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectAdguard)))
  40. mux.Handle("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
  41. mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
  42. mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
  43. mux.Handle("POST /api/config/proxmox/test", auth.RequireAdmin(http.HandlerFunc(s.handleTestProxmoxConfig)))
  44. mux.Handle("POST /api/config/proxmox/detect", auth.RequireAdmin(http.HandlerFunc(s.handleDetectProxmox)))
  45. }
  46. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  47. func (s *server) syncRouters() {
  48. if s.adapter != nil {
  49. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  50. }
  51. }
  52. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  53. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  54. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  55. if key == nil {
  56. writeError(w, http.StatusInternalServerError, "no_key")
  57. return
  58. }
  59. writeJSON(w, http.StatusOK, key)
  60. }
  61. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  62. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  63. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  64. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  65. // (la UI pide escribir la palabra de confirmación).
  66. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  67. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  68. if err != nil {
  69. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  70. return
  71. }
  72. writeJSON(w, http.StatusOK, map[string]any{
  73. "publicKey": key.PublicKey,
  74. "fingerprint": key.Fingerprint,
  75. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  76. })
  77. }
  78. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  79. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  80. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  81. writeJSON(w, http.StatusOK, result)
  82. }
  83. // GET /api/config/routers — lista configurada (no el estado sondeado).
  84. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  85. writeJSON(w, http.StatusOK, map[string]any{"routers": routerstore.ListRouters(s.db.DB)})
  86. }
  87. type routerInput struct {
  88. Name *string `json:"name"`
  89. Host *string `json:"host"`
  90. Type string `json:"type"`
  91. Gateway bool `json:"gateway"`
  92. AgentOnly bool `json:"agent_only"`
  93. // Disabled (issue #1085): pausa la unidad (nil = no tocar).
  94. Disabled *bool `json:"disabled"`
  95. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  96. FirmwareTarget *string `json:"firmware_target"`
  97. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  98. SnmpEnabled *bool `json:"snmp_enabled"`
  99. // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
  100. ConsolePolling *bool `json:"console_polling"`
  101. SnmpCommunity *string `json:"snmp_community"`
  102. SnmpPort *int `json:"snmp_port"`
  103. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  104. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  105. // estándar). Ausente/0 → 22.
  106. SSHPort *int `json:"ssh_port"`
  107. // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
  108. // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
  109. TempThreshold *int `json:"temp_threshold"`
  110. // RouterOS: credenciales de la REST API nativa (Type "routeros").
  111. RouterOSUser *string `json:"routeros_user"`
  112. RouterOSPassword *string `json:"routeros_password"`
  113. RouterOSInsecure *bool `json:"routeros_insecure"`
  114. }
  115. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  116. // trimmeado o "" + mensaje de error.
  117. func validateHost(host string) (string, string) {
  118. h := strings.TrimSpace(host)
  119. if len(h) < 1 {
  120. return "", "String must contain at least 1 character(s)"
  121. }
  122. if len(h) > 253 {
  123. return "", "String must contain at most 253 character(s)"
  124. }
  125. if !hostRe.MatchString(h) {
  126. return "", "host debe ser una IP o hostname válido"
  127. }
  128. return h, ""
  129. }
  130. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  131. // host, puerto y mensaje de error.
  132. func validateAdGuardHost(host string) (string, int, string) {
  133. h := strings.TrimSpace(host)
  134. if len(h) < 1 {
  135. return "", 0, "String must contain at least 1 character(s)"
  136. }
  137. if len(h) > 253 {
  138. return "", 0, "String must contain at most 253 character(s)"
  139. }
  140. m := hostPortRe.FindStringSubmatch(h)
  141. if m == nil {
  142. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  143. }
  144. addr := m[1]
  145. port := 0
  146. if m[2] != "" {
  147. p, err := strconv.Atoi(m[2][1:])
  148. if err != nil || p < 1 || p > 65535 {
  149. return "", 0, "puerto fuera de rango (1-65535)"
  150. }
  151. port = p
  152. }
  153. return addr, port, ""
  154. }
  155. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  156. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  157. var in routerInput
  158. if st := readJSONBody(w, r, &in); st != 0 {
  159. writeBodyError(w, st, "invalid_json", "")
  160. return
  161. }
  162. // Orden de validación del schema zod: name, host, type
  163. name := ""
  164. if in.Name != nil {
  165. name = strings.TrimSpace(*in.Name)
  166. if len(name) < 1 {
  167. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  168. return
  169. }
  170. if len(name) > 60 {
  171. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  172. return
  173. }
  174. }
  175. if in.Host == nil {
  176. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  177. return
  178. }
  179. host, msg := validateHost(*in.Host)
  180. if msg != "" {
  181. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  182. return
  183. }
  184. typ := in.Type
  185. if typ == "" {
  186. typ = "openwrt"
  187. }
  188. if typ != "glinet" && typ != "openwrt" && typ != "routeros" && typ != "managed-switch" && typ != "external" {
  189. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
  190. return
  191. }
  192. var firmwareTarget string
  193. if in.FirmwareTarget != nil {
  194. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  195. }
  196. snmpEnabled := false
  197. if in.SnmpEnabled != nil {
  198. snmpEnabled = *in.SnmpEnabled
  199. }
  200. snmpCommunity := ""
  201. if in.SnmpCommunity != nil {
  202. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  203. }
  204. snmpPort := 0
  205. if in.SnmpPort != nil {
  206. snmpPort = *in.SnmpPort
  207. if snmpPort < 0 || snmpPort > 65535 {
  208. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  209. return
  210. }
  211. }
  212. snmpInterval := 60
  213. if in.SnmpPollInterval != nil {
  214. snmpInterval = *in.SnmpPollInterval
  215. if snmpInterval < 10 || snmpInterval > 3600 {
  216. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  217. return
  218. }
  219. }
  220. for _, rt := range routerstore.ListRouters(s.db.DB) {
  221. if rt.Host == host {
  222. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  223. return
  224. }
  225. }
  226. sshPort := 0
  227. if in.SSHPort != nil {
  228. p := *in.SSHPort
  229. if p < 1 || p > 65535 {
  230. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  231. return
  232. }
  233. sshPort = p
  234. }
  235. routerosUser := ""
  236. if in.RouterOSUser != nil {
  237. routerosUser = strings.TrimSpace(*in.RouterOSUser)
  238. }
  239. routerosPassword := ""
  240. if in.RouterOSPassword != nil {
  241. routerosPassword = *in.RouterOSPassword
  242. }
  243. routerosInsecure := false
  244. if in.RouterOSInsecure != nil {
  245. routerosInsecure = *in.RouterOSInsecure
  246. }
  247. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  248. Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  249. FirmwareTarget: firmwareTarget,
  250. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  251. SSHPort: sshPort,
  252. RouterOSUser: routerosUser, RouterOSPassword: routerosPassword, RouterOSInsecure: routerosInsecure,
  253. })
  254. if err != nil {
  255. writeError(w, http.StatusInternalServerError, "internal_error")
  256. return
  257. }
  258. s.syncRouters()
  259. writeJSON(w, http.StatusCreated, map[string]any{"router": created})
  260. }
  261. // DELETE /api/config/routers/:id — 204 o 404.
  262. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  263. id := r.PathValue("id")
  264. // #1276: MAC aprendida del último push del agente (bridge MAC), para
  265. // purgar su entrada del registro de clientes tras borrar el router.
  266. var macs []string
  267. if s.agents != nil {
  268. if p, ok := s.agents.StalePayload(id); ok {
  269. if sys := p.Data.System; sys != nil && sys.BridgeMAC != "" {
  270. macs = append(macs, sys.BridgeMAC)
  271. }
  272. }
  273. }
  274. if !routerstore.RemoveRouter(s.db.DB, id) {
  275. writeError(w, http.StatusNotFound, "not_found")
  276. return
  277. }
  278. // #1276: limpieza del stub de Dispositivos/Agentes. Sin esto, el estado
  279. // persistido (agent.state.*) y el registro seguían listando la unidad
  280. // borrada sin forma de quitarla. Se revoca TAMBIÉN el token: si el
  281. // agente sigue instalado en la caja, su siguiente push recibe 401 y
  282. // deja de re-crear la entrada. Re-añadir el router requiere re-emparejar
  283. // el agente (reinstall).
  284. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTokenKeyPrefix+id)
  285. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentStateKeyPrefix+id)
  286. _, _ = s.db.Exec("DELETE FROM kv WHERE key = ?", agentTransportPrefix+id)
  287. if s.agents != nil {
  288. s.agents.Forget(id)
  289. }
  290. for _, m := range macs {
  291. _, _ = s.db.Exec("DELETE FROM device_seen WHERE mac = ? OR mac = ?",
  292. strings.ToUpper(m), strings.ToLower(strings.ReplaceAll(m, ":", "-")))
  293. }
  294. s.syncRouters()
  295. w.WriteHeader(http.StatusNoContent)
  296. }
  297. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  298. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  299. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  300. id := r.PathValue("id")
  301. var in routerInput
  302. if st := readJSONBody(w, r, &in); st != 0 {
  303. writeBodyError(w, st, "invalid_json", "")
  304. return
  305. }
  306. var name *string
  307. if in.Name != nil {
  308. n := strings.TrimSpace(*in.Name)
  309. if len(n) < 1 {
  310. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  311. return
  312. }
  313. if len(n) > 60 {
  314. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  315. return
  316. }
  317. name = &n
  318. }
  319. var host *string
  320. if in.Host != nil {
  321. h, msg := validateHost(*in.Host)
  322. if msg != "" {
  323. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  324. return
  325. }
  326. // Duplicado: otro router con ese host (excluyendo el propio id).
  327. for _, rt := range routerstore.ListRouters(s.db.DB) {
  328. if rt.Host == h && rt.ID != id {
  329. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  330. return
  331. }
  332. }
  333. host = &h
  334. }
  335. var typ *string
  336. if in.Type != "" {
  337. t := in.Type
  338. if t != "glinet" && t != "openwrt" && t != "routeros" && t != "managed-switch" && t != "external" {
  339. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
  340. return
  341. }
  342. typ = &t
  343. }
  344. gw := in.Gateway
  345. ao := in.AgentOnly
  346. var firmwareTarget *string
  347. if in.FirmwareTarget != nil {
  348. v := strings.TrimSpace(*in.FirmwareTarget)
  349. firmwareTarget = &v
  350. }
  351. var snmpPollInterval *int
  352. if in.SnmpPollInterval != nil {
  353. v := *in.SnmpPollInterval
  354. if v < 10 || v > 3600 {
  355. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  356. return
  357. }
  358. snmpPollInterval = &v
  359. }
  360. var snmpPort *int
  361. if in.SnmpPort != nil {
  362. p := *in.SnmpPort
  363. if p < 0 || p > 65535 {
  364. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  365. return
  366. }
  367. snmpPort = &p
  368. }
  369. var snmpCommunity *string
  370. if in.SnmpCommunity != nil {
  371. v := strings.TrimSpace(*in.SnmpCommunity)
  372. snmpCommunity = &v
  373. }
  374. var sshPort *int
  375. if in.SSHPort != nil {
  376. p := *in.SSHPort
  377. if p < 1 || p > 65535 {
  378. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  379. return
  380. }
  381. sshPort = &p
  382. }
  383. var tempThreshold *int
  384. if in.TempThreshold != nil {
  385. v := *in.TempThreshold
  386. if v > 150 {
  387. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  388. return
  389. }
  390. tempThreshold = &v
  391. }
  392. var routerosUser *string
  393. if in.RouterOSUser != nil {
  394. v := strings.TrimSpace(*in.RouterOSUser)
  395. routerosUser = &v
  396. }
  397. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  398. Name: name, Host: host, Type: typ,
  399. IsGateway: &gw, AgentOnly: &ao,
  400. Disabled: in.Disabled,
  401. FirmwareTarget: firmwareTarget,
  402. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  403. SSHPort: sshPort,
  404. TempThreshold: tempThreshold,
  405. ConsolePolling: in.ConsolePolling,
  406. RouterOSUser: routerosUser, RouterOSPassword: in.RouterOSPassword, RouterOSInsecure: in.RouterOSInsecure,
  407. })
  408. if !ok {
  409. writeError(w, http.StatusNotFound, "not_found")
  410. return
  411. }
  412. s.syncRouters()
  413. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  414. }
  415. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  416. func kvGet(db *sql.DB, key string) string {
  417. var v string
  418. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  419. return ""
  420. }
  421. return v
  422. }
  423. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  424. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  425. user := kvGet(s.db.DB, "adguard_user")
  426. if user == "" {
  427. user = "root"
  428. }
  429. mode := kvGet(s.db.DB, "adguard_mode")
  430. if mode == "" {
  431. mode = "glinet"
  432. }
  433. portStr := kvGet(s.db.DB, "adguard_port")
  434. port := 0
  435. if p, err := strconv.Atoi(portStr); err == nil {
  436. port = p
  437. }
  438. writeJSON(w, http.StatusOK, map[string]any{
  439. "mode": mode,
  440. "host": kvGet(s.db.DB, "adguard_host"),
  441. "port": port,
  442. "user": user,
  443. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  444. })
  445. }
  446. type adguardInput struct {
  447. Mode string `json:"mode"`
  448. Host *string `json:"host"`
  449. Port int `json:"port"`
  450. User string `json:"user"`
  451. Password string `json:"password"`
  452. }
  453. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  454. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  455. var in adguardInput
  456. if st := readJSONBody(w, r, &in); st != 0 {
  457. writeBodyError(w, st, "invalid_json", "")
  458. return
  459. }
  460. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  461. if mode == "" {
  462. mode = "glinet"
  463. }
  464. if mode != "glinet" && mode != "standard" {
  465. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  466. return
  467. }
  468. if in.Host == nil {
  469. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  470. return
  471. }
  472. host := strings.TrimSpace(*in.Host)
  473. port := 0
  474. if mode == "standard" {
  475. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  476. if msg != "" {
  477. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  478. return
  479. }
  480. host = hostFromVal
  481. if in.Port < 1 || in.Port > 65535 {
  482. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  483. return
  484. }
  485. port = in.Port
  486. if port == 0 {
  487. port = portFromHost
  488. }
  489. if port == 0 {
  490. port = 3000
  491. }
  492. }
  493. user := strings.TrimSpace(in.User)
  494. if user == "" {
  495. user = "root"
  496. }
  497. if len(user) > 64 {
  498. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  499. return
  500. }
  501. if len(in.Password) > 128 {
  502. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  503. return
  504. }
  505. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  506. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  507. writeError(w, http.StatusInternalServerError, "internal_error")
  508. return
  509. }
  510. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  511. writeError(w, http.StatusInternalServerError, "internal_error")
  512. return
  513. }
  514. if mode == "standard" {
  515. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  516. writeError(w, http.StatusInternalServerError, "internal_error")
  517. return
  518. }
  519. } else {
  520. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  521. writeError(w, http.StatusInternalServerError, "internal_error")
  522. return
  523. }
  524. }
  525. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  526. writeError(w, http.StatusInternalServerError, "internal_error")
  527. return
  528. }
  529. if in.Password != "" {
  530. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  531. writeError(w, http.StatusInternalServerError, "internal_error")
  532. return
  533. }
  534. }
  535. w.WriteHeader(http.StatusNoContent)
  536. }
  537. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  538. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  539. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  540. // Idempotente: 204 aunque no hubiera nada configurado.
  541. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  542. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  543. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  544. writeError(w, http.StatusInternalServerError, "internal_error")
  545. return
  546. }
  547. }
  548. if s.pollNow != nil {
  549. s.pollNow()
  550. }
  551. w.WriteHeader(http.StatusNoContent)
  552. }
  553. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  554. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  555. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  556. // para no romper frontends cacheados.
  557. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  558. instances := pve.LoadInstances(s.db.DB)
  559. // Vista sanitizada: el secret JAMAS sale del server (#764).
  560. view := make([]map[string]string, 0, len(instances))
  561. for _, in := range instances {
  562. view = append(view, map[string]string{
  563. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  564. })
  565. }
  566. out := map[string]any{
  567. "instances": view,
  568. "url": "",
  569. "tokenId": "",
  570. "tokenSet": false,
  571. }
  572. if len(instances) > 0 {
  573. out["url"] = instances[0].URL
  574. out["tokenId"] = instances[0].TokenID
  575. out["tokenSet"] = instances[0].Secret != ""
  576. }
  577. writeJSON(w, http.StatusOK, out)
  578. }
  579. type proxmoxInput struct {
  580. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  581. TokenID string `json:"tokenId"`
  582. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  583. }
  584. type proxmoxInstanceInput struct {
  585. ID string `json:"id"`
  586. Name string `json:"name"`
  587. URL string `json:"url"`
  588. TokenID string `json:"tokenId"`
  589. Secret string `json:"secret"` // vacío en edición = conservar el actual
  590. }
  591. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  592. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  593. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  594. // migrada "default", creándola si hace falta; url "" desactiva todo).
  595. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  596. var in proxmoxInstanceInput
  597. if st := readJSONBody(w, r, &in); st != 0 {
  598. writeBodyError(w, st, "invalid_json", "")
  599. return
  600. }
  601. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  602. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  603. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  604. tokenID := strings.TrimSpace(in.TokenID)
  605. if len(tokenID) > 128 || len(in.Secret) > 256 {
  606. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  607. return
  608. }
  609. id := strings.TrimSpace(in.ID)
  610. if id == "" {
  611. id = "default" // legacy sin id
  612. }
  613. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  614. if url != "" {
  615. u, err := urlpkg.Parse(url)
  616. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  617. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  618. return
  619. }
  620. }
  621. list := pve.LoadInstances(s.db.DB)
  622. var current *pve.Instance
  623. for i := range list {
  624. if list[i].ID == id {
  625. current = &list[i]
  626. break
  627. }
  628. }
  629. if current != nil {
  630. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
  631. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  632. return
  633. }
  634. if url != "" {
  635. current.URL = url
  636. }
  637. if tokenID != "" {
  638. current.TokenID = tokenID
  639. }
  640. if in.Secret != "" {
  641. current.Secret = in.Secret
  642. }
  643. if n := strings.TrimSpace(in.Name); n != "" {
  644. current.Name = n
  645. }
  646. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  647. writeError(w, http.StatusInternalServerError, "internal_error")
  648. return
  649. }
  650. w.WriteHeader(http.StatusNoContent)
  651. return
  652. }
  653. // Instancia nueva: completa.
  654. if url == "" || tokenID == "" || in.Secret == "" {
  655. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  656. return
  657. }
  658. name := strings.TrimSpace(in.Name)
  659. if name == "" {
  660. name = id
  661. }
  662. inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
  663. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  664. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  665. return
  666. }
  667. w.WriteHeader(http.StatusNoContent)
  668. }
  669. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  670. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  671. id := r.PathValue("id")
  672. if !pve.ValidInstanceID(id) {
  673. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  674. return
  675. }
  676. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  677. writeError(w, http.StatusInternalServerError, "internal_error")
  678. return
  679. }
  680. w.WriteHeader(http.StatusNoContent)
  681. }
  682. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  683. //
  684. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  685. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  686. // rechaza) y la integración se queda muda — indistinguible de un cluster
  687. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  688. //
  689. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  690. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  691. // reutiliza el almacenado, igual que el PUT.
  692. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  693. var in proxmoxInstanceInput
  694. _ = readJSONBody(w, r, &in) // cuerpo opcional
  695. id := strings.TrimSpace(in.ID)
  696. if id == "" {
  697. id = "default"
  698. }
  699. var cfg pve.Config
  700. for _, inst := range pve.LoadInstances(s.db.DB) {
  701. if inst.ID == id {
  702. cfg = inst.Config
  703. break
  704. }
  705. }
  706. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  707. cfg.URL = u
  708. }
  709. if t := strings.TrimSpace(in.TokenID); t != "" {
  710. cfg.TokenID = t
  711. }
  712. if in.Secret != "" {
  713. cfg.Secret = in.Secret
  714. }
  715. if !cfg.Enabled() {
  716. writeError(w, http.StatusBadRequest, "invalid_input", "faltan url, tokenId o secret")
  717. return
  718. }
  719. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  720. // poder enseñar lo que contestó Proxmox.
  721. res, err := pve.NewClient(cfg).Test(r.Context())
  722. if err != nil {
  723. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  724. return
  725. }
  726. writeJSON(w, http.StatusOK, map[string]any{
  727. "ok": true, "version": res.Version, "nodes": res.Nodes,
  728. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  729. })
  730. }