config.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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("GET /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handleGetProxmoxConfig)))
  40. mux.Handle("PUT /api/config/proxmox", auth.RequireAdmin(http.HandlerFunc(s.handlePutProxmoxConfig)))
  41. mux.Handle("DELETE /api/config/proxmox/{id}", auth.RequireAdmin(http.HandlerFunc(s.handleDeleteProxmoxConfig)))
  42. }
  43. // syncRouters replica sync() de config.js: adapter.setRouters(listRouters(db)).
  44. func (s *server) syncRouters() {
  45. if s.adapter != nil {
  46. s.adapter.SetRouters(routerstore.ListRouters(s.db.DB))
  47. }
  48. }
  49. // GET /api/config/sshkey — clave pública propia para autorizar en routers.
  50. func (s *server) handleGetSSHKey(w http.ResponseWriter, r *http.Request) {
  51. key := sshkey.GetPublicKey(s.cfg.SSHKeyPath)
  52. if key == nil {
  53. writeError(w, http.StatusInternalServerError, "no_key")
  54. return
  55. }
  56. writeJSON(w, http.StatusOK, key)
  57. }
  58. // POST /api/config/sshkey/rotate — rota el par ed25519 del servidor (#242).
  59. // Respalda el par actual (keyPath.bak.<epoch>) y genera uno nuevo; devuelve
  60. // la nueva pública + fingerprint para reautorizarla en los routers. La clave
  61. // vieja deja de funcionar de inmediato: exige confirmación explícita del admin
  62. // (la UI pide escribir la palabra de confirmación).
  63. func (s *server) handleRotateSSHKey(w http.ResponseWriter, r *http.Request) {
  64. key, err := sshkey.RotateKeypair(s.cfg.SSHKeyPath)
  65. if err != nil {
  66. writeError(w, http.StatusInternalServerError, "rotate_failed", err.Error())
  67. return
  68. }
  69. writeJSON(w, http.StatusOK, map[string]any{
  70. "publicKey": key.PublicKey,
  71. "fingerprint": key.Fingerprint,
  72. "warning": "The previous key is no longer valid. Re-authorize this public key on every router before rotating again.",
  73. })
  74. }
  75. // GET /api/config/discover?force=1 — escaneo de la LAN (cacheado 60 s).
  76. func (s *server) handleDiscover(w http.ResponseWriter, r *http.Request) {
  77. result := discover.Routers(r.Context(), s.db.DB, s.cfg.SSHKeyPath, r.URL.Query().Get("force") == "1")
  78. writeJSON(w, http.StatusOK, result)
  79. }
  80. // GET /api/config/routers — lista configurada (no el estado sondeado).
  81. func (s *server) handleListConfigRouters(w http.ResponseWriter, r *http.Request) {
  82. writeJSON(w, http.StatusOK, map[string]any{"routers": routerstore.ListRouters(s.db.DB)})
  83. }
  84. type routerInput struct {
  85. Name *string `json:"name"`
  86. Host *string `json:"host"`
  87. Type string `json:"type"`
  88. Gateway bool `json:"gateway"`
  89. AgentOnly bool `json:"agent_only"`
  90. // FirmwareTarget: versión objetivo del firmware (issue #241; opcional).
  91. FirmwareTarget *string `json:"firmware_target"`
  92. // SNMP (issue #309): credenciales para sondeo SNMP del switch gestionado.
  93. SnmpEnabled *bool `json:"snmp_enabled"`
  94. // ConsolePolling (issue #863): sondeo HTTP de la consola del switch.
  95. ConsolePolling *bool `json:"console_polling"`
  96. SnmpCommunity *string `json:"snmp_community"`
  97. SnmpPort *int `json:"snmp_port"`
  98. SnmpPollInterval *int `json:"snmp_poll_interval"` // issue #414; segundos
  99. // SSHPort (issue #605): puerto SSH del router (dropbear en puerto no
  100. // estándar). Ausente/0 → 22.
  101. SSHPort *int `json:"ssh_port"`
  102. // TempThreshold (issue #716): umbral de alerta por temperatura alta (°C).
  103. // Ausente = no tocar; 0 = reset a default (65); 1..150 = fijar.
  104. TempThreshold *int `json:"temp_threshold"`
  105. }
  106. // validateHost replica hostSchema (trim, 1..253, regex). Devuelve el valor
  107. // trimmeado o "" + mensaje de error.
  108. func validateHost(host string) (string, string) {
  109. h := strings.TrimSpace(host)
  110. if len(h) < 1 {
  111. return "", "String must contain at least 1 character(s)"
  112. }
  113. if len(h) > 253 {
  114. return "", "String must contain at most 253 character(s)"
  115. }
  116. if !hostRe.MatchString(h) {
  117. return "", "host debe ser una IP o hostname válido"
  118. }
  119. return h, ""
  120. }
  121. // validateAdGuardHost permite host o host:puerto (1..65535). Devuelve
  122. // host, puerto y mensaje de error.
  123. func validateAdGuardHost(host string) (string, int, string) {
  124. h := strings.TrimSpace(host)
  125. if len(h) < 1 {
  126. return "", 0, "String must contain at least 1 character(s)"
  127. }
  128. if len(h) > 253 {
  129. return "", 0, "String must contain at most 253 character(s)"
  130. }
  131. m := hostPortRe.FindStringSubmatch(h)
  132. if m == nil {
  133. return "", 0, "host debe ser una IP, hostname o host:puerto válido"
  134. }
  135. addr := m[1]
  136. port := 0
  137. if m[2] != "" {
  138. p, err := strconv.Atoi(m[2][1:])
  139. if err != nil || p < 1 || p > 65535 {
  140. return "", 0, "puerto fuera de rango (1-65535)"
  141. }
  142. port = p
  143. }
  144. return addr, port, ""
  145. }
  146. // POST /api/config/routers — añadir router manualmente desde Ajustes.
  147. func (s *server) handleAddConfigRouter(w http.ResponseWriter, r *http.Request) {
  148. var in routerInput
  149. if st := readJSONBody(w, r, &in); st != 0 {
  150. writeBodyError(w, st, "invalid_json", "")
  151. return
  152. }
  153. // Orden de validación del schema zod: name, host, type
  154. name := ""
  155. if in.Name != nil {
  156. name = strings.TrimSpace(*in.Name)
  157. if len(name) < 1 {
  158. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  159. return
  160. }
  161. if len(name) > 60 {
  162. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  163. return
  164. }
  165. }
  166. if in.Host == nil {
  167. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  168. return
  169. }
  170. host, msg := validateHost(*in.Host)
  171. if msg != "" {
  172. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  173. return
  174. }
  175. typ := in.Type
  176. if typ == "" {
  177. typ = "openwrt"
  178. }
  179. if typ != "glinet" && typ != "openwrt" && typ != "managed-switch" && typ != "external" {
  180. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  181. return
  182. }
  183. var firmwareTarget string
  184. if in.FirmwareTarget != nil {
  185. firmwareTarget = strings.TrimSpace(*in.FirmwareTarget)
  186. }
  187. snmpEnabled := false
  188. if in.SnmpEnabled != nil {
  189. snmpEnabled = *in.SnmpEnabled
  190. }
  191. snmpCommunity := ""
  192. if in.SnmpCommunity != nil {
  193. snmpCommunity = strings.TrimSpace(*in.SnmpCommunity)
  194. }
  195. snmpPort := 0
  196. if in.SnmpPort != nil {
  197. snmpPort = *in.SnmpPort
  198. if snmpPort < 0 || snmpPort > 65535 {
  199. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  200. return
  201. }
  202. }
  203. snmpInterval := 60
  204. if in.SnmpPollInterval != nil {
  205. snmpInterval = *in.SnmpPollInterval
  206. if snmpInterval < 10 || snmpInterval > 3600 {
  207. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  208. return
  209. }
  210. }
  211. for _, rt := range routerstore.ListRouters(s.db.DB) {
  212. if rt.Host == host {
  213. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+host)
  214. return
  215. }
  216. }
  217. sshPort := 0
  218. if in.SSHPort != nil {
  219. p := *in.SSHPort
  220. if p < 1 || p > 65535 {
  221. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  222. return
  223. }
  224. sshPort = p
  225. }
  226. created, err := routerstore.AddRouter(s.db.DB, routerstore.AddInput{
  227. Name: name, Host: host, Type: typ, IsGateway: in.Gateway, AgentOnly: in.AgentOnly,
  228. FirmwareTarget: firmwareTarget,
  229. SnmpEnabled: snmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpInterval,
  230. SSHPort: sshPort,
  231. })
  232. if err != nil {
  233. writeError(w, http.StatusInternalServerError, "internal_error")
  234. return
  235. }
  236. s.syncRouters()
  237. writeJSON(w, http.StatusCreated, map[string]any{"router": created})
  238. }
  239. // DELETE /api/config/routers/:id — 204 o 404.
  240. func (s *server) handleDeleteConfigRouter(w http.ResponseWriter, r *http.Request) {
  241. if !routerstore.RemoveRouter(s.db.DB, r.PathValue("id")) {
  242. writeError(w, http.StatusNotFound, "not_found")
  243. return
  244. }
  245. s.syncRouters()
  246. w.WriteHeader(http.StatusNoContent)
  247. }
  248. // PUT /api/config/routers/:id — edita host/name/type/gateway/agent_only.
  249. // Campos omitidos (nil) no se tocan. 404 si el router no existe.
  250. func (s *server) handleUpdateConfigRouter(w http.ResponseWriter, r *http.Request) {
  251. id := r.PathValue("id")
  252. var in routerInput
  253. if st := readJSONBody(w, r, &in); st != 0 {
  254. writeBodyError(w, st, "invalid_json", "")
  255. return
  256. }
  257. var name *string
  258. if in.Name != nil {
  259. n := strings.TrimSpace(*in.Name)
  260. if len(n) < 1 {
  261. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at least 1 character(s)")
  262. return
  263. }
  264. if len(n) > 60 {
  265. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 60 character(s)")
  266. return
  267. }
  268. name = &n
  269. }
  270. var host *string
  271. if in.Host != nil {
  272. h, msg := validateHost(*in.Host)
  273. if msg != "" {
  274. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  275. return
  276. }
  277. // Duplicado: otro router con ese host (excluyendo el propio id).
  278. for _, rt := range routerstore.ListRouters(s.db.DB) {
  279. if rt.Host == h && rt.ID != id {
  280. writeError(w, http.StatusConflict, "duplicate_host", "Ya hay un router con "+h)
  281. return
  282. }
  283. }
  284. host = &h
  285. }
  286. var typ *string
  287. if in.Type != "" {
  288. t := in.Type
  289. if t != "glinet" && t != "openwrt" && t != "managed-switch" && t != "external" {
  290. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'openwrt' | 'managed-switch' | 'external'")
  291. return
  292. }
  293. typ = &t
  294. }
  295. gw := in.Gateway
  296. ao := in.AgentOnly
  297. var firmwareTarget *string
  298. if in.FirmwareTarget != nil {
  299. v := strings.TrimSpace(*in.FirmwareTarget)
  300. firmwareTarget = &v
  301. }
  302. var snmpPollInterval *int
  303. if in.SnmpPollInterval != nil {
  304. v := *in.SnmpPollInterval
  305. if v < 10 || v > 3600 {
  306. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_poll_interval must be between 10 and 3600")
  307. return
  308. }
  309. snmpPollInterval = &v
  310. }
  311. var snmpPort *int
  312. if in.SnmpPort != nil {
  313. p := *in.SnmpPort
  314. if p < 0 || p > 65535 {
  315. writeError(w, http.StatusBadRequest, "invalid_input", "snmp_port must be between 0 and 65535")
  316. return
  317. }
  318. snmpPort = &p
  319. }
  320. var snmpCommunity *string
  321. if in.SnmpCommunity != nil {
  322. v := strings.TrimSpace(*in.SnmpCommunity)
  323. snmpCommunity = &v
  324. }
  325. var sshPort *int
  326. if in.SSHPort != nil {
  327. p := *in.SSHPort
  328. if p < 1 || p > 65535 {
  329. writeError(w, http.StatusBadRequest, "invalid_input", "ssh_port must be between 1 and 65535")
  330. return
  331. }
  332. sshPort = &p
  333. }
  334. var tempThreshold *int
  335. if in.TempThreshold != nil {
  336. v := *in.TempThreshold
  337. if v > 150 {
  338. writeError(w, http.StatusBadRequest, "invalid_input", "temp_threshold must be between 0 and 150")
  339. return
  340. }
  341. tempThreshold = &v
  342. }
  343. updated, ok := routerstore.UpdateRouter(s.db.DB, id, routerstore.UpdateInput{
  344. Name: name, Host: host, Type: typ,
  345. IsGateway: &gw, AgentOnly: &ao,
  346. FirmwareTarget: firmwareTarget,
  347. SnmpEnabled: in.SnmpEnabled, SnmpCommunity: snmpCommunity, SnmpPort: snmpPort, SnmpPollInterval: snmpPollInterval,
  348. SSHPort: sshPort,
  349. TempThreshold: tempThreshold,
  350. ConsolePolling: in.ConsolePolling,
  351. })
  352. if !ok {
  353. writeError(w, http.StatusNotFound, "not_found")
  354. return
  355. }
  356. s.syncRouters()
  357. writeJSON(w, http.StatusOK, map[string]any{"router": updated})
  358. }
  359. // --- AdGuard Home (GL.iNet) — solo admin; la contraseña NO se devuelve ---
  360. func kvGet(db *sql.DB, key string) string {
  361. var v string
  362. if err := db.QueryRow("SELECT value FROM kv WHERE key = ?", key).Scan(&v); err != nil {
  363. return ""
  364. }
  365. return v
  366. }
  367. // GET /api/config/adguard — {mode, host, port, user ('root' por defecto), passSet}.
  368. func (s *server) handleGetAdguardConfig(w http.ResponseWriter, r *http.Request) {
  369. user := kvGet(s.db.DB, "adguard_user")
  370. if user == "" {
  371. user = "root"
  372. }
  373. mode := kvGet(s.db.DB, "adguard_mode")
  374. if mode == "" {
  375. mode = "glinet"
  376. }
  377. portStr := kvGet(s.db.DB, "adguard_port")
  378. port := 0
  379. if p, err := strconv.Atoi(portStr); err == nil {
  380. port = p
  381. }
  382. writeJSON(w, http.StatusOK, map[string]any{
  383. "mode": mode,
  384. "host": kvGet(s.db.DB, "adguard_host"),
  385. "port": port,
  386. "user": user,
  387. "passSet": kvGet(s.db.DB, "adguard_pass") != "",
  388. })
  389. }
  390. type adguardInput struct {
  391. Mode string `json:"mode"`
  392. Host *string `json:"host"`
  393. Port int `json:"port"`
  394. User string `json:"user"`
  395. Password string `json:"password"`
  396. }
  397. // PUT /api/config/adguard — upsert en kv (password solo si viene). 204.
  398. func (s *server) handlePutAdguardConfig(w http.ResponseWriter, r *http.Request) {
  399. var in adguardInput
  400. if st := readJSONBody(w, r, &in); st != 0 {
  401. writeBodyError(w, st, "invalid_json", "")
  402. return
  403. }
  404. mode := strings.ToLower(strings.TrimSpace(in.Mode))
  405. if mode == "" {
  406. mode = "glinet"
  407. }
  408. if mode != "glinet" && mode != "standard" {
  409. writeError(w, http.StatusBadRequest, "invalid_input", "Invalid enum value. Expected 'glinet' | 'standard'")
  410. return
  411. }
  412. if in.Host == nil {
  413. writeError(w, http.StatusBadRequest, "invalid_input", "Required")
  414. return
  415. }
  416. host := strings.TrimSpace(*in.Host)
  417. port := 0
  418. if mode == "standard" {
  419. hostFromVal, portFromHost, msg := validateAdGuardHost(host)
  420. if msg != "" {
  421. writeError(w, http.StatusBadRequest, "invalid_input", msg)
  422. return
  423. }
  424. host = hostFromVal
  425. if in.Port < 1 || in.Port > 65535 {
  426. writeError(w, http.StatusBadRequest, "invalid_input", "port must be between 1 and 65535")
  427. return
  428. }
  429. port = in.Port
  430. if port == 0 {
  431. port = portFromHost
  432. }
  433. if port == 0 {
  434. port = 3000
  435. }
  436. }
  437. user := strings.TrimSpace(in.User)
  438. if user == "" {
  439. user = "root"
  440. }
  441. if len(user) > 64 {
  442. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 64 character(s)")
  443. return
  444. }
  445. if len(in.Password) > 128 {
  446. writeError(w, http.StatusBadRequest, "invalid_input", "String must contain at most 128 character(s)")
  447. return
  448. }
  449. upsert := "INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
  450. if _, err := s.db.Exec(upsert, "adguard_mode", mode); err != nil {
  451. writeError(w, http.StatusInternalServerError, "internal_error")
  452. return
  453. }
  454. if _, err := s.db.Exec(upsert, "adguard_host", host); err != nil {
  455. writeError(w, http.StatusInternalServerError, "internal_error")
  456. return
  457. }
  458. if mode == "standard" {
  459. if _, err := s.db.Exec(upsert, "adguard_port", strconv.Itoa(port)); err != nil {
  460. writeError(w, http.StatusInternalServerError, "internal_error")
  461. return
  462. }
  463. } else {
  464. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", "adguard_port"); err != nil {
  465. writeError(w, http.StatusInternalServerError, "internal_error")
  466. return
  467. }
  468. }
  469. if _, err := s.db.Exec(upsert, "adguard_user", user); err != nil {
  470. writeError(w, http.StatusInternalServerError, "internal_error")
  471. return
  472. }
  473. if in.Password != "" {
  474. if _, err := s.db.Exec(upsert, "adguard_pass", in.Password); err != nil {
  475. writeError(w, http.StatusInternalServerError, "internal_error")
  476. return
  477. }
  478. }
  479. w.WriteHeader(http.StatusNoContent)
  480. }
  481. // DELETE /api/config/adguard - desactiva AdGuard Home (#813): borra la config
  482. // (mode/host/user/pass/port) para que deje de sondearse y de penalizar la
  483. // salud (el poller devuelve nil y computeHealth ya no resta "AdGuard inactivo").
  484. // Idempotente: 204 aunque no hubiera nada configurado.
  485. func (s *server) handleDeleteAdguardConfig(w http.ResponseWriter, r *http.Request) {
  486. for _, k := range []string{"adguard_mode", "adguard_host", "adguard_user", "adguard_pass", "adguard_port"} {
  487. if _, err := s.db.Exec("DELETE FROM kv WHERE key = ?", k); err != nil {
  488. writeError(w, http.StatusInternalServerError, "internal_error")
  489. return
  490. }
  491. }
  492. if s.pollNow != nil {
  493. s.pollNow()
  494. }
  495. w.WriteHeader(http.StatusNoContent)
  496. }
  497. // GET /api/config/proxmox - instancias configuradas (#764 multi-endpoint).
  498. // El secret nunca sale: tokenSet por instancia. Los campos planos legacy
  499. // (url/tokenId/tokenSet de la PRIMERA instancia) se mantienen una version
  500. // para no romper frontends cacheados.
  501. func (s *server) handleGetProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  502. instances := pve.LoadInstances(s.db.DB)
  503. // Vista sanitizada: el secret JAMAS sale del server (#764).
  504. view := make([]map[string]string, 0, len(instances))
  505. for _, in := range instances {
  506. view = append(view, map[string]string{
  507. "id": in.ID, "name": in.Name, "url": in.URL, "tokenId": in.TokenID,
  508. })
  509. }
  510. out := map[string]any{
  511. "instances": view,
  512. "url": "",
  513. "tokenId": "",
  514. "tokenSet": false,
  515. }
  516. if len(instances) > 0 {
  517. out["url"] = instances[0].URL
  518. out["tokenId"] = instances[0].TokenID
  519. out["tokenSet"] = instances[0].Secret != ""
  520. }
  521. writeJSON(w, http.StatusOK, out)
  522. }
  523. type proxmoxInput struct {
  524. URL *string `json:"url"` // nil = no tocar; "" = desactivar
  525. TokenID string `json:"tokenId"`
  526. Secret string `json:"secret"` // solo si viene (se conserva el anterior)
  527. }
  528. type proxmoxInstanceInput struct {
  529. ID string `json:"id"`
  530. Name string `json:"name"`
  531. URL string `json:"url"`
  532. TokenID string `json:"tokenId"`
  533. Secret string `json:"secret"` // vacío en edición = conservar el actual
  534. }
  535. // PUT /api/config/proxmox - upsert de UNA instancia multi (#764): body
  536. // {id, name, url, tokenId, secret?}. Compat: si el body NO lleva id, se
  537. // aplica al estilo legacy single (url/tokenId/secret sobre la instancia
  538. // migrada "default", creándola si hace falta; url "" desactiva todo).
  539. func (s *server) handlePutProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  540. var in proxmoxInstanceInput
  541. if st := readJSONBody(w, r, &in); st != 0 {
  542. writeBodyError(w, st, "invalid_json", "")
  543. return
  544. }
  545. // Parcial (#764): sobre una instancia EXISTENTE, los campos vacíos se
  546. // conservan (url/tokenId/secret opcionales); para una NUEVA se exigen
  547. // url + tokenId + secret. Borrar es DELETE (ya no "url vacía").
  548. tokenID := strings.TrimSpace(in.TokenID)
  549. if len(tokenID) > 128 || len(in.Secret) > 256 {
  550. writeError(w, http.StatusBadRequest, "invalid_input", "token too long")
  551. return
  552. }
  553. id := strings.TrimSpace(in.ID)
  554. if id == "" {
  555. id = "default" // legacy sin id
  556. }
  557. url := strings.TrimRight(strings.TrimSpace(in.URL), "/")
  558. if url != "" {
  559. u, err := urlpkg.Parse(url)
  560. if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
  561. writeError(w, http.StatusBadRequest, "invalid_input", "url must be a valid http(s) URL")
  562. return
  563. }
  564. }
  565. list := pve.LoadInstances(s.db.DB)
  566. var current *pve.Instance
  567. for i := range list {
  568. if list[i].ID == id {
  569. current = &list[i]
  570. break
  571. }
  572. }
  573. if current != nil {
  574. if url == "" && tokenID == "" && strings.TrimSpace(in.Name) == "" && in.Secret == "" {
  575. writeError(w, http.StatusBadRequest, "invalid_input", "nada que actualizar")
  576. return
  577. }
  578. if url != "" {
  579. current.URL = url
  580. }
  581. if tokenID != "" {
  582. current.TokenID = tokenID
  583. }
  584. if in.Secret != "" {
  585. current.Secret = in.Secret
  586. }
  587. if n := strings.TrimSpace(in.Name); n != "" {
  588. current.Name = n
  589. }
  590. if err := pve.SaveInstances(s.db.DB, list); err != nil {
  591. writeError(w, http.StatusInternalServerError, "internal_error")
  592. return
  593. }
  594. w.WriteHeader(http.StatusNoContent)
  595. return
  596. }
  597. // Instancia nueva: completa.
  598. if url == "" || tokenID == "" || in.Secret == "" {
  599. writeError(w, http.StatusBadRequest, "invalid_input", "url, tokenId y secret son requeridos para una instancia nueva")
  600. return
  601. }
  602. name := strings.TrimSpace(in.Name)
  603. if name == "" {
  604. name = id
  605. }
  606. inst := pve.Instance{ID: id, Name: name, Config: pve.Config{URL: url, TokenID: tokenID, Secret: in.Secret}}
  607. if err := pve.UpsertInstance(s.db.DB, inst); err != nil {
  608. writeError(w, http.StatusBadRequest, "invalid_input", err.Error())
  609. return
  610. }
  611. w.WriteHeader(http.StatusNoContent)
  612. }
  613. // DELETE /api/config/proxmox/{id} - elimina una instancia (#764).
  614. func (s *server) handleDeleteProxmoxConfig(w http.ResponseWriter, r *http.Request) {
  615. id := r.PathValue("id")
  616. if !pve.ValidInstanceID(id) {
  617. writeError(w, http.StatusBadRequest, "invalid_input", "id inválido")
  618. return
  619. }
  620. if err := pve.DeleteInstance(s.db.DB, id); err != nil {
  621. writeError(w, http.StatusInternalServerError, "internal_error")
  622. return
  623. }
  624. w.WriteHeader(http.StatusNoContent)
  625. }