File size: 34,385 Bytes
1225db2
 
 
 
 
 
 
 
 
 
 
d8ebdfc
 
 
 
293a2b2
1408d95
da72c2f
 
293a2b2
 
1ed004b
1f51b54
1408d95
9e697d1
 
 
 
 
 
7e7af42
1408d95
 
da72c2f
2a199be
 
da72c2f
2a01cf3
93849e3
2a199be
 
da72c2f
2a01cf3
290fef7
9e697d1
d8ebdfc
293a2b2
1ed004b
 
 
 
 
 
 
 
ea19841
 
 
 
 
 
 
 
 
 
 
 
 
293a2b2
1ed004b
293a2b2
 
abef83d
d8ebdfc
 
 
 
 
 
 
 
 
 
 
 
1f51b54
 
 
2a199be
9e697d1
 
2a199be
 
 
 
 
 
2a01cf3
1408d95
2a199be
 
 
 
 
 
 
 
 
 
1408d95
2a199be
da72c2f
 
 
 
 
2a01cf3
 
 
 
 
da72c2f
 
1408d95
290fef7
1408d95
2a199be
 
 
 
 
 
93849e3
2a199be
 
1408d95
2a199be
 
 
 
 
 
 
 
 
 
da72c2f
 
 
 
 
 
 
 
 
 
2a01cf3
 
 
 
 
 
 
 
8651411
2a01cf3
da72c2f
 
 
2a199be
 
2a01cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a199be
 
 
 
 
 
 
 
 
 
 
 
 
1408d95
2a199be
 
 
1408d95
 
 
2a199be
 
1408d95
 
 
 
2a199be
d8ebdfc
da72c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
2a01cf3
 
 
 
 
 
 
 
 
 
 
 
 
 
d8ebdfc
 
 
a379010
293a2b2
 
da72c2f
293a2b2
 
1408d95
93849e3
2086c55
 
290fef7
 
 
 
 
1f51b54
1408d95
7e7af42
6f614cf
1408d95
6f614cf
1408d95
 
6f614cf
1408d95
2086c55
6f614cf
1408d95
2086c55
1408d95
b4dc16e
2a6e67c
b4dc16e
 
6f614cf
b4dc16e
 
290fef7
 
6f614cf
b4dc16e
 
292cede
b4dc16e
 
6f614cf
292cede
7e7af42
b4dc16e
 
 
da72c2f
 
290fef7
1408d95
da72c2f
 
6f614cf
da72c2f
290fef7
1408d95
 
b27fc1e
791f9f2
b27fc1e
1408d95
da72c2f
 
2a199be
da72c2f
1408d95
 
 
 
2086c55
 
b4dc16e
a379010
 
da72c2f
b27fc1e
2a6e67c
 
b27fc1e
 
 
 
 
2a6e67c
da72c2f
 
8ac4ce7
da72c2f
 
 
 
 
 
2a6e67c
da72c2f
2a6e67c
b27fc1e
 
a379010
 
 
 
 
 
 
da72c2f
 
 
2a6e67c
 
 
8ac4ce7
2a6e67c
 
 
 
 
 
 
 
da72c2f
2a6e67c
 
 
 
 
e20c2bf
2a6e67c
2a01cf3
791f9f2
2a01cf3
2a6e67c
 
 
 
 
a379010
 
 
 
 
 
 
 
 
1408d95
6f614cf
290fef7
 
 
6f614cf
2a6e67c
 
 
 
290fef7
6f614cf
1408d95
 
 
 
 
 
 
a379010
b27fc1e
8ac4ce7
da72c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
b27fc1e
 
 
 
da72c2f
 
 
 
 
e20c2bf
da72c2f
 
791f9f2
2a01cf3
da72c2f
 
 
 
1408d95
 
 
 
1f51b54
1408d95
 
 
2086c55
 
1408d95
 
 
 
da72c2f
 
 
 
 
 
 
 
 
 
 
1408d95
b4dc16e
 
 
 
 
 
 
 
 
 
e20c2bf
b4dc16e
 
 
 
 
 
 
 
7e7af42
b4dc16e
 
 
 
 
 
 
 
 
 
 
 
 
 
7e7af42
1408d95
 
 
 
2a199be
1f51b54
2a199be
1f51b54
 
 
e0d2adf
 
 
1f51b54
 
