package bridge import ( "context" "crypto/subtle" "encoding/hex" "encoding/json" "io" "net" "net/http" "os" "path/filepath" "strings" "sync" "sync/atomic" "time" ) // Health is what a monitoring channel reports: enough to tell a dead process from an idle one, an // unreachable node from a quiet chain, and a relay that dropped from a gateway that never started. type Health struct { Version string `json:"version"` PID int `json:"pid"` StartedAt string `json:"started_at"` UptimeSeconds float64 `json:"uptime_seconds"` SessionsActive int64 `json:"sessions_active"` SessionsTotal int64 `json:"sessions_total"` Chains []string `json:"chains"` Nodes map[string]NodeHealth `json:"nodes"` LastPresenceSeconds float64 `json:"last_presence_seconds_ago"` // Healthy is false when any node has not answered since the gateway started, or when no // presence has ever been published: both mean a client cannot use this gateway, even though // the process is up. Healthy bool `json:"healthy"` // Exe is the binary this process is running from, and ExeWritable says whether the release // machinery could replace it. Both exist because "why will this gateway not update itself" // is answered here and not in the log: an update installs into the running file's directory. Exe string `json:"exe,omitempty"` ExeWritable bool `json:"exe_writable"` UpdateConfigured bool `json:"update_configured"` AdminEnabled bool `json:"admin_enabled"` UpdateURL string `json:"update_url,omitempty"` // Admins are the operator keys allowed to command this gateway, so a second administrator can // see that they are registered and the first can see that they are not alone. Admins []string `json:"admins,omitempty"` // Relays is what each configured relay says about this gateway: whether it already lists it, // and who to ask if it does not. It is the answer to "why is my gateway not on that relay", // asked without a conversation. Relays map[string]RelayHealth `json:"relays,omitempty"` // ListingsPending is how many swaps are quoted but not paid for yet. ListingsPending int `json:"listings_pending"` // Billing is what this gateway charges, without the wallet secret: an operator answering "what // am I charging" should not have to read a file on a machine they may not have access to. Billing map[string]any `json:"billing,omitempty"` } // RelayHealth is one relay's NIP-11 as it applies to this gateway. type RelayHealth struct { Name string `json:"name,omitempty"` Contact string `json:"contact,omitempty"` Authorized bool `json:"authorized"` Error string `json:"error,omitempty"` Checked string `json:"checked,omitempty"` // Paid access to this relay, when the relay charges: the gateway asks, and the countdown is // the answer. Zero rate means the relay charges nothing. Paid bool `json:"paid,omitempty"` Blocked bool `json:"blocked,omitempty"` RemainingSeconds int64 `json:"remaining_seconds,omitempty"` PaidUntil string `json:"paid_until,omitempty"` RateSatsPerDay int64 `json:"rate_sats_per_day,omitempty"` // Warning is the sentence an operator needs: nothing, a countdown, or a reason. Warning string `json:"warning,omitempty"` } // NodeHealth is one chain's node as the last presence check saw it. type NodeHealth struct { Addr string `json:"addr"` OK bool `json:"ok"` Tip int64 `json:"tip,omitempty"` Error string `json:"error,omitempty"` Checked string `json:"checked,omitempty"` // Services is the node's advertised service bits, and CompactFilters is // the NODE_COMPACT_FILTERS bit of it. It is the answer to "why does this // gateway not hand out filters": the backend node does not advertise them. Services uint64 `json:"services,omitempty"` CompactFilters bool `json:"compact_filters"` } // healthState is the mutable side of the report. type healthState struct { started time.Time active int64 total int64 presence int64 nodeHealth map[string]NodeHealth relays map[string]RelayHealth } func newHealthState(started time.Time, chains []string) *healthState { return &healthState{ started: started, nodeHealth: make(map[string]NodeHealth, len(chains)), relays: make(map[string]RelayHealth), } } func (s *Server) Health() Health { state := s.health now := time.Now() out := Health{ Version: s.cfg.Version, PID: s.pid, StartedAt: state.started.UTC().Format(time.RFC3339), UptimeSeconds: now.Sub(state.started).Seconds(), SessionsActive: atomic.LoadInt64(&state.active), SessionsTotal: atomic.LoadInt64(&state.total), Chains: append([]string{}, s.cfg.Chains...), Nodes: make(map[string]NodeHealth, len(s.cfg.Nodes)), Relays: make(map[string]RelayHealth, len(s.cfg.Relays)), Healthy: true, } out.Exe, out.ExeWritable = exeInfo() out.UpdateConfigured = s.updateConfigured() out.AdminEnabled = s.cfg.Admin && len(s.cfg.Admins) > 0 out.Admins = append([]string{}, s.cfg.Admins...) out.UpdateURL = s.cfg.Update.ManifestURL s.billingMu.Lock() out.Billing = s.billing.Redacted() s.billingMu.Unlock() if s.listings != nil { out.ListingsPending = len(s.listings.Pending()) } s.mu.Lock() for url, relay := range state.relays { out.Relays[url] = relay } for chain, node := range s.cfg.Nodes { health := state.nodeHealth[chain] if health.Addr == "" { health.Addr = node.Addr } out.Nodes[chain] = health } s.mu.Unlock() if last := atomic.LoadInt64(&state.presence); last > 0 { out.LastPresenceSeconds = now.Sub(time.Unix(0, last)).Seconds() } else { out.Healthy = false } for _, node := range out.Nodes { if !node.OK { out.Healthy = false } } return out } // exeProbe is the answer to "can this process replace itself". It is measured once: after an // update the gateway execs and is a new process, which measures again. var exeProbe struct { sync.Once path string writable bool } func exeInfo() (string, bool) { exeProbe.Do(func() { path, err := os.Executable() if err != nil { return } exeProbe.path = path exeProbe.writable = dirWritable(filepath.Dir(path)) }) return exeProbe.path, exeProbe.writable } // dirWritable reports whether a file can be created in dir. That is exactly what an update needs: // it stages the new binary beside the running one and renames it into place. func dirWritable(dir string) bool { probe, err := os.CreateTemp(dir, ".nostrino-probe-*") if err != nil { return false } name := probe.Name() probe.Close() _ = os.Remove(name) return true } // recordPresence records when the gateway last told the relays it exists. func (s *Server) recordPresence() { atomic.StoreInt64(&s.health.presence, time.Now().UnixNano()) } // recordRelay records what one relay's NIP-11 said about this gateway. func (s *Server) recordRelay(url string, health RelayHealth) { s.mu.Lock() s.health.relays[url] = health s.mu.Unlock() } // recordNode records the last node check for one chain. func (s *Server) recordNode(chain string, health NodeHealth) { s.mu.Lock() s.health.nodeHealth[chain] = health s.mu.Unlock() } // startHealth serves the health report on addr, if one was configured. func (s *Server) startHealth(addr string) error { if addr == "" { return nil } ln, err := net.Listen("tcp", addr) if err != nil { return err } mux := http.NewServeMux() mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("content-type", "application/json") _ = json.NewEncoder(w).Encode(s.Health()) }) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } w.Header().Set("content-type", "text/html; charset=utf-8") _, _ = io.WriteString(w, adminPage) }) if s.cfg.AdminToken != "" { mux.HandleFunc("/admin", s.handleAdmin) } srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second} s.healthServer = srv go func() { if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed { s.cfg.Logf("bridge: health server: %v", err) } }() s.cfg.Logf("bridge: health on http://%s/health", ln.Addr()) return nil } // handleAdmin is the LAN control surface. It is registered only when -admin-token // is set, so an unconfigured gateway never exposes control on the local network. // The token is the credential: it is compared in constant time and never leaves // the process. func (s *Server) handleAdmin(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") if len(token) == 0 || subtle.ConstantTimeCompare([]byte(token), []byte(s.cfg.AdminToken)) != 1 { http.Error(w, "unauthorized", http.StatusUnauthorized) return } body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } reply, err := s.adminCommand(r.Context(), s.localPeer(), body) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } w.Header().Set("content-type", "application/json") _, _ = w.Write(reply) } // localPeer is the identity logged for a LAN admin command: the first operator // key when one is configured, a fixed marker otherwise. It is only for the log // and the control-holder note; the token has already authenticated the caller. func (s *Server) localPeer() [32]byte { if len(s.cfg.Admins) > 0 { if b, err := hex.DecodeString(s.cfg.Admins[0]); err == nil && len(b) == 32 { var peer [32]byte copy(peer[:], b) return peer } } var peer [32]byte copy(peer[:], "local") return peer } // adminPage is the one page the gateway serves on the LAN. It is read-only unless // the operator pastes the -admin-token, at which point the admin commands become // available. Everything it shows comes from /health, so there is no second view of // the truth to drift out of step. const adminPage = `
no command run yet