-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.py
More file actions
1847 lines (1699 loc) · 95.7 KB
/
Copy pathserver.py
File metadata and controls
1847 lines (1699 loc) · 95.7 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TermChat v6.1 — Serveur (version sécurisée)
by Aboudev Labs CI
Base de données : Firebase Firestore (données permanentes)
Correctifs sécurité v6.1 :
- Protection contre la substitution silencieuse de clé publique E2E
- Admin login durci (comparaison constante déjà présente + commentaires)
- Fichiers optionnellement chiffrés au repos (FILE_ENCRYPTION_KEY)
- Nettoyage code (doublons de commentaires)
"""
import socket, threading, json, os, hashlib, re, uuid, binascii, ipaddress
import datetime, time, base64, signal, sys, ssl, secrets
from pathlib import Path
import bcrypt
# Firebase Admin SDK
try:
import firebase_admin
from firebase_admin import credentials, firestore
from google.cloud.firestore_v1.base_query import FieldFilter
FIREBASE_OK = True
except ImportError:
FIREBASE_OK = False
print("⚠️ firebase-admin non installe — pip install firebase-admin")
# ══════════════════════════════════════════════════════════
# CONFIG
# ══════════════════════════════════════════════════════════
PORT = int(os.environ.get("PORT", 9999))
BIND_HOST = os.environ.get("BIND_HOST", "0.0.0.0")
ADMIN_CODE = os.environ.get("ADMIN_CODE", "")
PRODUCTION_MODE = os.environ.get("PRODUCTION_MODE", "1") != "0"
REQUIRE_TLS = os.environ.get("REQUIRE_TLS", "1") != "0"
REQUIRE_FIREBASE = os.environ.get("REQUIRE_FIREBASE", "1") != "0"
REQUIRE_EXISTING_TLS_CERT = os.environ.get("REQUIRE_EXISTING_TLS_CERT", "0") != "0"
ALLOW_SELF_SIGNED_DEV_CERT = os.environ.get("ALLOW_SELF_SIGNED_DEV_CERT", "0") == "1"
ALLOW_INSECURE_GEOIP_CHECK = os.environ.get("ALLOW_INSECURE_GEOIP_CHECK", "0") == "1"
ALLOW_LEGACY_SHA256_LOGIN = os.environ.get("ALLOW_LEGACY_SHA256_LOGIN", "0") == "1"
ALLOW_INLINE_MEDIA = os.environ.get("ALLOW_INLINE_MEDIA", "0") == "1"
ALLOW_ACCOUNT_DELETION = os.environ.get("ALLOW_ACCOUNT_DELETION", "0") == "1"
MIN_PASSWORD_LEN = int(os.environ.get("MIN_PASSWORD_LEN", "12"))
MAX_MESSAGE_LEN_FREE = int(os.environ.get("MAX_MESSAGE_LEN_FREE", "150"))
MAX_MESSAGE_LEN_PREMIUM = int(os.environ.get("MAX_MESSAGE_LEN_PREMIUM", "4000"))
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", str(5 * 1024 * 1024)))
MAX_BUFFER_BYTES = int(os.environ.get("MAX_BUFFER_BYTES", str(MAX_UPLOAD_BYTES * 2 + 1024 * 1024)))
MAX_FEEDBACK_LEN = int(os.environ.get("MAX_FEEDBACK_LEN", "500"))
MAX_BIO_LEN = int(os.environ.get("MAX_BIO_LEN", "150"))
MAX_FILES_DIR_BYTES = int(os.environ.get("MAX_FILES_DIR_BYTES", str(256 * 1024 * 1024)))
MAX_FILE_RETENTION_SECONDS = int(os.environ.get("MAX_FILE_RETENTION_SECONDS", str(24 * 3600)))
GLOBAL_ACTIONS_PER_MIN = int(os.environ.get("GLOBAL_ACTIONS_PER_MIN", "180"))
AUTH_ATTEMPTS_PER_5MIN_IP = int(os.environ.get("AUTH_ATTEMPTS_PER_5MIN_IP", "20"))
AUTH_ATTEMPTS_PER_15MIN_ACCOUNT = int(os.environ.get("AUTH_ATTEMPTS_PER_15MIN_ACCOUNT", "10"))
ADMIN_ALLOWED_IPS_RAW = os.environ.get("ADMIN_ALLOWED_IPS", "")
# Clé optionnelle pour chiffrer les fichiers au repos (Fernet url-safe base64, 32 bytes)
# Générer avec : python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
FILE_ENCRYPTION_KEY = os.environ.get("FILE_ENCRYPTION_KEY", "").strip() or None
if not ADMIN_CODE or len(ADMIN_CODE) < 12:
print("❌ ERREUR : la variable d'environnement ADMIN_CODE doit être définie "
"(minimum 12 caractères, aléatoire). Aucune valeur par défaut n'est autorisée.")
print(' Exemple : export ADMIN_CODE=$(python3 -c "import secrets;print(secrets.token_urlsafe(24))")')
sys.exit(1)
RE_PSEUDO = re.compile(r"^[a-zA-Z][a-zA-Z0-9_]{2,19}$")
RE_EMAIL = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
FIREBASE_CREDS = os.environ.get("FIREBASE_CREDS", "") # JSON string
CERT_DIR = os.path.join(os.path.expanduser("~"), ".termchat_tls")
CERT_FILE = os.environ.get("TLS_CERT_FILE", os.path.join(CERT_DIR, "cert.pem"))
KEY_FILE = os.environ.get("TLS_KEY_FILE", os.path.join(CERT_DIR, "key.pem"))
def preparer_certificat_tls():
"""Prépare TLS.
En mode production, on exige un certificat existant fourni par l'opérateur.
L'auto-signé n'est autorisé qu'en mode développement local explicite.
"""
os.makedirs(CERT_DIR, exist_ok=True)
# Si un certificat fixe est fourni via variables d'environnement, l'utiliser en priorite
cert_b64 = os.environ.get("CERT_B64", "")
key_b64 = os.environ.get("KEY_B64", "")
if cert_b64 and key_b64:
try:
with open(CERT_FILE, "wb") as f:
f.write(base64.b64decode(cert_b64))
with open(KEY_FILE, "wb") as f:
f.write(base64.b64decode(key_b64))
os.chmod(KEY_FILE, 0o600)
print("Certificat fixe charge depuis CERT_B64/KEY_B64.")
return True
except Exception as e:
print(f"Erreur chargement certificat fixe: {e}")
if os.path.exists(CERT_FILE) and os.path.exists(KEY_FILE):
return True
if REQUIRE_EXISTING_TLS_CERT or PRODUCTION_MODE:
return False
try:
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
import datetime as dt
cle = rsa.generate_private_key(public_exponent=65537, key_size=2048)
nom = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
maintenant = dt.datetime.now(dt.timezone.utc)
cert = (x509.CertificateBuilder()
.subject_name(nom).issuer_name(nom).public_key(cle.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(maintenant)
.not_valid_after(maintenant + dt.timedelta(days=30))
.sign(cle, hashes.SHA256()))
with open(KEY_FILE, "wb") as f:
f.write(cle.private_bytes(serialization.Encoding.PEM,
serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()))
os.chmod(KEY_FILE, 0o600)
with open(CERT_FILE, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
os.chmod(CERT_FILE, 0o600)
print("✅ Certificat TLS de développement auto-signé généré.")
return True
except Exception as e:
print(f"⚠️ Impossible de générer le certificat TLS: {e}")
return False
PAYS = {
"1": ("Cote d'Ivoire", "+225"),
"2": ("Senegal", "+221"),
"3": ("Guinee", "+224"),
"4": ("Burkina Faso", "+226"),
"5": ("Ghana", "+233"),
"6": ("Mali", "+223"),
"7": ("Togo", "+228"),
"8": ("Benin", "+229"),
"9": ("Niger", "+227"),
"10": ("Nigeria", "+234"),
"11": ("Cameroun", "+237"),
}
# Correspondance code pays ISO (retourne par la geolocalisation IP) -> prefixe telephonique
ISO_VERS_PREFIXE = {
"CI": "+225", "SN": "+221", "GN": "+224", "BF": "+226", "GH": "+233",
"ML": "+223", "TG": "+228", "BJ": "+229", "NE": "+227", "NG": "+234", "CM": "+237",
}
def verifier_pays_ip(ip, prefixe_declare):
"""Retourne (ok, pays_detecte).
Désactivé par défaut car la version gratuite du service de géolocalisation
IP utilisée ici n'offre pas un transport de confiance.
"""
if not ALLOW_INSECURE_GEOIP_CHECK:
return True, None
try:
import urllib.request, json as _json
with urllib.request.urlopen(f"http://ip-api.com/json/{ip}?fields=countryCode,country", timeout=3) as resp:
data = _json.loads(resp.read().decode())
code_iso = data.get("countryCode", "")
if not code_iso:
return True, None
prefixe_detecte = ISO_VERS_PREFIXE.get(code_iso)
if prefixe_detecte is None:
return True, data.get("country")
return (prefixe_detecte == prefixe_declare), data.get("country")
except Exception:
return True, None
STATUTS = ["disponible", "occupe", "ne_pas_deranger", "absent"]
# ══════════════════════════════════════════════════════════
# FIREBASE FIRESTORE
# ══════════════════════════════════════════════════════════
db = None
def init_firebase():
global db
if not FIREBASE_OK:
print("⚠️ Firebase non disponible")
return False
try:
if FIREBASE_CREDS:
try:
creds_dict = json.loads(FIREBASE_CREDS)
cred = credentials.Certificate(creds_dict)
except Exception as e:
print(f"⚠️ FIREBASE_CREDS invalide: {e}")
return False
elif os.path.exists("firebase-credentials.json"):
cred = credentials.Certificate("firebase-credentials.json")
else:
print("⚠️ Pas de credentials Firebase")
return False
if not firebase_admin._apps:
firebase_admin.initialize_app(cred)
db = firestore.client()
print("✅ Firebase Firestore connecté !")
return True
except Exception as e:
print(f"⚠️ Firebase erreur: {e}")
return False
# ══════════════════════════════════════════════════════════
# UTILITAIRES
# ══════════════════════════════════════════════════════════
# UTILITAIRES
# ══════════════════════════════════════════════════════════
def hacher(s):
return bcrypt.hashpw(s.encode(), bcrypt.gensalt()).decode()
def gen_id(prefix):
return f"{prefix}{uuid.uuid4().hex}"
def nettoyer_nom_fichier(nom_fichier):
brut = (nom_fichier or "fichier").strip()
safe = "".join(c for c in brut if c.isalnum() or c in "._-") or "fichier"
return safe[:120]
def decoder_base64_strict(c64, taille_annoncee=0, max_bytes=MAX_UPLOAD_BYTES):
if not isinstance(c64, str) or not c64:
raise ValueError("Contenu manquant.")
try:
data = base64.b64decode(c64, validate=True)
except (binascii.Error, ValueError):
raise ValueError("Base64 invalide.")
taille_reelle = len(data)
if taille_reelle <= 0:
raise ValueError("Contenu vide.")
if taille_reelle > max_bytes:
raise ValueError(f"Fichier trop volumineux (max {max_bytes // (1024*1024)} MB).")
if taille_annoncee:
try:
annoncee = int(taille_annoncee)
except Exception:
raise ValueError("Taille invalide.")
if annoncee != taille_reelle:
raise ValueError("La taille annoncée ne correspond pas au contenu reçu.")
return data, taille_reelle
def _fernet_fichiers():
"""Retourne un Fernet si FILE_ENCRYPTION_KEY est définie, sinon None."""
if not FILE_ENCRYPTION_KEY:
return None
try:
from cryptography.fernet import Fernet
return Fernet(FILE_ENCRYPTION_KEY.encode() if isinstance(FILE_ENCRYPTION_KEY, str) else FILE_ENCRYPTION_KEY)
except Exception as e:
print(f"⚠️ FILE_ENCRYPTION_KEY invalide ({e}) — fichiers stockés en clair.")
return None
def ecrire_fichier_protege(chemin, data: bytes):
"""Écrit un fichier, chiffré au repos si une clé est configurée."""
fernet = _fernet_fichiers()
payload = fernet.encrypt(data) if fernet else data
with open(chemin, "wb") as f:
f.write(payload)
try:
os.chmod(chemin, 0o600)
except Exception:
pass
def lire_fichier_protege(chemin) -> bytes:
"""Lit un fichier, le déchiffre si nécessaire."""
with open(chemin, "rb") as f:
raw = f.read()
fernet = _fernet_fichiers()
if fernet:
try:
return fernet.decrypt(raw)
except Exception:
# Peut être un ancien fichier en clair
return raw
return raw
def taille_stockage_local():
total = 0
for p in Path(FILES_DIR).glob("*"):
try:
if p.is_file():
total += p.stat().st_size
except OSError:
continue
return total
def nettoyer_fichiers_temporaires():
maintenant = time.time()
for p in Path(FILES_DIR).glob("*"):
try:
if p.is_file() and maintenant - p.stat().st_mtime > MAX_FILE_RETENTION_SECONDS:
p.unlink(missing_ok=True)
except OSError:
continue
def verifier_budget_stockage():
nettoyer_fichiers_temporaires()
if taille_stockage_local() > MAX_FILES_DIR_BYTES:
raise ValueError("Stockage temporaire saturé. Réessaie plus tard.")
def verifier_mdp(mdp, hash_stocke):
"""Vérifie un mot de passe.
Le format SHA-256 historique est désactivé par défaut en production.
"""
if not hash_stocke:
return False
if hash_stocke.startswith(("$2b$", "$2a$")):
try:
return bcrypt.checkpw(mdp.encode(), hash_stocke.encode())
except Exception:
return False
if not ALLOW_LEGACY_SHA256_LOGIN:
return False
return hash_stocke == hashlib.sha256(mdp.encode()).hexdigest()
def mot_de_passe_est_fort(mdp):
if len(mdp) < MIN_PASSWORD_LEN:
return False
classes = [
any(c.islower() for c in mdp),
any(c.isupper() for c in mdp),
any(c.isdigit() for c in mdp),
any(not c.isalnum() for c in mdp),
]
return sum(classes) >= 3
def horodatage(): return datetime.datetime.now().isoformat()
def heure(): return datetime.datetime.now().strftime("%H:%M")
def est_premium_actif(user):
"""True si le compte a un premium actif et non expire (ou a vie)."""
if not user or not user.get("premium"): return False
exp = user.get("premium_expire")
if exp is None and user.get("premium_type") == "fondateur": return True
if not exp: return False
try: return datetime.datetime.fromisoformat(exp) > datetime.datetime.now()
except Exception: return False
def gen_numero(prefixe):
if db:
try:
users = db.collection("users").where(filter=FieldFilter("prefixe", "==", prefixe)).stream()
nums = {u.to_dict().get("numero","") for u in users}
except Exception:
nums = set()
else:
nums = set()
while True:
n = prefixe + str(secrets.randbelow(9000000000) + 1000000000)
if n not in nums:
return n
# ══════════════════════════════════════════════════════════
# OPÉRATIONS FIRESTORE
# ══════════════════════════════════════════════════════════
def fs_get_user_by_numero(numero):
if not db: return None, None
try:
docs = db.collection("users").where(filter=FieldFilter("numero", "==", numero)).limit(1).stream()
for doc in docs:
return doc.id, doc.to_dict()
return None, None
except Exception as e:
print(f"Firestore erreur: {e}"); return None, None
def fs_get_user_by_nom(nom):
if not db: return []
try:
docs = db.collection("users").where(filter=FieldFilter("nom_lower", "==", nom.lower())).stream()
return [(doc.id, doc.to_dict()) for doc in docs]
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_get_user_by_pseudo(pseudo):
if not db: return None, None
try:
docs = db.collection("users").where(filter=FieldFilter("pseudo_lower", "==", pseudo.lower().lstrip("@"))).limit(1).stream()
for doc in docs:
return doc.id, doc.to_dict()
return None, None
except Exception as e:
print(f"Firestore erreur: {e}"); return None, None
def fs_get_user_by_email(email):
if not db: return None, None
try:
docs = db.collection("users").where(filter=FieldFilter("email_lower", "==", email.lower())).limit(1).stream()
for doc in docs:
return doc.id, doc.to_dict()
return None, None
except Exception as e:
print(f"Firestore erreur: {e}"); return None, None
def fs_save_user(uid, data):
if not db: return
try: db.collection("users").document(uid).set(data)
except Exception as e: print(f"Firestore erreur: {e}")
def fs_update_user(uid, fields):
if not db: return
try: db.collection("users").document(uid).update(fields)
except Exception as e: print(f"Firestore erreur: {e}")
def fs_delete_user(uid):
if not db: return
try: db.collection("users").document(uid).delete()
except Exception as e: print(f"Firestore erreur: {e}")
RESEND_API_KEY = os.environ.get("RESEND_API_KEY", "")
RESEND_FROM = os.environ.get("RESEND_FROM", "onboarding@resend.dev")
def envoyer_email_resend(destinataire, sujet, corps_html):
"""Envoie un email via l'API Resend (urllib, pas de dependance supplementaire)."""
if not RESEND_API_KEY:
print("RESEND_API_KEY non configuree, email non envoye.")
return False
try:
import urllib.request
payload = json.dumps({
"from": RESEND_FROM,
"to": [destinataire],
"subject": sujet,
"html": corps_html
}).encode()
req = urllib.request.Request(
"https://api.resend.com/emails",
data=payload,
headers={
"Authorization": f"Bearer {RESEND_API_KEY}",
"Content-Type": "application/json"
},
method="POST"
)
with urllib.request.urlopen(req, timeout=8) as resp:
return resp.status in (200, 201)
except Exception as e:
print(f"Erreur envoi email Resend: {e}")
return False
otp_2fa_pendants = {} # numero -> {"code_hash":..., "expire":timestamp, "uid":...}
def fs_log_audit(admin_numero, action, cible="", details=""):
"""Enregistre une action admin dans le journal d'audit (jamais modifiable/supprimable via l'app)."""
if not db: return
try:
aid = f"audit_{int(time.time())}_{random.randint(1000,9999)}"
db.collection("audit_log").document(aid).set({
"admin": admin_numero, "action": action, "cible": cible,
"details": details, "heure": horodatage()
})
except Exception as e:
print(f"Firestore erreur (audit): {e}")
def fs_save_feedback(numero, nom, texte, prioritaire=False):
if not db: return
try:
fid = gen_id("fb_")
db.collection("feedback").document(fid).set({
"numero": numero, "nom": nom, "texte": texte,
"heure": horodatage(), "lu": False, "prioritaire": prioritaire
})
except Exception as e: print(f"Firestore erreur: {e}")
def fs_save_paiement_attente(numero, nom, code_transaction, montant):
if not db: return None
try:
pid = gen_id("pay_")
db.collection("paiements_attente").document(pid).set({
"numero": numero, "nom": nom, "code_transaction": code_transaction,
"montant": montant, "heure": horodatage(), "statut": "attente"
})
return pid
except Exception as e:
print(f"Firestore erreur: {e}"); return None
def fs_get_paiements_attente():
if not db: return []
try:
docs = db.collection("paiements_attente")\
.where(filter=FieldFilter("statut", "==", "attente"))\
.order_by("heure").stream()
return [{**d.to_dict(), "id": d.id} for d in docs]
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_update_paiement(pid, statut):
if not db: return
try:
db.collection("paiements_attente").document(pid).update({"statut": statut})
except Exception as e:
print(f"Firestore erreur: {e}")
def fs_get_feedback(limite=30):
if not db: return []
try:
docs = db.collection("feedback")\
.order_by("heure", direction=firestore.Query.DESCENDING)\
.limit(limite).stream()
return [doc.to_dict() for doc in docs]
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_save_message(cle_conv, msg):
if not db: return
try:
db.collection("historique").document(cle_conv)\
.collection("messages").document(msg["id"]).set(msg)
db.collection("historique").document(cle_conv)\
.set({"derniere_activite": horodatage(), "participants": cle_conv.split("_")}, merge=True)
except Exception as e: print(f"Firestore erreur: {e}")
def fs_get_messages(n1, n2, limite=50):
if not db: return []
try:
if not n1 or not n2: return []
cle = "_".join(sorted([n1, n2]))
docs = db.collection("historique").document(cle)\
.collection("messages")\
.order_by("heure", direction=firestore.Query.DESCENDING)\
.limit(limite).stream()
msgs = [doc.to_dict() for doc in docs]
msgs.reverse()
now = time.time()
return [m for m in msgs if not m.get("expire_a") or m["expire_a"] > now]
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_marquer_lus(dest, exp):
if not db: return
try:
cle = "_".join(sorted([dest, exp]))
docs = db.collection("historique").document(cle)\
.collection("messages")\
.where(filter=FieldFilter("vers", "==", dest))\
.where(filter=FieldFilter("lu", "==", False)).stream()
batch = db.batch()
for doc in docs:
batch.update(doc.reference, {"lu": True})
batch.commit()
except Exception as e: print(f"Firestore erreur: {e}")
def fs_mes_contacts(numero):
"""Retourne la liste des numeros avec qui l'utilisateur a deja une conversation."""
if not db: return []
try:
contacts = set()
convs = db.collection("historique")\
.where(filter=FieldFilter("participants", "array_contains", numero)).stream()
for conv in convs:
data = conv.to_dict() or {}
for part in data.get("participants", []):
if part != numero: contacts.add(part)
return list(contacts)
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_compter_non_lus(numero):
if not db: return 0
try:
count = 0
convs = db.collection("historique")\
.where(filter=FieldFilter("participants", "array_contains", numero)).stream()
for conv in convs:
msgs = db.collection("historique").document(conv.id)\
.collection("messages")\
.where(filter=FieldFilter("vers", "==", numero))\
.where(filter=FieldFilter("lu", "==", False)).stream()
count += sum(1 for _ in msgs)
return count
except Exception as e:
print(f"Firestore erreur: {e}"); return 0
def fs_compter_contacts_distincts(numero):
"""Compte le nombre de conversations distinctes (contacts) d'un utilisateur."""
if not db: return 0
try:
docs = db.collection("historique")\
.where(filter=FieldFilter("participants", "array_contains", numero))\
.stream()
return sum(1 for _ in docs)
except Exception:
return 0
def fs_get_conversations(numero):
if not db: return []
try:
convs_ref = db.collection("historique")\
.where(filter=FieldFilter("participants", "array_contains", numero))\
.order_by("derniere_activite", direction=firestore.Query.DESCENDING)\
.limit(20).stream()
result = []
for conv in convs_ref:
cid = conv.id
parts = cid.split("_")
autre = next((p for p in parts if p != numero), None)
if not autre: continue
_, autre_user = fs_get_user_by_numero(autre)
if not autre_user: continue
msgs = db.collection("historique").document(cid)\
.collection("messages")\
.order_by("heure", direction=firestore.Query.DESCENDING)\
.limit(1).stream()
dernier_msg = ""
for m in msgs: dernier_msg = m.to_dict().get("texte","")[:40]
non_lus = 0
msgs_nl = db.collection("historique").document(cid)\
.collection("messages")\
.where(filter=FieldFilter("vers", "==", numero))\
.where(filter=FieldFilter("lu", "==", False)).stream()
for _ in msgs_nl: non_lus += 1
conv_data = conv.to_dict() or {}
result.append({
"numero": autre, "nom": autre_user.get("nom","?"),
"dernier_msg": dernier_msg, "non_lus": non_lus,
"heure": conv_data.get("derniere_activite","")[:16].replace("T"," ")
})
return result
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_save_groupe(gid, data):
if not db or not gid: return
try: db.collection("groupes").document(gid).set(data, merge=True)
except Exception as e: print(f"Firestore erreur: {e}")
def fs_get_groupe(gid):
if not db or not gid: return None
try:
doc = db.collection("groupes").document(gid).get()
return doc.to_dict() if doc.exists else None
except Exception as e:
print(f"Firestore erreur: {e}"); return None
def fs_mes_groupes(numero):
if not db: return []
try:
docs = db.collection("groupes")\
.where(filter=FieldFilter("membres", "array_contains", numero)).stream()
return [(doc.id, doc.to_dict()) for doc in docs]
except Exception as e:
print(f"Firestore erreur: {e}"); return []
def fs_save_msg_groupe(gid, msg):
if not db or not gid: return
try:
db.collection("groupes").document(gid)\
.collection("messages").add(msg)
db.collection("groupes").document(gid)\
.update({"derniere_activite": horodatage()})
except Exception as e: print(f"Firestore erreur: {e}")
def fs_get_stats():
if not db: return {}
try:
nb_users = sum(1 for _ in db.collection("users").stream())
nb_convs = sum(1 for _ in db.collection("historique").stream())
nb_groupes= sum(1 for _ in db.collection("groupes").stream())
return {"utilisateurs": nb_users, "conversations": nb_convs, "groupes": nb_groupes}
except Exception as e:
print(f"Firestore erreur: {e}"); return {}
# ══════════════════════════════════════════════════════════
# FICHIERS LOCAUX (temporaires)
# ══════════════════════════════════════════════════════════
FILES_DIR = os.path.join(os.path.expanduser("~"), ".termchat_files")
os.makedirs(FILES_DIR, exist_ok=True)
try:
os.chmod(FILES_DIR, 0o700)
except Exception:
pass
# ══════════════════════════════════════════════════════════
# CLIENTS CONNECTÉS
# ══════════════════════════════════════════════════════════
clients = {} # numero -> socket
admins_connectes = set()
lock = threading.Lock()
TIMEOUT = 1800
MAX_CONNEXIONS_SIMULTANEES = 500 # au-dela, nouvelles connexions refusees (protection DoS)
MAX_TAILLE_BUFFER = MAX_BUFFER_BYTES
# ── Anti-bruteforce ──────────────────────────────────────────
tentatives_echec = {} # cle (ex: "login_ip") -> [nb_echecs, timestamp_dernier_echec]
MAX_TENTATIVES = 5
BLOCAGE_SECONDES = 300 # 5 minutes
def bloque(cle):
"""True si cette cle a depasse le nombre d'echecs autorises recemment."""
with lock:
nb, t = tentatives_echec.get(cle, [0, 0])
if nb >= MAX_TENTATIVES and time.time() - t < BLOCAGE_SECONDES:
return True
if nb >= MAX_TENTATIVES:
tentatives_echec[cle] = [0, 0] # blocage expire, on reinitialise
return False
def signaler_echec(cle):
with lock:
nb, _ = tentatives_echec.get(cle, [0, 0])
tentatives_echec[cle] = [nb + 1, time.time()]
def signaler_succes(cle):
with lock:
tentatives_echec.pop(cle, None)
def temps_restant(cle):
with lock:
nb, t = tentatives_echec.get(cle, [0, 0])
return max(0, int(BLOCAGE_SECONDES - (time.time() - t)))
# ── Cooldown feedback (anti-spam simple, independant de l'anti-bruteforce) ──
dernier_feedback = {} # numero -> timestamp du dernier envoi
FEEDBACK_COOLDOWN = 60 # secondes entre deux feedbacks du meme compte
dernier_paiement = {} # numero -> timestamp de la derniere soumission
PAIEMENT_COOLDOWN = 120 # secondes entre deux soumissions de paiement
rate_limits = {}
try:
ADMIN_ALLOWED_IPS = [ipaddress.ip_network(x.strip(), strict=False) for x in ADMIN_ALLOWED_IPS_RAW.split(",") if x.strip()]
except Exception:
ADMIN_ALLOWED_IPS = []
def limite_depassee(cle, limite, fenetre_sec):
maintenant = time.time()
with lock:
serie = [t for t in rate_limits.get(cle, []) if maintenant - t < fenetre_sec]
if len(serie) >= limite:
rate_limits[cle] = serie
return True
serie.append(maintenant)
rate_limits[cle] = serie
return False
def ip_autorisee_pour_admin(ip):
if not ADMIN_ALLOWED_IPS:
return True
try:
ip_obj = ipaddress.ip_address(ip)
return any(ip_obj in net for net in ADMIN_ALLOWED_IPS)
except ValueError:
return False
envoi_lock = threading.Lock()
def envoyer_srv(sock, paquet):
try:
data = (json.dumps(paquet, ensure_ascii=False) + "\n").encode()
with envoi_lock:
sock.sendall(data)
except Exception:
return False
return True
def livrer(numero, paquet):
with lock:
s = clients.get(numero)
if s:
envoyer_srv(s, paquet)
return True
return False
def notifier_statut(numero, en_ligne):
uid, user = fs_get_user_by_numero(numero)
if not user: return
contacts = set(fs_mes_contacts(numero))
if not contacts: return
with lock: cibles = list(clients.items())
for num, sock in cibles:
if num != numero and num in contacts:
envoyer_srv(sock, {"type": "statut", "numero": numero,
"nom": user.get("nom","?"), "en_ligne": en_ligne})
def _connecter_user(conn, user, uid):
"""Finalise la connexion d'un utilisateur."""
num_co = user["numero"]
est_admin = user.get("est_admin", False)
non_lus = fs_compter_non_lus(num_co)
fs_update_user(uid, {"derniere_connexion": horodatage()})
with lock:
clients[num_co] = conn
if est_admin: admins_connectes.add(num_co)
envoyer_srv(conn, {
"ok": True, "nom": user.get("nom","?"), "numero": num_co,
"pays": user.get("pays",""), "bio": user.get("bio",""),
"couleur": user.get("couleur","cyan"),
"statut": user.get("statut","disponible"),
"est_admin": est_admin, "non_lus": non_lus,
"a_pin": bool(user.get("pin")),
"pseudo": user.get("pseudo",""),
"premium": est_premium_actif(user),
"premium_type": user.get("premium_type")
})
notifier_statut(num_co, True)
return num_co, est_admin
# ══════════════════════════════════════════════════════════
# GESTION D'UN CLIENT TCP
# ══════════════════════════════════════════════════════════
def gerer_client(conn, addr):
num_co = None
buf = ""
est_admin = False
try:
while True:
conn.settimeout(TIMEOUT)
try: chunk = conn.recv(8192).decode("utf-8", errors="replace")
except socket.timeout:
if num_co: envoyer_srv(conn, {"type":"timeout","msg":"Deconnecte pour inactivite."})
break
if not chunk: break
buf += chunk
if len(buf) > MAX_TAILLE_BUFFER:
try: envoyer_srv(conn, {"ok":False,"msg":"Message trop volumineux."})
except Exception: pass
break
while "\n" in buf:
ligne, buf = buf.split("\n", 1)
ligne = ligne.strip()
if not ligne: continue
try: p = json.loads(ligne)
except Exception: continue
act = p.get("action", "")
ip_client = addr[0]
if not isinstance(p, dict) or not act:
envoyer_srv(conn, {"ok":False,"msg":"Requête invalide."})
continue
if limite_depassee(f"act_ip:{ip_client}", GLOBAL_ACTIONS_PER_MIN, 60):
envoyer_srv(conn, {"ok":False,"msg":"Trop de requêtes. Réessaie plus tard."})
continue
# ─── INSCRIPTION ──────────────────────────
if act == "inscrire":
cle_bf_insc = f"inscrire_{addr[0]}"
if bloque(cle_bf_insc):
envoyer_srv(conn, {"ok":False,"msg":f"Trop de tentatives d'inscription. Reessaie dans {temps_restant(cle_bf_insc)}s."})
continue
nom = p.get("nom","").strip()
mdp = p.get("mdp","").strip()
prefixe = p.get("prefixe","+225").strip()
couleur = p.get("couleur","cyan")
pseudo = p.get("pseudo","").strip().lstrip("@")
email = p.get("email","").strip().lower()
geo_ok, pays_reel = verifier_pays_ip(addr[0], prefixe)
prefixes_valides = [v[1] for v in PAYS.values()]
if not nom or len(nom) < 2 or len(nom) > 20:
signaler_echec(cle_bf_insc)
envoyer_srv(conn, {"ok":False,"msg":"Nom: 2 à 20 caractères."})
elif not mot_de_passe_est_fort(mdp):
signaler_echec(cle_bf_insc)
envoyer_srv(conn, {"ok":False,"msg":f"Mot de passe insuffisamment robuste (min {MIN_PASSWORD_LEN} caractères, 3 classes parmi minuscule/majuscule/chiffre/symbole)."})
elif prefixe not in prefixes_valides:
signaler_echec(cle_bf_insc)
envoyer_srv(conn, {"ok":False,"msg":"Pays/prefixe invalide."})
elif not RE_PSEUDO.match(pseudo):
envoyer_srv(conn, {"ok":False,"msg":"Pseudo invalide: 3-20 caractères, doit commencer par une lettre, lettres/chiffres/underscore uniquement."})
elif email and not RE_EMAIL.match(email):
envoyer_srv(conn, {"ok":False,"msg":"Format d'email invalide."})
elif fs_get_user_by_pseudo(pseudo)[1] is not None:
envoyer_srv(conn, {"ok":False,"msg":f"Le pseudo @{pseudo} est déjà pris."})
elif email and fs_get_user_by_email(email)[1] is not None:
envoyer_srv(conn, {"ok":False,"msg":"Cet email est déjà associé à un compte."})
else:
numero = gen_numero(prefixe)
pays = next((v[0] for v in PAYS.values() if v[1] == prefixe), "Inconnu")
uid = gen_id("u_")
user_data = {
"nom": nom, "nom_lower": nom.lower(), "numero": numero,
"pseudo": pseudo, "pseudo_lower": pseudo.lower(),
"email": email, "email_lower": email if email else None,
"mdp": hacher(mdp), "pays": pays, "prefixe": prefixe,
"bio": "", "couleur": couleur, "statut": "disponible",
"inscription": horodatage(), "derniere_connexion": None,
"favoris": [], "bloque": [], "est_admin": False, "pin": None,
"cle_publique": (p.get("cle_publique") or "")[:8192] or None,
"premium": False, "premium_expire": None,
"premium_type": None, "active_par": None,
"pays_incoherent": (not geo_ok),
"pays_detecte_ip": pays_reel
}
if not geo_ok:
print(f"⚠️ Inscription avec pays incoherent: {nom} declare {pays} mais IP detectee comme {pays_reel or '?'}")
fs_save_user(uid, user_data)
signaler_succes(cle_bf_insc)
envoyer_srv(conn, {"ok":True,"numero":numero,"nom":nom,"pays":pays,"pseudo":pseudo})
# ─── CONNEXION (numéro) ───────────────────
elif act == "connecter_numero":
ip = addr[0]
cle_bf_ip = f"login_ip:{ip}"
numero = p.get("numero","").strip()
mdp = p.get("mdp","").strip()
cle_bf_acct = f"login_numero:{numero}"
if limite_depassee(cle_bf_ip, AUTH_ATTEMPTS_PER_5MIN_IP, 300) or (numero and limite_depassee(cle_bf_acct, AUTH_ATTEMPTS_PER_15MIN_ACCOUNT, 900)):
envoyer_srv(conn, {"ok":False,"msg":"Trop de tentatives. Réessaie plus tard."})
continue
uid, user = fs_get_user_by_numero(numero)
if not user or not verifier_mdp(mdp, user.get("mdp")):
signaler_echec(cle_bf_ip)
if numero:
signaler_echec(cle_bf_acct)
envoyer_srv(conn, {"ok":False,"msg":"Identifiants invalides."})
else:
signaler_succes(cle_bf_ip)
signaler_succes(cle_bf_acct)
if ALLOW_LEGACY_SHA256_LOGIN and not user.get("mdp","").startswith(("$2b$","$2a$")):
fs_update_user(uid, {"mdp": hacher(mdp)})
if user.get("email"):
code_otp = f"{random.randint(0,999999):06d}"
with lock:
otp_2fa_pendants[user.get("numero")] = {
"code_hash": hashlib.sha256(code_otp.encode()).hexdigest(),
"expire": time.time() + 300,
"uid": uid
}
envoyer_email_resend(user.get("email"),
"Ton code de connexion TermChat",
f"<p>Ton code de verification est : <b>{code_otp}</b></p><p>Valide 5 minutes.</p>")
envoyer_srv(conn, {"ok":True,"besoin_2fa":True,"numero":user.get("numero")})
else:
num_co, est_admin = _connecter_user(conn, user, uid)
# ─── CONNEXION (email) ─────────────────────
# ─── CONNEXION (email) ─────────────────────
elif act == "connecter_email":
ip = addr[0]
cle_bf_ip = f"login_ip:{ip}"
email = p.get("email","").strip().lower()
mdp = p.get("mdp","").strip()
cle_bf_acct = f"login_email:{email}"
if limite_depassee(cle_bf_ip, AUTH_ATTEMPTS_PER_5MIN_IP, 300) or (email and limite_depassee(cle_bf_acct, AUTH_ATTEMPTS_PER_15MIN_ACCOUNT, 900)):
envoyer_srv(conn, {"ok":False,"msg":"Trop de tentatives. Réessaie plus tard."})
continue
uid, user = fs_get_user_by_email(email)
if not user or not verifier_mdp(mdp, user.get("mdp")):
signaler_echec(cle_bf_ip)
if email:
signaler_echec(cle_bf_acct)
envoyer_srv(conn, {"ok":False,"msg":"Identifiants invalides."})
else:
signaler_succes(cle_bf_ip)
signaler_succes(cle_bf_acct)
if ALLOW_LEGACY_SHA256_LOGIN and not user.get("mdp","").startswith(("$2b$","$2a$")):
fs_update_user(uid, {"mdp": hacher(mdp)})
if user.get("email"):
code_otp = f"{random.randint(0,999999):06d}"
with lock:
otp_2fa_pendants[user.get("numero")] = {
"code_hash": hashlib.sha256(code_otp.encode()).hexdigest(),
"expire": time.time() + 300,
"uid": uid
}
envoyer_email_resend(user.get("email"),
"Ton code de connexion TermChat",
f"<p>Ton code de verification est : <b>{code_otp}</b></p><p>Valide 5 minutes.</p>")
envoyer_srv(conn, {"ok":True,"besoin_2fa":True,"numero":user.get("numero")})
else:
num_co, est_admin = _connecter_user(conn, user, uid)
elif act == "verifier_2fa":
numero_2fa = p.get("numero","").strip()
code_saisi = p.get("code","").strip()
cle_bf_2fa = f"2fa_{numero_2fa}"
if bloque(cle_bf_2fa):
envoyer_srv(conn, {"ok":False,"msg":f"Trop de tentatives. Reessaie dans {temps_restant(cle_bf_2fa)}s."})
continue
with lock:
pending = otp_2fa_pendants.get(numero_2fa)
if not pending or time.time() > pending["expire"]:
signaler_echec(cle_bf_2fa)
envoyer_srv(conn, {"ok":False,"msg":"Code expire ou introuvable. Reconnecte-toi."})
continue
if hashlib.sha256(code_saisi.encode()).hexdigest() != pending["code_hash"]:
signaler_echec(cle_bf_2fa)
envoyer_srv(conn, {"ok":False,"msg":"Code incorrect."})
continue
signaler_succes(cle_bf_2fa)
with lock:
otp_2fa_pendants.pop(numero_2fa, None)
uid_2fa = pending["uid"]
_, user_2fa = fs_get_user_by_numero(numero_2fa)
if not user_2fa:
envoyer_srv(conn, {"ok":False,"msg":"Compte introuvable."})
continue
num_co, est_admin = _connecter_user(conn, user_2fa, uid_2fa)
# ─── DEFINIR PSEUDO (migration anciens comptes) ──
elif act == "definir_pseudo":
if not num_co:
envoyer_srv(conn, {"ok":False,"msg":"Non connecte."})
else: