Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
9436 lines (7877 loc) · 455 KB
/
Copy pathmain.py
File metadata and controls
9436 lines (7877 loc) · 455 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
# ============================================================
# VodiWalker 15.0.0
# Railway Ready
# ============================================================
import asyncio
import ipaddress
import base64
import hashlib
import json
import logging
import os
import re
import secrets
import string
import time
import psutil
from collections import defaultdict, deque
from datetime import datetime, timedelta
from pathlib import Path
from urllib.parse import quote, parse_qs
import aiofiles
import httpx
import uvicorn
from fastapi import (
FastAPI,
Request,
HTTPException,
Depends,
)
from fastapi.responses import (
Response,
HTMLResponse,
JSONResponse,
RedirectResponse,
)
from fastapi.middleware.cors import CORSMiddleware
# ============================================================
# APP
# ============================================================
APP_NAME = "VodiWalker"
APP_VERSION = "27.3.0"
# فقط ویرایش «متنهای ربات» قفل است؛ تنظیمات و روشن/خاموش ربات آزاد است
BOT_TEXTS_LOCKED = True
BOT_TEXTS_LOCKED_MSG = "ویرایش متنهای ربات قفل شده است و امکان تغییر ندارد"
SUPPORT_USERNAME = "@VodiWalker"
CHANNEL_USERNAME = "vodiwalkervpn03"
# تنظیماتی که باید بعد از ریاستارت هم بمانند (قبلاً فقط در حافظه بودند و با هر ریاستارت پاک میشدند)
PERSISTED_EXTRA_SETTINGS = (
"sub_remark_show_name", "sub_remark_show_volume", "sub_remark_show_id", "sub_remark_show_inbound",
"sub_info_line_enabled", "sub_info_line_show_volume", "sub_info_line_show_expiry",
"support_username", "channel_username", "name_style_enabled",
"last_public_host", "last_public_scheme",
)
_TG_USER_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]{4,31}$")
def _clean_tg_username(raw) -> str:
value = str(raw or "").strip()
for prefix in ("https://t.me/", "http://t.me/", "t.me/", "https://telegram.me/", "@"):
if value.lower().startswith(prefix):
value = value[len(prefix):]
return value.strip().strip("/")
def get_support_username() -> str:
"""آیدی پشتیبان تلگرام (قابل تنظیم از داخل پنل)؛ اگر خالی باشد مقدار پیشفرض."""
raw = _clean_tg_username(CONFIG.get("support_username"))
return "@" + raw if raw and _TG_USER_RE.match(raw) else SUPPORT_USERNAME
def get_support_url() -> str:
return "https://t.me/" + get_support_username().lstrip("@")
def get_channel_url() -> str:
raw = _clean_tg_username(CONFIG.get("channel_username"))
return "https://t.me/" + (raw if raw and _TG_USER_RE.match(raw) else CHANNEL_USERNAME)
SUPPORT_URL = "https://t.me/VodiWalker"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
)
logger = logging.getLogger(APP_NAME)
# ============================================================
# TIMEZONE
# ============================================================
try:
from zoneinfo import ZoneInfo
IRAN_TZ = ZoneInfo("Asia/Tehran")
except Exception:
IRAN_TZ = None
# ============================================================
# RAILWAY
# ============================================================
PORT = int(
os.environ.get(
"PORT",
"8000",
)
)
DATA_DIR = Path(
os.environ.get(
"RAILWAY_VOLUME_MOUNT_PATH",
os.environ.get(
"DATA_DIR",
"./data",
),
)
)
DATA_DIR.mkdir(
parents=True,
exist_ok=True,
)
DATA_FILE = DATA_DIR / "vodiwalker_state.json"
SECRET_FILE = DATA_DIR / "vodiwalker_secret.key"
# ============================================================
# FASTAPI
# ============================================================
app = FastAPI(
title=APP_NAME,
version=APP_VERSION,
docs_url=None,
redoc_url=None,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================
# LOCKS
# ============================================================
SAVE_LOCK = asyncio.Lock()
LINKS_LOCK = asyncio.Lock()
SUBS_LOCK = asyncio.Lock()
SESSIONS_LOCK = asyncio.Lock()
# ============================================================
# SECRET
# ============================================================
def load_or_create_secret() -> str:
env_secret = os.environ.get("SECRET_KEY")
if env_secret:
return env_secret
try:
if SECRET_FILE.exists():
existing = (
SECRET_FILE
.read_text(
encoding="utf-8"
)
.strip()
)
if existing:
return existing
generated = secrets.token_urlsafe(48)
SECRET_FILE.write_text(
generated,
encoding="utf-8",
)
return generated
except Exception as exc:
logger.warning(
"Could not persist SECRET_KEY: %s",
exc,
)
return secrets.token_urlsafe(48)
SECRET_KEY = load_or_create_secret()
# ============================================================
# CONFIG
# ============================================================
CONFIG = {
"port": PORT,
"secret": SECRET_KEY,
"host": os.environ.get(
"RAILWAY_PUBLIC_DOMAIN",
"localhost",
),
"tcp_public_host": os.environ.get("TCP_PUBLIC_HOST", "").strip(),
"tcp_public_port": os.environ.get("TCP_PUBLIC_PORT", "").strip(),
}
# ============================================================
# STATE
# ============================================================
LINKS: dict = {}
SUBS: dict = {}
# Per-subscription live usage samples. Values come from the real link used_bytes field.
SUB_USAGE_HISTORY = defaultdict(lambda: deque(maxlen=144))
USAGE_PERSIST_TASK = None
SESSIONS: dict = {}
connections: dict = {}
CATEGORIES: dict = {}
DAILY_STATS: dict = {} # "YYYY-MM-DD" -> {"traffic_bytes":.., "new_links":.., "orders":.., "stars":..}
DAILY_STATS_LOCK = asyncio.Lock()
def _today_key() -> str:
now = datetime.now(IRAN_TZ) if IRAN_TZ else datetime.now()
return now.strftime("%Y-%m-%d")
def bump_daily_stat(field: str, amount=1):
"""Increment a counter in today's reporting bucket (best-effort, in-memory)."""
try:
key = _today_key()
bucket = DAILY_STATS.setdefault(
key, {"traffic_bytes": 0, "new_links": 0, "orders": 0, "stars": 0}
)
bucket[field] = bucket.get(field, 0) + amount
# keep only the last 180 days to avoid unbounded growth
if len(DAILY_STATS) > 180:
for old_key in sorted(DAILY_STATS.keys())[: len(DAILY_STATS) - 180]:
DAILY_STATS.pop(old_key, None)
except Exception:
pass
stats = {
"total_bytes": 0,
"total_requests": 0,
"total_errors": 0,
"start_time": time.time(),
}
_telemetry_lock = asyncio.Lock()
_telemetry_prev = {"ts": time.time(), "rx": 0, "tx": 0}
def _pct(v):
try:
return round(float(v), 1)
except Exception:
return 0.0
def _human_uptime(seconds):
seconds = max(0, int(seconds))
days, rem = divmod(seconds, 86400)
hours, rem = divmod(rem, 3600)
minutes, secs = divmod(rem, 60)
if days:
return f"{days}d {hours:02d}:{minutes:02d}"
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
error_logs = deque(maxlen=100)
activity_logs = deque(maxlen=250)
hourly_traffic = defaultdict(int)
# Real server telemetry samples used by the dashboard charts.
# Samples are collected from psutil; no placeholder/synthetic values are generated.
TELEMETRY_HISTORY = deque(maxlen=90)
http_client: httpx.AsyncClient | None = None
# ============================================================
# PROTOCOL
# ============================================================
PROTOCOLS = (
"vless-ws",
"vless-tcp",
"xhttp-packet-up",
"xhttp-stream-up",
"xhttp-stream-one",
"vmess-ws",
"trojan-ws",
)
# این پروتکلها روی همان پورت HTTP/WebSocket برنامه (پشت TLS ریورسپروکسی یا Railway)
# سرو میشن و واقعاً روی سرور پیادهسازی شدهن.
REAL_TRANSPORT_PROTOCOLS = {
"vless-ws", "xhttp-packet-up", "xhttp-stream-up",
}
# vless-tcp هم واقعی و پیادهسازیشدهست ولی روی یک پورت TCP خام و جداگانه
# (بهصورت پیشفرض 6543، قابل تغییر با TCP_LISTEN_PORT) — نه پورت HTTP اصلی.
REAL_RAW_TCP_PROTOCOLS = {"vless-tcp"}
# همهی پروتکلهای دمو/غیرفعال از پنل حذف شدهاند — هر چیزی که در PROTOCOLS باشد واقعاً کار میکند.
NON_FUNCTIONAL_DEMO_PROTOCOLS = {"vmess-ws", "trojan-ws"}
# Protocols that this project actually serves itself. VMess/Trojan entries may
# still be generated as client-side links, but they are NOT advertised as live
# listeners because this backend has no VMess/Trojan inbound parser.
LIVE_PROTOCOLS = REAL_TRANSPORT_PROTOCOLS | REAL_RAW_TCP_PROTOCOLS
PROTOCOL_LABELS = {
"vless-ws": "VLESS WebSocket",
"vless-tcp": "VLESS TCP (خام)",
"xhttp-packet-up": "XHTTP Packet Up",
"xhttp-stream-up": "XHTTP Stream Up",
"xhttp-stream-one": "XHTTP Stream One",
"vmess-ws": "VMess WebSocket",
"trojan-ws": "Trojan WebSocket",
"manual": "پروتکل دستی (سفارشی)",
}
PROTOCOL_ALIASES = {
"vmess": "vmess-ws", "trojan": "trojan-ws", "ss": "shadowsocks",
"socks": "socks5", "hy2": "hysteria2", "hysteria": "hysteria2",
}
DEFAULT_PROTOCOL = "vless-ws"
# نگاشت هر پروتکل غیر-دستی (manual) به Network/Security واقعیای که در لینک
# نهایی (generate_vless_link) استفاده میشود. این فقط برای نمایش صحیح در پنل
# است (تگهای "ws/tls" و ...)؛ چون قبلاً این مقادیر همیشه روی مقدار پیشفرض
# فیلدهای دستی (tcp/none) میافتادند، حتی برای پروتکلهایی که واقعاً ws+tls بودند.
PROTOCOL_NETWORK_SECURITY = {
"vless-ws": ("ws", "tls"),
"vless-tcp": ("tcp", "none"),
"xhttp-packet-up": ("xhttp", "tls"),
"xhttp-stream-up": ("xhttp", "tls"),
"xhttp-stream-one": ("xhttp", "tls"),
"vmess-ws": ("ws", "tls"),
"trojan-ws": ("ws", "tls"),
}
FINGERPRINTS = (
"chrome",
"firefox",
"safari",
"ios",
"android",
"edge",
"360",
"qq",
"random",
"randomized",
)
DEFAULT_FINGERPRINT = "chrome"
DEFAULT_ALPN_BY_PROTOCOL = {
"vless-ws": "http/1.1",
"xhttp-packet-up": "h2,http/1.1",
"xhttp-stream-up": "h2,http/1.1",
"xhttp-stream-one": "h2,http/1.1",
}
DEFAULT_PORT = 443
MIN_PORT = 1
MAX_PORT = 65535
DEFAULT_SPEED_LIMIT = 0
# ============================================================
# MANUAL PROTOCOL BUILDER (پروتکل دستی — مثل پنلهای 3x-ui/Sanaei)
# ============================================================
MANUAL_BASE_PROTOCOLS = ("vless", "vmess", "trojan", "shadowsocks")
MANUAL_BASE_PROTOCOL_LABELS = {
"vless": "VLESS",
"vmess": "VMess",
"trojan": "Trojan",
"shadowsocks": "Shadowsocks",
}
NETWORKS = ("tcp", "ws", "grpc", "xhttp")
NETWORK_LABELS = {
"tcp": "TCP",
"ws": "WebSocket (ws)",
"grpc": "gRPC",
"xhttp": "XHTTP",
}
SECURITIES = ("none", "tls", "reality")
SECURITY_LABELS = {
"none": "بدون امنیت (None)",
"tls": "TLS",
"reality": "Reality",
}
XHTTP_MODES = ("auto", "packet-up", "stream-up", "stream-one")
SHADOWSOCKS_METHODS = ("chacha20-ietf-poly1305", "aes-128-gcm", "aes-256-gcm", "2022-blake3-aes-128-gcm", "2022-blake3-aes-256-gcm")
# ترکیبهایی که همین پنل واقعاً بهصورت زنده سرو میکند (بدون نیاز به Xray-core
# جداگانه). سایر ترکیبها (مثل هر چیزی با Reality) فقط لینک/کانفیگ برای استفاده
# روی یک نود Xray-core واقعی میسازند و به همین دلیل در پنل با یک نشان
# «فقط ساخت لینک» مشخص میشوند — این محدودیت صادقانه در UI نشان داده میشود.
MANUAL_LIVE_COMBOS = {
("ws", "tls"),
("ws", "none"),
("xhttp", "tls"),
("xhttp", "none"),
("tcp", "none"),
}
def normalize_protocol(protocol: str | None) -> str:
value = str(protocol or DEFAULT_PROTOCOL).strip().lower()
value = PROTOCOL_ALIASES.get(value, value)
if value == "manual":
return value
return value if value in PROTOCOLS else DEFAULT_PROTOCOL
def normalize_network(network: str | None) -> str:
value = str(network or "tcp").strip().lower()
return value if value in NETWORKS else "tcp"
def normalize_security(security: str | None) -> str:
value = str(security or "none").strip().lower()
return value if value in SECURITIES else "none"
def normalize_xhttp_mode(mode: str | None) -> str:
value = str(mode or "auto").strip().lower()
return value if value in XHTTP_MODES else "auto"
def normalize_base_protocol(value: str | None) -> str:
v = str(value or "vless").strip().lower()
return v if v in MANUAL_BASE_PROTOCOLS else "vless"
def protocol_display_label(link: dict) -> str:
"""برچسب نمایشی پروتکل برای جدولها و گزارشها.
برای کانفیگهای دستی بهصورت «VLESS · WebSocket · TLS» نمایش داده میشود."""
protocol = link.get("protocol", DEFAULT_PROTOCOL)
if protocol != "manual":
return PROTOCOL_LABELS.get(protocol, protocol)
base = MANUAL_BASE_PROTOCOL_LABELS.get(normalize_base_protocol(link.get("base_protocol")), "VLESS")
network = NETWORK_LABELS.get(normalize_network(link.get("network")), "TCP")
security = SECURITY_LABELS.get(normalize_security(link.get("security")), "بدون امنیت")
if base == "Shadowsocks":
return f"Shadowsocks · {network}"
return f"{base} · {network} · {security}"
# ============================================================
# LOGGING
# ============================================================
def log_activity(
kind: str,
message: str,
level: str = "info",
):
activity_logs.append(
{
"kind": kind,
"level": level,
"message": message,
"time": datetime.now().isoformat(),
}
)
# ============================================================
# HELPERS
# ============================================================
def escape_html(value) -> str:
return (
str(
value
if value is not None
else ""
)
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
def safe_int(
value,
default=0,
minimum=0,
maximum=None,
):
try:
number = int(value)
except Exception:
number = default
if number < minimum:
number = minimum
if maximum is not None and number > maximum:
number = maximum
return number
def safe_float(
value,
default=0.0,
minimum=0.0,
):
try:
number = float(value)
except Exception:
number = default
return max(
minimum,
number,
)
def generate_uuid():
value = secrets.token_hex(16)
return (
f"{value[:8]}-"
f"{value[8:12]}-"
f"{value[12:16]}-"
f"{value[16:20]}-"
f"{value[20:32]}"
)
def random_config_name(existing=None):
existing = existing or set()
alphabet = string.ascii_lowercase + string.digits
for _ in range(80):
length = secrets.randbelow(6) + 8
name = "".join(secrets.choice(alphabet) for _ in range(length))
if name not in existing and name and not name[0].isdigit():
return name
return secrets.token_hex(6)
def sanitize_config_name(name: str) -> str:
if not name:
return random_config_name()
cleaned = "".join(ch for ch in str(name) if ch.isascii() and ch.isalnum())
if not cleaned or cleaned[0].isdigit():
cleaned = ("a" + cleaned) if cleaned else random_config_name()
return cleaned[:40]
def auto_config_name() -> str:
return random_config_name()
def now_ir():
if IRAN_TZ:
return datetime.now(IRAN_TZ)
return datetime.now()
def uptime():
seconds = int(
time.time()
- stats["start_time"]
)
h = seconds // 3600
m = (
seconds
% 3600
) // 60
s = (
seconds
% 60
)
return (
f"{h:02d}:"
f"{m:02d}:"
f"{s:02d}"
)
def fmt_bytes(value: int):
value = int(
value or 0
)
if value < 1024:
return f"{value} B"
if value < 1024 ** 2:
return (
f"{value / 1024:.1f} KB"
)
if value < 1024 ** 3:
return (
f"{value / 1024 ** 2:.2f} MB"
)
return (
f"{value / 1024 ** 3:.2f} GB"
)
def parse_size_to_bytes(
value: float,
unit: str,
):
if value <= 0:
return 0
unit = (
unit
or "GB"
).upper()
if unit == "TB":
return int(
value
* 1024 ** 4
)
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 parse_speed_to_bytes(
value: float,
unit: str,
):
if value <= 0:
return 0
unit = (
unit
or "MBIT"
).upper()
if unit == "MBIT":
return int(
value
* 1024
* 1024
/ 8
)
if unit == "KB":
return int(
value * 1024
)
if unit == "MB":
return int(
value
* 1024
* 1024
)
return int(value)
def is_link_expired(
link: dict,
):
expiry = link.get(
"expires_at"
)
if not expiry:
return False
try:
return (
datetime.now()
> datetime.fromisoformat(
expiry
)
)
except Exception:
return False
def is_link_allowed(
link: dict | None,
):
if link is None:
return False
if not link.get(
"active",
True,
):
return False
if is_link_expired(link):
return False
limit = int(
link.get(
"limit_bytes",
0,
)
or 0
)
used = int(
link.get(
"used_bytes",
0,
)
or 0
)
if (
limit > 0
and used >= limit
):
return False
return True
def unique_ips_for_uuid(
uuid: str,
):
return {
connection.get("ip")
for connection in connections.values()
if connection.get("uuid") == uuid
and connection.get("ip")
}
def client_ip(
request: Request,
):
forwarded = request.headers.get(
"x-forwarded-for"
)
if forwarded:
return (
forwarded
.split(",")[0]
.strip()
)
real = request.headers.get(
"x-real-ip"
)
if real:
return real.strip()
if request.client:
return request.client.host
return "unknown"
def is_ip_allowed(
link: dict | None,
uuid: str,
ip: str,
):
if link is None:
return False
limit = int(
link.get(
"ip_limit",
0,
)
or 0
)
if limit <= 0:
return True
ips = unique_ips_for_uuid(uuid)
if ip in ips:
return True
return len(ips) < limit
def _split_base_url(raw: str):
"""آدرس عمومی ذخیرهشده رو به (scheme, host) تجزیه میکنه. ورودی میتونه
با یا بدون scheme باشه (مثلاً 'panel.example.com' یا 'https://panel.example.com')."""
raw = (raw or "").strip()
if not raw:
return None, None
scheme = "https"
rest = raw
if "://" in raw:
scheme, rest = raw.split("://", 1)
scheme = scheme.strip().lower() or "https"
host = rest.split("/", 1)[0].split(":")[0].strip()
return (scheme if scheme in ("http", "https") else "https"), (host or None)
_DOMAIN_RE = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$")
def _is_real_public_host(host) -> bool:
"""True فقط برای دامنه/آیپی عمومی واقعی؛ localhost / 0.0.0.0 / آیپی خصوصی / آدرس داخلی ریلوی → False."""
h = str(host or "").strip().lower().strip("[]")
if not h or h in ("localhost", "0.0.0.0", "::", "::1"):
return False
if h.endswith((".local", ".internal", ".localhost", ".lan")):
return False
try:
return ipaddress.ip_address(h).is_global
except ValueError:
pass
return bool(_DOMAIN_RE.match(h))
def _request_public_host(request) -> str | None:
try:
raw = request.headers.get("x-forwarded-host") or request.headers.get("host") or ""
host = raw.split(",")[0].split(":")[0].strip().lower()
return host if _is_real_public_host(host) else None
except Exception:
return None
def remember_public_host(request) -> None:
"""آدرس واقعی پنل را از اولین درخواست ادمینِ واردشده به خاطر میسپارد (برای ربات و لینکهایی که بدون درخواست ساخته میشوند)."""
try:
host = _request_public_host(request)
if not host:
return
proto = (request.headers.get("x-forwarded-proto") or request.url.scheme or "https").split(",")[0].strip().lower()
if proto not in ("http", "https"):
proto = "https"
if CONFIG.get("last_public_host") != host or CONFIG.get("last_public_scheme") != proto:
CONFIG["last_public_host"] = host
CONFIG["last_public_scheme"] = proto
asyncio.get_running_loop().create_task(save_state())
except Exception:
pass
def get_public_host_strict(request=None) -> str | None:
"""آدرس واقعی و قابلاتصال پنل؛ اگر هیچ آدرس معتبری پیدا نشود None (هرگز localhost/0.0.0.0 نمیدهد)."""
_, override = _split_base_url(CONFIG.get("public_base_url"))
if override and _is_real_public_host(override):
return override
if request is not None:
host = _request_public_host(request)
if host:
return host
env_domain = os.environ.get("RAILWAY_PUBLIC_DOMAIN", "").strip()
if _is_real_public_host(env_domain):
return env_domain
last = str(CONFIG.get("last_public_host") or "").strip()
if _is_real_public_host(last):
return last
cfg_host = str(CONFIG.get("host") or "").strip()
if _is_real_public_host(cfg_host):
return cfg_host
return None
def get_public_base(request=None) -> str | None:
host = get_public_host_strict(request)
if not host:
return None
_, override = _split_base_url(CONFIG.get("public_base_url"))
scheme = get_scheme() if override else (CONFIG.get("last_public_scheme") or "https")
return f"{scheme}://{host}"
def get_host(
request: Request | None = None,
) -> str:
# اولویت اول: آدرس عمومی صریحی که در تنظیمات پنل ثبت شده (پایدار، مستقل از
# اینکه درخواست از کجا اومده — پروکسی، آیپی داخلی، هلثچک و ...).
_, override_host = _split_base_url(CONFIG.get("public_base_url"))
if override_host:
return override_host
if request is not None:
forwarded = request.headers.get(
"x-forwarded-host"
)
normal = request.headers.get(
"host"
)
host = (
forwarded
or normal
)
if host:
# توجه: دیگه CONFIG["host"] رو اینجا آپدیت نمیکنیم؛ این یک متغیر سراسری
# مشترک بین همهی درخواستها بود و هر درخواست با Host نادرست (هلثچک،
# اسکنر، وبهوک) میتونست لینکهای بعدیِ همه رو خراب کنه.
return host.split(":")[0].strip()
railway_domain = os.environ.get(
"RAILWAY_PUBLIC_DOMAIN"
)
if railway_domain:
return railway_domain
# بدون درخواست (مثلاً ربات تلگرام): آدرس واقعیِ ذخیرهشده؛ نه localhost فیک
return get_public_host_strict() or CONFIG["host"]
def get_scheme() -> str:
"""scheme (http/https) که باید برای ساخت لینکهای ساب استفاده بشه."""
scheme, host = _split_base_url(CONFIG.get("public_base_url"))
if host:
return scheme
return "https"
def _tcp_listen_port_snapshot() -> int:
try:
import tcp_relay
return tcp_relay.TCP_LISTEN_PORT
except Exception:
return int(os.environ.get("TCP_LISTEN_PORT", "6543"))
def _bot_settings_snapshot() -> dict:
"""وضعیت فعلی ربات تلگرام رو برمیگردونه؛ اگه ماژول ربات هنوز ایمپورت نشده
یا مشکلی داشته باشه، مقدار خالی/امن برمیگردونه (این نباید کل پنل رو خراب کنه)."""
try:
import telegram_bot
return telegram_bot.current_config()