1 package bridge
2 3 import (
4 "context"
5 "crypto/subtle"
6 "encoding/hex"
7 "encoding/json"
8 "io"
9 "net"
10 "net/http"
11 "os"
12 "path/filepath"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "time"
17 )
18 19 // Health is what a monitoring channel reports: enough to tell a dead process from an idle one, an
20 // unreachable node from a quiet chain, and a relay that dropped from a gateway that never started.
21 type Health struct {
22 Version string `json:"version"`
23 PID int `json:"pid"`
24 StartedAt string `json:"started_at"`
25 UptimeSeconds float64 `json:"uptime_seconds"`
26 SessionsActive int64 `json:"sessions_active"`
27 SessionsTotal int64 `json:"sessions_total"`
28 Chains []string `json:"chains"`
29 Nodes map[string]NodeHealth `json:"nodes"`
30 LastPresenceSeconds float64 `json:"last_presence_seconds_ago"`
31 // Healthy is false when any node has not answered since the gateway started, or when no
32 // presence has ever been published: both mean a client cannot use this gateway, even though
33 // the process is up.
34 Healthy bool `json:"healthy"`
35 // Exe is the binary this process is running from, and ExeWritable says whether the release
36 // machinery could replace it. Both exist because "why will this gateway not update itself"
37 // is answered here and not in the log: an update installs into the running file's directory.
38 Exe string `json:"exe,omitempty"`
39 ExeWritable bool `json:"exe_writable"`
40 UpdateConfigured bool `json:"update_configured"`
41 AdminEnabled bool `json:"admin_enabled"`
42 UpdateURL string `json:"update_url,omitempty"`
43 // Admins are the operator keys allowed to command this gateway, so a second administrator can
44 // see that they are registered and the first can see that they are not alone.
45 Admins []string `json:"admins,omitempty"`
46 // Relays is what each configured relay says about this gateway: whether it already lists it,
47 // and who to ask if it does not. It is the answer to "why is my gateway not on that relay",
48 // asked without a conversation.
49 Relays map[string]RelayHealth `json:"relays,omitempty"`
50 // ListingsPending is how many swaps are quoted but not paid for yet.
51 ListingsPending int `json:"listings_pending"`
52 // Billing is what this gateway charges, without the wallet secret: an operator answering "what
53 // am I charging" should not have to read a file on a machine they may not have access to.
54 Billing map[string]any `json:"billing,omitempty"`
55 }
56 57 // RelayHealth is one relay's NIP-11 as it applies to this gateway.
58 type RelayHealth struct {
59 Name string `json:"name,omitempty"`
60 Contact string `json:"contact,omitempty"`
61 Authorized bool `json:"authorized"`
62 Error string `json:"error,omitempty"`
63 Checked string `json:"checked,omitempty"`
64 65 // Paid access to this relay, when the relay charges: the gateway asks, and the countdown is
66 // the answer. Zero rate means the relay charges nothing.
67 Paid bool `json:"paid,omitempty"`
68 Blocked bool `json:"blocked,omitempty"`
69 RemainingSeconds int64 `json:"remaining_seconds,omitempty"`
70 PaidUntil string `json:"paid_until,omitempty"`
71 RateSatsPerDay int64 `json:"rate_sats_per_day,omitempty"`
72 // Warning is the sentence an operator needs: nothing, a countdown, or a reason.
73 Warning string `json:"warning,omitempty"`
74 }
75 76 // NodeHealth is one chain's node as the last presence check saw it.
77 type NodeHealth struct {
78 Addr string `json:"addr"`
79 OK bool `json:"ok"`
80 Tip int64 `json:"tip,omitempty"`
81 Error string `json:"error,omitempty"`
82 Checked string `json:"checked,omitempty"`
83 // Services is the node's advertised service bits, and CompactFilters is
84 // the NODE_COMPACT_FILTERS bit of it. It is the answer to "why does this
85 // gateway not hand out filters": the backend node does not advertise them.
86 Services uint64 `json:"services,omitempty"`
87 CompactFilters bool `json:"compact_filters"`
88 }
89 90 // healthState is the mutable side of the report.
91 type healthState struct {
92 started time.Time
93 active int64
94 total int64
95 presence int64
96 nodeHealth map[string]NodeHealth
97 relays map[string]RelayHealth
98 }
99 100 func newHealthState(started time.Time, chains []string) *healthState {
101 return &healthState{
102 started: started,
103 nodeHealth: make(map[string]NodeHealth, len(chains)),
104 relays: make(map[string]RelayHealth),
105 }
106 }
107 108 func (s *Server) Health() Health {
109 state := s.health
110 now := time.Now()
111 112 out := Health{
113 Version: s.cfg.Version,
114 PID: s.pid,
115 StartedAt: state.started.UTC().Format(time.RFC3339),
116 UptimeSeconds: now.Sub(state.started).Seconds(),
117 SessionsActive: atomic.LoadInt64(&state.active),
118 SessionsTotal: atomic.LoadInt64(&state.total),
119 Chains: append([]string{}, s.cfg.Chains...),
120 Nodes: make(map[string]NodeHealth, len(s.cfg.Nodes)),
121 Relays: make(map[string]RelayHealth, len(s.cfg.Relays)),
122 Healthy: true,
123 }
124 125 out.Exe, out.ExeWritable = exeInfo()
126 out.UpdateConfigured = s.updateConfigured()
127 out.AdminEnabled = s.cfg.Admin && len(s.cfg.Admins) > 0
128 out.Admins = append([]string{}, s.cfg.Admins...)
129 out.UpdateURL = s.cfg.Update.ManifestURL
130 s.billingMu.Lock()
131 out.Billing = s.billing.Redacted()
132 s.billingMu.Unlock()
133 134 if s.listings != nil {
135 out.ListingsPending = len(s.listings.Pending())
136 }
137 138 s.mu.Lock()
139 for url, relay := range state.relays {
140 out.Relays[url] = relay
141 }
142 for chain, node := range s.cfg.Nodes {
143 health := state.nodeHealth[chain]
144 145 if health.Addr == "" {
146 health.Addr = node.Addr
147 }
148 149 out.Nodes[chain] = health
150 }
151 s.mu.Unlock()
152 153 if last := atomic.LoadInt64(&state.presence); last > 0 {
154 out.LastPresenceSeconds = now.Sub(time.Unix(0, last)).Seconds()
155 } else {
156 out.Healthy = false
157 }
158 159 for _, node := range out.Nodes {
160 if !node.OK {
161 out.Healthy = false
162 }
163 }
164 165 return out
166 }
167 168 // exeProbe is the answer to "can this process replace itself". It is measured once: after an
169 // update the gateway execs and is a new process, which measures again.
170 var exeProbe struct {
171 sync.Once
172 path string
173 writable bool
174 }
175 176 func exeInfo() (string, bool) {
177 exeProbe.Do(func() {
178 path, err := os.Executable()
179 180 if err != nil {
181 return
182 }
183 184 exeProbe.path = path
185 exeProbe.writable = dirWritable(filepath.Dir(path))
186 })
187 188 return exeProbe.path, exeProbe.writable
189 }
190 191 // dirWritable reports whether a file can be created in dir. That is exactly what an update needs:
192 // it stages the new binary beside the running one and renames it into place.
193 func dirWritable(dir string) bool {
194 probe, err := os.CreateTemp(dir, ".nostrino-probe-*")
195 196 if err != nil {
197 return false
198 }
199 200 name := probe.Name()
201 probe.Close()
202 _ = os.Remove(name)
203 204 return true
205 }
206 207 // recordPresence records when the gateway last told the relays it exists.
208 func (s *Server) recordPresence() {
209 atomic.StoreInt64(&s.health.presence, time.Now().UnixNano())
210 }
211 212 // recordRelay records what one relay's NIP-11 said about this gateway.
213 func (s *Server) recordRelay(url string, health RelayHealth) {
214 s.mu.Lock()
215 s.health.relays[url] = health
216 s.mu.Unlock()
217 }
218 219 // recordNode records the last node check for one chain.
220 func (s *Server) recordNode(chain string, health NodeHealth) {
221 s.mu.Lock()
222 s.health.nodeHealth[chain] = health
223 s.mu.Unlock()
224 }
225 226 // startHealth serves the health report on addr, if one was configured.
227 func (s *Server) startHealth(addr string) error {
228 if addr == "" {
229 return nil
230 }
231 232 ln, err := net.Listen("tcp", addr)
233 234 if err != nil {
235 return err
236 }
237 238 mux := http.NewServeMux()
239 mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {
240 w.Header().Set("content-type", "application/json")
241 _ = json.NewEncoder(w).Encode(s.Health())
242 })
243 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
244 if r.URL.Path != "/" {
245 http.NotFound(w, r)
246 return
247 }
248 w.Header().Set("content-type", "text/html; charset=utf-8")
249 _, _ = io.WriteString(w, adminPage)
250 })
251 if s.cfg.AdminToken != "" {
252 mux.HandleFunc("/admin", s.handleAdmin)
253 }
254 255 srv := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second}
256 s.healthServer = srv
257 258 go func() {
259 if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
260 s.cfg.Logf("bridge: health server: %v", err)
261 }
262 }()
263 264 s.cfg.Logf("bridge: health on http://%s/health", ln.Addr())
265 266 return nil
267 }
268 269 // handleAdmin is the LAN control surface. It is registered only when -admin-token
270 // is set, so an unconfigured gateway never exposes control on the local network.
271 // The token is the credential: it is compared in constant time and never leaves
272 // the process.
273 func (s *Server) handleAdmin(w http.ResponseWriter, r *http.Request) {
274 if r.Method != http.MethodPost {
275 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
276 return
277 }
278 279 token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
280 if len(token) == 0 || subtle.ConstantTimeCompare([]byte(token), []byte(s.cfg.AdminToken)) != 1 {
281 http.Error(w, "unauthorized", http.StatusUnauthorized)
282 return
283 }
284 285 body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
286 if err != nil {
287 http.Error(w, err.Error(), http.StatusBadRequest)
288 return
289 }
290 291 reply, err := s.adminCommand(r.Context(), s.localPeer(), body)
292 if err != nil {
293 http.Error(w, err.Error(), http.StatusBadRequest)
294 return
295 }
296 297 w.Header().Set("content-type", "application/json")
298 _, _ = w.Write(reply)
299 }
300 301 // localPeer is the identity logged for a LAN admin command: the first operator
302 // key when one is configured, a fixed marker otherwise. It is only for the log
303 // and the control-holder note; the token has already authenticated the caller.
304 func (s *Server) localPeer() [32]byte {
305 if len(s.cfg.Admins) > 0 {
306 if b, err := hex.DecodeString(s.cfg.Admins[0]); err == nil && len(b) == 32 {
307 var peer [32]byte
308 copy(peer[:], b)
309 return peer
310 }
311 }
312 var peer [32]byte
313 copy(peer[:], "local")
314 return peer
315 }
316 317 // adminPage is the one page the gateway serves on the LAN. It is read-only unless
318 // the operator pastes the -admin-token, at which point the admin commands become
319 // available. Everything it shows comes from /health, so there is no second view of
320 // the truth to drift out of step.
321 const adminPage = `<!doctype html>
322 <html lang="en">
323 <head>
324 <meta charset="utf-8">
325 <meta name="viewport" content="width=device-width, initial-scale=1">
326 <title>nostrino gateway</title>
327 <style>
328 body{background:#0d1117;color:#c9d1d9;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:13px;line-height:1.5;margin:0;padding:24px}
329 h1{font-size:15px;margin:0 0 16px}
330 .card{border:1px solid #30363d;border-radius:6px;padding:12px 16px;margin-bottom:16px}
331 .row{display:flex;justify-content:space-between;gap:12px;padding:3px 0;border-bottom:1px solid #161b22}
332 .row:last-child{border-bottom:0}
333 .k{color:#8b949e}
334 .ok{color:#3fb950}.bad{color:#f85149}.warn{color:#d29922}
335 button{background:#21262d;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:6px 12px;margin:2px;cursor:pointer;font-family:inherit}
336 button:hover{background:#30363d}
337 button.danger{border-color:#f85149;color:#f85149}
338 input{background:#161b22;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:6px 10px;font-family:inherit;width:420px;max-width:100%}
339 pre{white-space:pre-wrap;word-break:break-word;background:#161b22;border-radius:6px;padding:10px;max-height:340px;overflow:auto}
340 </style>
341 </head>
342 <body>
343 <h1>nostrino gateway</h1>
344 <div class="card" id="status">loading...</div>
345 <div class="card">
346 <div class="row"><span class="k">admin token</span><input id="token" type="password" placeholder="set with -admin-token"></div>
347 <div class="row">
348 <button onclick="run('health')">health</button>
349 <button onclick="run('version')">version</button>
350 <button onclick="run('update-check')">update-check</button>
351 <button class="danger" onclick="run('update-apply')">update-apply</button>
352 <button class="danger" onclick="run('rollback')">rollback</button>
353 <button onclick="run('billing')">billing</button>
354 <button onclick="run('listings')">listings</button>
355 </div>
356 </div>
357 <div class="card"><pre id="out">no command run yet</pre></div>
358 <script>
359 var TOKEN_KEY='nostrino-admin-token';
360 function $(id){return document.getElementById(id);}
361 var tok=$('token');
362 try{if(localStorage.getItem(TOKEN_KEY)){tok.value=localStorage.getItem(TOKEN_KEY);}}catch(e){}
363 tok.addEventListener('change',function(){try{localStorage.setItem(TOKEN_KEY,tok.value);}catch(e){}});
364 function esc(s){return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
365 function fmt(v){
366 if(v===null||v===undefined){return '-';}
367 if(typeof v==='boolean'){return '<span class="'+(v?'ok':'bad')+'">'+v+'</span>';}
368 if(typeof v==='number'){return String(v);}
369 return esc(v);
370 }
371 function row(k,v){return '<div class="row"><span class="k">'+esc(k)+'</span><span>'+fmt(v)+'</span></div>';}
372 function refresh(){
373 fetch('/health').then(function(r){return r.json();}).then(function(h){
374 var html='';
375 html+=row('version',h.version)+row('pid',h.pid)+row('uptime',Math.round(h.uptime_seconds)+'s')+row('healthy',h.healthy);
376 html+=row('sessions',h.sessions_active+' active / '+h.sessions_total+' total');
377 html+=row('presence',(h.last_presence_seconds_ago||0).toFixed(0)+'s ago');
378 html+=row('chains',(h.chains||[]).join(', '));
379 html+=row('update',(h.update_configured?'configured':'none')+' / exe writable '+(h.exe_writable?'yes':'no'));
380 html+=row('admins',(h.admins||[]).join(', '));
381 var nodes=h.nodes||{};var nk=Object.keys(nodes);
382 for(var i=0;i<nk.length;i++){
383 var n=nodes[nk[i]];var s;
384 if(n.ok){s='<span class="ok">ok</span> tip '+n.tip;}else{s='<span class="bad">down</span> '+esc(n.error||'');}
385 s+=' / filters <span class="'+(n.compact_filters?'ok':'bad')+'">'+n.compact_filters+'</span>';
386 html+='<div class="row"><span class="k">node '+esc(nk[i])+'</span><span>'+s+'</span></div>';
387 }
388 var rels=h.relays||{};var rk=Object.keys(rels);
389 for(var j=0;j<rk.length;j++){
390 var r=rels[rk[j]];
391 var a='<span class="'+(r.authorized?'ok':'bad')+'">'+(r.authorized?'authorized':'NOT authorized')+'</span>';
392 html+='<div class="row"><span class="k">relay</span><span>'+esc(rk[j])+' '+a+(r.warning?' '+esc(r.warning):'')+'</span></div>';
393 }
394 $('status').innerHTML=html;
395 }).catch(function(e){$('status').innerHTML=row('error',String(e));});
396 }
397 function run(cmd){
398 var out=$('out');out.textContent='running '+cmd+'...';
399 fetch('/admin',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer '+tok.value},body:JSON.stringify({cmd:cmd,args:{}})})
400 .then(function(r){return r.text().then(function(txt){out.textContent=(r.ok?'':'HTTP '+r.status+'\n')+txt;refresh();});})
401 .catch(function(e){out.textContent='error: '+e;});
402 }
403 refresh();
404 setInterval(refresh,15000);
405 </script>
406 </body>
407 </html>
408 `
409 410 // heartbeat logs a line at a fixed interval, so a log that stops is itself a signal.
411 func (s *Server) heartbeat(ctx context.Context) {
412 interval := s.cfg.Heartbeat
413 414 if interval <= 0 {
415 interval = time.Minute
416 }
417 418 ticker := time.NewTicker(interval)
419 defer ticker.Stop()
420 421 for {
422 select {
423 case <-s.done:
424 return
425 case <-ctx.Done():
426 return
427 case <-ticker.C:
428 health := s.Health()
429 s.cfg.Logf("bridge: alive up=%.0fs sessions=%d total=%d presence=%.0fs ago healthy=%v",
430 health.UptimeSeconds, health.SessionsActive, health.SessionsTotal,
431 health.LastPresenceSeconds, health.Healthy)
432 }
433 }
434 }
435