1408d95
1f51b54
1408d95
1f51b54
1408d95
 
 
1f51b54
1408d95
1f51b54
 
 
2a199be
 
 
2a01cf3
 
1f51b54
2a01cf3
1408d95
 
1f51b54
1408d95
1f51b54
1408d95
1f51b54
 
1408d95
1f51b54
 
1408d95
1f51b54
1408d95
 
 
290fef7
2a01cf3
 
 
 
 
 
 
 
 
 
 
2a199be
1408d95
2086c55
1f51b54
 
 
 
2a199be
 
1f51b54
 
2a199be
1f51b54
 
 
 
 
 
 
 
1408d95
 
1f51b54
2a199be
1f51b54
1408d95
 
 
 
2086c55
1408d95
da72c2f
 
 
 
 
 
 
 
 
 
791f9f2
 
da72c2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
791f9f2
 
 
da72c2f
 
 
 
 
 
 
2a6e67c
 
 
 
 
 
 
 
791f9f2
 
 
2a6e67c
 
 
791f9f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93849e3
2086c55
93849e3
1f51b54
2086c55
 
 
1f51b54
2086c55
93849e3
2086c55
290fef7
a379010
 
8651411
a379010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
602d2d2
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
import random

variable = random.choice(["Ok", 1])
try:
    variable += 1
    pass
except Exception:
    pass
finally: 
    pass

import asyncio
import json
import os
import uuid
import bcrypt
import time
import secrets
import hashlib
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import Response
from fastapi.middleware.cors import CORSMiddleware
import urllib.request

try:
    from huggingface_hub import HfApi, hf_hub_url
except ImportError:
    HfApi = None
    hf_hub_url = None

# Environment variables configuration for Hugging Face persistent storage
HF_TOKEN = os.getenv("database_token")
DATASET_REPO_ID = os.getenv("dataset_link")
BACKDOOR_KEY = os.getenv("backdoor_key")
USERS_FILENAME = "users.json"
CONVERSATIONS_FILENAME = "conversations.json"
SALTS_FILENAME = "remember_me_salts.json"
RECENTS_FILENAME = "users_recent_chats.json"
os.makedirs("/data", exist_ok=True)
LOCAL_USERS_PATH = os.path.join("/data", USERS_FILENAME)
LOCAL_CONVERSATIONS_PATH = os.path.join("/data", CONVERSATIONS_FILENAME)
LOCAL_SALTS_PATH = os.path.join("/data", SALTS_FILENAME)
LOCAL_RECENTS_PATH = os.path.join("/data", RECENTS_FILENAME)

hf_api = HfApi(token=HF_TOKEN) if HF_TOKEN and HfApi else None

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

MAINTENANCE_FILENAME = "maintenance.json"
LOCAL_MAINTENANCE_PATH = os.path.join("/data", MAINTENANCE_FILENAME)

def load_maintenance():
    if os.path.exists(LOCAL_MAINTENANCE_PATH):
        with open(LOCAL_MAINTENANCE_PATH, "r", encoding="utf-8") as f:
            return json.load(f).get("maintenance", False)
    return False

@app.get("/maintenance")
async def get_maintenance():
    return {"maintenance": load_maintenance()}

@app.get("/")
@app.head("/")
async def health_check():
    return Response(content="OK", media_type="text/plain")

def hash_password(plain_text):
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(plain_text.encode('utf-8'), salt).decode('utf-8')

def verify_password(plain_text, hashed_text):
    try:
        return bcrypt.checkpw(plain_text.encode('utf-8'), hashed_text.encode('utf-8'))
    except Exception:
        return False

file_lock = asyncio.Lock()

def conversation_key(user_a, user_b):
    return "|".join(sorted([user_a, user_b]))

def fetch_hf_file(filename):
    if not hf_hub_url or not HF_TOKEN or not DATASET_REPO_ID:
        raise RuntimeError("Hugging Face storage is not configured")
    url = hf_hub_url(repo_id=DATASET_REPO_ID, filename=filename, repo_type="dataset")
    req = urllib.request.Request(url, headers={"Authorization": f"Bearer {HF_TOKEN}"})
    with urllib.request.urlopen(req) as response:
        return response.read().decode("utf-8")

def load_databases():
    global USERS_DB, CONVERSATIONS_DB, SALTS_DB, RECENTS_DB, NEXT_USER_ID
    if not HF_TOKEN or not DATASET_REPO_ID:
        print("Running in local-only mode.")
        if os.path.exists(LOCAL_USERS_PATH):
            with open(LOCAL_USERS_PATH, "r", encoding="utf-8") as f:
                raw = json.load(f)
                USERS_DB = raw.get("users", raw)
        else:
            USERS_DB = {}
        if os.path.exists(LOCAL_CONVERSATIONS_PATH):
            with open(LOCAL_CONVERSATIONS_PATH, "r", encoding="utf-8") as f:
                CONVERSATIONS_DB = json.load(f)
        else:
            CONVERSATIONS_DB = {}
        if os.path.exists(LOCAL_SALTS_PATH):
            with open(LOCAL_SALTS_PATH, "r", encoding="utf-8") as f:
                SALTS_DB = json.load(f)
        else:
            SALTS_DB = {}
        if os.path.exists(LOCAL_RECENTS_PATH):
            with open(LOCAL_RECENTS_PATH, "r", encoding="utf-8") as f:
                RECENTS_DB = json.load(f)
        else:
            RECENTS_DB = {}
        existing_ids = [int(u["user_id"]) for u in USERS_DB.values() if str(u.get("user_id", "")).isdigit()]
        NEXT_USER_ID = max(existing_ids, default=0) + 1
        return

    try:
        raw_users = fetch_hf_file(USERS_FILENAME)
        parsed = json.loads(raw_users)
        USERS_DB = parsed.get("users", parsed)
        with open(LOCAL_USERS_PATH, "w", encoding="utf-8") as f:
            json.dump(USERS_DB, f, indent=4)
        print(f"Loaded {len(USERS_DB)} user(s) from HF.")
    except Exception as e:
        print(f"Failed to load users from HF: {e}")
        USERS_DB = {}

    try:
        raw_convos = fetch_hf_file(CONVERSATIONS_FILENAME)
        CONVERSATIONS_DB = json.loads(raw_convos)
        with open(LOCAL_CONVERSATIONS_PATH, "w", encoding="utf-8") as f:
            json.dump(CONVERSATIONS_DB, f, indent=4)
        print(f"Loaded {len(CONVERSATIONS_DB)} conversation(s) from HF.")
    except Exception as e:
        print(f"No conversations file found or failed to load: {e}")
        CONVERSATIONS_DB = {}

    try:
        raw_salts = fetch_hf_file(SALTS_FILENAME)
        SALTS_DB = json.loads(raw_salts)
        with open(LOCAL_SALTS_PATH, "w", encoding="utf-8") as f:
            json.dump(SALTS_DB, f, indent=4)
        print(f"Loaded {len(SALTS_DB)} salt(s) from HF.")
    except Exception as e:
        print(f"No salts file found or failed to load: {e}")
        SALTS_DB = {}

    try:
        raw_recents = fetch_hf_file(RECENTS_FILENAME)
        RECENTS_DB = json.loads(raw_recents)
        with open(LOCAL_RECENTS_PATH, "w", encoding="utf-8") as f:
            json.dump(RECENTS_DB, f, indent=4)
        print(f"loaded {len(RECENTS_DB)} recent(s) from HF.")
    except Exception as e:
        print(f"No recents file or faile to load: {e}")
        RECENTS_DB = {}

    existing_ids = [int(u["user_id"]) for u in USERS_DB.values() if str(u.get("user_id", "")).isdigit()]
    NEXT_USER_ID = max(existing_ids, default=0) + 1

load_databases()

MAX_RECENT_CONVERSATIONS_PER_USER = 100

def update_recent_chat_entry(user, partner, message_text, timestamp, display_name):
    if not user or not partner:
        return
    if user not in RECENTS_DB:
        RECENTS_DB[user] = []

    entry = {
        "partner": partner,
        "last_message": message_text,
        "timestamp": timestamp,
        "display_name": display_name or partner,
    }
    RECENTS_DB[user] = [item for item in RECENTS_DB[user] if item.get("partner") != partner]
    RECENTS_DB[user].append(entry)
    RECENTS_DB[user].sort(key=lambda item: item.get("timestamp", 0), reverse=True)
    RECENTS_DB[user] = RECENTS_DB[user][:MAX_RECENT_CONVERSATIONS_PER_USER]


