forked from economix-app/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
3018 lines (2576 loc) · 95.8 KB
/
main.py
File metadata and controls
3018 lines (2576 loc) · 95.8 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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import time
import random
import logging
from uuid import uuid4
from threading import Thread
from typing import Dict, Optional, Tuple
import traceback
import sys
from flask import Flask, request, jsonify, send_file, redirect
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
from hashlib import sha256
from functools import wraps
from pymongo import MongoClient, ASCENDING, DESCENDING
from pymongo.errors import DuplicateKeyError, PyMongoError
import re
import html
import pyotp
import qrcode
import io
from better_profanity import profanity
import requests
from logging.handlers import RotatingFileHandler
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Constants
ITEM_CREATE_COOLDOWN = 60 # 1 minute
TOKEN_MINE_COOLDOWN = 180 # 3 minutes
MAX_ITEM_PRICE = 1000000000000
MIN_ITEM_PRICE = 1
DEBUG_MODE = os.environ.get("FLASK_DEBUG", "true").lower() == "true"
# Application Setup
app = Flask(__name__)
app.config.update(
SECRET_KEY=os.environ.get("FLASK_SECRET_KEY", "1234"),
)
CORS(app, origins=os.environ.get("CORS_ORIGINS", "").split(","))
# Logging Configuration
handler = RotatingFileHandler("app.log", maxBytes=10 * 1024 * 1024, backupCount=5)
handler.setFormatter(
logging.Formatter(
"%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"
)
)
app.logger.addHandler(handler)
app.logger.setLevel(logging.INFO)
log_file = open("app.log", "r")
log_file.seek(0, 2) # Seek to the end of the file
active_queues = set() # Track active SSE connections
class LogHandler(FileSystemEventHandler):
"""Handle log file events detected by watchdog."""
def on_modified(self, event):
"""Read new lines when the log file is modified."""
if event.src_path == "app.log":
while True:
line = log_file.readline()
if not line:
break
for q in active_queues:
q.put(line)
def on_created(self, event):
"""Reopen the log file when a new one is created (e.g., after rotation)."""
if event.src_path == "app.log":
global log_file
log_file.close()
log_file = open("app.log", "r")
log_file.seek(0, 2)
# Initialize and start the watchdog observer
observer = Observer()
observer.schedule(LogHandler(), path=".", recursive=False)
observer.start()
# Database Setup
client = MongoClient(os.environ.get("MONGODB_URI"), maxPoolSize=50)
db = client[os.environ.get("MONGODB_DB")]
Collections = {
"users": db.users,
"items": db.items,
"messages": db.messages,
"item_meta": db.item_meta,
"misc": db.misc,
"pets": db.pets,
"account_creation_attempts": db.account_creation_attempts,
"message_attempts": db.message_attempts,
"blocked_ips": db.blocked_ips,
"failed_logins": db.failed_logins,
"user_history": db.user_history,
"creator_codes": db.creator_codes,
"companies": db.companies,
"auctions": db.auctions,
"trades": db.trades,
}
# AutoMod Configuration
AUTOMOD_CONFIG = {
"ACCOUNT_CREATION_THRESHOLD": 7,
"ACCOUNT_CREATION_TIME_WINDOW": 60,
"MESSAGE_SPAM_THRESHOLD": 5,
"MESSAGE_SPAM_TIME_WINDOW": 3,
"MESSAGE_SPAM_MUTE_DURATION": "5m",
"NEW_USER_MESSAGE_SPAM_MUTE_DURATION": "10m",
"ACCOUNT_CREATION_BLOCK_DURATION": 300,
"MESSAGE_IP_THRESHOLD": 15,
"MESSAGE_IP_WINDOW": 5,
"FAILED_LOGIN_THRESHOLD": 5,
"FAILED_LOGIN_WINDOW": 60,
"MIN_ACCOUNT_AGE": 3600,
"SUBNET_BLOCKING": True,
}
@app.errorhandler(500)
def internal_server_error(error):
# Log the full exception details
exc_type, exc_value, exc_traceback = sys.exc_info()
stack_trace = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
error_message = str(error) or "An unexpected error occurred"
app.logger.error(f"500 Internal Server Error: {error_message}\nStack Trace:\n{stack_trace}")
# Detailed response for debugging (only in DEBUG mode or if explicitly enabled)
if DEBUG_MODE:
response = {
"error": "Internal Server Error",
"code": "internal-server-error",
"message": error_message,
"details": {
"exception": str(exc_type.__name__),
"description": str(exc_value),
"stack_trace": stack_trace.splitlines(),
"request": {
"method": request.method,
"url": request.url,
"headers": dict(request.headers),
"body": request.get_data(as_text=True) if request.data else None,
"remote_addr": request.remote_addr,
},
},
"timestamp": int(time.time()),
}
else:
# Minimal response for production
response = {
"error": "Internal Server Error",
"code": "internal-server-error",
"message": "Something went wrong on the server. Please try again later.",
"timestamp": int(time.time()),
}
return jsonify(response), 500
@app.errorhandler(Exception)
def handle_unhandled_exception(e):
# Redirect all unhandled exceptions to the 500 handler
return internal_server_error(e)
# Load Word Lists
def load_word_lists():
global ADJECTIVES, MATERIALS, NOUNS, SUFFIXES, PET_NAMES
try:
with open("words/adjectives.json") as f:
ADJECTIVES = json.load(f)
with open("words/materials.json") as f:
MATERIALS = json.load(f)
with open("words/nouns.json") as f:
NOUNS = json.load(f)
with open("words/suffixes.json") as f:
SUFFIXES = json.load(f)
with open("words/pet_names.json") as f:
PET_NAMES = json.load(f)
app.logger.info("Loaded item generation word lists successfully")
except Exception as e:
app.logger.critical(f"Failed to load word lists: {str(e)}")
raise
load_word_lists()
profanity.load_censor_words()
# Index Creation
def create_indexes():
Collections["users"].create_index([("username", ASCENDING)], unique=True)
Collections["items"].create_index([("id", ASCENDING), ("owner", ASCENDING)])
Collections["messages"].create_index(
[("room", ASCENDING), ("timestamp", ASCENDING)]
)
Collections["item_meta"].create_index([("id", ASCENDING)])
Collections["misc"].create_index([("type", ASCENDING)])
Collections["pets"].create_index([("id", ASCENDING)], unique=True)
Collections["account_creation_attempts"].create_index(
[("timestamp", ASCENDING)],
expireAfterSeconds=AUTOMOD_CONFIG["ACCOUNT_CREATION_TIME_WINDOW"],
)
Collections["message_attempts"].create_index(
[("timestamp", ASCENDING)],
expireAfterSeconds=AUTOMOD_CONFIG["MESSAGE_SPAM_TIME_WINDOW"],
)
Collections["blocked_ips"].create_index(
[("blocked_until", ASCENDING)], expireAfterSeconds=0
)
Collections["blocked_ips"].create_index([("ip", ASCENDING)])
Collections["failed_logins"].create_index(
[("timestamp", ASCENDING)],
expireAfterSeconds=AUTOMOD_CONFIG["FAILED_LOGIN_WINDOW"],
)
Collections["message_attempts"].create_index(
[("ip", ASCENDING), ("timestamp", ASCENDING)]
)
Collections["user_history"].create_index([("username", ASCENDING)])
Collections["user_history"].create_index([("code", ASCENDING)])
Collections["companies"].create_index([("name", ASCENDING)], unique=True)
Collections["companies"].create_index([("owner", ASCENDING)])
Collections["auctions"].create_index([("item_id", ASCENDING)])
Collections["auctions"].create_index([("owner", ASCENDING)])
Collections["trades"].create_index([("offerOwner", ASCENDING), ("requestOwner", ASCENDING)])
create_indexes()
def is_ip_blocked(ip: str) -> bool:
"""Check if an IP or its subnet is blocked"""
current_time = time.time()
# Check exact IP match
if Collections["blocked_ips"].find_one(
{"ip": ip, "blocked_until": {"$gte": current_time}}
):
return True
# Check subnet if enabled
if AUTOMOD_CONFIG["SUBNET_BLOCKING"]:
subnet = ".".join(ip.split(".")[:3]) + ".0/24"
if Collections["blocked_ips"].find_one(
{"subnet": subnet, "blocked_until": {"$gte": current_time}}
):
return True
return False
def block_ip(ip: str, duration: str, reason: str, subnet: bool = False) -> None:
"""Block an IP address or subnet"""
end_time = parse_time(duration)
block_data = {
"ip": ip,
"blocked_until": end_time,
"reason": reason,
"timestamp": int(time.time()),
}
if subnet and AUTOMOD_CONFIG["SUBNET_BLOCKING"]:
block_data["subnet"] = ".".join(ip.split(".")[:3]) + ".0/24"
Collections["blocked_ips"].update_one({"ip": ip}, {"$set": block_data}, upsert=True)
send_discord_notification(
"IP Blocked",
f"IP {ip}{' subnet' if subnet else ''} blocked until {time.ctime(end_time)}. Reason: {reason}",
0xFF0000,
)
# Utility Functions
def split_name(name: str) -> Dict[str, str]:
parts = name.split(" ")
return {
"adjective": parts[0],
"material": parts[1],
"noun": parts[2],
"suffix": " ".join(parts[3:]).split("#")[0],
"number": " ".join(parts[3:]).split("#")[1],
}
def get_level(rarity: float) -> str:
thresholds = [
(0.1, "Godlike"),
(1, "Legendary"),
(5, "Epic"),
(10, "Rare"),
(25, "Uncommon"),
(50, "Common"),
(75, "Scrap"),
]
for threshold, level in thresholds:
if rarity <= threshold:
return level
return "Trash"
def parse_time(length: str) -> int:
if not length or length.lower() == "perma":
return 0
duration = 0
for part in length.split("+"):
value = int(part[:-1])
unit = part[-1].lower()
multipliers = {
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
"w": 604800,
"y": 31536000,
}
duration += value * multipliers.get(unit, 0)
return int(time.time()) + duration
def get_conversation_id(user1: str, user2: str) -> str:
return ":".join(sorted([user1, user2]))
def send_discord_notification(title: str, description: str, color: int = 0x00FF00):
webhook_url = os.environ.get("DISCORD_WEBHOOK")
if not webhook_url:
app.logger.error("Discord webhook URL not configured")
return
def _send():
data = {
"embeds": [{"title": title, "description": description, "color": color}]
}
response = requests.post(webhook_url, json=data)
if response.status_code != 204:
app.logger.error(f"Discord notification failed: {response.status_code}")
Collections["messages"].insert_one(
{
"room": "logs",
"username": "AutoMod",
"message": description,
"timestamp": int(time.time()),
"type": "system",
}
)
Thread(target=_send).start()
# Authentication Decorators
def requires_admin(f):
@wraps(f)
def decorated(*args, **kwargs):
user = Collections["users"].find_one({"username": request.username})
if user.get("type") != "admin":
return (
jsonify(
{"error": "Admin privileges required", "code": "admin-required"}
),
403,
)
return f(*args, **kwargs)
return decorated
def requires_mod(f):
@wraps(f)
def decorated(*args, **kwargs):
user = Collections["users"].find_one({"username": request.username})
if user.get("type") not in ["admin", "mod"]:
return (
jsonify({"error": "Mod privileges required", "code": "mod-required"}),
403,
)
return f(*args, **kwargs)
return decorated
def requires_unbanned(f):
@wraps(f)
def decorated(*args, **kwargs):
user = Collections["users"].find_one({"username": request.username})
if user.get("banned_until") and (
user["banned_until"] > time.time() or user["banned_until"] == 0
):
return jsonify({"error": "You are banned", "code": "banned"}), 403
return f(*args, **kwargs)
return decorated
def requires_pro(f):
@wraps(f)
def decorated(*args, **kwargs):
user = Collections["users"].find_one({"username": request.username})
if user.get("override_plan", "free") not in ["pro", "proplus"]:
if (
user.get("override_plan_expiration")
and user["override_plan_expiration"] < time.time()
):
return (
jsonify(
{
"error": "Subscription required",
"code": "subscription-required",
}
),
403,
)
return f(*args, **kwargs)
return decorated
def requires_proplus(f):
@wraps(f)
def decorated(*args, **kwargs):
user = Collections["users"].find_one({"username": request.username})
if user.get("override_plan", "free") not in ["proplus"]:
if (
user.get("override_plan_expiration")
and user["override_plan_expiration"] < time.time()
):
return (
jsonify(
{
"error": "Subscription required",
"code": "subscription-required",
}
),
403,
)
return f(*args, **kwargs)
return decorated
def has_pro(username):
user = Collections["users"].find_one({"username": username})
if user.get("override_plan", "free") in ["pro", "proplus"]:
if (
user.get("override_plan_expiration")
and user["override_plan_expiration"] > time.time()
):
return True
return False
def has_proplus(username):
user = Collections["users"].find_one({"username": username})
if user.get("override_plan", "free") in ["proplus"]:
if (
user.get("override_plan_expiration")
and user["override_plan_expiration"] > time.time()
):
return True
return False
# Middleware
@app.before_request
def authenticate_user():
public_endpoints = [
"register_endpoint",
"login_endpoint",
"index",
"stats_endpoint",
]
if request.method == "OPTIONS" or request.endpoint in public_endpoints:
return
auth = request.headers.get("Authorization")
if not auth or not auth.startswith("Bearer "):
return (
jsonify(
{
"error": "Missing or invalid Authorization header",
"code": "invalid-credentials",
}
),
401,
)
token = auth.split(" ")[1]
user = Collections["users"].find_one({"token": token})
if not user:
return jsonify({"error": "Invalid token", "code": "invalid-credentials"}), 401
request.username = user["username"]
request.user_type = user.get("type", "user")
# Database Updaters
def update_item(item_id: str):
item = Collections["items"].find_one({"id": item_id})
if not item:
return
name = item["name"]
meta_id = (
item.get("meta_id")
or sha256(
f"{name['adjective']}{name['material']}{name['noun']}{name['suffix']}".encode()
).hexdigest()
)
meta = Collections["item_meta"].find_one({"id": meta_id})
if not meta:
rarity = round(random.uniform(0.1, 100), 1)
meta = {
"id": meta_id,
"adjective": name["adjective"],
"material": name["material"],
"noun": name["noun"],
"suffix": name["suffix"],
"rarity": rarity,
"level": get_level(rarity),
"patented": False,
"patent_owner": None,
"price_history": [],
}
Collections["item_meta"].insert_one(meta)
updates = {"meta_id": meta_id, "rarity": meta["rarity"], "level": meta["level"]}
if "history" not in item:
updates["history"] = []
Collections["items"].update_one({"id": item_id}, {"$set": updates})
def update_pet(pet_id: str):
pet = Collections["pets"].find_one({"id": pet_id})
if not pet:
return
defaults = {
"alive": True,
"last_fed": int(time.time()),
"level": 1,
"exp": 0,
"benefits": {"token_bonus": 1},
"base_price": 100,
"hunger": 100,
"happiness": 100,
"last_play_time": int(time.time()), # Initialize last_play_time
"last_update_time": int(time.time()), # Track the last update time
}
updates = {}
for key, value in defaults.items():
if key not in pet:
updates[key] = value
if updates:
Collections["pets"].update_one({"id": pet_id}, {"$set": updates})
pet = Collections["pets"].find_one({"id": pet_id})
last_fed = pet["last_fed"]
last_play_time = pet.get("last_play_time", last_fed)
last_update_time = pet.get("last_update_time", last_fed)
now = int(time.time())
# Only update hunger and happiness if enough time has passed
update_interval = 60 * 60 # 1 hour in seconds
if now - last_update_time >= update_interval:
# Health status and death check
if pet["alive"]:
seconds_unfed = now - last_fed
seconds_unplayed = now - last_play_time
new_hunger = max(0, pet["hunger"] - (seconds_unfed * (1 / 3600)))
new_happiness = max(0, pet["happiness"] - (seconds_unplayed * (1 / 3600)))
if new_hunger <= 0 or new_happiness <= 0:
Collections["pets"].update_one(
{"id": pet_id}, {"$set": {"hunger": 0, "happiness": 0, "alive": False}}
)
send_discord_notification(
"Pet Died",
f"User {pet['owner']}'s pet {pet['name']} died due to neglect.",
0xFF0000,
)
else:
Collections["pets"].update_one(
{"id": pet_id},
{
"$set": {
"hunger": new_hunger,
"happiness": new_happiness,
"last_update_time": now,
}
},
)
# Update benefits based on level (only if alive)
if pet["alive"]:
pet["benefits"]["token_bonus"] = pet["level"] # +1 token per level
Collections["pets"].update_one(
{"id": pet_id}, {"$set": {"benefits": pet["benefits"]}}
)
def level_up_pet(pet_id: str, exp_gain: int):
pet = Collections["pets"].find_one({"id": pet_id})
if not pet or not pet["alive"]:
return
new_exp = pet["exp"] + exp_gain
next_level_exp = exp_for_level(pet["level"] + 1)
if new_exp >= next_level_exp:
Collections["pets"].update_one(
{"id": pet_id},
{"$set": {"level": pet["level"] + 1, "exp": new_exp - next_level_exp}},
)
send_discord_notification(
"Pet Leveled Up",
f"User {pet['owner']}'s pet {pet['name']} reached level {pet['level'] + 1}!",
0x00FF00,
)
else:
Collections["pets"].update_one({"id": pet_id}, {"$set": {"exp": new_exp}})
def update_account(username: str) -> Optional[Tuple[dict, int]]:
user = Collections["users"].find_one({"username": username})
if not user:
return jsonify({"error": "User not found", "code": "user-not-found"}), 404
defaults = {
"banned_until": None,
"banned_reason": None,
"banned": False,
"history": [],
"exp": 0,
"level": 1,
"frozen": False,
"muted": False,
"muted_until": None,
"inventory_visibility": "private",
"2fa_enabled": False,
"pets": [],
"override_plan": None,
"override_plan_expires": None,
"redeemed_creator_code": False,
"creator_code": None,
}
updates = {k: v for k, v in defaults.items() if k not in user}
if updates:
Collections["users"].update_one({"username": username}, {"$set": updates})
current_time = time.time()
if (
user.get("banned_until")
and user["banned_until"] < current_time
and user["banned_until"] != 0
):
Collections["users"].update_one(
{"username": username},
{"$set": {"banned_until": None, "banned_reason": None, "banned": False}},
)
if (
user.get("muted_until")
and user["muted_until"] < current_time
and user["muted_until"] != 0
):
Collections["users"].update_one(
{"username": username}, {"$set": {"muted": False, "muted_until": None}}
)
for item_id in user["items"]:
update_item(item_id)
pet_limit = 2
if has_pro(username):
pet_limit = 4
if has_proplus(username):
pet_limit = 8
if len(user["pets"]) > pet_limit:
refund = (len(user["pets"]) - 1) * 100
Collections["users"].update_one(
{"username": username},
{"$set": {"pets": [user["pets"][0]]}, "$inc": {"tokens": refund}},
)
for pet_id in user["pets"]:
update_pet(pet_id)
remove_companies()
# Item and Pet Generation
def generate_item(owner: str) -> dict:
def weighted_choice(items: dict, special_case: bool = False):
choices, weights = zip(*items.items())
if special_case:
weights = [1 / items[c]["rarity"] for c in choices]
return random.choices(choices, weights=weights, k=1)[0]
noun = weighted_choice(NOUNS, special_case=True)
name = {
"adjective": weighted_choice(ADJECTIVES),
"material": weighted_choice(MATERIALS),
"noun": noun,
"suffix": weighted_choice(SUFFIXES),
"number": random.randint(1, 9999),
"icon": NOUNS[noun]["icon"],
}
meta_id = sha256(
f"{name['adjective']}{name['material']}{name['noun']}{name['suffix']}".encode()
).hexdigest()
meta = Collections["item_meta"].find_one({"id": meta_id})
if not meta:
rarity = round(random.uniform(0.05, 100), 2)
meta = {
"id": meta_id,
"adjective": name["adjective"],
"material": name["material"],
"noun": name["noun"],
"suffix": name["suffix"],
"rarity": rarity,
"level": get_level(rarity),
"patented": False,
"patent_owner": None,
"price_history": [],
}
Collections["item_meta"].insert_one(meta)
return {
"id": str(uuid4()),
"meta_id": meta_id,
"item_secret": str(uuid4()),
"rarity": meta["rarity"],
"level": meta["level"],
"name": name,
"history": [],
"for_sale": False,
"price": 0,
"owner": owner,
"created_at": int(time.time()),
}
def generate_pet(owner: str, base_price: int = 100) -> dict:
return {
"id": str(uuid4()),
"name": random.choice(PET_NAMES),
"level": 1,
"exp": 0,
"owner": owner,
"created_at": int(time.time()),
"last_fed": int(time.time()),
"benefits": {"token_bonus": 1},
"alive": True,
"base_price": base_price,
"hunger": 0,
"happiness": 100,
}
# Experience System
def exp_for_level(level: int) -> int:
return int(25 * (1.2 ** (level - 1)))
def add_exp(username: str, exp: int):
user = Collections["users"].find_one({"username": username})
if not user:
return
new_exp = user["exp"] + exp
Collections["users"].update_one({"username": username}, {"$set": {"exp": new_exp}})
if new_exp >= exp_for_level(user["level"] + 1):
Collections["users"].update_one(
{"username": username}, {"$set": {"level": user["level"] + 1}}
)
def set_exp(username: str, exp: int):
user = Collections["users"].find_one({"username": username})
if not user:
return
Collections["users"].update_one({"username": username}, {"$set": {"exp": exp}})
if exp >= exp_for_level(user["level"] + 1):
Collections["users"].update_one(
{"username": username}, {"$set": {"level": user["level"] + 1}}
)
def set_level(username: str, level: int):
user = Collections["users"].find_one({"username": username})
if not user:
return
level_exp = exp_for_level(level)
Collections["users"].update_one(
{"username": username}, {"$set": {"level": level, "exp": level_exp}}
)
# Core Handlers
def register(username: str, password: str, ip: str) -> Tuple[dict, int]:
if is_ip_blocked(ip):
return jsonify({"error": "IP blocked", "code": "ip-blocked"}), 403
if not username or not password:
return (
jsonify({"error": "Missing credentials", "code": "missing-credentials"}),
400,
)
current_time = time.time()
recent_attempts = Collections["account_creation_attempts"].count_documents(
{
"ip": ip,
"timestamp": {
"$gt": current_time - AUTOMOD_CONFIG["ACCOUNT_CREATION_TIME_WINDOW"]
},
}
)
if recent_attempts >= AUTOMOD_CONFIG["ACCOUNT_CREATION_THRESHOLD"]:
block_ip(
ip,
str(AUTOMOD_CONFIG["ACCOUNT_CREATION_BLOCK_DURATION"] + "s"),
"Account creation spam",
subnet=True,
)
Collections["users"].update_many(
{"creation_ip": ip},
{
"$set": {
"banned": True,
"banned_until": 0,
"banned_reason": "AutoMod: Account spam",
}
},
)
Collections["messages"].insert_one(
{
"id": str(uuid4()),
"room": "global",
"username": "AutoMod",
"message": f"""
<p><span style="color: #FF5555">[WARNING]</span> Detected <b>{recent_attempts + 1}x</b> Account Creation Spam</p>
<p>IP: <b>{ip}</b> has been blocked for <b>{AUTOMOD_CONFIG['ACCOUNT_CREATION_BLOCK_DURATION']} seconds</b></p>
""",
"timestamp": current_time,
"type": "system",
}
)
return jsonify({"error": "Account spam detected", "code": "account-spam"}), 429
username = profanity.censor(username.strip(), censor_char="-")
if not re.match(r"^[a-zA-Z0-9_-]{3,20}$", username):
return jsonify({"error": "Invalid username"}), 400
try:
user_data = {
"created_at": int(time.time()),
"username": username,
"password_hash": generate_password_hash(password),
"type": "user",
"tokens": 100,
"last_item_time": 0,
"last_mine_time": 0,
"items": [],
"token": None,
"banned_until": None,
"banned_reason": None,
"banned": False,
"muted": False,
"muted_until": None,
"history": [],
"exp": 0,
"level": 1,
"2fa_enabled": False,
"inventory_visibility": "private",
"pets": [],
"creation_ip": ip,
"override_plan": None,
"override_plan_expires": None,
"redeemed_creator_code": False,
"creator_code": None,
}
Collections["users"].insert_one(user_data)
Collections["account_creation_attempts"].insert_one(
{"ip": ip, "timestamp": current_time}
)
send_discord_notification(
"New user registered", f"Username: {username}\nIP: {ip}"
)
return jsonify({"success": True}), 201
except DuplicateKeyError:
return jsonify({"error": "Username exists", "code": "username-exists"}), 400
def login(
username: str,
password: str,
ip: str,
code: Optional[str] = None,
token: Optional[str] = None,
) -> Tuple[dict, int]:
if is_ip_blocked(ip):
return jsonify({"error": "IP blocked", "code": "ip-blocked"}), 403
recent_fails = Collections["failed_logins"].count_documents(
{
"ip": ip,
"timestamp": {"$gt": time.time() - AUTOMOD_CONFIG["FAILED_LOGIN_WINDOW"]},
}
)
if recent_fails >= AUTOMOD_CONFIG["FAILED_LOGIN_THRESHOLD"]:
block_ip(
ip,
str(AUTOMOD_CONFIG["FAILED_LOGIN_WINDOW"]) + "s",
"Too many failed logins",
subnet=True,
)
return (
jsonify({"error": "Too many failed attempts", "code": "login-locked"}),
429,
)
user = Collections["users"].find_one({"username": username})
if not user or not check_password_hash(user["password_hash"], password):
Collections["failed_logins"].insert_one({"ip": ip, "timestamp": time.time()})
return (
jsonify({"error": "Invalid credentials", "code": "invalid-credentials"}),
401,
)
if user.get("2fa_enabled", False):
if not code and not token:
return jsonify({"error": "2FA required", "code": "2fa-required"}), 401
if code:
if user["2fa_code"] != code:
return (
jsonify({"error": "Invalid 2FA code", "code": "invalid-2fa-code"}),
401,
)
else:
totp = pyotp.TOTP(user["2fa_secret"])
if not totp.verify(token):
return (
jsonify(
{"error": "Invalid 2FA token", "code": "invalid-2fa-token"}
),
401,
)
token = str(uuid4())
Collections["users"].update_one({"username": username}, {"$set": {"token": token}})
send_discord_notification("User logged in", f"Username: {username}")
return jsonify({"success": True, "token": token})
def get_users() -> Tuple[dict, int]:
users = Collections["users"].find({}, {"_id": 0, "username": 1})
return jsonify({"usernames": [user["username"] for user in users]})
def get_user(username: str) -> Tuple[dict, int]:
user = Collections["users"].find_one({"username": username}, {"_id": 0})
return jsonify(user)
def parse_command(username: str, command: str, room_name: str) -> str:
user = Collections["users"].find_one({"username": username})
is_admin = user.get("type") == "admin"
is_mod = user.get("type") in ["admin", "mod"]
parts = command[1:].split(" ")
cmd, *args = parts
if cmd == "clear_chat" and is_admin:
Collections["messages"].delete_many({"room": room_name})
return f"Cleared chat in <b>{room_name}</b>"
elif cmd == "clear_user" and len(args) == 1 and is_admin:
Collections["messages"].delete_many({"room": room_name, "username": args[0]})
return f"Deleted messages from <b>{args[0]}</b> in <b>{room_name}</b>"
elif cmd == "delete_many" and len(args) == 1 and is_admin:
try:
amount = int(args[0])
messages = (
Collections["messages"]
.find({"room": room_name})
.sort("timestamp", DESCENDING)
.limit(amount)
)
ids = [doc["_id"] for doc in messages]
Collections["messages"].delete_many({"_id": {"$in": ids}})
return f"Deleted <b>{amount}</b> messages from <b>{room_name}</b>"
except ValueError:
return "Invalid amount specified"
elif cmd == "ban" and len(args) >= 3 and is_admin:
target, duration, *reason = args
ban_user(target, duration, " ".join(reason))