-
Notifications
You must be signed in to change notification settings - Fork 84
/
handlers.go
450 lines (389 loc) · 11.8 KB
/
handlers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package relayer
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/fasthttp/websocket"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip11"
"github.com/nbd-wtf/go-nostr/nip42"
"golang.org/x/exp/slices"
"golang.org/x/time/rate"
)
// TODO: consider moving these to Server as config params
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = pongWait / 2
// Maximum message size allowed from peer.
maxMessageSize = 512000
)
// TODO: consider moving these to Server as config params
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
func challenge(conn *websocket.Conn) *WebSocket {
// NIP-42 challenge
challenge := make([]byte, 8)
rand.Read(challenge)
return &WebSocket{
conn: conn,
challenge: hex.EncodeToString(challenge),
}
}
func (s *Server) doEvent(ctx context.Context, ws *WebSocket, request []json.RawMessage, store Storage) string {
advancedDeleter, _ := store.(AdvancedDeleter)
// it's a new event
var evt nostr.Event
if err := json.Unmarshal(request[1], &evt); err != nil {
return "failed to decode event: " + err.Error()
}
// check serialization
serialized := evt.Serialize()
// assign ID
hash := sha256.Sum256(serialized)
evt.ID = hex.EncodeToString(hash[:])
// check signature (requires the ID to be set)
if ok, err := evt.CheckSignature(); err != nil {
reason := "error: failed to verify signature"
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: false, Reason: &reason})
return ""
} else if !ok {
reason := "invalid: signature is invalid"
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: false, Reason: &reason})
return ""
}
if evt.Kind == 5 {
// event deletion -- nip09
for _, tag := range evt.Tags {
if len(tag) >= 2 && tag[0] == "e" {
if advancedDeleter != nil {
advancedDeleter.BeforeDelete(ctx, tag[1], evt.PubKey)
}
if err := store.DeleteEvent(ctx, tag[1], evt.PubKey); err != nil {
reason := fmt.Sprintf("error: %s", err.Error())
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: false, Reason: &reason})
return ""
}
if advancedDeleter != nil {
advancedDeleter.AfterDelete(tag[1], evt.PubKey)
}
}
}
return ""
}
ok, message := AddEvent(ctx, s.relay, &evt)
var reason *string
if message != "" {
reason = &message
}
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: ok, Reason: reason})
return ""
}
func (s *Server) doCount(ctx context.Context, ws *WebSocket, request []json.RawMessage, store Storage) string {
counter, ok := store.(EventCounter)
if !ok {
return "restricted: this relay does not support NIP-45"
}
var id string
json.Unmarshal(request[1], &id)
if id == "" {
return "COUNT has no <id>"
}
total := int64(0)
filters := make(nostr.Filters, len(request)-2)
for i, filterReq := range request[2:] {
if err := json.Unmarshal(filterReq, &filters[i]); err != nil {
return "failed to decode filter"
}
filter := &filters[i]
// prevent kind-4 events from being returned to unauthed users,
// only when authentication is a thing
if _, ok := s.relay.(Auther); ok {
if slices.Contains(filter.Kinds, 4) {
senders := filter.Authors
receivers, _ := filter.Tags["p"]
switch {
case ws.authed == "":
// not authenticated
return "restricted: this relay does not serve kind-4 to unauthenticated users, does your client implement NIP-42?"
case len(senders) == 1 && len(receivers) < 2 && (senders[0] == ws.authed):
// allowed filter: ws.authed is sole sender (filter specifies one or all receivers)
case len(receivers) == 1 && len(senders) < 2 && (receivers[0] == ws.authed):
// allowed filter: ws.authed is sole receiver (filter specifies one or all senders)
default:
// restricted filter: do not return any events,
// even if other elements in filters array were not restricted).
// client should know better.
return "restricted: authenticated user does not have authorization for requested filters."
}
}
}
count, err := counter.CountEvents(ctx, filter)
if err != nil {
s.Log.Errorf("store: %v", err)
continue
}
total += count
}
ws.WriteJSON([]interface{}{"COUNT", id, map[string]int64{"count": total}})
return ""
}
func (s *Server) doReq(ctx context.Context, ws *WebSocket, request []json.RawMessage, store Storage) string {
var id string
json.Unmarshal(request[1], &id)
if id == "" {
return "REQ has no <id>"
}
filters := make(nostr.Filters, len(request)-2)
for i, filterReq := range request[2:] {
if err := json.Unmarshal(
filterReq,
&filters[i],
); err != nil {
return "failed to decode filter"
}
filter := &filters[i]
// prevent kind-4 events from being returned to unauthed users,
// only when authentication is a thing
if _, ok := s.relay.(Auther); ok {
if slices.Contains(filter.Kinds, 4) {
senders := filter.Authors
receivers, _ := filter.Tags["p"]
switch {
case ws.authed == "":
// not authenticated
return "restricted: this relay does not serve kind-4 to unauthenticated users, does your client implement NIP-42?"
case len(senders) == 1 && len(receivers) < 2 && (senders[0] == ws.authed):
// allowed filter: ws.authed is sole sender (filter specifies one or all receivers)
case len(receivers) == 1 && len(senders) < 2 && (receivers[0] == ws.authed):
// allowed filter: ws.authed is sole receiver (filter specifies one or all senders)
default:
// restricted filter: do not return any events,
// even if other elements in filters array were not restricted).
// client should know better.
return "restricted: authenticated user does not have authorization for requested filters."
}
}
}
events, err := store.QueryEvents(ctx, filter)
if err != nil {
s.Log.Errorf("store: %v", err)
continue
}
// ensures the client won't be bombarded with events in case Storage doesn't do limits right
if filter.Limit == 0 {
filter.Limit = 9999999999
}
i := 0
for event := range events {
ws.WriteJSON(nostr.EventEnvelope{SubscriptionID: &id, Event: *event})
i++
if i > filter.Limit {
break
}
}
// exhaust the channel (in case we broke out of it early) so it is closed by the storage
for range events {
}
}
ws.WriteJSON(nostr.EOSEEnvelope(id))
setListener(id, ws, filters)
return ""
}
func (s *Server) doClose(ctx context.Context, ws *WebSocket, request []json.RawMessage, store Storage) string {
var id string
json.Unmarshal(request[1], &id)
if id == "" {
return "CLOSE has no <id>"
}
removeListenerId(ws, id)
return ""
}
func (s *Server) doAuth(ctx context.Context, ws *WebSocket, request []json.RawMessage, store Storage) string {
if auther, ok := s.relay.(Auther); ok {
var evt nostr.Event
if err := json.Unmarshal(request[1], &evt); err != nil {
return "failed to decode auth event: " + err.Error()
}
if pubkey, ok := nip42.ValidateAuthEvent(&evt, ws.challenge, auther.ServiceURL()); ok {
ws.authed = pubkey
ctx = context.WithValue(ctx, AUTH_CONTEXT_KEY, pubkey)
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: true})
} else {
reason := "error: failed to authenticate"
ws.WriteJSON(nostr.OKEnvelope{EventID: evt.ID, OK: false, Reason: &reason})
}
}
return ""
}
func (s *Server) handleMessage(ctx context.Context, ws *WebSocket, message []byte, store Storage) {
var notice string
defer func() {
if notice != "" {
ws.WriteJSON(nostr.NoticeEnvelope(notice))
}
}()
var request []json.RawMessage
if err := json.Unmarshal(message, &request); err != nil {
// stop silently
return
}
if len(request) < 2 {
notice = "request has less than 2 parameters"
return
}
var typ string
json.Unmarshal(request[0], &typ)
switch typ {
case "EVENT":
notice = s.doEvent(ctx, ws, request, store)
case "COUNT":
notice = s.doCount(ctx, ws, request, store)
case "REQ":
notice = s.doReq(ctx, ws, request, store)
case "CLOSE":
notice = s.doClose(ctx, ws, request, store)
case "AUTH":
notice = s.doAuth(ctx, ws, request, store)
default:
if cwh, ok := s.relay.(CustomWebSocketHandler); ok {
cwh.HandleUnknownType(ws, typ, request)
} else {
notice = "unknown message type " + typ
}
}
}
func (s *Server) HandleWebsocket(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
store := s.relay.Storage(ctx)
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
s.Log.Errorf("failed to upgrade websocket: %v", err)
return
}
s.clientsMu.Lock()
defer s.clientsMu.Unlock()
s.clients[conn] = struct{}{}
ticker := time.NewTicker(pingPeriod)
stop := make(chan struct{})
s.Log.Infof("connected from %s", conn.RemoteAddr().String())
ws := challenge(conn)
if s.options.perConnectionLimiter != nil {
ws.limiter = rate.NewLimiter(
s.options.perConnectionLimiter.Limit(),
s.options.perConnectionLimiter.Burst(),
)
}
// reader
go func() {
defer func() {
ticker.Stop()
stop <- struct{}{}
close(stop)
s.clientsMu.Lock()
if _, ok := s.clients[conn]; ok {
conn.Close()
delete(s.clients, conn)
removeListener(ws)
}
s.clientsMu.Unlock()
s.Log.Infof("disconnected from %s", conn.RemoteAddr().String())
ctx.Done()
}()
conn.SetReadLimit(maxMessageSize)
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
// NIP-42 auth challenge
if _, ok := s.relay.(Auther); ok {
ws.WriteJSON(nostr.AuthEnvelope{Challenge: &ws.challenge})
}
for {
typ, message, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(
err,
websocket.CloseGoingAway, // 1001
websocket.CloseNoStatusReceived, // 1005
websocket.CloseAbnormalClosure, // 1006
) {
s.Log.Warningf("unexpected close error from %s: %v", r.Header.Get("X-Forwarded-For"), err)
}
break
}
if ws.limiter != nil {
// NOTE: Wait will throttle the requests.
// To reject requests exceeding the limit, use if !ws.limiter.Allow()
if err := ws.limiter.Wait(context.TODO()); err != nil {
s.Log.Warningf("unexpected limiter error %v", err)
continue
}
}
if typ == websocket.PingMessage {
ws.WriteMessage(websocket.PongMessage, nil)
continue
}
go s.handleMessage(context.TODO(), ws, message, store)
}
}()
// writer
go func() {
defer func() {
ticker.Stop()
conn.Close()
for range stop {
}
}()
for {
select {
case <-ticker.C:
err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait))
if err != nil {
s.Log.Errorf("error writing ping: %v; closing websocket", err)
return
}
s.Log.Infof("pinging for %s", conn.RemoteAddr().String())
case <-stop:
return
}
}
}()
}
func (s *Server) HandleNIP11(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
supportedNIPs := []int{9, 11, 12, 15, 16, 20, 33}
if _, ok := s.relay.(Auther); ok {
supportedNIPs = append(supportedNIPs, 42)
}
if storage, ok := s.relay.(Storage); ok && storage != nil {
if _, ok = storage.(EventCounter); ok {
supportedNIPs = append(supportedNIPs, 45)
}
}
info := nip11.RelayInformationDocument{
Name: s.relay.Name(),
Description: "relay powered by the relayer framework",
PubKey: "~",
Contact: "~",
SupportedNIPs: supportedNIPs,
Software: "https://github.com/fiatjaf/relayer",
Version: "~",
}
if ifmer, ok := s.relay.(Informationer); ok {
info = ifmer.GetNIP11InformationDocument()
}
json.NewEncoder(w).Encode(info)
}