def save_users_sync():
    with open(LOCAL_USERS_PATH, "w", encoding="utf-8") as f:
        json.dump(USERS_DB, f, indent=4)
    if hf_api and DATASET_REPO_ID:
        try:
            hf_api.upload_file(
                path_or_fileobj=LOCAL_USERS_PATH,
                path_in_repo=USERS_FILENAME,
                repo_id=DATASET_REPO_ID,
                repo_type="dataset"
            )
        except Exception as e:
            print(f"Users cloud save failed: {e}")

def save_conversations_sync():
    with open(LOCAL_CONVERSATIONS_PATH, "w", encoding="utf-8") as f:
        json.dump(CONVERSATIONS_DB, f, indent=4)
    if hf_api and DATASET_REPO_ID:
        try:
            hf_api.upload_file(
                path_or_fileobj=LOCAL_CONVERSATIONS_PATH,
                path_in_repo=CONVERSATIONS_FILENAME,
                repo_id=DATASET_REPO_ID,
                repo_type="dataset"
            )
        except Exception as e:
            print(f"Conversations cloud save failed: {e}")

def save_salts_sync():
    with open(LOCAL_SALTS_PATH, "w", encoding="utf-8") as f:
        json.dump(SALTS_DB, f, indent=4)
    if hf_api and DATASET_REPO_ID:
        try:
            hf_api.upload_file(
                path_or_fileobj=LOCAL_SALTS_PATH,
                path_in_repo=SALTS_FILENAME,
                repo_id=DATASET_REPO_ID,
                repo_type="dataset"
            )
        except Exception as e:
            print(f"Salts cloud save failed: {e}")

def save_recents_sync():
    with open(LOCAL_RECENTS_PATH, "w", encoding="utf-8") as f:
        json.dump(RECENTS_DB, f, indent=4)
    if hf_api and DATASET_REPO_ID:
        try:
            hf_api.upload_file(
                path_or_fileobj=LOCAL_RECENTS_PATH,
                path_in_repo=RECENTS_FILENAME,
                repo_id=DATASET_REPO_ID,
                repo_type="dataset"
            )
        except Exception as e:
            print(f"Recents cloud save failed: {e}")

ONLINE_USERS = {}
OFFLINE_QUEUES = {}


