forked from arvin341az-glitch/RVG
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
2440 lines (2194 loc) · 105 KB
/
Copy pathmain.py
File metadata and controls
2440 lines (2194 loc) · 105 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 subprocess
import sys
_PACKAGES = [
"fastapi==0.104.1",
"uvicorn[standard]==0.24.0",
"uvloop>=0.19.0",
"httptools>=0.6.0",
"httpx[http2]==0.25.1",
"websockets==12.0",
"aiofiles>=23.2.1",
"cryptography>=39.0.0",
]
def _install_packages():
try:
subprocess.check_call(
[sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", *_PACKAGES],
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
)
except subprocess.CalledProcessError as e:
print(f"[STARTUP] خطا در نصب پکیجها:\n{e.stderr.decode()}", file=sys.stderr)
sys.exit(1)
# _install_packages() # deps preinstalled for local test
import asyncio
import json
import os
import hashlib
import secrets
import sys
import time
import central
import aiofiles
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from urllib.parse import quote
from collections import deque, defaultdict
from pathlib import Path
import bottokentcpproxy
from protocol.mtproto import mtproto
from typing import Optional
import base64
import botgeneratedomin
from fastapi import FastAPI, Request, HTTPException, WebSocket, WebSocketDisconnect, Depends
from fastapi.responses import Response, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import httpx
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("RVG-Gateway")
IRAN_TZ = ZoneInfo("Asia/Tehran")
app = FastAPI(title="RVG Gateway - codebox", docs_url=None, redoc_url=None)
# وقتی مستقیم با `python main.py` اجرا میشه، این ماژول با نام "__main__" ثبت
# میشه نه "main". چون protocol/vless/vless.py و protocol/trojan/trojan.py با
# `from main import (...)` به این فایل رفرنس میدن، بدون این خط پایتون مجبور
# میشه کل main.py رو یکبار دیگه از صفر بهعنوان ماژول جداگانهی "main" اجرا کنه
# که باعث circular import و کرش میشه. با alias کردن sys.modules، هر دو اسم
# به همین نمونهی در حال اجرا اشاره میکنن.
sys.modules.setdefault("main", sys.modules[__name__])
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ── Persistence ───────────────────────────────────────────────────────────────
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
DATA_FILE = DATA_DIR / "rvg_state.json"
SECRET_FILE = DATA_DIR / ".rvg_secret"
SAVE_LOCK = asyncio.Lock()
def _get_or_create_secret() -> str:
env_secret = os.environ.get("SECRET_KEY")
if env_secret:
return env_secret
try:
DATA_DIR.mkdir(parents=True, exist_ok=True)
if SECRET_FILE.exists():
val = SECRET_FILE.read_text(encoding="utf-8").strip()
if val:
return val
new_secret = secrets.token_urlsafe(32)
SECRET_FILE.write_text(new_secret, encoding="utf-8")
logger.info("SECRET_KEY جدید ساخته و در دیسک ذخیره شد (پایدار بین ریاستارتها).")
return new_secret
except Exception as e:
logger.warning(f"عدم امکان ذخیرهی SECRET_KEY روی دیسک: {e} — از مقدار موقت استفاده میشود.")
return secrets.token_urlsafe(32)
CONFIG = {
"port": int(os.environ.get("PORT", 8000)),
"secret": _get_or_create_secret(),
"host": os.environ.get("RAILWAY_PUBLIC_DOMAIN", "localhost"),
}
async def load_state():
global LINKS, AUTH, SUBS
try:
DATA_DIR.mkdir(parents=True, exist_ok=True)
if DATA_FILE.exists():
async with aiofiles.open(DATA_FILE, "r", encoding="utf-8") as f:
raw = await f.read()
data = json.loads(raw)
LINKS.update(data.get("links", {}))
SUBS.update(data.get("subs", {}))
NODE_KEYS.update(data.get("node_keys", {}))
for nid, n in (data.get("nodes") or {}).items():
NODES[nid] = _normalize_node(n)
if "password_hash" in data:
AUTH["password_hash"] = data["password_hash"]
logger.info(
f"State loaded: {len(LINKS)} links, {len(SUBS)} subs, "
f"{len(NODES)} nodes, {len(NODE_KEYS)} node keys"
)
except Exception as e:
logger.warning(f"Could not load state: {e}")
async def save_state():
async with SAVE_LOCK:
try:
DATA_DIR.mkdir(parents=True, exist_ok=True)
data = {
"links": dict(LINKS),
"subs": dict(SUBS),
"node_keys": dict(NODE_KEYS),
"nodes": dict(NODES),
"password_hash": AUTH["password_hash"],
"saved_at": datetime.now().isoformat(),
}
tmp = DATA_FILE.with_suffix(".tmp")
async with aiofiles.open(tmp, "w", encoding="utf-8") as f:
await f.write(json.dumps(data, ensure_ascii=False, indent=2))
tmp.replace(DATA_FILE)
except Exception as e:
logger.warning(f"Could not save state: {e}")
# ── Debounced save ─────────────────────────────────────────────────────────────
# هر بار که یک کانکشن (trojan/vless/shadowsocks/xhttp) بسته میشه، schedule_save()
# صدا زده میشه بهجای save_state() مستقیم. اگه صدها کانکشن در ثانیه باز و بسته بشن
# (که برای WebSocket-based transportها عادیه)، save_state() قبلی باعث میشد به همون
# تعداد، کل state سریالایز و روی دیسک نوشته بشه و event loop تکهستهای رو مسدود کنه.
# اینجا چندین درخواست ذخیرهسازی که در بازهی SAVE_DEBOUNCE_SECONDS اتفاق بیفتن،
# در یک نوشتن واحد روی دیسک ادغام میشن.
SAVE_DEBOUNCE_SECONDS = 2.0
_save_pending = False
_save_dirty_again = False
async def schedule_save():
"""نسخهی debounce شدهی save_state — برای صدا زدن مکرر و پرتعداد (هر بسته شدن کانکشن) امن است."""
global _save_pending, _save_dirty_again
if _save_pending:
_save_dirty_again = True
return
_save_pending = True
try:
while True:
_save_dirty_again = False
await asyncio.sleep(SAVE_DEBOUNCE_SECONDS)
await save_state()
if not _save_dirty_again:
break
finally:
_save_pending = False
# ── In-memory state ───────────────────────────────────────────────────────────
connections: dict = {}
stats = {
"total_bytes": 0,
"total_requests": 0,
"total_errors": 0,
"start_time": time.time(),
}
error_logs: deque = deque(maxlen=50)
activity_logs: deque = deque(maxlen=200)
hourly_traffic: dict = defaultdict(int)
http_client: httpx.AsyncClient | None = None
LINKS: dict = {}
LINKS_LOCK = asyncio.Lock()
SUBS: dict = {}
SUBS_LOCK = asyncio.Lock()
# ── Node linking (اتصال چند پنل به هم) ────────────────────────────────────────
# NODE_KEYS: کلیدهایی که *این* پنل صادر کرده. هر کلید به یک پنل دیگه اجازه میده
# دیتای این پنل رو بخونه و روی کانفیگهاش بنویسه (سمت inbound).
# NODES: پنلهایی که *این* پنل بهشون وصل شده و دیتاشون رو ادغام میکنه (سمت outbound).
NODE_KEYS: dict = {}
NODE_KEYS_LOCK = asyncio.Lock()
NODES: dict = {}
NODES_LOCK = asyncio.Lock()
_NODE_CACHE: dict = {} # node_id -> {"at": float, "data": dict}
NODE_CACHE_TTL = 8.0
NODE_KEY_PREFIX = "rvg-"
NODE_KEY_HEADER = "X-RVG-Node-Key"
NODE_SHARE_PARTS = ("usage", "links", "subs", "requests", "logs")
PROTOCOLS = (
"vless-ws", "xhttp-packet-up", "xhttp-stream-up",
"trojan-ws", "trojan-xhttp-packet-up", "trojan-xhttp-stream-up",
"mtproto", "shadowsocks",
)
DEFAULT_PROTOCOL = "vless-ws"
def log_activity(kind: str, message: str, level: str = "info"):
activity_logs.append({
"kind": kind,
"level": level,
"message": message,
"time": datetime.now().isoformat(),
})
# ── Auth ──────────────────────────────────────────────────────────────────────
SESSION_COOKIE = "rvg_session"
SESSION_TTL = 60 * 60 * 24 * 7
def hash_password(pw: str) -> str:
return hashlib.sha256(f"{pw}{CONFIG['secret']}".encode()).hexdigest()
AUTH = {"password_hash": hash_password(os.environ.get("ADMIN_PASSWORD", "123456"))}
SESSIONS: dict = {}
SESSIONS_LOCK = asyncio.Lock()
async def create_session() -> str:
token = secrets.token_urlsafe(32)
async with SESSIONS_LOCK:
SESSIONS[token] = time.time() + SESSION_TTL
return token
async def is_valid_session(token: str | None) -> bool:
if not token:
return False
async with SESSIONS_LOCK:
exp = SESSIONS.get(token)
if exp is None:
return False
if exp < time.time():
SESSIONS.pop(token, None)
return False
return True
async def destroy_session(token: str | None):
if not token:
return
async with SESSIONS_LOCK:
SESSIONS.pop(token, None)
async def require_auth(request: Request):
token = request.cookies.get(SESSION_COOKIE)
if not await is_valid_session(token):
raise HTTPException(status_code=401, detail="unauthorized")
return token
# ── Startup / Shutdown ────────────────────────────────────────────────────────
@app.on_event("startup")
async def startup():
asyncio.create_task(central.heartbeat_loop())
global http_client
limits = httpx.Limits(max_connections=500, max_keepalive_connections=100)
timeout = httpx.Timeout(30.0, connect=10.0)
http_client = httpx.AsyncClient(
limits=limits, timeout=timeout, follow_redirects=True,
)
await load_state()
await _restart_mtproto_instances()
log_activity("system", "سرور راهاندازی شد", "ok")
logger.info(f"RVG Gateway v9.2 started on port {CONFIG['port']}")
async def _restart_mtproto_instances():
async with LINKS_LOCK:
targets = [
(uid, d) for uid, d in LINKS.items()
if d.get("protocol") == "mtproto" and d.get("active", True)
]
for uid, d in targets:
try:
inst = await mtproto.start_instance(
uid,
secret=d.get("mtproto_secret"),
domain=d.get("mtproto_domain", mtproto.DEFAULT_FAKE_TLS_DOMAIN),
preferred_port=d.get("mtproto_port"),
force_port=d.get("mtproto_manual_port", False),
ad_tag=d.get("ad_tag"),
)
old_port = d.get("mtproto_port")
async with LINKS_LOCK:
LINKS[uid]["mtproto_port"] = inst["port"]
LINKS[uid]["mtproto_secret"] = inst["secret"]
if (d.get("mtproto_proxy_id") and inst["port"] != old_port
and not d.get("mtproto_manual_port", False)):
asyncio.create_task(_reattach_mtproto_public_proxy(
uid, inst["port"], d.get("mtproto_proxy_id"), d.get("label", "")
))
except Exception as exc:
logger.error(f"ریاستارت خودکار MTProto ناموفق برای {uid[:8]}: {exc}")
async def _mtproto_usage_callback(uuid: str, n_bytes: int) -> bool:
async with LINKS_LOCK:
link = LINKS.get(uuid)
if link is None:
return False
if not is_link_allowed(link):
return False
link["used_bytes"] += n_bytes
stats["total_bytes"] += n_bytes
hourly_traffic[now_ir().strftime("%H:00")] += n_bytes
return True
mtproto.set_usage_callback(_mtproto_usage_callback)
async def _attach_mtproto_public_proxy(uid: str, application_port: int, label: str):
try:
pub = await bottokentcpproxy.create_public_proxy_for_port(application_port)
except Exception as exc:
logger.warning(f"TCP Proxy عمومی برای {uid[:8]} ناموفق بود: {exc}")
async with LINKS_LOCK:
if uid in LINKS:
LINKS[uid]["mtproto_public_pending"] = False
log_activity("link", f"ساخت TCP Proxy عمومی برای «{label}» ناموفق بود: {exc}", "err")
return
async with LINKS_LOCK:
if uid in LINKS:
LINKS[uid]["mtproto_public_host"] = pub["domain"]
LINKS[uid]["mtproto_public_port"] = pub["port"]
LINKS[uid]["mtproto_proxy_id"] = pub["id"]
LINKS[uid]["mtproto_public_pending"] = False
asyncio.create_task(save_state())
log_activity("link", f"TCP Proxy عمومی «{label}» آماده شد ({pub['domain']}:{pub['port']})", "ok")
async def _reattach_mtproto_public_proxy(uid: str, new_port: int, old_proxy_id: Optional[str], label: str):
if old_proxy_id:
await bottokentcpproxy.delete_public_proxy(old_proxy_id)
await _attach_mtproto_public_proxy(uid, new_port, label)
# ===== تابع جدید برای بهروزرسانی ad_tag روی پروکسی =====
async def _update_mtproto_ad_tag(uuid: str, ad_tag: str):
try:
# اسنپشات اولیهی لینک قبل از هر کاری - برای مقایسهی پورت قدیم/جدید لازم است
async with LINKS_LOCK:
link = LINKS.get(uuid)
if not link:
return
old_port = link.get("mtproto_port")
old_proxy_id = link.get("mtproto_proxy_id")
manual_port = link.get("mtproto_manual_port", False)
label = link.get("label", "")
secret = link.get("mtproto_secret")
domain = link.get("mtproto_domain", mtproto.DEFAULT_FAKE_TLS_DOMAIN)
await mtproto.stop_instance(uuid)
try:
# force_port=True همیشه: چون تازه instance رو stop کردیم، پورت قدیمی
# قطعاً باید آزاد باشه. اگر force_port=False بذاریم و پورت به هر دلیلی
# (مثلاً TIME_WAIT) هنوز آزاد نشده بود، mtg یک پورت داخلی جدید و تصادفی
# انتخاب میکند و TCP Proxy عمومی روی Railway (که آدرسش را کاربر در
# @MTProxybot ثبت کرده) دیگر به mtg جدید اشاره نمیکند — دقیقاً همین
# چیزی بود که باعث میشد تبلیغ (ad_tag) کار نکند.
inst = await mtproto.start_instance(
uuid,
secret=secret,
domain=domain,
preferred_port=old_port,
force_port=True,
ad_tag=ad_tag,
)
except RuntimeError as exc:
logger.warning(
f"MTProto[{uuid[:8]}]: گرفتن دوبارهی پورت قبلی {old_port} برای "
f"ad_tag ناموفق بود ({exc})، تلاش با پورت جدید..."
)
inst = await mtproto.start_instance(
uuid,
secret=secret,
domain=domain,
preferred_port=None,
force_port=False,
ad_tag=ad_tag,
)
async with LINKS_LOCK:
link = LINKS.get(uuid)
if not link:
# لینک در حین ریاستارت حذف شده؛ instance تازهساز را متوقف کن
asyncio.create_task(mtproto.stop_instance(uuid))
return
link["mtproto_port"] = inst["port"]
link["mtproto_secret"] = inst["secret"]
link["mtproto_domain"] = inst["domain"]
link["ad_tag"] = ad_tag
link["ad_tag_status"] = "done"
link["ad_tag_link"] = generate_share_link(
uuid, get_host(), remark=f"RVG-{link.get('label','')}", protocol="mtproto"
)
if old_proxy_id and inst["port"] != old_port and not manual_port:
asyncio.create_task(_reattach_mtproto_public_proxy(
uuid, inst["port"], old_proxy_id, label
))
asyncio.create_task(save_state())
logger.info(
f"MTProto[{uuid[:8]}]: ad_tag بهروز شد، instance ریاستارت شد "
f"(port={inst['port']}, تغییر پورت={inst['port'] != old_port})"
)
log_activity("link", f"تبلیغ کانال برای «{label}» با موفقیت اعمال شد", "ok")
except Exception as exc:
logger.error(f"خطا در بهروزرسانی ad_tag برای {uuid[:8]}: {exc}")
async with LINKS_LOCK:
if uuid in LINKS:
LINKS[uuid]["active"] = False
LINKS[uuid]["ad_tag_status"] = "error"
log_activity("link", f"بهروزرسانی ad_tag برای «{LINKS.get(uuid,{}).get('label','')}» ناموفق بود", "err")
asyncio.create_task(save_state())
@app.on_event("shutdown")
async def shutdown():
await save_state()
await mtproto.stop_all()
if http_client:
await http_client.aclose()
# ── Helpers ───────────────────────────────────────────────────────────────────
def get_host() -> str:
return os.environ.get("RAILWAY_PUBLIC_DOMAIN", CONFIG["host"])
def generate_uuid() -> str:
h = secrets.token_hex(16)
return f"{h[:8]}-{h[8:12]}-{h[12:16]}-{h[16:20]}-{h[20:32]}"
def now_ir() -> datetime:
return datetime.now(IRAN_TZ)
def generate_share_link(uuid: str, host: str, remark: str = "RVG", protocol: str = DEFAULT_PROTOCOL) -> str:
link = LINKS.get(uuid) or {}
alpn = link.get("alpn", "h2")
fp = link.get("fingerprint", "chrome")
if protocol == "mtproto":
port = link.get("mtproto_port")
secret = link.get("mtproto_secret")
if not port or not secret:
return f"tg://proxy?server={host}&port=0&secret=not_ready#{quote(remark)}"
pub_host = link.get("mtproto_public_host")
pub_port = link.get("mtproto_public_port")
final_host = pub_host or host
final_port = pub_port or port
return mtproto.generate_mtproto_link(final_host, final_port, secret)
if protocol == "shadowsocks":
cipher = link.get("ss_cipher", DEFAULT_CIPHER)
password = link.get("ss_password", "")
return generate_ss_link(host, 443, cipher, password, remark)
if protocol == "trojan-ws":
params = {
"security": "tls", "type": "ws", "host": host,
"path": "/trojan-ws", "sni": host, "fp": fp, "alpn": alpn,
}
query = "&".join(f"{k}={quote(str(v))}" for k, v in params.items())
return f"trojan://{uuid}@{host}:443?{query}#{quote(remark)}"
if protocol.startswith("trojan-xhttp-"):
mode = protocol.replace("trojan-xhttp-", "")
path = f"/txhttp-siz10/{mode}/{uuid}"
params = {
"security": "tls", "type": "xhttp", "mode": mode, "host": host,
"path": path, "sni": host, "fp": fp, "alpn": alpn,
}
query = "&".join(f"{k}={quote(str(v))}" for k, v in params.items())
return f"trojan://{uuid}@{host}:443?{query}#{quote(remark)}"
if protocol == "vless-ws":
path = f"/ws/{uuid}"
params = {
"encryption": "none",
"security": "tls",
"type": "ws",
"host": host,
"path": path,
"sni": host,
"fp": fp,
"alpn": alpn,
}
else:
mode = protocol.replace("xhttp-", "")
path = f"/xhttp-siz10/{mode}/{uuid}"
params = {
"encryption": "none",
"security": "tls",
"type": "xhttp",
"mode": mode,
"host": host,
"path": path,
"sni": host,
"fp": fp,
"alpn": alpn,
}
query = "&".join(f"{k}={quote(str(v))}" for k, v in params.items())
return f"vless://{uuid}@{host}:443?{query}#{quote(remark)}"
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:
unit = unit.upper()
if unit == "GB": return int(value * 1024 ** 3)
if unit == "MB": return int(value * 1024 ** 2)
if unit == "KB": return int(value * 1024)
return int(value)
def is_link_expired(link: dict) -> bool:
exp = link.get("expires_at")
if not exp:
return False
try:
return datetime.now() > datetime.fromisoformat(exp)
except Exception:
return False
def is_link_allowed(link: dict | None) -> bool:
if link is None:
return False
if not link.get("active", True):
return False
if is_link_expired(link):
return False
lb = link.get("limit_bytes", 0)
if lb > 0 and link.get("used_bytes", 0) >= lb:
return False
return True
def fmt_bytes(b: int) -> str:
if b < 1024: return f"{b} B"
if b < 1024**2: return f"{b/1024:.1f} KB"
if b < 1024**3: return f"{b/1024**2:.2f} MB"
return f"{b/1024**3:.2f} GB"
def build_sub_headers(label: str, used_bytes: int, limit_bytes: int, expires_at: str | None, support_url: str = "https://t.me/CodeBoxo") -> dict:
total = limit_bytes if limit_bytes > 0 else 0
expire_ts = 0
if expires_at:
try:
expire_ts = int(datetime.fromisoformat(expires_at).timestamp())
except Exception:
expire_ts = 0
userinfo = f"upload=0; download={used_bytes}; total={total}; expire={expire_ts}"
title_b64 = base64.b64encode(label.encode("utf-8")).decode()
return {
"profile-title": f"base64:{title_b64}",
"subscription-userinfo": userinfo,
"profile-update-interval": "6",
"support-url": support_url,
}
def client_ip(request: Request) -> str:
fwd = request.headers.get("x-forwarded-for")
if fwd:
return fwd.split(",")[0].strip()
real_ip = request.headers.get("x-real-ip")
if real_ip:
return real_ip.strip()
return request.client.host if request.client else "نامشخص"
# ── Node linking helpers ──────────────────────────────────────────────────────
def _b64u_encode(s: str) -> str:
return base64.urlsafe_b64encode(s.encode("utf-8")).decode().rstrip("=")
def _b64u_decode(s: str) -> str:
pad = "=" * (-len(s) % 4)
return base64.urlsafe_b64decode(s + pad).decode("utf-8")
def build_node_key(host: str, secret: str) -> str:
"""کلید خودکفا: دامنهی این پنل داخل خودِ کلید کدگذاری میشه."""
return f"{NODE_KEY_PREFIX}{_b64u_encode(host)}.{secret}"
def parse_node_key(key: str) -> tuple[str, str]:
"""برمیگرداند (host, secret). در صورت نامعتبر بودن ValueError میدهد."""
key = (key or "").strip()
if not key.startswith(NODE_KEY_PREFIX):
raise ValueError("کلید باید با rvg- شروع شود")
body = key[len(NODE_KEY_PREFIX):]
if "." not in body:
raise ValueError("ساختار کلید نامعتبر است")
host_part, secret = body.split(".", 1)
if not secret:
raise ValueError("بخش سکرت کلید خالی است")
try:
host = _b64u_decode(host_part).strip()
except Exception:
raise ValueError("دامنهی داخل کلید قابل خواندن نیست")
if not host or "/" in host or " " in host:
raise ValueError("دامنهی داخل کلید نامعتبر است")
return host, secret
def _node_scheme(host: str) -> str:
# فقط برای تست محلی http مجاز است؛ در بقیهی موارد اجباراً https
return "http" if host.startswith(("localhost", "127.0.0.1")) else "https"
def _normalize_node(n: dict) -> dict:
share = n.get("share") or {}
return {
"label": str(n.get("label") or n.get("host") or "نود")[:60],
"host": str(n.get("host") or ""),
"key": str(n.get("key") or ""),
"enabled": bool(n.get("enabled", True)),
"merge_dashboard": bool(n.get("merge_dashboard", True)),
"share": {p: bool(share.get(p, p != "logs")) for p in NODE_SHARE_PARTS},
"created_at": n.get("created_at") or datetime.now().isoformat(),
"last_sync_at": n.get("last_sync_at"),
"last_error": n.get("last_error"),
"peer_version": n.get("peer_version"),
}
def _node_public(node_id: str, n: dict) -> dict:
"""نسخهی امن برای فرانتاند — کلید خام بیرون نمیرود."""
out = {k: v for k, v in n.items() if k != "key"}
out["node_id"] = node_id
out["key_preview"] = (n.get("key") or "")[:14] + "…"
return out
async def _node_request(node: dict, method: str, path: str, *,
params: dict | None = None,
json_body: dict | None = None,
timeout: float = 10.0) -> httpx.Response:
host = node["host"]
url = f"{_node_scheme(host)}://{host}{path}"
client = http_client or httpx.AsyncClient()
return await client.request(
method, url,
params=params, json=json_body,
headers={NODE_KEY_HEADER: node["key"]},
timeout=timeout, follow_redirects=False,
)
async def require_node_key(request: Request) -> str:
"""احراز هویت پنل مقابل با هدر X-RVG-Node-Key (بدون کوکی سشن)."""
raw = (request.headers.get(NODE_KEY_HEADER) or "").strip()
if not raw:
raise HTTPException(status_code=401, detail="node key missing")
try:
_, secret = parse_node_key(raw)
except ValueError:
raise HTTPException(status_code=401, detail="invalid node key")
matched = None
async with NODE_KEYS_LOCK:
for key_id, entry in NODE_KEYS.items():
if entry.get("revoked"):
continue
if secrets.compare_digest(str(entry.get("secret", "")), secret):
matched = key_id
break
if matched is None:
raise HTTPException(status_code=401, detail="unknown or revoked node key")
entry = NODE_KEYS[matched]
entry["last_used_at"] = datetime.now().isoformat()
entry["use_count"] = int(entry.get("use_count", 0)) + 1
asyncio.create_task(schedule_save())
return matched
# ── Default link ──────────────────────────────────────────────────────────────
_default_link_created = False
async def ensure_default_link():
global _default_link_created
if _default_link_created:
return
async with LINKS_LOCK:
if not any(l.get("is_default") for l in LINKS.values()):
uid = hashlib.sha256(f"default{CONFIG['secret']}".encode()).hexdigest()
uid = f"{uid[:8]}-{uid[8:12]}-{uid[12:16]}-{uid[16:20]}-{uid[20:32]}"
if uid not in LINKS:
LINKS[uid] = {
"label": "لینک پیشفرض",
"limit_bytes": 0,
"used_bytes": 0,
"created_at": datetime.now().isoformat(),
"active": True,
"expires_at": None,
"note": "",
"is_default": True,
"sub_id": None,
"protocol": DEFAULT_PROTOCOL,
}
asyncio.create_task(save_state())
_default_link_created = True
# ── Basic endpoints ───────────────────────────────────────────────────────────
@app.get("/")
async def root():
return {"service": "RVG Gateway", "version": "9.2", "status": "active", "channel": "https://t.me/CodeBoxo"}
@app.get("/health")
async def health():
return {"status": "ok", "connections": len(connections), "uptime": uptime()}
# ── Subscription (single link) ────────────────────────────────────────────────
@app.get("/sub/{uuid}")
async def subscription_single(uuid: str):
async with LINKS_LOCK:
link = LINKS.get(uuid)
if not link or not is_link_allowed(link):
raise HTTPException(status_code=404, detail="not found or inactive")
host = get_host()
proto = link.get("protocol", DEFAULT_PROTOCOL)
vless = generate_share_link(uuid, host, remark=f"RVG-{link['label']}", protocol=proto)
content = base64.b64encode(vless.encode()).decode()
headers = build_sub_headers(link["label"], link.get("used_bytes", 0), link.get("limit_bytes", 0), link.get("expires_at"))
return Response(content=content, media_type="text/plain", headers=headers)
@app.get("/sub-all")
async def subscription_all(_=Depends(require_auth)):
host = get_host()
async with LINKS_LOCK:
allowed = [d for d in LINKS.values() if is_link_allowed(d)]
lines = [
generate_share_link(uid, host, remark=f"RVG-{d['label']}", protocol=d.get("protocol", DEFAULT_PROTOCOL))
for uid, d in LINKS.items()
if is_link_allowed(d)
]
total_used = sum(d.get("used_bytes", 0) for d in allowed)
total_limit = sum(d.get("limit_bytes", 0) for d in allowed)
expiries = [d["expires_at"] for d in allowed if d.get("expires_at")]
nearest_exp = min(expiries) if expiries else None
content = base64.b64encode("\n".join(lines).encode()).decode()
headers = build_sub_headers("RVG-All", total_used, total_limit, nearest_exp)
return Response(content=content, media_type="text/plain", headers=headers)
# ══════════════════════════════════════════════════════════════════════════════
# SUB GROUP endpoints (بدون تغییر)
# ══════════════════════════════════════════════════════════════════════════════
async def _create_sub_core(body: dict) -> dict:
name = (body.get("name") or "گروه جدید").strip()[:60]
desc = (body.get("desc") or "").strip()[:200]
password = (body.get("password") or "").strip()
sub_id = generate_uuid()
uuid_key = secrets.token_urlsafe(16)
async with SUBS_LOCK:
SUBS[sub_id] = {
"name": name,
"desc": desc,
"password_hash": hash_password(password) if password else None,
"uuid_key": uuid_key,
"created_at": datetime.now().isoformat(),
"link_ids": [],
"node_link_ids": [],
}
asyncio.create_task(save_state())
log_activity("sub", f"گروه «{name}» ساخته شد", "ok")
host = get_host()
return {
"sub_id": sub_id,
**SUBS[sub_id],
"public_url": f"https://{host}/p/{uuid_key}",
"sub_url": f"https://{host}/sub-group/{uuid_key}",
}
@app.post("/api/subs")
async def create_sub(request: Request, _=Depends(require_auth)):
body = await request.json()
return await _create_sub_core(body)
@app.post("/api/node/subs")
async def node_create_sub(request: Request, key_id: str = Depends(require_node_key)):
await _require_node_manage(key_id)
body = await request.json()
return await _create_sub_core(body)
@app.get("/api/subs")
async def list_subs(_=Depends(require_auth)):
host = get_host()
async with SUBS_LOCK:
snap_subs = dict(SUBS)
async with LINKS_LOCK:
snap_links = dict(LINKS)
result = []
for sid, s in snap_subs.items():
link_ids = s.get("link_ids", [])
node_link_ids = s.get("node_link_ids", [])
foreign_links = s.get("foreign_links", [])
active_count = sum(1 for lid in link_ids if is_link_allowed(snap_links.get(lid)))
total_used = sum(snap_links[lid].get("used_bytes", 0) for lid in link_ids if lid in snap_links)
total_used += sum(int(fl.get("used_bytes") or 0) for fl in foreign_links)
result.append({
"sub_id": sid,
**s,
"node_link_ids": node_link_ids,
"foreign_links": foreign_links,
"password_hash": None,
"has_password": s.get("password_hash") is not None,
"links_count": len(link_ids) + len(node_link_ids) + len(foreign_links),
"active_count": active_count + len(foreign_links),
"total_used_bytes": total_used,
"total_used_fmt": fmt_bytes(total_used),
"public_url": f"https://{host}/p/{s['uuid_key']}",
"sub_url": f"https://{host}/sub-group/{s['uuid_key']}",
})
result.sort(key=lambda x: x["created_at"], reverse=True)
return {"subs": result}
@app.patch("/api/subs/{sub_id}")
async def update_sub(sub_id: str, request: Request, _=Depends(require_auth)):
body = await request.json()
async with SUBS_LOCK:
if sub_id not in SUBS:
raise HTTPException(status_code=404, detail="sub not found")
s = SUBS[sub_id]
if "name" in body:
s["name"] = str(body["name"])[:60]
if "desc" in body:
s["desc"] = str(body["desc"])[:200]
if "password" in body:
pw = str(body["password"]).strip()
s["password_hash"] = hash_password(pw) if pw else None
if "link_ids" in body:
s["link_ids"] = list(body["link_ids"])
if "node_link_ids" in body:
s["node_link_ids"] = [str(x) for x in body["node_link_ids"] if "::" in str(x)]
if "foreign_links" in body:
fl = body["foreign_links"] if isinstance(body["foreign_links"], list) else []
clean = []
for it in fl:
if not isinstance(it, dict) or not it.get("vless_link"):
continue
clean.append({
"key": str(it.get("key") or "")[:120],
"label": str(it.get("label") or "کانفیگ")[:60],
"vless_link": str(it.get("vless_link"))[:2000],
"used_bytes": int(it.get("used_bytes") or 0),
"source": str(it.get("source") or "")[:60],
})
s["foreign_links"] = clean
asyncio.create_task(save_state())
return {"ok": True}
@app.delete("/api/subs/{sub_id}")
async def delete_sub(sub_id: str, _=Depends(require_auth)):
async with SUBS_LOCK:
if sub_id not in SUBS:
raise HTTPException(status_code=404, detail="sub not found")
name = SUBS[sub_id].get("name", sub_id)
del SUBS[sub_id]
async with LINKS_LOCK:
for link in LINKS.values():
if link.get("sub_id") == sub_id:
link["sub_id"] = None
asyncio.create_task(save_state())
log_activity("sub", f"گروه «{name}» حذف شد", "warn")
return {"ok": True, "deleted": sub_id}
@app.post("/api/subs/{sub_id}/links")
async def assign_link_to_sub(sub_id: str, request: Request, _=Depends(require_auth)):
body = await request.json()
link_id = str(body.get("link_id", ""))
action = str(body.get("action", "add"))
async with SUBS_LOCK:
if sub_id not in SUBS:
raise HTTPException(status_code=404, detail="sub not found")
s = SUBS[sub_id]
ids = s.setdefault("link_ids", [])
if action == "add":
if link_id not in ids:
ids.append(link_id)
else:
if link_id in ids:
ids.remove(link_id)
async with LINKS_LOCK:
if link_id in LINKS:
LINKS[link_id]["sub_id"] = sub_id if action == "add" else None
asyncio.create_task(save_state())
return {"ok": True}
# ── مدیریت گروه از راه دور (توسط پنل مرکزی روی این نود) ──────────────────────
@app.patch("/api/node/subs/{sub_id}")
async def node_update_sub(sub_id: str, request: Request, key_id: str = Depends(require_node_key)):
peer = await _require_node_manage(key_id)
result = await update_sub(sub_id, request, None)
log_activity("node", f"گروه {sub_id[:8]} از راه دور توسط «{peer}» ویرایش شد", "warn")
return result
@app.delete("/api/node/subs/{sub_id}")
async def node_delete_sub(sub_id: str, key_id: str = Depends(require_node_key)):
peer = await _require_node_manage(key_id)
result = await delete_sub(sub_id, None)
log_activity("node", f"گروه {sub_id[:8]} از راه دور توسط «{peer}» حذف شد", "err")
return result
@app.post("/api/node/subs/{sub_id}/links")
async def node_assign_link_to_sub(sub_id: str, request: Request, key_id: str = Depends(require_node_key)):
await _require_node_manage(key_id)
return await assign_link_to_sub(sub_id, request, None)
# ── Public sub-group subscription file ───────────────────────────────────────
@app.get("/sub-group/{uuid_key}")
async def sub_group_subscription(uuid_key: str, request: Request):
async with SUBS_LOCK:
sub = next((s for s in SUBS.values() if s.get("uuid_key") == uuid_key), None)
if not sub:
raise HTTPException(status_code=404, detail="not found")
if sub.get("password_hash"):
pw = request.query_params.get("pw", "")
if hash_password(pw) != sub["password_hash"]:
raise HTTPException(status_code=403, detail="wrong password")
host = get_host()
link_ids = sub.get("link_ids", [])
node_link_ids = sub.get("node_link_ids", [])
async with LINKS_LOCK:
lines = []
allowed_links = []
for lid in link_ids:
link = LINKS.get(lid)
if link and is_link_allowed(link):
lines.append(generate_share_link(lid, host, remark=f"RVG-{link['label']}", protocol=link.get("protocol", DEFAULT_PROTOCOL)))
allowed_links.append(link)
total_used = sum(l.get("used_bytes", 0) for l in allowed_links)
total_limit = sum(l.get("limit_bytes", 0) for l in allowed_links)
expiries = [l["expires_at"] for l in allowed_links if l.get("expires_at")]
if node_link_ids:
async with NODES_LOCK:
nodes_snap = {nid: dict(n) for nid, n in NODES.items()}
needed_nodes = list({ref.split("::", 1)[0] for ref in node_link_ids if "::" in ref})
needed_nodes = [nid for nid in needed_nodes if nid in nodes_snap]
snapshots = await asyncio.gather(
*(_fetch_node_snapshot(nid, nodes_snap[nid], fresh=True) for nid in needed_nodes),
return_exceptions=True,
)
snap_by_node = dict(zip(needed_nodes, snapshots))
for ref in node_link_ids:
if "::" not in ref:
continue
nid, uid = ref.split("::", 1)
snap = snap_by_node.get(nid)
if not snap or isinstance(snap, Exception):
continue
node_link = next((l for l in (snap.get("links") or []) if l.get("uuid") == uid), None)
if not node_link or not node_link.get("vless_link"):
continue
if not node_link.get("active", True):
continue
if node_link.get("expired"):
continue
lb = node_link.get("limit_bytes", 0)
if lb > 0 and node_link.get("used_bytes", 0) >= lb:
continue
lines.append(node_link["vless_link"])
total_used += node_link.get("used_bytes", 0)
total_limit += node_link.get("limit_bytes", 0)
if node_link.get("expires_at"):
expiries.append(node_link["expires_at"])
for fl in sub.get("foreign_links", []):
vl = fl.get("vless_link")
if not vl:
continue
lines.append(vl)
total_used += int(fl.get("used_bytes") or 0)
nearest_exp = min(expiries) if expiries else None
content = base64.b64encode("\n".join(lines).encode()).decode()
headers = build_sub_headers(f"پنل: {sub['name']}", total_used, total_limit, nearest_exp)
return Response(content=content, media_type="text/plain", headers=headers)
# ── Auth endpoints ────────────────────────────────────────────────────────────
@app.post("/api/login")
async def api_login(request: Request):
body = await request.json()
ip = client_ip(request)
if hash_password(str(body.get("password", ""))) != AUTH["password_hash"]:
log_activity("auth", f"تلاش ورود ناموفق از {ip}", "err")
raise HTTPException(status_code=401, detail="رمز عبور اشتباه است")
token = await create_session()