-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware_expiration.go
More file actions
70 lines (58 loc) · 1.77 KB
/
middleware_expiration.go
File metadata and controls
70 lines (58 loc) · 1.77 KB
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
//go:build goexperiment.jsonv2
package mocrelay
import (
"context"
"strconv"
"time"
)
// ExpirationMiddleware implements NIP-40: Expiration Timestamp.
// Events with an "expiration" tag are rejected if expired on receipt,
// and dropped (not delivered) if expired on send.
type ExpirationMiddleware struct {
now func() time.Time
}
// NewExpirationMiddleware creates a new ExpirationMiddleware.
func NewExpirationMiddleware() Middleware {
return NewSimpleMiddleware(&ExpirationMiddleware{
now: time.Now,
})
}
func (m *ExpirationMiddleware) OnStart(ctx context.Context) (context.Context, *ServerMsg, error) {
return ctx, nil, nil
}
func (m *ExpirationMiddleware) OnEnd(ctx context.Context) (*ServerMsg, error) {
return nil, nil
}
func (m *ExpirationMiddleware) HandleClientMsg(ctx context.Context, msg *ClientMsg) (*ClientMsg, *ServerMsg, error) {
if msg.Type != MsgTypeEvent || msg.Event == nil {
return msg, nil, nil
}
if m.isExpired(msg.Event) {
resp := NewServerOKMsg(msg.Event.ID, false, "invalid: event has expired")
return nil, resp, nil
}
return msg, nil, nil
}
func (m *ExpirationMiddleware) HandleServerMsg(ctx context.Context, msg *ServerMsg) (*ServerMsg, error) {
// Drop expired events from being delivered
if msg.Type == MsgTypeEvent && msg.Event != nil {
if m.isExpired(msg.Event) {
return nil, nil // drop
}
}
return msg, nil
}
// isExpired checks if the event has an expiration tag and is expired.
func (m *ExpirationMiddleware) isExpired(event *Event) bool {
for _, tag := range event.Tags {
if len(tag) >= 2 && tag[0] == "expiration" {
expiration, err := strconv.ParseInt(tag[1], 10, 64)
if err != nil {
// Invalid expiration tag, treat as not expired
return false
}
return m.now().Unix() > expiration
}
}
return false
}