-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmain.py
More file actions
3401 lines (3247 loc) · 206 KB
/
Copy pathmain.py
File metadata and controls
3401 lines (3247 loc) · 206 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 asyncio
import json
import os
import hashlib
import secrets
import time
import re
import base64
import ipaddress
import uuid as uuid_lib
from datetime import datetime, timezone, timedelta
from urllib.parse import quote
from collections import deque, defaultdict
from typing import Optional, Dict, Any
from fastapi import FastAPI, Request, HTTPException, WebSocket, WebSocketDisconnect, Depends
from fastapi.responses import Response, HTMLResponse, JSONResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import uvicorn
import httpx
import psutil
import bcrypt
from jose import jwt, JWTError
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
import aiosqlite
import logging
import logging.config
try:
import uvloop
uvloop.install()
except ImportError:
pass
try:
import asyncpg
HAS_POSTGRES = True
except ImportError:
HAS_POSTGRES = False
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"json": {
"()": "pythonjsonlogger.jsonlogger.JsonFormatter",
"format": "%(asctime)s %(levelname)s %(name)s %(message)s",
}
},
"handlers": {"json_console": {"class": "logging.StreamHandler", "formatter": "json"}},
"root": {"level": "INFO", "handlers": ["json_console"]},
}
logging.config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("SulgX")
print("--- APPLICATION IS STARTING ---")
limiter = Limiter(key_func=get_remote_address, default_limits=["100/minute"])
CONFIG = {
"port": int(os.environ.get("PORT", 8000)),
"secret_key": os.environ.get("SECRET_KEY", secrets.token_urlsafe(32)),
"jwt_algorithm": "HS256",
"jwt_expire_minutes": 10080,
"db_path": os.environ.get("DB_PATH", "/data/panel.db"),
"admin_password": os.environ.get("ADMIN_PASSWORD", "admin"),
"database_url": os.environ.get("DATABASE_URL", ""),
}
if HAS_POSTGRES:
ADDRESS_INTEGRITY_ERRORS = (aiosqlite.IntegrityError, asyncpg.exceptions.UniqueViolationError)
else:
ADDRESS_INTEGRITY_ERRORS = (aiosqlite.IntegrityError,)
db_conn: Optional[aiosqlite.Connection] = None
db_lock = asyncio.Lock()
ENABLE_LOGGING = True
KEEP_ALIVE_INTERVAL = 300
TIMEZONE_OFFSET = 0.0
KEEP_ALIVE_ENABLED = True
KEEP_ALIVE_MODE = "simple"
traffic_buffer_lock = asyncio.Lock()
traffic_buffer = {
"hourly": defaultdict(int),
"daily": defaultdict(int),
}
LINKS: dict = {}
LINKS_LOCK = asyncio.Lock()
CUSTOM_ADDRESSES: list = ["www.speedtest.net"]
CUSTOM_ADDRESSES_LOCK = asyncio.Lock()
_scan_lock = asyncio.Lock()
if CONFIG["database_url"] and HAS_POSTGRES:
DB_BACKEND = "postgresql"
pg_pool: Optional[asyncpg.Pool] = None
async def init_pg():
global pg_pool
pg_pool = await asyncpg.create_pool(CONFIG["database_url"], min_size=2, max_size=10)
async with pg_pool.acquire() as conn:
await conn.execute("""
CREATE TABLE IF NOT EXISTS links (
uid TEXT PRIMARY KEY, label TEXT NOT NULL,
limit_bytes BIGINT DEFAULT 0, used_bytes BIGINT DEFAULT 0,
max_connections INT DEFAULT 0, created_at TEXT NOT NULL,
active BOOLEAN DEFAULT TRUE, expires_at TEXT,
custom_path TEXT DEFAULT '', custom_sni TEXT DEFAULT '',
custom_host TEXT DEFAULT '', custom_fp TEXT DEFAULT 'chrome',
color TEXT DEFAULT '#39ff14',
flag TEXT DEFAULT '',
fragment TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS hourly_traffic (hour TEXT PRIMARY KEY, bytes BIGINT DEFAULT 0);
CREATE TABLE IF NOT EXISTS daily_traffic (day TEXT PRIMARY KEY, bytes BIGINT DEFAULT 0);
CREATE TABLE IF NOT EXISTS custom_addresses (id SERIAL PRIMARY KEY, address TEXT NOT NULL UNIQUE);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS login_logs (
id SERIAL PRIMARY KEY,
timestamp TEXT NOT NULL,
ip TEXT,
success BOOLEAN DEFAULT TRUE,
user_agent TEXT DEFAULT '',
path TEXT DEFAULT ''
);
""")
try:
await conn.execute("ALTER TABLE links ADD COLUMN IF NOT EXISTS flag TEXT DEFAULT ''")
except Exception:
pass
try:
await conn.execute("ALTER TABLE links ADD COLUMN IF NOT EXISTS fragment TEXT DEFAULT ''")
except Exception:
pass
async def db_execute(sqlite_q: str, pg_q: str, params: tuple = ()):
async with pg_pool.acquire() as conn:
await conn.execute(pg_q, *params)
async def db_fetchall(sqlite_q: str, pg_q: str, params: tuple = ()) -> list:
async with pg_pool.acquire() as conn:
rows = await conn.fetch(pg_q, *params)
return [dict(r) for r in rows]
async def db_fetchone(sqlite_q: str, pg_q: str, params: tuple = ()) -> Optional[dict]:
async with pg_pool.acquire() as conn:
row = await conn.fetchrow(pg_q, *params)
return dict(row) if row else None
async def get_db():
return None
else:
DB_BACKEND = "sqlite"
async def init_db():
global db_conn
db_path = CONFIG["db_path"]
try:
test_file = os.path.join(os.path.dirname(db_path), ".write_test")
with open(test_file, "w") as f:
f.write("ok")
os.remove(test_file)
except Exception:
logger.warning(f"Cannot write to {db_path}, falling back to /tmp/panel.db")
CONFIG["db_path"] = "/tmp/panel.db"
db_path = "/tmp/panel.db"
db_conn = await aiosqlite.connect(db_path)
db_conn.row_factory = aiosqlite.Row
await db_conn.execute("PRAGMA journal_mode=WAL")
await db_conn.executescript("""
CREATE TABLE IF NOT EXISTS links (
uid TEXT PRIMARY KEY, label TEXT NOT NULL,
limit_bytes INTEGER DEFAULT 0, used_bytes INTEGER DEFAULT 0,
max_connections INTEGER DEFAULT 0, created_at TEXT NOT NULL,
active INTEGER DEFAULT 1, expires_at TEXT,
custom_path TEXT DEFAULT '', custom_sni TEXT DEFAULT '',
custom_host TEXT DEFAULT '', custom_fp TEXT DEFAULT 'chrome',
color TEXT DEFAULT '#39ff14',
flag TEXT DEFAULT '',
fragment TEXT DEFAULT ''
);
CREATE TABLE IF NOT EXISTS hourly_traffic (hour TEXT PRIMARY KEY, bytes INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS daily_traffic (day TEXT PRIMARY KEY, bytes INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS custom_addresses (id INTEGER PRIMARY KEY AUTOINCREMENT, address TEXT NOT NULL UNIQUE);
CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS login_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
ip TEXT,
success INTEGER DEFAULT 1,
user_agent TEXT DEFAULT '',
path TEXT DEFAULT ''
);
""")
try:
await db_conn.execute("ALTER TABLE links ADD COLUMN flag TEXT DEFAULT ''")
except Exception:
pass
try:
await db_conn.execute("ALTER TABLE links ADD COLUMN fragment TEXT DEFAULT ''")
except Exception:
pass
await db_conn.commit()
async def db_execute(sqlite_q: str, pg_q: str = "", params: tuple = ()):
async with db_lock:
await db_conn.execute(sqlite_q, params)
await db_conn.commit()
async def db_fetchall(sqlite_q: str, pg_q: str = "", params: tuple = ()) -> list:
async with db_lock:
cur = await db_conn.execute(sqlite_q, params)
rows = await cur.fetchall()
return [dict(r) for r in rows]
async def db_fetchone(sqlite_q: str, pg_q: str = "", params: tuple = ()) -> Optional[dict]:
async with db_lock:
cur = await db_conn.execute(sqlite_q, params)
row = await cur.fetchone()
return dict(row) if row else None
async def get_db():
return db_conn
async def flush_traffic_buffer():
while True:
await asyncio.sleep(10)
try:
async with traffic_buffer_lock:
if not traffic_buffer["hourly"] and not traffic_buffer["daily"]:
continue
for hour, bytes_val in traffic_buffer["hourly"].items():
await db_execute(
"INSERT INTO hourly_traffic (hour, bytes) VALUES (?,?) ON CONFLICT(hour) DO UPDATE SET bytes = bytes + ?",
"INSERT INTO hourly_traffic (hour, bytes) VALUES ($1,$2) ON CONFLICT (hour) DO UPDATE SET bytes = hourly_traffic.bytes + $2",
(hour, bytes_val, bytes_val)
)
for day, bytes_val in traffic_buffer["daily"].items():
await db_execute(
"INSERT INTO daily_traffic (day, bytes) VALUES (?,?) ON CONFLICT(day) DO UPDATE SET bytes = bytes + ?",
"INSERT INTO daily_traffic (day, bytes) VALUES ($1,$2) ON CONFLICT (day) DO UPDATE SET bytes = daily_traffic.bytes + $2",
(day, bytes_val, bytes_val)
)
traffic_buffer["hourly"].clear()
traffic_buffer["daily"].clear()
except Exception as e:
logger.error(f"flush_traffic_buffer error: {e}", exc_info=True)
async def add_traffic_to_buffer(hour: str, day: str, size: int):
async with traffic_buffer_lock:
traffic_buffer["hourly"][hour] += size
traffic_buffer["daily"][day] += size
async def sync_usage_to_db():
while True:
await asyncio.sleep(30)
try:
async with LINKS_LOCK:
for uid, link in LINKS.items():
await db_execute(
"UPDATE links SET used_bytes = ? WHERE uid = ?",
"UPDATE links SET used_bytes = $1 WHERE uid = $2",
(link["used_bytes"], uid)
)
except Exception as e:
logger.error(f"sync_usage_to_db error: {e}", exc_info=True)
async def load_initial_data():
rows = await db_fetchall("SELECT * FROM links", "SELECT * FROM links")
async with LINKS_LOCK:
for r in rows:
LINKS[r["uid"]] = dict(r)
addr_rows = await db_fetchall("SELECT address FROM custom_addresses", "SELECT address FROM custom_addresses")
async with CUSTOM_ADDRESSES_LOCK:
CUSTOM_ADDRESSES[:] = [r["address"] for r in addr_rows]
if not CUSTOM_ADDRESSES:
CUSTOM_ADDRESSES.append("www.speedtest.net")
if not LINKS:
default_uuid = str(uuid_lib.uuid4())
now = datetime.now(timezone.utc).isoformat()
default_link = {
"uid": default_uuid, "label": "This Server is Free", "limit_bytes": 0, "used_bytes": 0,
"max_connections": 0, "created_at": now, "active": 1, "expires_at": None,
"custom_path": "", "custom_sni": "", "custom_host": "", "custom_fp": "chrome",
"color": "#39ff14", "flag": "", "fragment": ""
}
async with LINKS_LOCK:
LINKS[default_uuid] = default_link
await db_execute(
"INSERT INTO links (uid, label, limit_bytes, max_connections, created_at, active, expires_at, flag, fragment) VALUES (?,?,?,?,?,1,?,'','')",
"INSERT INTO links (uid, label, limit_bytes, max_connections, created_at, active, expires_at, flag, fragment) VALUES ($1,$2,$3,$4,$5,TRUE,$6,'','')",
(default_uuid, "This Server is Free", 0, 0, now, None),
)
total_usage = sum(link.get("used_bytes", 0) for link in LINKS.values())
stats["total_bytes"] = total_usage
async def _keepalive_simple_loop():
global KEEP_ALIVE_INTERVAL, KEEP_ALIVE_ENABLED, KEEP_ALIVE_MODE
while True:
await asyncio.sleep(KEEP_ALIVE_INTERVAL)
if not KEEP_ALIVE_ENABLED or KEEP_ALIVE_MODE != "simple":
continue
domain = get_domain()
if domain == "localhost":
continue
try:
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.get(f"https://{domain}/health")
if resp.status_code == 200:
logger.info(f"Simple keep-alive successful: {domain}/health")
except Exception:
pass
async def _keepalive_advanced_loop():
global KEEP_ALIVE_INTERVAL, KEEP_ALIVE_ENABLED, KEEP_ALIVE_MODE
await asyncio.sleep(30)
while True:
if not KEEP_ALIVE_ENABLED or KEEP_ALIVE_MODE != "advanced":
await asyncio.sleep(KEEP_ALIVE_INTERVAL)
continue
domain = os.environ.get("DOMAIN", "").strip()
port = os.environ.get("PORT", "8000")
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,fa;q=0.8",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
}
target_urls = []
if domain:
if not domain.startswith(("http://", "https://")):
target_urls.append(f"https://{domain}/login")
target_urls.append(f"http://{domain}/login")
else:
target_urls.append(f"{domain}/login")
target_urls.append(f"http://127.0.0.1:{port}/login")
async with httpx.AsyncClient(verify=False, timeout=15.0, headers=headers) as client:
success = False
for url in target_urls:
try:
final_url = url + ("&" if "?" in url else "?") + f"_nocache={secrets.token_hex(4)}"
resp = await client.get(final_url, follow_redirects=True)
if resp.status_code == 200:
logger.info(f"Advanced keep-alive successful: {url}")
success = True
break
except Exception as e:
logger.debug(f"Advanced keep-alive attempt failed for {url}: {e}")
if not success:
logger.warning("Advanced keep-alive: all attempts failed.")
await asyncio.sleep(KEEP_ALIVE_INTERVAL)
async def cleanup_link_cache():
while True:
await asyncio.sleep(600)
now = time.time()
expired = [k for k, v in link_cache.items() if v["expires"] <= now]
for k in expired:
del link_cache[k]
@asynccontextmanager
async def lifespan(app: FastAPI):
global TIMEZONE_OFFSET, KEEP_ALIVE_ENABLED, KEEP_ALIVE_INTERVAL, KEEP_ALIVE_MODE
if DB_BACKEND == "postgresql":
await init_pg()
else:
await init_db()
await load_initial_data()
sk = await db_fetchone(
"SELECT value FROM settings WHERE key = 'jwt_secret_key'",
"SELECT value FROM settings WHERE key = 'jwt_secret_key'"
)
if sk:
CONFIG["secret_key"] = sk["value"]
else:
await db_execute(
"INSERT INTO settings (key, value) VALUES ('jwt_secret_key', ?)",
"INSERT INTO settings (key, value) VALUES ('jwt_secret_key', $1)",
(CONFIG["secret_key"],)
)
hash_row = await db_fetchone(
"SELECT value FROM settings WHERE key = 'admin_password_hash'",
"SELECT value FROM settings WHERE key = 'admin_password_hash'",
)
global ADMIN_PASSWORD_HASH
if hash_row:
ADMIN_PASSWORD_HASH = hash_row["value"]
else:
ADMIN_PASSWORD_HASH = bcrypt.hashpw(CONFIG["admin_password"].encode(), bcrypt.gensalt()).decode()
await db_execute(
"INSERT INTO settings (key, value) VALUES ('admin_password_hash', ?)",
"INSERT INTO settings (key, value) VALUES ('admin_password_hash', $1)",
(ADMIN_PASSWORD_HASH,),
)
log_row = await db_fetchone(
"SELECT value FROM settings WHERE key = 'log_enabled'",
"SELECT value FROM settings WHERE key = 'log_enabled'"
)
global ENABLE_LOGGING
ENABLE_LOGGING = (log_row and log_row["value"] == "1") if log_row else True
tz_row = await db_fetchone(
"SELECT value FROM settings WHERE key='timezone_offset'",
"SELECT value FROM settings WHERE key='timezone_offset'"
)
if tz_row and tz_row["value"]:
try:
TIMEZONE_OFFSET = float(tz_row["value"])
except:
TIMEZONE_OFFSET = 0.0
ke_row = await db_fetchone(
"SELECT value FROM settings WHERE key='keep_alive_enabled'",
"SELECT value FROM settings WHERE key='keep_alive_enabled'"
)
if ke_row and ke_row["value"] is not None:
KEEP_ALIVE_ENABLED = (ke_row["value"] == "1")
km_row = await db_fetchone(
"SELECT value FROM settings WHERE key='keep_alive_mode'",
"SELECT value FROM settings WHERE key='keep_alive_mode'"
)
if km_row and km_row["value"]:
KEEP_ALIVE_MODE = km_row["value"]
interval_row = await db_fetchone(
"SELECT value FROM settings WHERE key='keep_alive_interval'",
"SELECT value FROM settings WHERE key='keep_alive_interval'"
)
if interval_row and interval_row["value"]:
try:
KEEP_ALIVE_INTERVAL = max(60, int(interval_row["value"]))
except:
pass
asyncio.create_task(_keepalive_simple_loop())
asyncio.create_task(_keepalive_advanced_loop())
asyncio.create_task(cleanup_idle_connections())
asyncio.create_task(telegram_reporter())
asyncio.create_task(flush_traffic_buffer())
asyncio.create_task(sync_usage_to_db())
asyncio.create_task(auto_disable_expired_links())
asyncio.create_task(cleanup_link_cache())
yield
if DB_BACKEND == "sqlite" and db_conn:
await db_conn.close()
app = FastAPI(title="SulgX Panel", lifespan=lifespan, docs_url=None, redoc_url=None)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
@app.middleware("http")
async def security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
return response
connections: dict = {}
connections_lock = asyncio.Lock()
connection_sockets: dict = {}
link_ip_map: dict = defaultdict(set)
stats = {
"total_bytes": 0,
"total_requests": 0,
"total_errors": 0,
"start_time": time.time(),
"upload_bytes": 0,
"download_bytes": 0,
}
error_logs: deque = deque(maxlen=2000)
CACHE_TTL = 60
link_cache: dict = {}
SESSION_COOKIE = "SulgX_session"
UNLIMITED_QUOTA_BYTES = 53687091200000
ADMIN_PASSWORD_HASH: str = ""
ENABLE_LOGGING: bool = True
KEEP_ALIVE_ENABLED: bool = True
KEEP_ALIVE_MODE: str = "simple"
def verify_password(plain: str, hashed: str) -> bool:
return bcrypt.checkpw(plain.encode(), hashed.encode())
def create_jwt_token(data: dict, expires_delta: timedelta = None) -> str:
to_encode = data.copy()
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=CONFIG["jwt_expire_minutes"]))
to_encode.update({"exp": expire})
return jwt.encode(to_encode, CONFIG["secret_key"], algorithm=CONFIG["jwt_algorithm"])
def decode_jwt_token(token: str) -> Optional[dict]:
try:
return jwt.decode(token, CONFIG["secret_key"], algorithms=[CONFIG["jwt_algorithm"]])
except JWTError:
return None
async def require_auth(request: Request):
token = request.cookies.get(SESSION_COOKIE)
if not token or not decode_jwt_token(token):
raise HTTPException(status_code=401, detail="unauthorized")
return token
async def cleanup_idle_connections():
while True:
await asyncio.sleep(60)
now = time.time()
async with connections_lock:
idle = [cid for cid, info in connections.items() if now - info.get("last_active", 0) > 300]
for cid in idle:
ws = connection_sockets.get(cid)
if ws:
try: await ws.close(code=1000, reason="idle timeout")
except Exception: pass
async with connections_lock: connections.pop(cid, None)
connection_sockets.pop(cid, None)
async def auto_disable_expired_links():
while True:
await asyncio.sleep(60)
try:
row = await db_fetchone("SELECT value FROM settings WHERE key='auto_disable_enabled'", "SELECT value FROM settings WHERE key='auto_disable_enabled'")
if row and row["value"] != "1":
continue
now = datetime.now(timezone.utc)
async with LINKS_LOCK:
for uid, link in LINKS.items():
if link.get("active") and link.get("expires_at"):
exp = parse_expires_at(link["expires_at"])
if exp and exp < now:
link["active"] = 0
await db_execute("UPDATE links SET active = 0 WHERE uid = ?", "UPDATE links SET active = FALSE WHERE uid = $1", (uid,))
log_event("Auto", f"Expired inbound {link['label']} auto-disabled")
except Exception as e:
logger.error(f"auto_disable_expired_links error: {e}", exc_info=True)
async def telegram_reporter():
while True:
interval_hours = 1
row = await db_fetchone("SELECT value FROM settings WHERE key = 'telegram_interval'", "SELECT value FROM settings WHERE key = 'telegram_interval'")
if row and row["value"]:
try: interval_hours = float(row["value"])
except: interval_hours = 1
await asyncio.sleep(3600 * interval_hours)
en_row = await db_fetchone("SELECT value FROM settings WHERE key='telegram_report_enabled'", "SELECT value FROM settings WHERE key='telegram_report_enabled'")
if en_row and en_row["value"] != "1":
continue
try:
token_row = await db_fetchone("SELECT value FROM settings WHERE key = 'tg_bot_token'", "SELECT value FROM settings WHERE key = 'tg_bot_token'")
chat_row = await db_fetchone("SELECT value FROM settings WHERE key = 'tg_chat_id'", "SELECT value FROM settings WHERE key = 'tg_chat_id'")
if token_row and chat_row and token_row["value"] and chat_row["value"]:
msg = (
f"📊 SulgX Panel Stats\n"
f"🕒 Uptime: {uptime()}\n"
f"🔗 Conns: {len(connections)}\n"
f"📦 Traffic: {round(stats['total_bytes']/(1024*1024),2)} MB\n"
f"📡 Requests: {stats['total_requests']}\n"
f"❌ Errors: {stats['total_errors']}"
)
url = f"https://api.telegram.org/bot{token_row['value']}/sendMessage"
async with httpx.AsyncClient(timeout=10.0) as client:
await client.post(url, json={"chat_id": chat_row["value"], "text": msg})
except Exception:
pass
def get_domain() -> str:
domain = (
os.environ.get("DOMAIN") or
os.environ.get("RENDER_EXTERNAL_URL") or
os.environ.get("RAILWAY_PUBLIC_DOMAIN") or
"localhost"
)
return domain.replace("https://", "").replace("http://", "")
def validate_address(addr: str) -> bool:
try:
ipaddress.ip_address(addr.strip('[]'))
return True
except ValueError:
pass
try:
ipaddress.ip_network(addr.strip('[]'), strict=False)
return True
except ValueError:
pass
return re.match(r'^[a-zA-Z0-9\-_.%]+$', addr) is not None
def format_host_port(host: str, port: int = 443) -> str:
host = host.strip('[]')
try:
ipaddress.IPv6Address(host)
return f"[{host}]:{port}"
except ipaddress.AddressValueError:
return f"{host}:{port}"
def code_to_flag(code: str) -> str:
if not code or len(code) != 2:
return ""
code = code.upper()
try:
return chr(ord(code[0]) + 127397) + chr(ord(code[1]) + 127397)
except:
return ""
def generate_vless_link(uid: str, remark: str = "SulgX", address: str = None, extra: dict = None) -> str:
cache_key = f"{uid}:{remark}:{address}:{json.dumps(extra) if extra else ''}"
if cache_key in link_cache and link_cache[cache_key]["expires"] > time.time():
return link_cache[cache_key]["link"]
domain = get_domain()
addr = address if address else domain
path = (extra.get("custom_path") or f"/ws/{uid}") if extra else f"/ws/{uid}"
sni = (extra.get("custom_sni") or domain) if extra else domain
host = (extra.get("custom_host") or domain) if extra else domain
fp = (extra.get("custom_fp") or "chrome") if extra else "chrome"
fragment = extra.get("fragment", "") if extra else ""
params = {
"encryption": "none", "security": "tls", "type": "ws",
"host": host, "path": path, "sni": sni, "fp": fp, "alpn": "http/1.1"
}
if fragment:
params["fragment"] = fragment
query = "&".join(f"{k}={quote(str(v))}" for k, v in params.items())
link = f"vless://{uid}@{format_host_port(addr, 443)}?{query}#{quote(remark)}"
link_cache[cache_key] = {"link": link, "expires": time.time() + CACHE_TTL}
return link
def uptime() -> str:
secs = int(time.time() - stats["start_time"])
h, m, s = secs // 3600, (secs % 3600) // 60, secs % 60
return f"{h:02d}:{m:02d}:{s:02d}"
def parse_size_to_bytes(value: float, unit: str) -> int:
u = unit.upper()
if u == "GB": return int(value * 1024**3)
if u == "MB": return int(value * 1024**2)
if u == "KB": return int(value * 1024)
return int(value)
def parse_expires_at(raw: Optional[str]) -> Optional[datetime]:
if not raw: return None
try:
s = raw.replace("Z", "+00:00")
dt = datetime.fromisoformat(s)
return dt.replace(tzinfo=timezone.utc) if dt.tzinfo is None else dt
except Exception: return None
def seconds_until_expiry(expires_at_str: Optional[str]) -> Optional[int]:
exp = parse_expires_at(expires_at_str)
if exp is None: return None
return max(0, int((exp - datetime.now(timezone.utc)).total_seconds()))
async def count_connections_for_link(uid: str) -> int:
async with connections_lock:
return sum(1 for info in connections.values() if info.get("uuid") == uid)
async def close_connections_for_link(uid: str):
async with connections_lock:
to_close = [cid for cid, info in connections.items() if info.get("uuid") == uid]
for cid in to_close:
ws = connection_sockets.get(cid)
if ws:
try: await ws.close(code=1000, reason="link deleted/blocked")
except Exception: pass
async with connections_lock: connections.pop(cid, None)
connection_sockets.pop(cid, None)
async with connections_lock: link_ip_map.pop(uid, None)
def log_event(etype: str, message: str, ip: str = "", ua: str = ""):
error_logs.append({
"time": datetime.now(timezone.utc).isoformat(),
"type": etype,
"error": message or "(no detail)",
"ip": ip,
"ua": ua,
})
# ═══ ROUTES ═══
@app.api_route("/", methods=["GET", "HEAD"])
async def root():
return {"service": "SulgX Panel", "version": "1.1.0", "status": "active", "domain": get_domain()}
@app.get("/health")
async def health():
async with connections_lock: cnt = len(connections)
return {"status": "ok", "connections": cnt, "uptime": uptime()}
@app.get("/favicon.ico")
async def favicon():
return Response(content=b"", media_type="image/x-icon", status_code=204)
@app.get("/api/public-settings")
async def public_settings():
rows = await db_fetchall("SELECT key, value FROM settings WHERE key IN ('footer_text')",
"SELECT key, value FROM settings WHERE key IN ('footer_text')")
result = {}
for r in rows:
result[r["key"]] = r["value"]
return result
@app.post("/api/login")
@limiter.limit("5/minute")
async def api_login(request: Request):
body = await request.json()
password = str(body.get("password") or "")
ip = request.client.host
user_agent = request.headers.get("user-agent", "")
success = verify_password(password, ADMIN_PASSWORD_HASH)
asyncio.create_task(log_login(ip, success, user_agent, "/api/login"))
if not success:
log_event("Auth", f"Failed login attempt from {ip}", ip, user_agent)
raise HTTPException(status_code=401, detail="Invalid password")
log_event("Auth", f"Successful panel login from {ip}", ip, user_agent)
token = create_jwt_token({"sub": "admin"})
resp = JSONResponse({"ok": True})
resp.set_cookie(key=SESSION_COOKIE, value=token, max_age=CONFIG["jwt_expire_minutes"]*60,
httponly=True, samesite="lax", secure=True if get_domain()!="localhost" else False, path="/")
return resp
async def log_login(ip: str, success: bool, ua: str, path: str):
if not ENABLE_LOGGING:
return
try:
await db_execute(
"INSERT INTO login_logs (timestamp, ip, success, user_agent, path) VALUES (?,?,?,?,?)",
"INSERT INTO login_logs (timestamp, ip, success, user_agent, path) VALUES ($1,$2,$3,$4,$5)",
(datetime.now(timezone.utc).isoformat(), ip, 1 if success else 0, ua, path)
)
if success:
await notify_telegram_login(ip, ua)
except Exception as e:
logger.error(f"log_login error: {e}")
async def notify_telegram_login(ip: str, ua: str):
notif_row = await db_fetchone("SELECT value FROM settings WHERE key='telegram_notify_enabled'", "SELECT value FROM settings WHERE key='telegram_notify_enabled'")
if notif_row and notif_row["value"] != "1":
return
token_row = await db_fetchone("SELECT value FROM settings WHERE key = 'tg_bot_token'", "SELECT value FROM settings WHERE key = 'tg_bot_token'")
chat_row = await db_fetchone("SELECT value FROM settings WHERE key = 'tg_chat_id'", "SELECT value FROM settings WHERE key = 'tg_chat_id'")
if not token_row or not chat_row or not token_row["value"] or not chat_row["value"]:
return
lang = 'en'
lang_row = await db_fetchone("SELECT value FROM settings WHERE key='telegram_lang'", "SELECT value FROM settings WHERE key='telegram_lang'")
if lang_row and lang_row["value"] == 'fa':
lang = 'fa'
templates_key = f'telegram_templates_{lang}'
tmpl_row = await db_fetchone(f"SELECT value FROM settings WHERE key='{templates_key}'", f"SELECT value FROM settings WHERE key='{templates_key}'")
templates = {}
if tmpl_row and tmpl_row["value"]:
try: templates = json.loads(tmpl_row["value"])
except: pass
now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M")
if lang == 'fa':
default_login = f"🔐 ورود SulgX\n🌐 IP: {ip}\n🤖 UA: {ua}\n📅 {now_str}"
else:
default_login = f"🔐 SulgX Panel login\n🌐 IP: {ip}\n🤖 UA: {ua}\n📅 {now_str}"
msg = templates.get('login', default_login)
msg = msg.replace("{ip}", ip).replace("{ua}", ua).replace("{time}", now_str)
panel_url = f"https://{get_domain()}/panel"
msg += f'\n\n<a href="{panel_url}">Open SulgX Panel</a>'
url = f"https://api.telegram.org/bot{token_row['value']}/sendMessage"
try:
async with httpx.AsyncClient(timeout=5.0) as client:
await client.post(url, json={"chat_id": chat_row["value"], "text": msg, "parse_mode": "HTML"})
except Exception:
pass
@app.post("/api/logout")
async def api_logout(request: Request):
resp = JSONResponse({"ok": True})
resp.delete_cookie(SESSION_COOKIE, path="/")
return resp
@app.get("/api/me")
async def api_me(_: str = Depends(require_auth)):
return {"authenticated": True}
@app.post("/api/change-password")
@limiter.limit("3/minute")
async def api_change_password(request: Request, _=Depends(require_auth)):
global ADMIN_PASSWORD_HASH
body = await request.json()
current = str(body.get("current_password") or "")
new = str(body.get("new_password") or "")
if not verify_password(current, ADMIN_PASSWORD_HASH):
raise HTTPException(status_code=400, detail="Current password is incorrect")
if len(new) < 8:
raise HTTPException(status_code=400, detail="Password must be at least 8 characters")
if not re.search(r'[A-Z]', new) or not re.search(r'[a-z]', new) or not re.search(r'[0-9]', new):
raise HTTPException(status_code=400, detail="Password must contain uppercase, lowercase, and digit")
new_hash = bcrypt.hashpw(new.encode(), bcrypt.gensalt()).decode()
ADMIN_PASSWORD_HASH = new_hash
await db_execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES ('admin_password_hash', ?)",
"INSERT INTO settings (key, value) VALUES ('admin_password_hash', $1) ON CONFLICT (key) DO UPDATE SET value = $1",
(new_hash,),
)
log_event("Security", "Admin password changed")
return {"ok": True}
@app.get("/api/settings")
async def get_settings(_=Depends(require_auth)):
keys = ['tg_bot_token', 'max_scan_ips', 'tg_chat_id', 'footer_text', 'default_path', 'log_enabled', 'timezone_offset',
'default_limit_bytes', 'default_expiry_days', 'default_max_connections',
'telegram_events', 'telegram_interval', 'keep_alive_interval', 'keep_alive_enabled', 'keep_alive_mode',
'log_max_entries', 'scanner_timeout', 'theme_color',
'telegram_templates_en', 'telegram_templates_fa', 'telegram_lang', 'default_lang',
'auto_disable_enabled', 'telegram_report_enabled', 'telegram_notify_enabled',
'monthly_limit_gb']
result = {}
for k in keys:
row = await db_fetchone("SELECT value FROM settings WHERE key = ?", "SELECT value FROM settings WHERE key = $1", (k,))
result[k] = row["value"] if row else ""
return result
@app.post("/api/settings")
async def save_settings(request: Request, _=Depends(require_auth)):
global ENABLE_LOGGING, TIMEZONE_OFFSET, KEEP_ALIVE_ENABLED, KEEP_ALIVE_INTERVAL, KEEP_ALIVE_MODE
body = await request.json()
for k in ('tg_bot_token', 'tg_chat_id', 'max_scan_ips', 'footer_text', 'default_path', 'log_enabled', 'timezone_offset',
'default_limit_bytes', 'default_expiry_days', 'default_max_connections',
'telegram_events', 'telegram_interval', 'keep_alive_interval', 'keep_alive_enabled', 'keep_alive_mode',
'log_max_entries', 'scanner_timeout', 'theme_color',
'telegram_templates_en', 'telegram_templates_fa', 'telegram_lang', 'default_lang',
'auto_disable_enabled', 'telegram_report_enabled', 'telegram_notify_enabled',
'monthly_limit_gb'):
if k in body:
val = str(body[k]).strip()
await db_execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
"INSERT INTO settings (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = $2",
(k, val),
)
if 'log_enabled' in body:
ENABLE_LOGGING = body['log_enabled'] == '1'
if 'keep_alive_enabled' in body:
KEEP_ALIVE_ENABLED = body['keep_alive_enabled'] == '1'
if 'keep_alive_mode' in body:
KEEP_ALIVE_MODE = body['keep_alive_mode']
if 'keep_alive_interval' in body:
try:
KEEP_ALIVE_INTERVAL = max(60, int(body['keep_alive_interval']))
except:
pass
if 'timezone_offset' in body:
try:
TIMEZONE_OFFSET = float(body['timezone_offset'])
except:
TIMEZONE_OFFSET = 0.0
return {"ok": True}
@app.post("/api/settings/reset")
@limiter.limit("3/minute")
async def reset_settings(request: Request, _=Depends(require_auth)):
PROTECTED_KEYS = {'jwt_secret_key', 'admin_password_hash'}
all_keys = await db_fetchall("SELECT key FROM settings", "SELECT key FROM settings")
for row in all_keys:
k = row["key"]
if k not in PROTECTED_KEYS:
await db_execute("DELETE FROM settings WHERE key = ?", "DELETE FROM settings WHERE key = $1", (k,))
global ENABLE_LOGGING, KEEP_ALIVE_INTERVAL, TIMEZONE_OFFSET, KEEP_ALIVE_ENABLED, KEEP_ALIVE_MODE
ENABLE_LOGGING = True
KEEP_ALIVE_INTERVAL = 300
TIMEZONE_OFFSET = 0.0
KEEP_ALIVE_ENABLED = True
KEEP_ALIVE_MODE = "simple"
log_event("Settings", "All settings reset to defaults")
return {"ok": True}
@app.get("/stats")
async def get_stats(_=Depends(require_auth)):
global TIMEZONE_OFFSET
async with connections_lock: conn_count = len(connections)
cpu = 0.0
try:
cpu = await asyncio.to_thread(psutil.cpu_percent, 0.1)
if cpu == 0.0:
try:
with open('/proc/loadavg', 'r') as f:
cpu = float(f.readline().split()[0]) * 10
except:
cpu = None
except:
try:
with open('/proc/loadavg', 'r') as f:
cpu = float(f.readline().split()[0]) * 10
except:
cpu = None
mem_percent = 0
try: mem_percent = psutil.virtual_memory().percent
except: pass
disk_percent = 0; disk_free = 0.0
try:
disk = psutil.disk_usage("/")
disk_percent = disk.percent
disk_free = round(disk.free / (1024**3), 1)
except: pass
now = datetime.now(timezone.utc) + timedelta(hours=TIMEZONE_OFFSET)
today_str = now.strftime("%Y-%m-%d")
rows = await db_fetchall(
"SELECT hour, bytes FROM hourly_traffic WHERE hour LIKE ? ORDER BY hour ASC",
"SELECT hour, bytes FROM hourly_traffic WHERE hour LIKE $1 ORDER BY hour ASC",
(today_str + '%',)
)
hourly_dict = {f"{h:02d}:00": 0 for h in range(24)}
for r in rows:
hour_part = r["hour"][-5:] if len(r["hour"]) >= 5 else r["hour"]
if hour_part in hourly_dict:
hourly_dict[hour_part] = r["bytes"]
async with traffic_buffer_lock:
for h_key, b_val in traffic_buffer["hourly"].items():
hour_part = h_key[-5:] if len(h_key) >= 5 else h_key
if hour_part in hourly_dict:
hourly_dict[hour_part] += b_val
sorted_hours = [f"{h:02d}:00" for h in range(24)]
hourly_data = {h: hourly_dict[h] for h in sorted_hours}
month_start = now.strftime("%Y-%m") + "-01"
monthly_bytes = 0
month_rows = await db_fetchall(
"SELECT SUM(bytes) as total FROM daily_traffic WHERE day >= ?",
"SELECT SUM(bytes) as total FROM daily_traffic WHERE day >= $1",
(month_start,)
)
if month_rows and month_rows[0]["total"]:
monthly_bytes = month_rows[0]["total"]
monthly_limit = 0
limit_row = await db_fetchone("SELECT value FROM settings WHERE key='monthly_limit_gb'", "SELECT value FROM settings WHERE key='monthly_limit_gb'")
if limit_row and limit_row["value"]:
try: monthly_limit = float(limit_row["value"]) * 1024**3
except: pass
return {
"active_connections": conn_count,
"total_traffic_mb": round(stats["total_bytes"]/(1024*1024),2),
"total_requests": stats["total_requests"],
"total_errors": stats["total_errors"],
"uptime": uptime(),
"timestamp": datetime.now(timezone.utc).isoformat(),
"recent_errors": list(error_logs)[-20:],
"links_count": len(LINKS),
"domain": get_domain(),
"cpu_percent": cpu,
"memory_percent": mem_percent,
"disk_percent": disk_percent,
"disk_free_gb": disk_free,
"hourly_traffic": hourly_data,
"hourly_labels": sorted_hours,
"upload_bytes": stats["upload_bytes"],
"download_bytes": stats["download_bytes"],
"monthly_usage_bytes": monthly_bytes,
"monthly_limit_bytes": int(monthly_limit),
}
@app.get("/stats/detailed")
async def get_detailed_stats(_=Depends(require_auth)):
async with LINKS_LOCK:
links = list(LINKS.values())
active = sum(1 for l in links if l["active"])
inactive = sum(1 for l in links if not l["active"])
expired = 0
now = datetime.now(timezone.utc)
for l in links:
if l.get("expires_at"):
exp = parse_expires_at(l["expires_at"])
if exp and exp < now:
expired += 1
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
today_row = await db_fetchone("SELECT bytes FROM daily_traffic WHERE day = ?", "SELECT bytes FROM daily_traffic WHERE day = $1", (today,))
today_bytes = today_row["bytes"] if today_row else 0
daily_rows = await db_fetchall("SELECT day, bytes FROM daily_traffic ORDER BY day DESC LIMIT 7",
"SELECT day, bytes FROM daily_traffic ORDER BY day DESC LIMIT 7")
daily_traffic = {row["day"]: row["bytes"] for row in daily_rows}
return {
"total_links": len(links),
"active_links": active,
"inactive_links": inactive,
"expired_links": expired,
"today_traffic_bytes": today_bytes,
"daily_traffic": daily_traffic,
}
@app.get("/api/login-logs")
async def get_login_logs(_=Depends(require_auth)):
rows = await db_fetchall(
"SELECT timestamp, ip, success, user_agent, path FROM login_logs ORDER BY timestamp DESC LIMIT 20",
"SELECT timestamp, ip, success, user_agent, path FROM login_logs ORDER BY timestamp DESC LIMIT 20"
)
return {"logs": [dict(r) for r in rows]}