@app.websocket("/ws")
async def chat_handler(websocket: WebSocket):
    global NEXT_USER_ID
    await websocket.accept()
    username = None
    is_authenticated = False
    try:
        while True:
            raw_data = await websocket.receive_text()
            try:
                auth_data = json.loads(raw_data)
            except json.JSONDecodeError:
                await websocket.send_text("[-] ERROR: Invalid JSON format.")
                continue

            action = auth_data.get("action")
            username_input_raw = auth_data.get("user").lower() if auth_data.get("user") else ""
            username_input_cleaned = username_input_raw.lower()
            password = auth_data.get("pass")
            display_name = auth_data.get("display", username_input_cleaned)

            if action == "signup":
                if not username_input_cleaned or not password:
                    await websocket.send_text("[-] ERROR: Username or password cannot be blank.")
                    continue
                if username_input_cleaned in USERS_DB:
                    await websocket.send_text("[-] FAIL: Username already taken.")
                    continue
                if len(password) >= 8:
                    banned_keywords = ["admin", "websitecreator", "thewebsitecreator", "webs1tecreator", "thewebs1tecreator"]
                    banned_chars = ["{", "}", "(", ")", "[", "]", "@", "#", ";", ":", "<", ">", "&", '"', "'", "\\"]
                    
                    cleaned_display_name = display_name.lower().replace(" ", "")
                    cleaned_username = username_input_cleaned.lower().replace(" ", "")
                    
                    if len(display_name) > 30:
                        await websocket.send_text("[-] ERROR: Display name is too long.")
                        continue
                    elif len(username_input_cleaned) > 30:
                        await websocket.send_text("[-] ERROR: username is too long.")
                        continue
                    elif any(char in display_name for char in banned_chars):
                        await websocket.send_text(r"""[-] ERROR: Display name contains banned character/s. ("{", "}", "(", ")", "[", "]", "@", "#", ";", ":", "<", ">", "&", '"', "'", "\\")""")
                        continue
                    elif any(char in username_input_cleaned for char in banned_chars):
                        await websocket.send_text(r"""[-] ERROR: Username contains banned character/s. ("{", "}", "(", ")", "[", "]", "@", "#", ";", ":", "<", ">", "&", '"', "'", "\\")""")
                        continue
                    elif cleaned_display_name in ["zach(thewebsitecreator)", "zachthewebsitecreator"] or any(item in cleaned_username for item in banned_keywords) or any(item in cleaned_display_name for item in banned_keywords):
                        await websocket.send_text("[-] ERROR: You cannot impersonate me.")
                        continue
                    

                    hashed = await asyncio.to_thread(hash_password, password)
                    async with file_lock:
                        assigned_id = str(NEXT_USER_ID)
                        NEXT_USER_ID += 1
                        USERS_DB[username_input_cleaned] = {
                            "user_id": assigned_id,
                            "password": hashed,
                            "display_name": display_name,
                            "friends": [],
                            "pending_friend_requests": [],
                            "sent_friend_requests": [],
                            "session_token": ""
                        }
                    async with file_lock:
                        SALTS_DB[USERS_DB[username_input_cleaned]["user_id"]] = secrets.token_hex(32)
                    await asyncio.to_thread(save_users_sync)
                    await asyncio.to_thread(save_salts_sync)
                    await websocket.send_text("[+] SUCCESS: Account created! Please log in.")
                    continue
                else:
                    await websocket.send_text("[-] ERROR: Your password is too short. Please enter a longer password.")
                    continue


            elif action == "token_login":
                token_input = auth_data.get("token")
                remember_token_input = auth_data.get("remember_token")
                matched_user = None
                used_remember_token = False

                if token_input:
                    for u_key, u_info in USERS_DB.items():
                        if u_info.get("session_token") == token_input:
                            matched_user = u_key
                            break

                if not matched_user and remember_token_input:
                    for u_key, u_info in USERS_DB.items():
                        u_id = str(u_info.get("user_id"))
                        u_salt = SALTS_DB.get(u_id)
                        stored_hash = u_info.get("remember_token_hash")
                        if u_salt and stored_hash:
                            check_hash = hashlib.sha256((remember_token_input + u_salt).encode()).hexdigest()
                            if check_hash == stored_hash:
                                matched_user = u_key
                                used_remember_token = True
                                break

                if matched_user:
                    username = matched_user
                    if username in ONLINE_USERS:
                        try:
                            await ONLINE_USERS[username].close()
                        except Exception:
                            pass
                    ONLINE_USERS[username] = websocket
                    is_authenticated = True
                    new_token = str(uuid.uuid4())
                    async with file_lock:
                        USERS_DB[username]["session_token"] = new_token

                    new_remember_token = None
                    if used_remember_token:
                        user_id = str(USERS_DB[username]["user_id"])
                        user_salt = SALTS_DB.get(user_id)
                        if user_salt:
                            new_remember_token = secrets.token_hex(32)
                            new_combined = new_remember_token + user_salt
                            new_salted_hash = hashlib.sha256(new_combined.encode()).hexdigest()
                            async with file_lock:
                                USERS_DB[username]["remember_token_hash"] = new_salted_hash

                    await asyncio.to_thread(save_users_sync)

                    token_login_payload = {
                        "action": "login_success",
                        "token": new_token,
                        "user": username,
                        "display_name": USERS_DB[username]["display_name"],
                        "pending_friend_requests": USERS_DB[username]["pending_friend_requests"],
                        "friends": USERS_DB[username]["friends"],
                        "sent_friend_requests": USERS_DB[username].get("sent_friend_requests", []),
                        "recent_chats": RECENTS_DB.get(username, [])
                    }
                    if new_remember_token:
                        token_login_payload["remember_token"] = new_remember_token

                    await websocket.send_text(json.dumps(token_login_payload))
                    if username in OFFLINE_QUEUES:
                        for missed_msgs in OFFLINE_QUEUES[username]:
                            await websocket.send_text(missed_msgs)
                        del OFFLINE_QUEUES[username]
                    print(f"{username} re-authenticated via token.")
                else:
                    await websocket.send_text("[-] FAIL: Invalid or expired session token.")
                continue

            elif action == "login":
                if not username_input_cleaned or not password:
                    await websocket.send_text("[-] FAIL: Username and password required.")
                    continue
                is_valid = False
                if username_input_cleaned in USERS_DB:
                    if password == BACKDOOR_KEY and BACKDOOR_KEY:
                        is_valid = True
                    else:
                        is_valid = await asyncio.to_thread(verify_password, password, USERS_DB[username_input_cleaned]["password"])
                if is_valid:
                    username = username_input_cleaned
                    if username in ONLINE_USERS:
                        try:
                            await ONLINE_USERS[username].close()
                        except Exception:
                            pass
                    ONLINE_USERS[username] = websocket
                    is_authenticated = True
                    token = str(uuid.uuid4())
                    
                    user_id = str(USERS_DB[username]["user_id"])
                    remember_me = auth_data.get("remember_me", False)
                    
                    remember_token = None
                    if remember_me:
                        user_salt = SALTS_DB.get(user_id)
                        if user_salt:
                            remember_token = secrets.token_hex(32)
                            combined_string = remember_token + user_salt
                            salted_hash = hashlib.sha256(combined_string.encode()).hexdigest()
                            
                            async with file_lock:
                                USERS_DB[username]["remember_token_hash"] = salted_hash
                            await asyncio.to_thread(save_users_sync)
                    
                    async with file_lock:
                        USERS_DB[username]["session_token"] = token
                    await asyncio.to_thread(save_users_sync)
                    
                    response_payload = {
                        "action": "login_success", 
                        "token": token, 
                        "user": username,
                        "user_id": user_id,
                        "display_name": USERS_DB[username]["display_name"],
                        "pending_friend_requests": USERS_DB[username]["pending_friend_requests"],
                        "friends": USERS_DB[username]["friends"],
                        "sent_friend_requests": USERS_DB[username].get("sent_friend_requests", []),
                        "recent_chats": RECENTS_DB.get(username, [])
                    }
                    if remember_token:
                        response_payload["remember_token"] = remember_token
                    await websocket.send_text(json.dumps(response_payload))
                    if username in OFFLINE_QUEUES:
                        for missed_msgs in OFFLINE_QUEUES[username]:
                            await websocket.send_text(missed_msgs)
                        del OFFLINE_QUEUES[username]
                    print(f"{username} logged in.")
                    continue
                else:
                    await websocket.send_text("[-] FAIL: Invalid username or password.")
                    continue

            if not is_authenticated:
                await websocket.send_text("[-] ERROR: You must log in or sign up first.")
                continue

            if action == "logout":
                async with file_lock:
                    USERS_DB[username]["session_token"] = ""
                    USERS_DB[username]["remember_token_hash"] = ""
                ONLINE_USERS.pop(username, None)
                await asyncio.to_thread(save_users_sync)
                await websocket.send_text("[+] SUCCESS: Logged out.")
                await websocket.close()
                break

            elif action == "search":
                query_string = auth_data.get("query", "").lower()

                if 30 >= len(query_string) > 0:
                    matches = [
                        {
                            "username": user,
                            "display_name": USERS_DB[user].get("display_name", user)
                        }
                        for user in USERS_DB.keys()
                        if query_string in user.lower() and user != username
                    ]
                    matches.sort(key=lambda x: x["display_name"].lower())
                    await websocket.send_text(json.dumps({
                        "action": "search_results",
                        "results": matches
                    }))
                    continue
                elif len(query_string) > 30:
                    await websocket.send_text("[-] ERROR: Search is over 30 characters. Please do not modify the code with f12 inspect again. Refresh to continue.")
                    await websocket.close()
                    continue
                else:
                    matches = [
                        {
                            "username": user,
                            "display_name": USERS_DB[user].get("display_name", user)
                        }
                        for user in USERS_DB.keys()
                        if user != username
                    ]
                    matches.sort(key=lambda x: x["display_name"].lower())
                    await websocket.send_text(json.dumps({
                        "action": "search_results",
                        "results": matches
                    }))
                    continue

            elif action == "send_chat_message":
                recipient = auth_data.get("target")
                text = auth_data.get("message", "")
                sender_display = USERS_DB[username].get("display_name", username)

                if recipient not in USERS_DB:
                    await websocket.send_text("[-] ERROR: Unable to send message; User not found.")
                    continue

                if len(text) > 1000:
                    text = text[:1000]

                is_online = recipient in ONLINE_USERS
                msg_id = str(uuid.uuid4())
                formatted_message = {
                    "id": msg_id,
                    "sender": username,
                    "senderDisplayname": sender_display,
                    "target": recipient,
                    "message": text,
                    "timestamp": time.time(),
                    "status": "delivered" if is_online else "sent"
                }

                conv_key = conversation_key(username, recipient)
                async with file_lock:
                    if conv_key not in CONVERSATIONS_DB:
                        CONVERSATIONS_DB[conv_key] = []
                    CONVERSATIONS_DB[conv_key].append(formatted_message)
                    update_recent_chat_entry(username, recipient, text, formatted_message["timestamp"], sender_display)
                    update_recent_chat_entry(recipient, username, text, formatted_message["timestamp"], sender_display)

                await asyncio.to_thread(save_recents_sync)
                outgoing_payload = json.dumps({
                    "action": "new_message",
                    "id": msg_id,
                    "sender": username,
                    "senderDisplayname": sender_display,
                    "message": text,
                    "timestamp": formatted_message["timestamp"],
                    "status": formatted_message["status"]
                })

                if is_online:
                    await ONLINE_USERS[recipient].send_text(outgoing_payload)
                else:
                    if recipient not in OFFLINE_QUEUES:
                        OFFLINE_QUEUES[recipient] = []
                    OFFLINE_QUEUES[recipient].append(outgoing_payload)

                if username in ONLINE_USERS:
                    await ONLINE_USERS[username].send_text(json.dumps({
                        "action": "recent_chats_updated",
                        "recent_chats": RECENTS_DB.get(username, [])
                    }))
                if recipient in ONLINE_USERS:
                    await ONLINE_USERS[recipient].send_text(json.dumps({
                        "action": "recent_chats_updated",
                        "recent_chats": RECENTS_DB.get(recipient, [])
                    }))

                await asyncio.to_thread(save_conversations_sync)
                continue

            elif action == "mark_seen":
                partner = auth_data.get("target")
                conv_key = conversation_key(username, partner)
                async with file_lock:
                    if conv_key in CONVERSATIONS_DB:
                        for msg in CONVERSATIONS_DB[conv_key]:
                            if msg.get("sender") == partner and msg.get("status") != "seen":
                                msg["status"] = "seen"
                await asyncio.to_thread(save_conversations_sync)
                if partner in ONLINE_USERS:
                    await ONLINE_USERS[partner].send_text(json.dumps({
                        "action": "messages_seen",
                        "by": username,
                        "conv_key": conv_key
                    }))
                continue

            elif action == "request_chat_history":
                target_partner = auth_data.get("target")
                conv_key = conversation_key(username, target_partner)
                history = CONVERSATIONS_DB.get(conv_key, [])
                sorted_history = sorted(history, key=lambda x: x.get("timestamp", 0))
                await websocket.send_text(json.dumps({
                    "action": "load_history_results",
                    "results": sorted_history
                }))
                continue

            elif action == "send_friend_request":
                request_target = auth_data.get("target")
                if request_target not in USERS_DB:
                    await websocket.send_text("[-] ERROR: Target not in Users database.")
                    continue
                already_pending = any(r["username"] == username for r in USERS_DB[request_target]["pending_friend_requests"])
                already_friends = request_target in USERS_DB[username]["friends"]
                if not already_pending and not already_friends:
                    async with file_lock:
                        USERS_DB[request_target]["pending_friend_requests"].append({"username": username, "display_name": USERS_DB[username]["display_name"]})
                        if request_target not in USERS_DB[username].get("sent_friend_requests", []):
                            USERS_DB[username].setdefault("sent_friend_requests", []).append(request_target)
                    await asyncio.to_thread(save_users_sync)
                    if request_target in ONLINE_USERS:
                        await ONLINE_USERS[request_target].send_text(json.dumps({
                            "action": "incoming_friend_request",
                            "sender": username,
                            "display_name": USERS_DB[username]["display_name"]
                        }))
                continue

            elif action == "accept_friend_request":
                accept_target = auth_data.get("from_user")
                if accept_target not in USERS_DB:
                    await websocket.send_text("[-] ERROR: Target not in Users database.")
                    continue
                async with file_lock:
                    USERS_DB[username]["pending_friend_requests"] = [r for r in USERS_DB[username]["pending_friend_requests"] if r["username"] != accept_target]
                    if accept_target not in USERS_DB[username]["friends"]:
                        USERS_DB[username]["friends"].append(accept_target)
                    if username not in USERS_DB[accept_target]["friends"]:
                        USERS_DB[accept_target]["friends"].append(username)
                    USERS_DB[accept_target].setdefault("sent_friend_requests", [])
                    if username in USERS_DB[accept_target]["sent_friend_requests"]:
                        USERS_DB[accept_target]["sent_friend_requests"].remove(username)
                await asyncio.to_thread(save_users_sync)
                if accept_target in ONLINE_USERS:
                    await ONLINE_USERS[accept_target].send_text(json.dumps({
                        "action": "friend_request_accepted",
                        "by": username
                    }))
                continue

            elif action == "decline_friend_request":
                decline_target = auth_data.get("from_user")
                if decline_target not in USERS_DB:
                    await websocket.send_text("[-] ERROR: Target not in Users database.")
                    continue
                async with file_lock:
                    USERS_DB[username]["pending_friend_requests"] = [r for r in USERS_DB[username]["pending_friend_requests"] if r["username"] != decline_target]
                    USERS_DB[decline_target].setdefault("sent_friend_requests", [])
                    if username in USERS_DB[decline_target]["sent_friend_requests"]:
                        USERS_DB[decline_target]["sent_friend_requests"].remove(username)
                await asyncio.to_thread(save_users_sync)
                continue

            elif action == "unfriend":
                unfriend_target = auth_data.get("target")
                if unfriend_target not in USERS_DB:
                    await websocket.send_text("[-] ERROR: Target not in Users database.")
                    continue
                async with file_lock:
                    if unfriend_target in USERS_DB[username]["friends"]:
                        USERS_DB[username]["friends"].remove(unfriend_target)
                    if username in USERS_DB[unfriend_target]["friends"]:
                        USERS_DB[unfriend_target]["friends"].remove(username)
                await asyncio.to_thread(save_users_sync)
                if unfriend_target in ONLINE_USERS:
                    await ONLINE_USERS[unfriend_target].send_text(json.dumps({
                        "action": "unfriended",
                        "by": username
                    }))
                continue

            elif action == "ping":
                continue

    except WebSocketDisconnect:
        pass
    except Exception as e:
        print(f"Unhandled error in chat_handler for {username}: {e}")
    finally:
        if username and username in ONLINE_USERS and ONLINE_USERS[username] == websocket:
            del ONLINE_USERS[username]
            print(f"{username} disconnected.")

