diff --git a/khatru/handlers.go b/khatru/handlers.go index 7be728a..2cade5c 100644 --- a/khatru/handlers.go +++ b/khatru/handlers.go @@ -5,6 +5,7 @@ import ( "crypto/rand" "errors" "net/http" + "net/url" "slices" "strconv" "strings" @@ -41,15 +42,30 @@ func (rl *Relay) ServeHTTP(w http.ResponseWriter, r *http.Request) { MaxAge: 86400, }) - if r.Header.Get("Upgrade") == "websocket" { - rl.HandleWebsocket(w, r) - } else if r.Header.Get("Accept") == "application/nostr+json" { - corsMiddleware.Handler(http.HandlerFunc(rl.HandleNIP11)).ServeHTTP(w, r) - } else if r.Header.Get("Content-Type") == "application/nostr+json+rpc" { - corsMiddleware.Handler(http.HandlerFunc(rl.HandleNIP86)).ServeHTTP(w, r) - } else { - corsMiddleware.Handler(rl.serveMux).ServeHTTP(w, r) + relayPathMatches := true + if rl.ServiceURL != "" { + p, err := url.Parse(rl.ServiceURL) + if err == nil { + relayPathMatches = strings.TrimSuffix(r.URL.Path, "/") == strings.TrimSuffix(p.Path, "/") + } } + + if relayPathMatches { + if r.Header.Get("Upgrade") == "websocket" { + rl.HandleWebsocket(w, r) + return + } + if r.Header.Get("Accept") == "application/nostr+json" { + corsMiddleware.Handler(http.HandlerFunc(rl.HandleNIP11)).ServeHTTP(w, r) + return + } + if r.Header.Get("Content-Type") == "application/nostr+json+rpc" { + corsMiddleware.Handler(http.HandlerFunc(rl.HandleNIP86)).ServeHTTP(w, r) + return + } + } + + corsMiddleware.Handler(rl.serveMux).ServeHTTP(w, r) } func (rl *Relay) HandleWebsocket(w http.ResponseWriter, r *http.Request) { diff --git a/khatru/relay.go b/khatru/relay.go index 229f0b5..9c2b70b 100644 --- a/khatru/relay.go +++ b/khatru/relay.go @@ -59,7 +59,8 @@ type Relay struct { ctx context.Context cancel context.CancelCauseFunc - // setting this variable overwrites the hackish workaround we do to try to figure out our own base URL + // setting this variable overwrites the hackish workaround we do to try to figure out our own base URL. + // it also ensures the relay stuff is served only from that path and not from any path possible. ServiceURL string // hooks that will be called at various times