pairing.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. // pairing.go: modo bootstrap (Fase 9 R3). Con pairing_token en vez de
  2. // token, el agente contacta al servidor una vez, obtiene el token real, lo
  3. // escribe al env file y sale. procd (o el embedder) reinicia, y el agente
  4. // arranca en modo normal.
  5. package runtime
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net/http"
  11. "os"
  12. "strings"
  13. "time"
  14. )
  15. // pairWithServer contacta POST /api/agents/pair con el pairing token,
  16. // recibe el token real del agente y lo escribe al env file. Usa el
  17. // server_fp para validar TLS (el admin lo proporciona junto con el
  18. // pairing token).
  19. func pairWithServer(opts Options) error {
  20. transport, err := buildTransport(opts)
  21. if err != nil {
  22. return err
  23. }
  24. body := fmt.Sprintf(`{"pairing_token":%q,"slug":%q}`, opts.PairingToken, opts.Slug)
  25. req, err := http.NewRequest("POST", opts.Server+"/api/agents/pair", strings.NewReader(body))
  26. if err != nil {
  27. return err
  28. }
  29. req.Header.Set("Content-Type", "application/json")
  30. hc := &http.Client{Transport: transport, Timeout: 15 * time.Second}
  31. log := opts.logger()
  32. log.Info("[netpulse-agent] pairing", "server", opts.Server, "slug", opts.Slug)
  33. res, err := hc.Do(req)
  34. if err != nil {
  35. return fmt.Errorf("pairing: %w", err)
  36. }
  37. defer res.Body.Close()
  38. if res.StatusCode != http.StatusCreated {
  39. respBody, _ := io.ReadAll(io.LimitReader(res.Body, 512))
  40. return fmt.Errorf("pairing fallido (HTTP %d): %s", res.StatusCode, respBody)
  41. }
  42. var pr struct {
  43. Slug string `json:"slug"`
  44. Token string `json:"token"`
  45. ServerFP string `json:"server_fp"`
  46. }
  47. if err := json.NewDecoder(res.Body).Decode(&pr); err != nil {
  48. return fmt.Errorf("parsear respuesta pairing: %w", err)
  49. }
  50. if pr.Token == "" {
  51. return fmt.Errorf("pairing: token vacío en respuesta")
  52. }
  53. // Escribir el token real al env file (reemplaza PAIRING_TOKEN por TOKEN).
  54. if err := writePairedToken(opts.EnvFile, pr.Token); err != nil {
  55. return fmt.Errorf("escribir token al env file: %w", err)
  56. }
  57. log.Info("[netpulse-agent] pairing OK", "slug", pr.Slug, "env_file", opts.EnvFile)
  58. // Salir limpiamente: quien arranque el agente lo relanza y este lee
  59. // NETPULSE_TOKEN del env file en modo normal.
  60. return nil
  61. }
  62. // writePairedToken reescribe el env file: quita NETPULSE_PAIRING_TOKEN y
  63. // añade/actualiza NETPULSE_TOKEN. Conserva el resto de líneas.
  64. func writePairedToken(path, token string) error {
  65. data, err := os.ReadFile(path)
  66. if err != nil {
  67. // Si no existe, crear uno nuevo con el token.
  68. return os.WriteFile(path, []byte("NETPULSE_TOKEN="+token+"\n"), 0o600)
  69. }
  70. var out []string
  71. haveToken := false
  72. for _, line := range strings.Split(string(data), "\n") {
  73. trimmed := strings.TrimSpace(line)
  74. if trimmed == "" || strings.HasPrefix(trimmed, "#") {
  75. out = append(out, line)
  76. continue
  77. }
  78. k, _, ok := strings.Cut(trimmed, "=")
  79. if !ok {
  80. out = append(out, line)
  81. continue
  82. }
  83. key := strings.TrimSpace(k)
  84. if key == "NETPULSE_PAIRING_TOKEN" {
  85. continue // eliminar
  86. }
  87. if key == "NETPULSE_TOKEN" {
  88. out = append(out, "NETPULSE_TOKEN="+token)
  89. haveToken = true
  90. continue
  91. }
  92. out = append(out, line)
  93. }
  94. if !haveToken {
  95. out = append(out, "NETPULSE_TOKEN="+token)
  96. }
  97. return os.WriteFile(path, []byte(strings.Join(out, "\n")+"\n"), 0o600)
  98. }