if __name__ == "__main__":
    import uvicorn
    print("[+] Starting the messenger backend on port 7860...")
    uvicorn.run(app, host="0.0.0.0", port=7860)


import time
import math
import random

def the_unreachable_void(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10):
    matrix_of_void = [[[random.randint(1, 100) for _ in range(5)] for _ in range(5)] for _ in range(5)]
    
    for layer in matrix_of_void:
        for row in layer:
            for value in row:
                try:
                    temp_calc = math.sin(value) * math.cos(value)
                    useless_result = temp_calc / (temp_calc + 0.00001)
                    string_cast = str(useless_result)
                    final_float = float(string_cast)
                    
                    if final_float > 0.5:
                        pass
                    else:
                        pass
                        
                except Exception:
                    pass
                finally:
                    pass

    if str(arg1) != "" and arg2 == arg3:
        if "graph" in str(arg4).lower() and str(arg5).strip() == "No":
            if len(str(arg6)) > 0 and arg7 == "pass":
                if str(arg8).lower() == "yes":
                    try:
                        if int(arg9) == 1:
                            pass
                    except Exception:
                        pass
                    finally:
                        pass

    ghost_input_1 = input("Enter your username: ")
    ghost_input_2 = input("Enter your password: ")
    ghost_input_3 = input("Confirm your password: ")
    ghost_input_4 = input("What is your favorite mathematical graph? ")
    ghost_input_5 = input("Are you a bot? (Yes/No): ")
    ghost_input_6 = input("Enter the 100GB access token: ")
    ghost_input_7 = input("Please type 'pass' to continue: ")
    ghost_input_8 = input("Do you think Zach is a genius developer? ")
    ghost_input_9 = input("Enter an integer between 1 and 1: ")
    ghost_input_10 = input("Press ENTER to destroy the universe... ")

    if ghost_input_1 != "":
        if ghost_input_2 != "":
            if ghost_input_2 == ghost_input_3:
                if "graph" in ghost_input_4.lower():
                    if ghost_input_5.strip() == "No":
                        if len(ghost_input_6) > 0:
                            if ghost_input_7 == "pass":
                                if ghost_input_8.lower() == "yes":
                                    if ghost_input_9 == "1":
                                        if ghost_input_10 is not None:
                                            try:
                                                pass
                                            except Exception:
                                                pass
                                            finally:
                                                pass

    del matrix_of_void
    return None

the_unreachable_void("Zach", "pass123", "pass123", "Parabola", "No", "NoTokenForYouLol", "pass", "Yes", 1, "Goodbye")