From 21b08cb044265ed1185d0a858b3b388928e59f7f Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Wed, 27 Dec 2023 12:30:23 -0300 Subject: [PATCH] fix closing of closed ws.Authed channel when client AUTHs twice. --- handlers.go | 7 +++++-- utils.go | 3 +++ websocket.go | 2 ++ 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/handlers.go b/handlers.go index c36c6d7..b3e95b8 100644 --- a/handlers.go +++ b/handlers.go @@ -50,7 +50,6 @@ func (rl *Relay) HandleWebsocket(w http.ResponseWriter, r *http.Request) { conn: conn, Request: r, Challenge: hex.EncodeToString(challenge), - Authed: make(chan struct{}), } ctx, cancel := context.WithCancel( @@ -204,7 +203,11 @@ func (rl *Relay) HandleWebsocket(w http.ResponseWriter, r *http.Request) { 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.authLock.Lock() + if ws.Authed != nil { + close(ws.Authed) + } + ws.authLock.Unlock() 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"}) diff --git a/utils.go b/utils.go index 7681ac0..3f64313 100644 --- a/utils.go +++ b/utils.go @@ -14,6 +14,9 @@ const ( func RequestAuth(ctx context.Context) { ws := GetConnection(ctx) + ws.authLock.Lock() + ws.Authed = make(chan struct{}) + ws.authLock.Unlock() ws.WriteJSON(nostr.AuthEnvelope{Challenge: &ws.Challenge}) } diff --git a/websocket.go b/websocket.go index 9f75d69..f00a636 100644 --- a/websocket.go +++ b/websocket.go @@ -18,6 +18,8 @@ type WebSocket struct { Challenge string AuthedPublicKey string Authed chan struct{} + + authLock sync.Mutex } func (ws *WebSocket) WriteJSON(any any) error {