config.go 21 KB

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