-
Notifications
You must be signed in to change notification settings - Fork 35
/
server.go
200 lines (163 loc) · 5.18 KB
/
server.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
package httpserver
import (
"bytes"
"context"
"encoding/hex"
"io"
"net/http"
"sync"
"time"
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/json"
"github.com/disgoorg/log"
)
type (
// EventHandlerFunc is used to handle events from Discord's Outgoing Webhooks
EventHandlerFunc func(responseFunc RespondFunc, event EventInteractionCreate)
// RespondFunc is used to respond to Discord's Outgoing Webhooks
RespondFunc func(response discord.InteractionResponse) error
)
// EventInteractionCreate is the event payload when an interaction is created via Discord's Outgoing Webhooks
type EventInteractionCreate struct {
discord.Interaction
}
func (e *EventInteractionCreate) UnmarshalJSON(data []byte) error {
var interaction discord.UnmarshalInteraction
if err := json.Unmarshal(data, &interaction); err != nil {
return err
}
e.Interaction = interaction.Interaction
return nil
}
// Server is used for receiving Discord's interactions via Outgoing Webhooks
type Server interface {
// Start starts the Server
Start()
// Close closes the Server
Close(ctx context.Context)
}
// VerifyRequest implements the verification side of the discord interactions api signing algorithm, as documented here: https://discord.com/developers/docs/interactions/slash-commands#security-and-authorization
// Credit: https://github.com/bsdlp/discord-interactions-go/blob/main/interactions/verify.go
func VerifyRequest(r *http.Request, key PublicKey) bool {
var msg bytes.Buffer
signature := r.Header.Get("X-Signature-Ed25519")
if signature == "" {
return false
}
sig, err := hex.DecodeString(signature)
if err != nil {
return false
}
if len(sig) != SignatureSize || sig[63]&224 != 0 {
return false
}
timestamp := r.Header.Get("X-Signature-Timestamp")
if timestamp == "" {
return false
}
msg.WriteString(timestamp)
defer func() {
_ = r.Body.Close()
}()
var body bytes.Buffer
defer func() {
r.Body = io.NopCloser(&body)
}()
_, err = io.Copy(&msg, io.TeeReader(r.Body, &body))
if err != nil {
return false
}
return Verify(key, msg.Bytes(), sig)
}
type replyStatus int
const (
replyStatusWaiting replyStatus = iota
replyStatusReplied
replyStatusTimedOut
)
// HandleInteraction handles an interaction from Discord's Outgoing Webhooks. It verifies and parses the interaction and then calls the passed EventHandlerFunc.
func HandleInteraction(publicKey PublicKey, logger log.Logger, handleFunc EventHandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if ok := VerifyRequest(r, publicKey); !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
data, _ := io.ReadAll(r.Body)
logger.Trace("received http interaction with invalid signature. body: ", string(data))
return
}
defer func() {
_ = r.Body.Close()
}()
buff := new(bytes.Buffer)
rqData, _ := io.ReadAll(io.TeeReader(r.Body, buff))
logger.Trace("received http interaction. body: ", string(rqData))
var v EventInteractionCreate
if err := json.NewDecoder(buff).Decode(&v); err != nil {
logger.Error("error while decoding interaction: ", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// these channels are used to communicate between the http handler and where the interaction is responded to
responseChannel := make(chan discord.InteractionResponse, 1)
defer close(responseChannel)
errorChannel := make(chan error, 1)
defer close(errorChannel)
// status of this interaction with a mutex to ensure usage between multiple goroutines
var (
status replyStatus
mu sync.Mutex
)
// send interaction to our handler
go handleFunc(func(response discord.InteractionResponse) error {
mu.Lock()
defer mu.Unlock()
if status == replyStatusTimedOut {
return discord.ErrInteractionExpired
}
if status == replyStatusReplied {
return discord.ErrInteractionAlreadyReplied
}
status = replyStatusReplied
responseChannel <- response
// wait if we get any error while processing the response
return <-errorChannel
}, v)
var (
body any
err error
)
// wait for the interaction to be responded to or to time out after 3s
ctx, cancel := context.WithTimeout(context.Background(), 3100*time.Millisecond)
defer cancel()
select {
case response := <-responseChannel:
if body, err = response.ToBody(); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
errorChannel <- err
return
}
case <-ctx.Done():
mu.Lock()
defer mu.Unlock()
status = replyStatusTimedOut
logger.Debug("interaction timed out")
http.Error(w, "Interaction Timed Out", http.StatusRequestTimeout)
errorChannel <- ctx.Err()
return
}
rsBody := &bytes.Buffer{}
multiWriter := io.MultiWriter(w, rsBody)
if multiPart, ok := body.(*discord.MultipartBuffer); ok {
w.Header().Set("Content-Type", multiPart.ContentType)
_, err = io.Copy(multiWriter, multiPart.Buffer)
} else {
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(multiWriter).Encode(body)
}
if err != nil {
errorChannel <- err
return
}
rsData, _ := io.ReadAll(rsBody)
logger.Trace("response to http interaction. body: ", string(rsData))
}
}