config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  94. FirmwareTarget *string `json:"firmware_target"`
  95. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  96. SnmpEnabled *bool `json:"snmp_enabled"`
  97. // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
  98. ConsolePolling *bool `json:"console_polling"`
  99. SnmpCommunity *string `json:"snmp_community"`
  100. SnmpPort *int `json:"snmp_port"`
  101. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  102. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  103. // estándar). Ausente/0 → 22.
  104. SSHPort *int `json:"ssh_port"`
  105. // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
  106. // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
  107. TempThreshold *int `json:"temp_threshold"`
  108. // RouterOS: credenciales de la REST API nativa (Type "routeros").
  109. RouterOSUser *string `json:"routeros_user"`
  110. RouterOSPassword *string `json:"routeros_password"`
  111. RouterOSInsecure *bool `json:"routeros_insecure"`
  112. }
  113. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  114. // trimmeado o "" + mensaje de error.
  115. func validateHost(host string) (string, string) {
  116. h := strings.TrimSpace(host)
  117. if len(h) < 1 {
  118. return "", "String must contain at least 1 character(s)"
  119. }
  120. if len(h) > 253 {
  121. return "", "String must contain at most 253 character(s)"
  122. }
  123. if !hostRe.MatchString(h) {
  124. return "", "host debe ser una IP o hostname válido"
  125. }
  126. return h, ""
  127. }
  128. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  129. // host, puerto y mensaje de error.
  130. func validateAdGuardHost(host string) (string, int, string) {
  131. h := strings.TrimSpace(host)
  132. if len(h) < 1 {
  133. return "", 0, "String must contain at least 1 character(s)"
  134. }
  135. if len(h) > 253 {
  136. return "", 0, "String must contain at most 253 character(s)"
  137. }
  138. m := hostPortRe.FindStringSubmatch(h)
  139. if m == nil {
  140. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  141. }
  142. addr := m[1]
  143. port := 0
  144. if m[2] != "" {
  145. p, err := strconv.Atoi(m[2][1:])
  146. if err != nil || p < 1 || p > 65535 {
  147. return "", 0, "puerto fuera de rango (1-65535)"
  148. }
  149. port = p
  150. }
  151. return addr, port, ""
  152. }
  153. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  154. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  155. var in routerInput
  156. if st := readJSONBody(w, r, &in); st != 0 {
  157. writeBodyError(w, st, "invalid_json", "")
  158. return
  159. }
  160. // Orden de validación del schema zod: name, host, type
  161. name := ""
  162. if in.Name != nil {
  163. name = strings.TrimSpace(*in.Name)
  164. if len(name) < 1 {
  165. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  166. return
  167. }
  168. if len(name) > 60 {
  169. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  170. return
  171. }
  172. }
  173. if in.Host == nil {
  174. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  175. return
  176. }
  177. host, msg := validateHost(*in.Host)
  178. if msg != "" {
  179. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  180. return
  181. }
  182. typ := in.Type
  183. if typ == "" {
  184. typ = "openwrt"
  185. }
  186. if typ != "glinet" && typ != "openwrt" && typ != "routeros" && typ != "managed-switch" && typ != "external" {
  187. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
  188. return
  189. }
  190. var firmwareTarget string
  191. if in.FirmwareTarget != nil {
  192. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  193. }
  194. snmpEnabled := false
  195. if in.SnmpEnabled != nil {
  196. snmpEnabled = *in.SnmpEnabled
  197. }
  198. snmpCommunity := ""
  199. if in.SnmpCommunity != nil {
  200. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  201. }
  202. snmpPort := 0
  203. if in.SnmpPort != nil {
  204. snmpPort = *in.SnmpPort
  205. if snmpPort < 0 || snmpPort > 65535 {
  206. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  207. return
  208. }
  209. }
  210. snmpInterval := 60
  211. if in.SnmpPollInterval != nil {
  212. snmpInterval = *in.SnmpPollInterval
  213. if snmpInterval < 10 || snmpInterval > 3600 {
  214. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  215. return
  216. }
  217. }
  218. for _, rt := range routerstore.ListRouters(s.db.DB) {
  219. if rt.Host == host {
  220. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  221. return
  222. }
  223. }
  224. sshPort := 0
  225. if in.SSHPort != nil {
  226. p := *in.SSHPort
  227. if p < 1 || p > 65535 {
  228. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  229. return
  230. }
  231. sshPort = p
  232. }
  233. routerosUser := ""
  234. if in.RouterOSUser != nil {
  235. routerosUser = strings.TrimSpace(*in.RouterOSUser)
  236. }
  237. routerosPassword := ""
  238. if in.RouterOSPassword != nil {
  239. routerosPassword = *in.RouterOSPassword
  240. }
  241. routerosInsecure := false
  242. if in.RouterOSInsecure != nil {
  243. routerosInsecure = *in.RouterOSInsecure
  244. }
  245. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  246. Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  247. FirmwareTarget: firmwareTarget,
  248. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  249. SSHPort: sshPort,
  250. RouterOSUser: routerosUser, RouterOSPassword: routerosPassword, RouterOSInsecure: routerosInsecure,
  251. })
  252. if err != nil {
  253. writeError(w, http.StatusInternalServerError, "internal_error")
  254. return
  255. }
  256. s.syncRouters()
  257. writeJSON(w, http.StatusCreated, map[string]any{"router": created})
  258. }
  259. // DELETE /api/config/routers/:id — 204 o 404.
  260. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  261. if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
  262. writeError(w, http.StatusNotFound, "not_found")
  263. return
  264. }
  265. s.syncRouters()
  266. w.WriteHeader(http.StatusNoContent)
  267. }
  268. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  269. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  270. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  271. id := r.PathValue("id")
  272. var in routerInput
  273. if st := readJSONBody(w, r, &in); st != 0 {
  274. writeBodyError(w, st, "invalid_json", "")
  275. return
  276. }
  277. var name *string
  278. if in.Name != nil {
  279. n := strings.TrimSpace(*in.Name)
  280. if len(n) < 1 {
  281. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  282. return
  283. }
  284. if len(n) > 60 {
  285. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  286. return
  287. }
  288. name = &n
  289. }
  290. var host *string
  291. if in.Host != nil {
  292. h, msg := validateHost(*in.Host)
  293. if msg != "" {
  294. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  295. return
  296. }
  297. // Duplicado: otro router con ese host (excluyendo el propio id).
  298. for _, rt := range routerstore.ListRouters(s.db.DB) {
  299. if rt.Host == h && rt.ID != id {
  300. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  301. return
  302. }
  303. }
  304. host = &h
  305. }
  306. var typ *string
  307. if in.Type != "" {
  308. t := in.Type
  309. if t != "glinet" && t != "openwrt" && t != "routeros" && t != "managed-switch" && t != "external" {
  310. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'routeros' | 'managed-switch' | 'external'")
  311. return
  312. }
  313. typ = &t
  314. }
  315. gw := in.Gateway
  316. ao := in.AgentOnly
  317. var firmwareTarget *string
  318. if in.FirmwareTarget != nil {
  319. v := strings.TrimSpace(*in.FirmwareTarget)
  320. firmwareTarget = &v
  321. }
  322. var snmpPollInterval *int
  323. if in.SnmpPollInterval != nil {
  324. v := *in.SnmpPollInterval
  325. if v < 10 || v > 3600 {
  326. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  327. return
  328. }
  329. snmpPollInterval = &v
  330. }
  331. var snmpPort *int
  332. if in.SnmpPort != nil {
  333. p := *in.SnmpPort
  334. if p < 0 || p > 65535 {
  335. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  336. return
  337. }
  338. snmpPort = &p
  339. }
  340. var snmpCommunity *string
  341. if in.SnmpCommunity != nil {
  342. v := strings.TrimSpace(*in.SnmpCommunity)
  343. snmpCommunity = &v
  344. }
  345. var sshPort *int
  346. if in.SSHPort != nil {
  347. p := *in.SSHPort
  348. if p < 1 || p > 65535 {
  349. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  350. return
  351. }
  352. sshPort = &p
  353. }
  354. var tempThreshold *int
  355. if in.TempThreshold != nil {
  356. v := *in.TempThreshold
  357. if v > 150 {
  358. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  359. return
  360. }
  361. tempThreshold = &v
  362. }
  363. var routerosUser *string
  364. if in.RouterOSUser != nil {
  365. v := strings.TrimSpace(*in.RouterOSUser)
  366. routerosUser = &v
  367. }
  368. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  369. Name: name, Host: host, Type: typ,
  370. IsGateway: &gw, AgentOnly: &ao,
  371. FirmwareTarget: firmwareTarget,
  372. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  373. SSHPort: sshPort,
  374. TempThreshold: tempThreshold,
  375. ConsolePolling: in.ConsolePolling,
  376. RouterOSUser: routerosUser, RouterOSPassword: in.RouterOSPassword, RouterOSInsecure: in.RouterOSInsecure,
  377. })
  378. if !ok {
  379. writeError(w, http.StatusNotFound, "not_found")
  380. return
  381. }
  382. s.syncRouters()
  383. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  384. }
  385. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  386. func kvGet(db *sql.DB, key string) string {
  387. var v string
  388. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  389. return ""
  390. }
  391. return v
  392. }
  393. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  394. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  395. user := kvGet(s.db.DB, "adguard_user")
  396. if user == "" {
  397. user = "root"
  398. }
  399. mode := kvGet(s.db.DB, "adguard_mode")
  400. if mode == "" {
  401. mode = "glinet"
  402. }
  403. portStr := kvGet(s.db.DB, "adguard_port")
  404. port := 0
  405. if p, err := strconv.Atoi(portStr); err == nil {
  406. port = p
  407. }
  408. writeJSON(w, http.StatusOK, map[string]any{
  409. "mode": mode,
  410. "host": kvGet(s.db.DB, "adguard_host"),
  411. "port": port,
  412. "user": user,
  413. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  414. })
  415. }
  416. type adguardInput struct {
  417. Mode string `json:"mode"`
  418. Host *string `json:"host"`
  419. Port int `json:"port"`
  420. User string `json:"user"`
  421. Password string `json:"password"`
  422. }
  423. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  424. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  425. var in adguardInput
  426. if st := readJSONBody(w, r, &in); st != 0 {
  427. writeBodyError(w, st, "invalid_json", "")
  428. return
  429. }
  430. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  431. if mode == "" {
  432. mode = "glinet"
  433. }
  434. if mode != "glinet" && mode != "standard" {
  435. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  436. return
  437. }
  438. if in.Host == nil {
  439. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  440. return
  441. }
  442. host := strings.TrimSpace(*in.Host)
  443. port := 0
  444. if mode == "standard" {
  445. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  446. if msg != "" {
  447. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  448. return
  449. }
  450. host = hostFromVal
  451. if in.Port < 1 || in.Port > 65535 {
  452. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  453. return
  454. }
  455. port = in.Port
  456. if port == 0 {
  457. port = portFromHost
  458. }
  459. if port == 0 {
  460. port = 3000
  461. }
  462. }
  463. user := strings.TrimSpace(in.User)
  464. if user == "" {
  465. user = "root"
  466. }
  467. if len(user) > 64 {
  468. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  469. return
  470. }
  471. if len(in.Password) > 128 {
  472. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  473. return
  474. }
  475. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  476. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  477. writeError(w, http.StatusInternalServerError, "internal_error")
  478. return
  479. }
  480. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  481. writeError(w, http.StatusInternalServerError, "internal_error")
  482. return
  483. }
  484. if mode == "standard" {
  485. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  486. writeError(w, http.StatusInternalServerError, "internal_error")
  487. return
  488. }
  489. } else {
  490. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  491. writeError(w, http.StatusInternalServerError, "internal_error")
  492. return
  493. }
  494. }
  495. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  496. writeError(w, http.StatusInternalServerError, "internal_error")
  497. return
  498. }
  499. if in.Password != "" {
  500. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  501. writeError(w, http.StatusInternalServerError, "internal_error")
  502. return
  503. }
  504. }
  505. w.WriteHeader(http.StatusNoContent)
  506. }
  507. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  508. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  509. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  510. // Idempotente: 204 aunque no hubiera nada configurado.
  511. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  512. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  513. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  514. writeError(w, http.StatusInternalServerError, "internal_error")
  515. return
  516. }
  517. }
  518. if s.pollNow != nil {
  519. s.pollNow()
  520. }
  521. w.WriteHeader(http.StatusNoContent)
  522. }
  523. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  524. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  525. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  526. // para no romper frontends cacheados.
  527. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  528. instances := pve.LoadInstances(s.db.DB)
  529. // Vista sanitizada: el secret JAMAS sale del server (#764).
  530. view := make([]map[string]string, 0, len(instances))
  531. for _, in := range instances {
  532. view = append(view, map[string]string{
  533. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  534. })
  535. }
  536. out := map[string]any{
  537. "instances": view,
  538. "url": "",
  539. "tokenId": "",
  540. "tokenSet": false,
  541. }
  542. if len(instances) > 0 {
  543. out["url"] = instances[0].URL
  544. out["tokenId"] = instances[0].TokenID
  545. out["tokenSet"] = instances[0].Secret != ""
  546. }
  547. writeJSON(w, http.StatusOK, out)
  548. }
  549. type proxmoxInput struct {
  550. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  551. TokenID string `json:"tokenId"`
  552. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  553. }
  554. type proxmoxInstanceInput struct {
  555. ID string `json:"id"`
  556. Name string `json:"name"`
  557. URL string `json:"url"`
  558. TokenID string `json:"tokenId"`
  559. Secret string `json:"secret"` // vacío en edición = conservar el actual
  560. }
  561. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  562. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  563. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  564. // migrada "default", creándola si hace falta; url "" desactiva todo).
  565. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  566. var in proxmoxInstanceInput
  567. if st := readJSONBody(w, r, &in); st != 0 {
  568. writeBodyError(w, st, "invalid_json", "")
  569. return
  570. }
  571. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  572. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  573. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  574. tokenID := strings.TrimSpace(in.TokenID)
  575. if len(tokenID) > 128 || len(in.Secret) > 256 {
  576. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  577. return
  578. }
  579. id := strings.TrimSpace(in.ID)
  580. if id == "" {
  581. id = "default" // legacy sin id
  582. }
  583. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  584. if url != "" {
  585. u, err := urlpkg.Parse(url)
  586. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  587. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  588. return
  589. }
  590. }
  591. list := pve.LoadInstances(s.db.DB)
  592. var current *pve.Instance
  593. for i := range list {
  594. if list[i].ID == id {
  595. current = &list[i]
  596. break
  597. }
  598. }
  599. if current != nil {
  600. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
  601. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  602. return
  603. }
  604. if url != "" {
  605. current.URL = url
  606. }
  607. if tokenID != "" {
  608. current.TokenID = tokenID
  609. }
  610. if in.Secret != "" {
  611. current.Secret = in.Secret
  612. }
  613. if n := strings.TrimSpace(in.Name); n != "" {
  614. current.Name = n
  615. }
  616. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  617. writeError(w, http.StatusInternalServerError, "internal_error")
  618. return
  619. }
  620. w.WriteHeader(http.StatusNoContent)
  621. return
  622. }
  623. // Instancia nueva: completa.
  624. if url == "" || tokenID == "" || in.Secret == "" {
  625. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  626. return
  627. }
  628. name := strings.TrimSpace(in.Name)
  629. if name == "" {
  630. name = id
  631. }
  632. inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
  633. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  634. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  635. return
  636. }
  637. w.WriteHeader(http.StatusNoContent)
  638. }
  639. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  640. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  641. id := r.PathValue("id")
  642. if !pve.ValidInstanceID(id) {
  643. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  644. return
  645. }
  646. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  647. writeError(w, http.StatusInternalServerError, "internal_error")
  648. return
  649. }
  650. w.WriteHeader(http.StatusNoContent)
  651. }
  652. // POST /api/config/proxmox/test - prueba una instancia y cuenta lo que ve.
  653. //
  654. // Sin esto, guardar la config no daba señal alguna: un token sin permisos
  655. // autentica igual, la API responde 200 con listas vacías (PVE filtra, no
  656. // rechaza) y la integración se queda muda — indistinguible de un cluster
  657. // sin invitados. El resultado dice también QUÉ falta cuando es eso.
  658. //
  659. // Body opcional: {id} prueba la instancia guardada; {url, tokenId, secret}
  660. // prueba lo que el usuario acaba de teclear sin guardarlo. Un secret vacío
  661. // reutiliza el almacenado, igual que el PUT.
  662. func (s *server) handleTestProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  663. var in proxmoxInstanceInput
  664. _ = readJSONBody(w, r, &in) // cuerpo opcional
  665. id := strings.TrimSpace(in.ID)
  666. if id == "" {
  667. id = "default"
  668. }
  669. var cfg pve.Config
  670. for _, inst := range pve.LoadInstances(s.db.DB) {
  671. if inst.ID == id {
  672. cfg = inst.Config
  673. break
  674. }
  675. }
  676. if u := strings.TrimRight(strings.TrimSpace(in.URL), "/"); u != "" {
  677. cfg.URL = u
  678. }
  679. if t := strings.TrimSpace(in.TokenID); t != "" {
  680. cfg.TokenID = t
  681. }
  682. if in.Secret != "" {
  683. cfg.Secret = in.Secret
  684. }
  685. if !cfg.Enabled() {
  686. writeError(w, http.StatusBadRequest, "invalid_input", "faltan url, tokenId o secret")
  687. return
  688. }
  689. // Un fallo es un RESULTADO, no un error HTTP: el formulario tiene que
  690. // poder enseñar lo que contestó Proxmox.
  691. res, err := pve.NewClient(cfg).Test(r.Context())
  692. if err != nil {
  693. writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
  694. return
  695. }
  696. writeJSON(w, http.StatusOK, map[string]any{
  697. "ok": true, "version": res.Version, "nodes": res.Nodes,
  698. "vms": res.VMs, "cts": res.CTs, "limited": res.Limited,
  699. })
  700. }