config.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
  264. writeError(w, http.StatusNotFound, "not_found")
  265. return
  266. }
  267. s.syncRouters()
  268. w.WriteHeader(http.StatusNoContent)
  269. }
  270. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  271. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  272. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  273. id := r.PathValue("id")
  274. var in routerInput
  275. if st := readJSONBody(w, r, &in); st != 0 {
  276. writeBodyError(w, st, "invalid_json", "")
  277. return
  278. }
  279. var name *string
  280. if in.Name != nil {
  281. n := strings.TrimSpace(*in.Name)
  282. if len(n) < 1 {
  283. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  284. return
  285. }
  286. if len(n) > 60 {
  287. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  288. return
  289. }
  290. name = &n
  291. }
  292. var host *string
  293. if in.Host != nil {
  294. h, msg := validateHost(*in.Host)
  295. if msg != "" {
  296. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  297. return
  298. }
  299. // Duplicado: otro router con ese host (excluyendo el propio id).
  300. for _, rt := range routerstore.ListRouters(s.db.DB) {
  301. if rt.Host == h && rt.ID != id {
  302. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  303. return
  304. }
  305. }
  306. host = &h
  307. }
  308. var typ *string
  309. if in.Type != "" {
  310. t := in.Type
  311. if t != "glinet" && t != "openwrt" && t != "routeros" && t != "managed-switch" && t != "external" {
  312. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
  313. return
  314. }
  315. typ = &t
  316. }
  317. gw := in.Gateway
  318. ao := in.AgentOnly
  319. var firmwareTarget *string
  320. if in.FirmwareTarget != nil {
  321. v := strings.TrimSpace(*in.FirmwareTarget)
  322. firmwareTarget = &v
  323. }
  324. var snmpPollInterval *int
  325. if in.SnmpPollInterval != nil {
  326. v := *in.SnmpPollInterval
  327. if v < 10 || v > 3600 {
  328. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  329. return
  330. }
  331. snmpPollInterval = &v
  332. }
  333. var snmpPort *int
  334. if in.SnmpPort != nil {
  335. p := *in.SnmpPort
  336. if p < 0 || p > 65535 {
  337. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  338. return
  339. }
  340. snmpPort = &p
  341. }
  342. var snmpCommunity *string
  343. if in.SnmpCommunity != nil {
  344. v := strings.TrimSpace(*in.SnmpCommunity)
  345. snmpCommunity = &v
  346. }
  347. var sshPort *int
  348. if in.SSHPort != nil {
  349. p := *in.SSHPort
  350. if p < 1 || p > 65535 {
  351. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  352. return
  353. }
  354. sshPort = &p
  355. }
  356. var tempThreshold *int
  357. if in.TempThreshold != nil {
  358. v := *in.TempThreshold
  359. if v > 150 {
  360. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  361. return
  362. }
  363. tempThreshold = &v
  364. }
  365. var routerosUser *string
  366. if in.RouterOSUser != nil {
  367. v := strings.TrimSpace(*in.RouterOSUser)
  368. routerosUser = &v
  369. }
  370. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  371. Name: name, Host: host, Type: typ,
  372. IsGateway: &gw, AgentOnly: &ao,
  373. Disabled: in.Disabled,
  374. FirmwareTarget: firmwareTarget,
  375. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  376. SSHPort: sshPort,
  377. TempThreshold: tempThreshold,
  378. ConsolePolling: in.ConsolePolling,
  379. RouterOSUser: routerosUser, RouterOSPassword: in.RouterOSPassword, RouterOSInsecure: in.RouterOSInsecure,
  380. })
  381. if !ok {
  382. writeError(w, http.StatusNotFound, "not_found")
  383. return
  384. }
  385. s.syncRouters()
  386. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  387. }
  388. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  389. func kvGet(db *sql.DB, key string) string {
  390. var v string
  391. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  392. return ""
  393. }
  394. return v
  395. }
  396. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  397. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  398. user := kvGet(s.db.DB, "adguard_user")
  399. if user == "" {
  400. user = "root"
  401. }
  402. mode := kvGet(s.db.DB, "adguard_mode")
  403. if mode == "" {
  404. mode = "glinet"
  405. }
  406. portStr := kvGet(s.db.DB, "adguard_port")
  407. port := 0
  408. if p, err := strconv.Atoi(portStr); err == nil {
  409. port = p
  410. }
  411. writeJSON(w, http.StatusOK, map[string]any{
  412. "mode": mode,
  413. "host": kvGet(s.db.DB, "adguard_host"),
  414. "port": port,
  415. "user": user,
  416. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  417. })
  418. }
  419. type adguardInput struct {
  420. Mode string `json:"mode"`
  421. Host *string `json:"host"`
  422. Port int `json:"port"`
  423. User string `json:"user"`
  424. Password string `json:"password"`
  425. }
  426. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  427. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  428. var in adguardInput
  429. if st := readJSONBody(w, r, &in); st != 0 {
  430. writeBodyError(w, st, "invalid_json", "")
  431. return
  432. }
  433. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  434. if mode == "" {
  435. mode = "glinet"
  436. }
  437. if mode != "glinet" && mode != "standard" {
  438. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  439. return
  440. }
  441. if in.Host == nil {
  442. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  443. return
  444. }
  445. host := strings.TrimSpace(*in.Host)
  446. port := 0
  447. if mode == "standard" {
  448. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  449. if msg != "" {
  450. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  451. return
  452. }
  453. host = hostFromVal
  454. if in.Port < 1 || in.Port > 65535 {
  455. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  456. return
  457. }
  458. port = in.Port
  459. if port == 0 {
  460. port = portFromHost
  461. }
  462. if port == 0 {
  463. port = 3000
  464. }
  465. }
  466. user := strings.TrimSpace(in.User)
  467. if user == "" {
  468. user = "root"
  469. }
  470. if len(user) > 64 {
  471. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  472. return
  473. }
  474. if len(in.Password) > 128 {
  475. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  476. return
  477. }
  478. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  479. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  480. writeError(w, http.StatusInternalServerError, "internal_error")
  481. return
  482. }
  483. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  484. writeError(w, http.StatusInternalServerError, "internal_error")
  485. return
  486. }
  487. if mode == "standard" {
  488. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  489. writeError(w, http.StatusInternalServerError, "internal_error")
  490. return
  491. }
  492. } else {
  493. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  494. writeError(w, http.StatusInternalServerError, "internal_error")
  495. return
  496. }
  497. }
  498. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  499. writeError(w, http.StatusInternalServerError, "internal_error")
  500. return
  501. }
  502. if in.Password != "" {
  503. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  504. writeError(w, http.StatusInternalServerError, "internal_error")
  505. return
  506. }
  507. }
  508. w.WriteHeader(http.StatusNoContent)
  509. }
  510. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  511. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  512. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  513. // Idempotente: 204 aunque no hubiera nada configurado.
  514. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  515. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  516. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  517. writeError(w, http.StatusInternalServerError, "internal_error")
  518. return
  519. }
  520. }
  521. if s.pollNow != nil {
  522. s.pollNow()
  523. }
  524. w.WriteHeader(http.StatusNoContent)
  525. }
  526. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  527. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  528. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  529. // para no romper frontends cacheados.
  530. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  531. instances := pve.LoadInstances(s.db.DB)
  532. // Vista sanitizada: el secret JAMAS sale del server (#764).
  533. view := make([]map[string]string, 0, len(instances))
  534. for _, in := range instances {
  535. view = append(view, map[string]string{
  536. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  537. })
  538. }
  539. out := map[string]any{
  540. "instances": view,
  541. "url": "",
  542. "tokenId": "",
  543. "tokenSet": false,
  544. }
  545. if len(instances) > 0 {
  546. out["url"] = instances[0].URL
  547. out["tokenId"] = instances[0].TokenID
  548. out["tokenSet"] = instances[0].Secret != ""
  549. }
  550. writeJSON(w, http.StatusOK, out)
  551. }
  552. type proxmoxInput struct {
  553. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  554. TokenID string `json:"tokenId"`
  555. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  556. }
  557. type proxmoxInstanceInput struct {
  558. ID string `json:"id"`
  559. Name string `json:"name"`
  560. URL string `json:"url"`
  561. TokenID string `json:"tokenId"`
  562. Secret string `json:"secret"` // vacío en edición = conservar el actual
  563. }
  564. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  565. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  566. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  567. // migrada "default", creándola si hace falta; url "" desactiva todo).
  568. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  569. var in proxmoxInstanceInput
  570. if st := readJSONBody(w, r, &in); st != 0 {
  571. writeBodyError(w, st, "invalid_json", "")
  572. return
  573. }
  574. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  575. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  576. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  577. tokenID := strings.TrimSpace(in.TokenID)
  578. if len(tokenID) > 128 || len(in.Secret) > 256 {
  579. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  580. return
  581. }
  582. id := strings.TrimSpace(in.ID)
  583. if id == "" {
  584. id = "default" // legacy sin id
  585. }
  586. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  587. if url != "" {
  588. u, err := urlpkg.Parse(url)
  589. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  590. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  591. return
  592. }
  593. }
  594. list := pve.LoadInstances(s.db.DB)
  595. var current *pve.Instance
  596. for i := range list {
  597. if list[i].ID == id {
  598. current = &list[i]
  599. break
  600. }
  601. }
  602. if current != nil {
  603. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
  604. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  605. return
  606. }
  607. if url != "" {
  608. current.URL = url
  609. }
  610. if tokenID != "" {
  611. current.TokenID = tokenID
  612. }
  613. if in.Secret != "" {
  614. current.Secret = in.Secret
  615. }
  616. if n := strings.TrimSpace(in.Name); n != "" {
  617. current.Name = n
  618. }
  619. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  620. writeError(w, http.StatusInternalServerError, "internal_error")
  621. return
  622. }
  623. w.WriteHeader(http.StatusNoContent)
  624. return
  625. }
  626. // Instancia nueva: completa.
  627. if url == "" || tokenID == "" || in.Secret == "" {
  628. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  629. return
  630. }
  631. name := strings.TrimSpace(in.Name)
  632. if name == "" {
  633. name = id
  634. }
  635. inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
  636. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  637. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  638. return
  639. }
  640. w.WriteHeader(http.StatusNoContent)
  641. }
  642. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  643. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  644. id := r.PathValue("id")
  645. if !pve.ValidInstanceID(id) {
  646. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  647. return
  648. }
  649. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  650. writeError(w, http.StatusInternalServerError, "internal_error")
  651. return
  652. }
  653. w.WriteHeader(http.StatusNoContent)
  654. }
  655. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  656. //
  657. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  658. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  659. // rechaza) y la integración se queda muda — indistinguible de un cluster
  660. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  661. //
  662. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  663. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  664. // reutiliza el almacenado, igual que el PUT.
  665. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  666. var in proxmoxInstanceInput
  667. _ = readJSONBody(w, r, &in) // cuerpo opcional
  668. id := strings.TrimSpace(in.ID)
  669. if id == "" {
  670. id = "default"
  671. }
  672. var cfg pve.Config
  673. for _, inst := range pve.LoadInstances(s.db.DB) {
  674. if inst.ID == id {
  675. cfg = inst.Config
  676. break
  677. }
  678. }
  679. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  680. cfg.URL = u
  681. }
  682. if t := strings.TrimSpace(in.TokenID); t != "" {
  683. cfg.TokenID = t
  684. }
  685. if in.Secret != "" {
  686. cfg.Secret = in.Secret
  687. }
  688. if !cfg.Enabled() {
  689. writeError(w, http.StatusBadRequest, "invalid_input", "faltan url, tokenId o secret")
  690. return
  691. }
  692. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  693. // poder enseñar lo que contestó Proxmox.
  694. res, err := pve.NewClient(cfg).Test(r.Context())
  695. if err != nil {
  696. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  697. return
  698. }
  699. writeJSON(w, http.StatusOK, map[string]any{
  700. "ok": true, "version": res.Version, "nodes": res.Nodes,
  701. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  702. })
  703. }