forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
verification_bot.go
528 lines (425 loc) · 14.1 KB
/
verification_bot.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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package verification
import (
"context"
"database/sql"
"fmt"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/bot/eventsystem"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/scheduledevents2"
seventsmodels "github.com/jonas747/yagpdb/common/scheduledevents2/models"
"github.com/jonas747/yagpdb/common/templates"
"github.com/jonas747/yagpdb/moderation"
"github.com/jonas747/yagpdb/verification/models"
"github.com/jonas747/yagpdb/web"
"github.com/volatiletech/sqlboiler/boil"
"math/rand"
"strings"
"sync"
"time"
"unicode/utf8"
)
const InTicketPerms = discordgo.PermissionSendMessages | discordgo.PermissionReadMessages
var _ bot.BotInitHandler = (*Plugin)(nil)
type VerificationEventData struct {
UserID int64 `json:"user_id"`
Token string `json:"token"`
}
func (p *Plugin) BotInit() {
eventsystem.AddHandlerAsyncLast(p.handleMemberJoin, eventsystem.EventGuildMemberAdd)
eventsystem.AddHandlerAsyncLast(p.handleBanAdd, eventsystem.EventGuildBanAdd)
scheduledevents2.RegisterHandler("verification_user_verified", int64(0), ScheduledEventMW(p.handleUserVerifiedScheduledEvent))
scheduledevents2.RegisterHandler("verification_user_warn", VerificationEventData{}, ScheduledEventMW(p.handleWarnUserVerification))
scheduledevents2.RegisterHandler("verification_user_kick", VerificationEventData{}, ScheduledEventMW(p.handleKickUser))
go gcRecentGuildBansLoop()
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func (p *Plugin) handleMemberJoin(evt *eventsystem.EventData) {
m := evt.GuildMemberAdd()
if m.User.Bot {
return
}
conf, err := models.FindVerificationConfigG(context.Background(), m.GuildID)
if err != nil {
if err != sql.ErrNoRows {
logger.WithError(err).WithField("guild", m.GuildID).WithField("user", m.User.ID).Error("unable to retrieve config")
}
// either no config or an error occured
return
}
if !conf.Enabled {
return
}
go p.startVerificationProcess(conf, m.GuildID, m.User)
}
func (p *Plugin) createVerificationSession(userID, guildID int64) (string, error) {
for {
token := RandStringRunes(32)
model := &models.VerificationSession{
Token: token,
UserID: userID,
GuildID: guildID,
CreatedAt: time.Now(),
}
err := model.InsertG(context.Background(), boil.Infer())
if err == nil {
return token, nil
}
if common.ErrPQIsUniqueViolation(err) {
// somehow we made a duplicate token...
continue
}
// otherwise an unknown error occured
return token, err
}
}
func (p *Plugin) startVerificationProcess(conf *models.VerificationConfig, guildID int64, target *discordgo.User) {
token, err := p.createVerificationSession(target.ID, guildID)
if err != nil {
logger.WithError(err).WithField("user", target.ID).WithField("guild", guildID).Error("failed creating verification session")
return
}
gs := bot.State.Guild(true, guildID)
if gs == nil {
logger.Error("guild not available")
return
}
msg := conf.DMMessage
if strings.TrimSpace(msg) == "" {
msg = DefaultDMMessage
}
ms, err := bot.GetMember(guildID, target.ID)
if err != nil {
logger.WithError(err).Error("failed retrieving member")
return
}
channel, err := common.BotSession.UserChannelCreate(ms.ID)
if err != nil {
logger.WithError(err).Error("failed creating user channel")
return
}
tmplCTX := templates.NewContext(gs, dstate.NewChannelState(gs, gs, channel), ms)
tmplCTX.Name = "dm_veification_message"
tmplCTX.Data["Link"] = fmt.Sprintf("%s/public/%d/verify/%d/%s", web.BaseURL(), guildID, target.ID, token)
err = tmplCTX.ExecuteAndSendWithErrors(msg, channel.ID)
if err != nil {
logger.WithError(err).WithField("guild", gs.ID).WithField("user", ms.ID).Error("failed sending verification dm message")
}
evt := &VerificationEventData{
UserID: target.ID,
Token: token,
}
// schedule the kick and warnings
if conf.WarnUnverifiedAfter > 0 && conf.WarnMessage != "" {
scheduledevents2.ScheduleEvent("verification_user_warn", guildID, time.Now().Add(time.Minute*time.Duration(conf.WarnUnverifiedAfter)), evt)
}
if conf.KickUnverifiedAfter > 0 {
scheduledevents2.ScheduleEvent("verification_user_kick", guildID, time.Now().Add(time.Minute*time.Duration(conf.KickUnverifiedAfter)), evt)
}
p.logAction(conf.LogChannel, target, "New user joined waiting to be verified as a human", 0x47aaed)
}
func ScheduledEventMW(innerHandler func(ms *dstate.MemberState, guildID int64, conf *models.VerificationConfig, rawData interface{}) (bool, error)) func(evt *seventsmodels.ScheduledEvent, data interface{}) (retry bool, err error) {
return func(evt *seventsmodels.ScheduledEvent, data interface{}) (retry bool, err error) {
userID := int64(0)
switch t := data.(type) {
case *int64:
userID = *t
case *VerificationEventData:
userID = t.UserID
}
conf, err := models.FindVerificationConfigG(context.Background(), evt.GuildID)
if err != nil {
if err != sql.ErrNoRows {
logger.WithError(err).WithField("guild", evt.GuildID).WithField("user", userID).Error("unable to retrieve config")
return true, err
}
// either no config anymore? shouldn't be possible
return false, nil
}
gs := bot.State.Guild(true, evt.GuildID)
if gs == nil {
return false, nil
}
ms := gs.MemberCopy(true, userID)
if ms == nil {
if gs.IsAvailable(true) {
return false, nil // probably left
}
// unavailable, we might be starting up
return true, nil
}
return innerHandler(ms, evt.GuildID, conf, data)
}
}
func (p *Plugin) handleUserVerifiedScheduledEvent(ms *dstate.MemberState, guildID int64, conf *models.VerificationConfig, rawData interface{}) (retry bool, err error) {
err = common.BotSession.GuildMemberRoleAdd(guildID, ms.ID, conf.VerifiedRole)
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
model, err := models.FindVerifiedUserG(context.Background(), guildID, ms.ID)
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
if !confVerificationTrackIPs.GetBool() || model.IP == "" {
p.logAction(conf.LogChannel, ms.DGoUser(), "User successfully verified", 0x49ed47)
return false, nil
}
// Check for IP conflicts
conflicts, err := p.findIPConflicts(guildID, ms.ID, model.IP)
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
if len(conflicts) < 1 {
p.logAction(conf.LogChannel, ms.DGoUser(), "User successfully verified", 0x49ed47)
return false, nil
}
// check if the user shares a IP with a banned user
ban, err := p.CheckBanned(guildID, conflicts)
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
if ban != nil {
// shares a IP with a banned user
banReason := "Alt-" + ban.User.Username + ": " + ban.Reason
if utf8.RuneCountInString(banReason) > 512 {
// trim ban reason
r := []rune(banReason)
r = r[:509]
banReason = string(r) + "..."
}
err := moderation.BanUser(nil, guildID, 0, common.BotUser, banReason, ms.DGoUser())
if err != nil {
return scheduledevents2.CheckDiscordErrRetry(err), err
}
p.logAction(conf.LogChannel, ms.DGoUser(), fmt.Sprintf("User banned for sharing IP with banned user %s#%s (%d)\nReason: %s",
ban.User.Username, ban.User.Discriminator, ban.User.ID, ban.Reason), 0xef4640)
return false, nil
}
// Does not share the IP with a banned user, but warn about alt account
var builder strings.Builder
builder.WriteString("User verified but verified with the same IP as the following users: \n")
for i, v := range conflicts {
builder.WriteString(fmt.Sprintf("\n%s#%s (%d)", v.Username, v.Discriminator, v.ID))
if i >= 20 && len(conflicts) > 21 {
builder.WriteString(fmt.Sprintf("\n\nAnd %d other users...", len(conflicts)-21))
break
}
}
p.logAction(conf.LogChannel, ms.DGoUser(), builder.String(), 0xff8228)
return false, nil
}
func (p *Plugin) findIPConflicts(guildID int64, userID int64, ip string) ([]*discordgo.User, error) {
conflicts, err := models.VerifiedUsers(models.VerifiedUserWhere.GuildID.EQ(guildID), models.VerifiedUserWhere.IP.EQ(ip)).AllG(context.Background())
if err != nil {
return nil, err
}
if len(conflicts) < 2 {
// this will include ourselves so ignore that
return nil, nil
}
userIDs := make([]int64, 0, len(conflicts))
for _, v := range conflicts {
if v.UserID == userID {
continue
}
userIDs = append(userIDs, v.UserID)
}
users := bot.GetUsers(guildID, userIDs...)
return users, nil
}
func (p *Plugin) CheckBanned(guildID int64, users []*discordgo.User) (*discordgo.GuildBan, error) {
for _, v := range users {
ban, err := common.BotSession.GuildBan(guildID, v.ID)
if err != nil {
if cast, ok := err.(*discordgo.RESTError); ok && cast.Response != nil {
if cast.Response.StatusCode == 404 {
continue // Not banned, ban not found
}
}
return nil, err
}
if ban != nil {
return ban, nil
}
}
return nil, nil
}
func (p *Plugin) handleWarnUserVerification(ms *dstate.MemberState, guildID int64, conf *models.VerificationConfig, rawData interface{}) (retry bool, err error) {
gs := bot.State.Guild(true, guildID)
if gs == nil {
return false, nil
}
d := rawData.(*VerificationEventData)
if !common.ContainsInt64Slice(ms.Roles, conf.VerifiedRole) {
err := p.sendWarning(ms, gs, d.Token, conf)
return scheduledevents2.CheckDiscordErrRetry(err), err
}
// verified
return false, nil
}
func (p *Plugin) sendWarning(ms *dstate.MemberState, gs *dstate.GuildState, token string, conf *models.VerificationConfig) error {
msg := conf.WarnMessage
if strings.TrimSpace(msg) == "" {
return nil // no message to send
}
channel, err := common.BotSession.UserChannelCreate(ms.ID)
if err != nil {
return err
}
tmplCTX := templates.NewContext(gs, dstate.NewChannelState(gs, gs, channel), ms)
tmplCTX.Name = "warn message"
tmplCTX.Data["Link"] = fmt.Sprintf("%s/public/%d/verify/%d/%s", web.BaseURL(), gs.ID, ms.ID, token)
err = tmplCTX.ExecuteAndSendWithErrors(msg, channel.ID)
if err != nil {
logger.WithError(err).WithField("guild", gs.ID).WithField("user", ms.ID).Error("failed sending warning message")
}
return nil
}
func (p *Plugin) handleKickUser(ms *dstate.MemberState, guildID int64, conf *models.VerificationConfig, rawData interface{}) (retry bool, err error) {
if !common.ContainsInt64Slice(ms.Roles, conf.VerifiedRole) {
err := common.BotSession.GuildMemberDelete(guildID, ms.ID)
if err == nil {
p.logAction(conf.LogChannel, ms.DGoUser(), "Kicked for not verifying within deadline", 0xef4640)
}
return scheduledevents2.CheckDiscordErrRetry(err), err
}
// verified
return false, nil
}
func (p *Plugin) logAction(channelID int64, author *discordgo.User, action string, color int) {
if channelID == 0 {
return
}
_, err := common.BotSession.ChannelMessageSendEmbed(channelID, &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{
IconURL: author.AvatarURL("128"),
Name: fmt.Sprintf("%s#%s (%d)", author.Username, author.Discriminator, author.ID),
},
Description: action,
Color: color,
})
if err != nil {
logger.WithError(err).WithField("channel", channelID).Error("failed sending log message")
}
}
type RecentGuildBan struct {
GuildID int64
UserID int64
T time.Time
}
// to avoid getting in a ban loop, we keep a cache of recently banned users by the bot
var (
recentGuildBans []*RecentGuildBan
recentGuildBansmu sync.Mutex
)
func gcRecentGuildBansLoop() {
tc := time.NewTicker(time.Minute)
for {
<-tc.C
gcRecentGuildBans()
}
}
func gcRecentGuildBans() {
recentGuildBansmu.Lock()
defer recentGuildBansmu.Unlock()
if len(recentGuildBans) < 1 {
return
}
newGuildBans := make([]*RecentGuildBan, 0, len(recentGuildBans))
for _, v := range recentGuildBans {
if time.Since(v.T) < time.Second*10 {
newGuildBans = append(newGuildBans, v)
}
}
recentGuildBans = newGuildBans
}
func wasRecentlyBannedByVerification(guildID int64, userID int64) bool {
recentGuildBansmu.Lock()
defer recentGuildBansmu.Unlock()
for _, v := range recentGuildBans {
if v.GuildID != guildID || v.UserID != userID {
continue
}
if time.Since(v.T) > time.Second*10 {
continue
}
return true
}
return false
}
func markRecentlyBannedByVerification(guildID int64, userID int64) {
recentGuildBansmu.Lock()
defer recentGuildBansmu.Unlock()
for _, v := range recentGuildBans {
if v.GuildID == guildID && v.UserID == userID {
v.T = time.Now()
return
}
}
recentGuildBans = append(recentGuildBans, &RecentGuildBan{
UserID: userID,
GuildID: guildID,
T: time.Now(),
})
}
func (p *Plugin) handleBanAdd(evt *eventsystem.EventData) {
ban := evt.GuildBanAdd()
if !confVerificationTrackIPs.GetBool() {
return
}
if wasRecentlyBannedByVerification(ban.GuildID, ban.User.ID) {
return
}
model, err := models.FindVerifiedUserG(context.Background(), ban.GuildID, ban.User.ID)
if err != nil {
if err == sql.ErrNoRows {
return
}
logger.WithError(err).Error("error finding verified user in banadd")
return
}
if model.IP == "" {
return
}
alts, err := p.findIPConflicts(ban.GuildID, ban.User.ID, model.IP)
if err != nil {
logger.WithError(err).Error("error finding ip conflicts in banadd")
return
}
if len(alts) < 1 {
return
}
go p.banAlts(ban, alts)
}
func (p *Plugin) banAlts(ban *discordgo.GuildBanAdd, alts []*discordgo.User) {
for i, v := range alts {
if i != 0 {
time.Sleep(time.Second)
}
// check if they're already banned
_, err := common.BotSession.GuildBan(ban.GuildID, v.ID)
if err == nil {
continue
}
if cast, ok := err.(*discordgo.RESTError); ok && cast.Response != nil {
if cast.Response.StatusCode == 404 {
// not banned
logger.WithField("guild", ban.GuildID).WithField("user", v.ID).WithField("dupe-of", ban.User.ID).Info("banning alt account")
reason := fmt.Sprintf("Alt of banned user (%s#%s (%d))", ban.User.Username, ban.User.Discriminator, ban.User.ID)
markRecentlyBannedByVerification(ban.GuildID, v.ID)
moderation.BanUser(nil, ban.GuildID, 0, common.BotUser, reason, v)
continue
}
}
logger.WithError(err).Error("failed retrieving guild ban")
}
}