-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
667 lines (565 loc) · 13.5 KB
/
utils.go
File metadata and controls
667 lines (565 loc) · 13.5 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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"regexp"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
// Helper functions
func generateToken() string {
bytes := make([]byte, 16)
rand.Read(bytes)
return hex.EncodeToString(bytes)
}
func generateShortToken() string {
bytes := make([]byte, 8)
rand.Read(bytes)
return hex.EncodeToString(bytes)
}
func roundVal(val float64) float64 {
return math.Round(val*100) / 100
}
func getStringOrEmpty(val any) string {
return getStringOrDefault(val, "")
}
func getStringOrDefault(val any, defaultVal string) string {
if val == nil {
return ""
}
if s, ok := val.(string); ok {
return s
}
return defaultVal
}
func getIntOrDefault(val any, defaultVal int) int {
if val == nil {
return defaultVal
}
switch v := val.(type) {
case int:
return v
case int64:
return int(v)
case float64:
return int(v)
}
return defaultVal
}
func getFloatOrDefault(val any, defaultVal float64) float64 {
if val == nil {
return defaultVal
}
switch val := val.(type) {
case float64:
return val
case float32:
return float64(val)
case int:
return float64(val)
case int64:
return float64(val)
case json.Number:
f, _ := val.Float64()
return f
default:
return defaultVal
}
}
func requireTier(tier string) gin.HandlerFunc {
return func(c *gin.Context) {
user := c.MustGet("user").(*User)
user_tier := user.GetSubscription().Tier
if hasTierOrHigher(user_tier, tier) {
c.Next()
return
}
c.JSON(403, gin.H{"error": "You need a higher subscription tier to access this endpoint"})
c.Abort()
}
}
func doAfter(fn func(any), data any, after time.Duration) {
time.Sleep(after)
go func() {
fn(data)
}()
}
func hasTierOrHigher(tier string, required string) bool {
tier = strings.ToLower(tier)
switch strings.ToLower(required) {
case "max":
return tier == "max"
case "pro":
return tier == "pro" || tier == "max"
case "drive":
return tier == "drive" || tier == "pro" || tier == "max"
case "lite":
return tier == "lite" || tier == "drive" || tier == "pro" || tier == "max"
}
return false
}
func hasRequiredStanding(current StandingLevel, required StandingLevel) bool {
switch required {
case StandingBanned:
return true
case StandingSuspended:
return current == StandingGood || current == StandingWarning || current == StandingSuspended
case StandingWarning:
return current == StandingGood || current == StandingWarning
case StandingGood:
return current == StandingGood
}
return false
}
func requireStanding(minLevel StandingLevel) gin.HandlerFunc {
return func(c *gin.Context) {
user := c.MustGet("user").(*User)
if user.HasStandingOrHigher(minLevel) {
c.Next()
return
}
current := user.GetStanding()
c.JSON(403, gin.H{"error": fmt.Sprintf("Your account standing does not allow this action. Current: %s", current)})
c.Abort()
}
}
func loadBannedWords() {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(BANNED_WORDS_URL)
if err != nil {
log.Printf("Error loading banned words list: %v", err)
derogatoryTerms = []string{} // Fallback to empty list
return
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading banned words: %v", err)
return
}
words := strings.Split(string(body), "\n")
derogatoryTerms = make([]string, 0, len(words))
for _, word := range words {
word = strings.TrimSpace(word)
if word != "" {
derogatoryTerms = append(derogatoryTerms, word)
}
}
log.Printf("Loaded %d banned words", len(derogatoryTerms))
} else {
log.Printf("Failed to load banned words list: HTTP %d", resp.StatusCode)
derogatoryTerms = []string{} // Fallback to empty list
}
}
func containsDerogatory(text string) bool {
if text == "" {
return false
}
textLower := strings.ToLower(text)
for _, term := range derogatoryTerms {
pattern := `\b` + regexp.QuoteMeta(strings.ToLower(term)) + `\b`
matched, _ := regexp.MatchString(pattern, textLower)
if matched {
return true
}
}
return false
}
func accountExists(userId UserId) bool {
idToUserMutex.RLock()
defer idToUserMutex.RUnlock()
_, ok := idToUser[userId]
return ok
}
func isUserBlockedBy(user User, userId UserId) bool {
usersMutex.RLock()
defer usersMutex.RUnlock()
blocked := user.GetBlocked()
for _, blockedId := range blocked {
if blockedId == userId {
return true
}
}
return false
}
func isFromBannedDomain(url string) bool {
if url == "" {
return false
}
urlLower := strings.ToLower(url)
for _, domain := range bannedDomains {
if strings.Contains(urlLower, domain) {
return true
}
}
return false
}
func isValidMimeType(url string, allowedTypes []string) bool {
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Head(url)
if err != nil {
return false
}
defer resp.Body.Close()
contentType := resp.Header.Get("Content-Type")
return slices.Contains(allowedTypes, contentType)
}
// Rate limiting functions
func applyRateLimit(key string, limitType string) (bool, int, float64) {
rateLimitMutex.Lock()
defer rateLimitMutex.Unlock()
currentTime := time.Now().Unix()
limits, exists := rateLimits[limitType]
if !exists {
limits = rateLimits["default"]
}
compositeKey := limitType + ":" + key
rateLimit, exists := rateLimitStorage[compositeKey]
if !exists || currentTime > rateLimit.ResetAt {
rateLimitStorage[compositeKey] = &RateLimit{
Count: 0,
ResetAt: currentTime + int64(limits.Period),
}
rateLimit = rateLimitStorage[compositeKey]
}
rateLimit.Count++
isAllowed := rateLimit.Count <= limits.Count
remaining := max(limits.Count-rateLimit.Count, 0)
// If rate limit exceeded, add 10 seconds penalty
// Fuck scrapers and bots ngl
if !isAllowed {
rateLimit.ResetAt += 10
}
resetTime := float64(rateLimit.ResetAt)
return isAllowed, remaining, resetTime
}
func getRateLimitKey(c *gin.Context) string {
authKey := c.Query("auth")
if authKey != "" {
return authKey
}
clientIP := c.ClientIP()
if clientIP != "" {
return clientIP
}
return "unknown_client"
}
func cleanRateLimitStorage() {
for {
time.Sleep(5 * time.Minute)
currentTime := time.Now().Unix()
rateLimitMutex.Lock()
keysToRemove := make([]string, 0)
for key, data := range rateLimitStorage {
if currentTime > data.ResetAt {
keysToRemove = append(keysToRemove, key)
}
}
for _, key := range keysToRemove {
delete(rateLimitStorage, key)
}
rateLimitMutex.Unlock()
}
}
func getUserByIdx(idx int) (*User, error) {
usersMutex.RLock()
defer usersMutex.RUnlock()
if idx < 0 || len(users) <= idx {
return nil, fmt.Errorf("index out of bounds")
}
user := &users[idx]
return user, nil
}
func rateLimit(limitType string) gin.HandlerFunc {
return func(c *gin.Context) {
rateLimitKey := getRateLimitKey(c)
isAllowed, remaining, resetTime := applyRateLimit(rateLimitKey, limitType)
if !isAllowed {
c.Header("X-RateLimit-Limit", strconv.Itoa(rateLimits[limitType].Count))
c.Header("X-RateLimit-Remaining", strconv.Itoa(remaining))
c.Header("X-RateLimit-Reset", strconv.FormatFloat(resetTime, 'f', 0, 64))
c.JSON(429, gin.H{"error": "Rate limit exceeded. Rate limit extended by 10 seconds due to violation.", "reset_time": resetTime, "remaining": remaining})
c.Abort()
return
}
c.Next()
}
}
func requiresAuth(c *gin.Context) {
authKey := c.Query("auth")
if authKey == "" {
c.JSON(403, gin.H{"error": "auth key is required"})
c.Abort()
return
}
user := authenticateWithKey(authKey)
if user == nil {
c.JSON(403, gin.H{"error": "Invalid authentication key"})
c.Abort()
return
}
if user.IsBanned() {
c.JSON(403, gin.H{"error": "User is banned"})
return
}
user.GetSubscription()
c.Set("user", user)
c.Next()
}
func getBannedIPs() []string {
file, err := os.Open("/Users/admin/Documents/rotur/banned.json")
if err != nil {
return []string{}
}
defer file.Close()
var data struct {
IPs []string `json:"ips"`
}
if err := json.NewDecoder(file).Decode(&data); err != nil {
return []string{}
}
return data.IPs
}
func isBannedIp(ip string) bool {
bannedIPs := getBannedIPs()
if slices.Contains(bannedIPs, ip) {
return true
}
for _, bannedIP := range bannedIPs {
// handle when ipv6 all start with the same prefix, so ban a block of them
if bannedIP[4] == ":"[0] && strings.HasPrefix(ip, bannedIP) {
return true
}
}
return false
}
func corsMiddleware() gin.HandlerFunc {
config := cors.DefaultConfig()
config.AllowAllOrigins = true
config.AllowMethods = []string{"GET", "POST", "PATCH", "DELETE", "PUT", "OPTIONS"}
config.AllowHeaders = []string{"Content-Type", "Authorization"}
return cors.New(config)
}
func JSONStringify(v any) string {
data, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf(`%v`, v)
}
return string(data)
}
func fileExists(path string) bool {
info, err := os.Stat(path)
return !os.IsNotExist(err) && info.Mode().IsRegular()
}
func dirExists(path string) bool {
info, err := os.Stat(path)
if err == nil {
return info.IsDir()
}
if os.IsNotExist(err) {
return false
}
return false
}
func copyAndReplace(src, dst, old, new string) error {
data, err := os.ReadFile(src)
if err != nil {
return err
}
updated := strings.ReplaceAll(string(data), old, new)
return os.WriteFile(dst, []byte(updated), 0644)
}
func removeUserPath(path string) error {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil // already gone, not an error
}
return err
}
if info.IsDir() {
return os.RemoveAll(path)
}
return os.Remove(path)
}
func sendWebhook(url string, data map[string]any) error {
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 204 {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("unexpected status code: %d (%s)", resp.StatusCode, string(body))
}
return nil
}
func hmacIp(ip string) string {
mac := hmac.New(sha256.New, []byte(os.Getenv("HMAC_KEY")))
mac.Write([]byte(ip))
return hex.EncodeToString(mac.Sum(nil))
}
func sendDiscordWebhook(data []map[string]any) {
webhook := os.Getenv("ACCOUNT_CREATION_WEBHOOK")
if webhook == "" {
log.Println("No webhook configured, not sending Discord webhook")
return
}
body := map[string]any{
"embeds": data,
}
go func() {
if err := sendWebhook(webhook, body); err != nil {
log.Println("Failed to send account creation webhook:", err)
}
}()
}
func clamp(num int, low int, high int) int {
if num > high {
return high
}
if num < low {
return low
}
return num
}
func deleteAccountAtIndexFast(idx int) error {
usersMutex.Lock()
defer usersMutex.Unlock()
if idx < 0 || idx >= len(users) {
return fmt.Errorf("index out of range")
}
users[idx] = users[len(users)-1]
users = users[:len(users)-1]
go saveUsers()
return nil
}
func loadGifts() {
file, err := os.Open("gifts.json")
if err != nil {
if os.IsNotExist(err) {
gifts = []Gift{}
return
}
log.Printf("Error opening gifts.json: %v", err)
gifts = []Gift{}
return
}
defer file.Close()
var loaded []Gift
decoder := json.NewDecoder(file)
if err := decoder.Decode(&loaded); err != nil {
log.Printf("Error decoding gifts.json: %v", err)
gifts = []Gift{}
return
}
gifts = loaded
log.Printf("Loaded %d gifts", len(gifts))
}
func saveGifts() {
giftsMutex.RLock()
defer giftsMutex.RUnlock()
data, err := json.MarshalIndent(gifts, "", " ")
if err != nil {
log.Printf("Error marshaling gifts: %v", err)
return
}
tmpFile := "gifts.json.tmp"
if err := os.WriteFile(tmpFile, data, 0644); err != nil {
log.Printf("Error writing gifts temp file: %v", err)
return
}
if err := os.Rename(tmpFile, "gifts.json"); err != nil {
log.Printf("Error renaming gifts file: %v", err)
}
}
func cleanExpiredGifts() {
for {
time.Sleep(1 * time.Hour)
giftsMutex.Lock()
now := time.Now().UnixMilli()
changed := false
for i := range gifts {
gift := &gifts[i]
if gift.IsActive() && gift.IsExpired() {
creator := getUserById(gift.CreatorId)
if len(creator) > 0 {
newBal := roundVal(creator.GetCredits() + gift.Amount)
creator.SetBalance(newBal)
nowTs := now
creator.addTransaction(Transaction{
Note: "Gift expired: " + gift.Code,
User: UserId(""),
Amount: gift.Amount,
Type: "gift_refund",
Timestamp: nowTs,
NewTotal: newBal,
GiftId: gift.Id,
GiftCode: gift.Code,
})
}
cancelledAt := now
gift.CancelledAt = &cancelledAt
changed = true
}
}
giftsMutex.Unlock()
if changed {
go saveGifts()
go saveUsers()
}
}
}
func generateGiftCode() string {
return generateShortToken() + generateShortToken()
}
func getGiftByCode(code string) (*Gift, bool) {
giftsMutex.RLock()
defer giftsMutex.RUnlock()
for i := range gifts {
if gifts[i].Code == code {
return &gifts[i], true
}
}
return nil, false
}
func getGiftById(id string) (*Gift, bool) {
giftsMutex.RLock()
defer giftsMutex.RUnlock()
for i := range gifts {
if gifts[i].Id == id {
return &gifts[i], true
}
}
return nil, false
}
func getGiftsByCreator(creatorId UserId) []Gift {
giftsMutex.RLock()
defer giftsMutex.RUnlock()
result := make([]Gift, 0)
for _, gift := range gifts {
if gift.CreatorId == creatorId {
result = append(result, gift)
}
}
return result
}