config.go 28 KB

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