khatru/handlers.go

247 lines
6.6 KiB
Go
Raw Permalink Normal View History

package khatru
2021-01-13 23:46:06 -03:00
import (
"context"
"crypto/rand"
2021-01-13 23:46:06 -03:00
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
2021-01-13 23:46:06 -03:00
"net/http"
"strings"
"sync"
2021-01-13 23:46:06 -03:00
"time"
2023-06-23 07:10:03 -03:00
"github.com/fasthttp/websocket"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip42"
2023-11-20 08:44:45 -03:00
"github.com/rs/cors"
2021-01-13 23:46:06 -03:00
)
// ServeHTTP implements http.Handler interface.
func (rl *Relay) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if rl.ServiceURL == "" {
rl.ServiceURL = getServiceBaseURL(r)
}
if r.Header.Get("Upgrade") == "websocket" {
rl.HandleWebsocket(w, r)
} else if r.Header.Get("Accept") == "application/nostr+json" {
2023-11-20 08:44:45 -03:00
cors.AllowAll().Handler(http.HandlerFunc(rl.HandleNIP11)).ServeHTTP(w, r)
} else {
rl.serveMux.ServeHTTP(w, r)
}
2021-01-13 23:46:06 -03:00
}
func (rl *Relay) HandleWebsocket(w http.ResponseWriter, r *http.Request) {
conn, err := rl.upgrader.Upgrade(w, r, nil)
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
if err != nil {
rl.Log.Printf("failed to upgrade websocket: %v\n", err)
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
return
}
rl.clients.Store(conn, struct{}{})
ticker := time.NewTicker(rl.PingPeriod)
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
// NIP-42 challenge
challenge := make([]byte, 8)
rand.Read(challenge)
ws := &WebSocket{
conn: conn,
Request: r,
Challenge: hex.EncodeToString(challenge),
Authed: make(chan struct{}),
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
ctx, cancel := context.WithCancel(
context.WithValue(
context.Background(),
2023-12-25 09:14:09 -03:00
wsKey, ws,
),
)
kill := func() {
2023-12-09 09:00:11 -03:00
for _, ondisconnect := range rl.OnDisconnect {
ondisconnect(ctx)
}
ticker.Stop()
cancel()
if _, ok := rl.clients.Load(conn); ok {
conn.Close()
rl.clients.Delete(conn)
removeListener(ws)
}
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
go func() {
defer kill()
2021-01-13 23:46:06 -03:00
conn.SetReadLimit(rl.MaxMessageSize)
conn.SetReadDeadline(time.Now().Add(rl.PongWait))
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(rl.PongWait))
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
return nil
})
for _, onconnect := range rl.OnConnect {
onconnect(ctx)
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
for {
typ, message, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(
err,
2023-11-19 08:30:06 -03:00
websocket.CloseNormalClosure, // 1000
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
websocket.CloseGoingAway, // 1001
websocket.CloseNoStatusReceived, // 1005
websocket.CloseAbnormalClosure, // 1006
) {
rl.Log.Printf("unexpected close error from %s: %v\n", r.Header.Get("X-Forwarded-For"), err)
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
}
2023-12-09 00:14:08 -03:00
return
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
}
2021-01-13 23:46:06 -03:00
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
if typ == websocket.PingMessage {
ws.WriteMessage(websocket.PongMessage, nil)
continue
}
go func(message []byte) {
envelope := nostr.ParseMessage(message)
if envelope == nil {
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
// stop silently
return
2021-02-17 16:59:56 -03:00
}
2021-01-13 23:46:06 -03:00
switch env := envelope.(type) {
case *nostr.EventEnvelope:
// check id
hash := sha256.Sum256(env.Event.Serialize())
id := hex.EncodeToString(hash[:])
if id != env.Event.ID {
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: false, Reason: "invalid: id is computed incorrectly"})
2023-11-22 17:30:34 -03:00
return
}
2021-02-14 21:08:02 -03:00
2023-11-20 08:44:45 -03:00
// check signature
if ok, err := env.Event.CheckSignature(); err != nil {
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: false, Reason: "error: failed to verify signature"})
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
return
} else if !ok {
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: false, Reason: "invalid: signature is invalid"})
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
return
}
2021-02-14 21:08:02 -03:00
var ok bool
var writeErr error
if env.Event.Kind == 5 {
// this always returns "blocked: " whenever it returns an error
writeErr = rl.handleDeleteRequest(ctx, &env.Event)
} else {
// this will also always return a prefixed reason
writeErr = rl.AddEvent(ctx, &env.Event)
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
}
2023-12-22 22:35:44 -03:00
var reason string
if writeErr == nil {
ok = true
} else {
2023-12-22 22:35:44 -03:00
reason = writeErr.Error()
2023-12-09 14:41:54 -03:00
if strings.HasPrefix(reason, "auth-required:") {
RequestAuth(ctx)
}
2023-06-16 17:38:32 -03:00
}
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: ok, Reason: reason})
case *nostr.CountEnvelope:
if rl.CountEvents == nil {
ws.WriteJSON(nostr.ClosedEnvelope{SubscriptionID: env.SubscriptionID, Reason: "unsupported: this relay does not support NIP-45"})
2023-05-17 19:54:56 +09:00
return
}
var total int64
for _, filter := range env.Filters {
total += rl.handleCountRequest(ctx, ws, filter)
2023-05-17 19:54:56 +09:00
}
ws.WriteJSON(nostr.CountEnvelope{SubscriptionID: env.SubscriptionID, Count: &total})
case *nostr.ReqEnvelope:
eose := sync.WaitGroup{}
eose.Add(len(env.Filters))
// a context just for the "stored events" request handler
reqCtx, cancelReqCtx := context.WithCancelCause(ctx)
2023-12-25 09:14:09 -03:00
// expose subscription id in the context
reqCtx = context.WithValue(reqCtx, subscriptionIdKey, env.SubscriptionID)
// handle each filter separately -- dispatching events as they're loaded from databases
for _, filter := range env.Filters {
err := rl.handleRequest(reqCtx, env.SubscriptionID, &eose, ws, filter)
2023-12-06 21:32:48 -03:00
if err != nil {
// fail everything if any filter is rejected
2023-12-09 14:41:54 -03:00
reason := err.Error()
if strings.HasPrefix(reason, "auth-required:") {
RequestAuth(ctx)
}
ws.WriteJSON(nostr.ClosedEnvelope{SubscriptionID: env.SubscriptionID, Reason: reason})
cancelReqCtx(errors.New("filter rejected"))
return
}
}
go func() {
// when all events have been loaded from databases and dispatched
// we can cancel the context and fire the EOSE message
eose.Wait()
cancelReqCtx(nil)
ws.WriteJSON(nostr.EOSEEnvelope(env.SubscriptionID))
}()
setListener(env.SubscriptionID, ws, env.Filters, cancelReqCtx)
case *nostr.CloseEnvelope:
removeListenerId(ws, string(*env))
case *nostr.AuthEnvelope:
wsBaseUrl := strings.Replace(rl.ServiceURL, "http", "ws", 1)
if pubkey, ok := nip42.ValidateAuthEvent(&env.Event, ws.Challenge, wsBaseUrl); ok {
ws.AuthedPublicKey = pubkey
close(ws.Authed)
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: true})
} else {
ws.WriteJSON(nostr.OKEnvelope{EventID: env.Event.ID, OK: false, Reason: "error: failed to authenticate"})
}
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
}(message)
}
}()
go func() {
defer kill()
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
for {
select {
case <-ctx.Done():
return
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
case <-ticker.C:
err := ws.WriteMessage(websocket.PingMessage, nil)
if err != nil {
if !strings.HasSuffix(err.Error(), "use of closed network connection") {
rl.Log.Printf("error writing ping: %v; closing websocket\n", err)
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
return
}
}
}
start: introduce Server type and Shutdown (breaking change) the main motivation for this change is to be able to run tests. before this commit, Start, Router and Log operated on global variables, making automated testing unreasonably hard. this commit puts all that a server needs in a new Server type, which also made it possible for a Server.Shutdown - see ShutdownAware doc comments. BREAKING CHANGES: - Relay.OnInitialized takes one argument now, *relayer.Server. - relayer.Router is now replaced by relayer.Server.Router(). package users can still hook into the router from OnInitialized for custom HTTP routing. - relayer.Log is gone. apart from another global var, imho this was a too opinionated choice for a framework to build a custom relay upon. this commit introduces a Logger interface which package users can implement for zerolog to make it log like before. see Server.Log for details. other notable changes: finally added a couple basic tests, for start up and shutdown. doc comments now explain most of the essentials, hopefully making it more approachable for newcomers and easier to understand the relayer package. the changes in handlers.go are minimal, although git diff goes crazy. this is because most of the lines are simply shifted indentation back by one due to go fmt. before this commit: func handleWebsocket(relay Relay) func(http.ResponseWriter, *http.Request) func handleNIP11(relay Relay) func(http.ResponseWriter, *http.Request) after: func (s *Server) handleWebsocket(w http.ResponseWriter, r *http.Request) func (s *Server) handleNIP11(w http.ResponseWriter, r *http.Request)
2022-12-24 22:21:26 +01:00
}()
}
func (rl *Relay) HandleNIP11(w http.ResponseWriter, r *http.Request) {
2023-11-09 21:39:28 -03:00
w.Header().Set("Content-Type", "application/nostr+json")
2023-11-27 00:54:45 -03:00
info := *rl.Info
for _, ovw := range rl.OverwriteRelayInformation {
info = ovw(r.Context(), r, info)
}
json.NewEncoder(w).Encode(info)
}