File size: 79,124 Bytes
9e79329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4c7f5f
9e79329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
import asyncio
import base64
import hashlib
import hmac
import json
import os
import platform
import secrets
import socket
import subprocess
import time
import threading
import urllib.error
import urllib.request
import uuid
import zipfile
from contextlib import asynccontextmanager
from pathlib import Path
from typing import AsyncIterator
from urllib.parse import quote, urlencode

try:
    import spaces
except ImportError:
    spaces = None

if spaces is not None:
    @spaces.GPU(duration=1)
    def _zerogpu_startup_probe():
        return None

import httpx
try:
    import qrcode
    from io import BytesIO
except ImportError:
    qrcode = None
    BytesIO = None
from fastapi import FastAPI, Form, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, PlainTextResponse, StreamingResponse
from starlette.background import BackgroundTask

# -----------------------------------------------------------------------------
# Runtime / performance tuning
# -----------------------------------------------------------------------------
XRAY_VERSION = os.getenv("XRAY_VERSION", "26.10.21")
SESSION_TTL = max(300, int(os.getenv("SESSION_TTL", "43200")))
PUBLIC_PORT = int(os.getenv("PORT", "7860"))
PANEL_PORT = int(os.getenv("PANEL_PORT", "7861"))

# First-run state. Default Space disk is ephemeral; prefer /data when a persistent
# Storage Bucket is attached, otherwise fall back to /tmp.
def _choose_state_dir() -> Path:
    override = os.getenv("HF_RVG_STATE_DIR", "").strip()
    candidates = [Path(override)] if override else [Path("/data/hf-rvg"), Path("/tmp/hf-rvg")]
    for candidate in candidates:
        try:
            candidate.mkdir(parents=True, exist_ok=True)
            test = candidate / ".write-test"
            test.write_text("ok", encoding="utf-8")
            test.unlink(missing_ok=True)
            return candidate
        except OSError:
            continue
    raise RuntimeError("No writable state directory is available")

STATE_DIR = _choose_state_dir()
STATE_FILE = STATE_DIR / "state.json"
STATE_LOCK = threading.RLock()
PBKDF2_ITERATIONS = max(200_000, int(os.getenv("PBKDF2_ITERATIONS", "310000")))

# Keep logs quiet in production; proxy traffic is I/O heavy and log I/O hurts throughput.
XRAY_LOGLEVEL = os.getenv("XRAY_LOGLEVEL", "warning")

# TCP socket settings. These are safe Linux defaults and can be disabled with 0.
TCP_KEEPALIVE_IDLE = max(0, int(os.getenv("TCP_KEEPALIVE_IDLE", "60")))
TCP_KEEPALIVE_INTERVAL = max(0, int(os.getenv("TCP_KEEPALIVE_INTERVAL", "20")))
TCP_KEEPALIVE_COUNT = max(0, int(os.getenv("TCP_KEEPALIVE_COUNT", "3")))

# Bridge buffering: avoid writer.drain() on every websocket frame, while keeping a
# bounded amount of user-space buffering per connection.
BRIDGE_DRAIN_BYTES = max(64 * 1024, int(os.getenv("BRIDGE_DRAIN_BYTES", str(1024 * 1024))))
BRIDGE_READ_BYTES = max(64 * 1024, int(os.getenv("BRIDGE_READ_BYTES", str(2 * 1024 * 1024))))
BRIDGE_SOCKET_BUFFER = max(256 * 1024, int(os.getenv("BRIDGE_SOCKET_BUFFER", str(4 * 1024 * 1024))))
BRIDGE_WRITE_HIGH_WATER = max(BRIDGE_SOCKET_BUFFER, int(os.getenv("BRIDGE_WRITE_HIGH_WATER", str(8 * 1024 * 1024))))
BRIDGE_WRITE_LOW_WATER = max(64 * 1024, int(os.getenv("BRIDGE_WRITE_LOW_WATER", str(2 * 1024 * 1024))))

# HTTP pool is used only by the XHTTP ASGI bridge.
HTTP_MAX_CONNECTIONS = max(64, int(os.getenv("HTTP_MAX_CONNECTIONS", "512")))
HTTP_MAX_KEEPALIVE = max(32, int(os.getenv("HTTP_MAX_KEEPALIVE", "256")))
HTTP_KEEPALIVE_EXPIRY = max(5.0, float(os.getenv("HTTP_KEEPALIVE_EXPIRY", "30")))

# On a Space with 2 vCPU, a single asyncio/Uvicorn process is preferable. Multiple
# workers would each try to start a separate Xray instance and waste resources.
UVICORN_BACKLOG = max(128, int(os.getenv("UVICORN_BACKLOG", "2048")))
WS_MAX_QUEUE = max(1, int(os.getenv("WS_MAX_QUEUE", "64")))
WS_PING_INTERVAL = max(5.0, float(os.getenv("WS_PING_INTERVAL", "20")))
WS_PING_TIMEOUT = max(5.0, float(os.getenv("WS_PING_TIMEOUT", "20")))

# Automatic Xray recovery.
XRAY_RESTART = os.getenv("XRAY_RESTART", "1") not in {"0", "false", "False", "no"}
XRAY_RESTART_MIN = max(0.5, float(os.getenv("XRAY_RESTART_MIN", "1.0")))
XRAY_RESTART_MAX = max(XRAY_RESTART_MIN, float(os.getenv("XRAY_RESTART_MAX", "30.0")))

WS_VLESS_PATH = os.getenv("WS_VLESS_PATH", "/ws/vless")
WS_TROJAN_PATH = os.getenv("WS_TROJAN_PATH", "/ws/trojan")
WS_VMESS_PATH = os.getenv("WS_VMESS_PATH", "/ws/vmess")
XHTTP_VLESS_PATH = os.getenv("XHTTP_VLESS_PATH", "/xhttp/vless")
XHTTP_TROJAN_PATH = os.getenv("XHTTP_TROJAN_PATH", "/xhttp/trojan")
XHTTP_VMESS_PATH = os.getenv("XHTTP_VMESS_PATH", "/xhttp/vmess")
XHTTP_PACKET_VLESS_PATH = os.getenv("XHTTP_PACKET_VLESS_PATH", "/xhttp/packet/vless")
XHTTP_PACKET_TROJAN_PATH = os.getenv("XHTTP_PACKET_TROJAN_PATH", "/xhttp/packet/trojan")
XHTTP_PACKET_VMESS_PATH = os.getenv("XHTTP_PACKET_VMESS_PATH", "/xhttp/packet/vmess")

WORKDIR = Path("/tmp/hf-rvg")
XRAY_BIN = WORKDIR / "xray"
XRAY_CFG = WORKDIR / "config.json"
XRAY_PROC: asyncio.subprocess.Process | None = None
XRAY_MONITOR_TASK: asyncio.Task | None = None
HTTP_CLIENT: httpx.AsyncClient | None = None
XRAY_LOCK = asyncio.Lock()

# Public traffic terminates at the Hugging Face HTTP frontend. Nginx forwards
# WebSocket/XHTTP bytes directly to Xray so Python is not in the data path.
NGINX_CFG = WORKDIR / "nginx.conf"
NGINX_PREFIX = WORKDIR / "nginx"
NGINX_PROC: asyncio.subprocess.Process | None = None
PANEL_PROC: asyncio.subprocess.Process | None = None

PROFILES = {
    "vless-ws": {"label": "VLESS · WebSocket + TLS", "protocol": "vless", "transport": "ws", "path": WS_VLESS_PATH, "port": 10086},
    "trojan-ws": {"label": "Trojan · WebSocket + TLS", "protocol": "trojan", "transport": "ws", "path": WS_TROJAN_PATH, "port": 10087},
    "vmess-ws": {"label": "VMess · WebSocket + TLS", "protocol": "vmess", "transport": "ws", "path": WS_VMESS_PATH, "port": 10088},
    "vless-xhttp": {"label": "VLESS · XHTTP auto + TLS", "protocol": "vless", "transport": "xhttp", "mode": "auto", "path": XHTTP_VLESS_PATH, "port": 10089},
    "trojan-xhttp": {"label": "Trojan · XHTTP auto + TLS", "protocol": "trojan", "transport": "xhttp", "mode": "auto", "path": XHTTP_TROJAN_PATH, "port": 10090},
    "vmess-xhttp": {"label": "VMess · XHTTP auto + TLS", "protocol": "vmess", "transport": "xhttp", "mode": "auto", "path": XHTTP_VMESS_PATH, "port": 10091},
    "vless-packet-up": {"label": "VLESS · XHTTP packet-up + TLS", "protocol": "vless", "transport": "xhttp", "mode": "packet-up", "path": XHTTP_PACKET_VLESS_PATH, "port": 10092},
    "trojan-packet-up": {"label": "Trojan · XHTTP packet-up + TLS", "protocol": "trojan", "transport": "xhttp", "mode": "packet-up", "path": XHTTP_PACKET_TROJAN_PATH, "port": 10093},
    "vmess-packet-up": {"label": "VMess · XHTTP packet-up + TLS", "protocol": "vmess", "transport": "xhttp", "mode": "packet-up", "path": XHTTP_PACKET_VMESS_PATH, "port": 10094},
    "vless-xhttp-split": {"label": "VLESS · XHTTP split download + TLS", "protocol": "vless", "transport": "xhttp", "mode": "packet-up", "split_download": True, "path": XHTTP_PACKET_VLESS_PATH, "port": 10092},
    "trojan-xhttp-split": {"label": "Trojan · XHTTP split download + TLS", "protocol": "trojan", "transport": "xhttp", "mode": "packet-up", "split_download": True, "path": XHTTP_PACKET_TROJAN_PATH, "port": 10093},
    "vmess-xhttp-split": {"label": "VMess · XHTTP split download + TLS", "protocol": "vmess", "transport": "xhttp", "mode": "packet-up", "split_download": True, "path": XHTTP_PACKET_VMESS_PATH, "port": 10094},
}

XHTTP_PROFILE_BY_PATH = {v["path"]: v for v in PROFILES.values() if v["transport"] == "xhttp"}


def xray_asset() -> str:
    machine = platform.machine().lower()
    if machine in {"x86_64", "amd64"}:
        return "Xray-linux-64.zip"
    if machine in {"aarch64", "arm64"}:
        return "Xray-linux-arm64-v8a.zip"
    raise RuntimeError(f"Unsupported CPU architecture: {machine}")


def download_xray() -> None:
    """Download Xray atomically with retries so a transient GitHub failure does not kill startup."""
    WORKDIR.mkdir(parents=True, exist_ok=True)
    if XRAY_BIN.exists() and XRAY_BIN.stat().st_size > 1024 * 1024:
        return

    asset = xray_asset()
    url = f"https://github.com/XTLS/Xray-core/releases/download/v{XRAY_VERSION}/{asset}"
    archive = WORKDIR / asset
    partial = WORKDIR / f"{asset}.part"
    attempts = max(1, int(os.getenv("XRAY_DOWNLOAD_RETRIES", "4")))
    timeout = max(10, int(os.getenv("XRAY_DOWNLOAD_TIMEOUT", "45")))

    last_error: Exception | None = None
    for attempt in range(1, attempts + 1):
        try:
            print(f"Downloading Xray {XRAY_VERSION} (attempt {attempt}/{attempts})", flush=True)
            req = urllib.request.Request(url, headers={"User-Agent": "hf-rvg-gateway/1.0"})
            with urllib.request.urlopen(req, timeout=timeout) as src, open(partial, "wb") as dst:
                while True:
                    chunk = src.read(1024 * 1024)
                    if not chunk:
                        break
                    dst.write(chunk)
            partial.replace(archive)
            with zipfile.ZipFile(archive) as zf:
                member = next((n for n in zf.namelist() if n.endswith("/xray") or n == "xray"), None)
                if not member:
                    raise RuntimeError("Xray executable not found in release archive")
                data = zf.read(member)
            tmp_bin = WORKDIR / "xray.new"
            tmp_bin.write_bytes(data)
            tmp_bin.chmod(0o755)
            tmp_bin.replace(XRAY_BIN)
            archive.unlink(missing_ok=True)
            print(f"Xray {XRAY_VERSION} downloaded and cached", flush=True)
            return
        except (OSError, urllib.error.URLError, zipfile.BadZipFile, RuntimeError) as exc:
            last_error = exc
            partial.unlink(missing_ok=True)
            if attempt < attempts:
                delay = min(2 ** (attempt - 1), 8)
                print(f"Xray download failed: {exc}; retrying in {delay}s", flush=True)
                time.sleep(delay)

    raise RuntimeError(f"Unable to download Xray after {attempts} attempts: {last_error}")


def _kernel_supports_bbr() -> bool:
    if platform.system().lower() != "linux":
        return False
    candidates = []
    for filename in (
        "/proc/sys/net/ipv4/tcp_available_congestion_control",
        "/proc/sys/net/ipv4/tcp_allowed_congestion_control",
    ):
        try:
            candidates.extend(Path(filename).read_text(encoding="utf-8").split())
        except OSError:
            pass
    return "bbr" in candidates


def _kernel_supports_tfo_client() -> bool:
    if platform.system().lower() != "linux":
        return False
    try:
        value = int(Path("/proc/sys/net/ipv4/tcp_fastopen").read_text(encoding="utf-8").strip())
        return bool(value & 0x1)
    except (OSError, ValueError):
        return False


def _sockopt_defaults() -> dict:
    # Only request kernel features that this particular Space can actually provide.
    # For AsIs, Go's TCP dialer already provides Happy Eyeballs.
    sockopt = {
        "domainStrategy": "AsIs",
        "tcpKeepAliveIdle": TCP_KEEPALIVE_IDLE,
        "tcpKeepAliveInterval": TCP_KEEPALIVE_INTERVAL,
        "tcpUserTimeout": 60000,
    }
    if _kernel_supports_bbr():
        sockopt["tcpcongestion"] = "bbr"
    if _kernel_supports_tfo_client():
        sockopt["tcpFastOpen"] = True
    return sockopt


def _atomic_write_json(path: Path, payload: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    try:
        os.chmod(tmp, 0o600)
    except OSError:
        pass
    tmp.replace(path)


def _read_state() -> dict:
    with STATE_LOCK:
        if not STATE_FILE.exists():
            return {}
        try:
            return json.loads(STATE_FILE.read_text(encoding="utf-8"))
        except (OSError, ValueError, TypeError):
            return {}



def _ensure_credentials() -> dict:
    """Load credentials from env/state or create strong random ones once."""
    state = _read_state()
    saved = state.get("credentials") if isinstance(state, dict) else None
    if not isinstance(saved, dict):
        saved = {}

    generated = {
        "vless_uuid": str(saved.get("vless_uuid") or uuid.uuid4()),
        "vmess_uuid": str(saved.get("vmess_uuid") or uuid.uuid4()),
        "trojan_password": str(saved.get("trojan_password") or secrets.token_urlsafe(32)),
    }

    state = state if isinstance(state, dict) else {}
    state.setdefault("version", 2)
    state.setdefault("created_at", int(time.time()))
    state["credentials"] = generated
    with STATE_LOCK:
        _atomic_write_json(STATE_FILE, state)
    return generated


CREDENTIALS = _ensure_credentials()
VLESS_UUID = CREDENTIALS["vless_uuid"]
VMESS_UUID = CREDENTIALS["vmess_uuid"]
TROJAN_PASSWORD = CREDENTIALS["trojan_password"]


def _hash_password(password: str, salt: bytes | None = None) -> tuple[str, str]:
    if salt is None:
        salt = secrets.token_bytes(16)
    digest = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS, dklen=32
    )
    return (
        base64.urlsafe_b64encode(salt).decode("ascii"),
        base64.urlsafe_b64encode(digest).decode("ascii"),
    )


def _password_record() -> dict:
    state = _read_state()
    if not isinstance(state, dict):
        return {}
    value = state.get("panel")
    return value if isinstance(value, dict) else {}


def _panel_is_configured() -> bool:
    return bool(_password_record().get("hash"))


def _verify_panel_password(password: str) -> bool:
    record = _password_record()
    try:
        salt = base64.urlsafe_b64decode(str(record["salt"]).encode("ascii"))
        expected = base64.urlsafe_b64decode(str(record["hash"]).encode("ascii"))
        iterations = int(record.get("iterations", PBKDF2_ITERATIONS))
    except (KeyError, ValueError, TypeError, base64.binascii.Error):
        return False
    actual = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf-8"), salt, max(200_000, iterations), dklen=32
    )
    return hmac.compare_digest(actual, expected)


def _set_panel_password(password: str) -> None:
    salt_b64, hash_b64 = _hash_password(password)
    state = _read_state()
    if not isinstance(state, dict):
        state = {}
    state["version"] = 2
    state["panel"] = {
        "salt": salt_b64,
        "hash": hash_b64,
        "iterations": PBKDF2_ITERATIONS,
    }
    state["credentials"] = CREDENTIALS
    state.setdefault("created_at", int(time.time()))
    with STATE_LOCK:
        _atomic_write_json(STATE_FILE, state)


def _auth_secret() -> bytes:
    record = _password_record()
    try:
        return base64.urlsafe_b64decode(str(record["hash"]).encode("ascii"))
    except (KeyError, ValueError, TypeError, base64.binascii.Error):
        return b"hf-rvg-unconfigured-auth-secret"


def _same_origin(request: Request) -> bool:
    # Hugging Face terminates TLS at its frontend, so the ASGI app may see
    # an internal HTTP scheme while the browser sends an HTTPS Origin.
    # Compare normalized external host + scheme instead of the backend URL.
    origin = request.headers.get("origin")
    if not origin or origin.lower() == "null":
        return True

    from urllib.parse import urlsplit

    origin_parts = urlsplit(origin)
    if origin_parts.scheme not in {"http", "https"} or not origin_parts.hostname:
        return False

    forwarded_host = request.headers.get("x-forwarded-host")
    host_header = forwarded_host or request.headers.get("host") or request.url.netloc
    host = host_header.split(",", 1)[0].strip().split(":", 1)[0].lower()
    origin_host = origin_parts.hostname.lower()

    # Host equality is the security boundary. Hugging Face may rewrite the
    # scheme internally, so only require a sensible HTTP(S) origin here.
    if not hmac.compare_digest(origin_host, host):
        return False

    return True


def _password_policy_error(password: str, confirmation: str = "") -> str | None:
    if len(password) < 12:
        return "رمز پنل باید حداقل ۱۲ کاراکتر باشد."
    if password != confirmation:
        return "تکرار رمز با رمز اصلی یکسان نیست."
    return None



def _users_from_state() -> list[dict]:
    state = _read_state()
    users = state.get("users", []) if isinstance(state, dict) else []
    if not isinstance(users, list):
        return []
    now = int(time.time())
    changed = False
    for user in users:
        if not isinstance(user, dict):
            continue
        # Expired accounts are disabled in the generated Xray config.
        expires = user.get("expires_at")
        if user.get("enabled", True) and expires and int(expires) <= now:
            user["enabled"] = False
            user["disabled_reason"] = "expired"
            changed = True
    if changed:
        state["users"] = users
        with STATE_LOCK:
            _atomic_write_json(STATE_FILE, state)
        # If the runtime is already up, immediately rewrite config so expired users are removed.
        if XRAY_CFG.exists():
            write_xray_config()
    return [u for u in users if isinstance(u, dict)]


def _save_users(users: list[dict]) -> None:
    state = _read_state()
    if not isinstance(state, dict):
        state = {}
    state["users"] = users
    state["version"] = max(3, int(state.get("version", 2) or 2))
    with STATE_LOCK:
        _atomic_write_json(STATE_FILE, state)


def _user_is_active(user: dict) -> bool:
    if not user.get("enabled", True):
        return False
    expires = user.get("expires_at")
    return not expires or int(expires) > int(time.time())


def _user_credential(user: dict, protocol: str) -> str:
    return {"vless": user["vless_uuid"], "vmess": user["vmess_uuid"], "trojan": user["trojan_password"]}[protocol]


def _reload_config_file() -> None:
    """Write config after user changes; the native supervisor notices the mtime and reloads Xray."""
    write_xray_config()


def inbound(protocol: str, transport: str, port: int, path: str) -> dict:
    users = [u for u in _users_from_state() if _user_is_active(u)]
    if protocol == "vless":
        clients = [{"id": VLESS_UUID, "email": f"legacy-vless-{transport}", "flow": ""}]
        clients.extend({"id": u["vless_uuid"], "email": f"user-{u['id']}", "flow": ""} for u in users)
        settings = {"clients": clients, "decryption": "none"}
    elif protocol == "trojan":
        clients = [{"password": TROJAN_PASSWORD, "email": f"legacy-trojan-{transport}"}]
        clients.extend({"password": u["trojan_password"], "email": f"user-{u['id']}"} for u in users)
        settings = {"clients": clients}
    elif protocol == "vmess":
        clients = [{"id": VMESS_UUID, "alterId": 0, "email": f"legacy-vmess-{transport}"}]
        clients.extend({"id": u["vmess_uuid"], "alterId": 0, "email": f"user-{u['id']}"} for u in users)
        settings = {"clients": clients}
    else:
        raise ValueError(protocol)

    # Public TLS is terminated by the HF frontend/Python layer. Xray receives the
    # decoded proxy protocol over localhost TCP. XHTTP remains a localhost HTTP
    # inbound and is reverse-proxied by the ASGI layer.
    if transport == "xhttp":
        mode = next((v.get("mode", "auto") for v in PROFILES.values() if v["port"] == port), "auto")
        extra = {}
        if mode == "packet-up":
            # Server-side safety/performance limits. The client receives the same
            # mode via the generated profile; 1 MiB keeps request count low while
            # staying below common HTTP intermediary limits.
            extra = {
                "scMaxEachPostBytes": 1000000,
                "scMaxBufferedPosts": 128,
                "scMinPostsIntervalMs": 20,
                "uplinkHTTPMethod": "POST",
                "uplinkDataPlacement": "body",
                "sessionPlacement": "path",
                "seqPlacement": "path",
            }
        xhttp = {"path": path, "mode": mode}
        xhttp.update(extra)
        stream = {"network": "xhttp", "security": "none", "xhttpSettings": xhttp}
    else:
        stream = {
            "network": "ws",
            "security": "none",
            "wsSettings": {"path": path, "headers": {}}
        }

    return {
        "listen": "127.0.0.1",
        "port": port,
        "protocol": protocol,
        "settings": settings,
        "streamSettings": stream,
    }


def write_xray_config() -> None:
    WORKDIR.mkdir(parents=True, exist_ok=True)
    cfg = {
        "log": {"loglevel": XRAY_LOGLEVEL},
        "inbounds": [inbound(v["protocol"], v["transport"], v["port"], v["path"]) for key, v in PROFILES.items() if not v.get("split_download")],
        "outbounds": [
            {"protocol": "freedom", "settings": {}, "tag": "direct", "streamSettings": {"sockopt": _sockopt_defaults()}},
            {"protocol": "blackhole", "settings": {}, "tag": "blocked"},
        ],
    }
    tmp = XRAY_CFG.with_suffix(".new.json")
    tmp.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
    tmp.replace(XRAY_CFG)


def run_xray_test() -> None:
    result = subprocess.run([str(XRAY_BIN), "run", "-test", "-c", str(XRAY_CFG)], capture_output=True, text=True, timeout=20)
    if result.returncode != 0:
        details = (result.stdout + "\n" + result.stderr).strip()
        raise RuntimeError("Xray configuration test failed:\n" + details)


async def _spawn_xray() -> asyncio.subprocess.Process:
    global XRAY_PROC
    async with XRAY_LOCK:
        if XRAY_PROC is not None and XRAY_PROC.returncode is None:
            return XRAY_PROC
        download_xray()
        write_xray_config()
        run_xray_test()
        XRAY_PROC = await asyncio.create_subprocess_exec(
            str(XRAY_BIN), "run", "-c", str(XRAY_CFG),
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT,
        )
        asyncio.create_task(pipe_xray_logs(XRAY_PROC))
        await asyncio.sleep(0.35)
        if XRAY_PROC.returncode is not None:
            raise RuntimeError(f"Xray exited during startup with code {XRAY_PROC.returncode}")
        print(f"Xray started: {len(PROFILES)} RVG-style profiles ready", flush=True)
        return XRAY_PROC


async def pipe_xray_logs(proc: asyncio.subprocess.Process) -> None:
    if proc.stdout is None:
        return
    while True:
        line = await proc.stdout.readline()
        if not line:
            break
        print("[xray] " + line.decode(errors="replace").rstrip(), flush=True)


async def xray_supervisor() -> None:
    global XRAY_PROC
    backoff = XRAY_RESTART_MIN
    seen_mtime = XRAY_CFG.stat().st_mtime_ns if XRAY_CFG.exists() else 0
    while True:
        # Periodically evaluate expiry timestamps even if nobody opens the admin panel.
        try:
            _users_from_state()
        except Exception as exc:
            print(f"User expiry check failed: {exc}", flush=True)
        proc = XRAY_PROC
        if proc is None:
            await asyncio.sleep(0.5)
            continue
        try:
            code = await asyncio.wait_for(proc.wait(), timeout=1.0)
            exited = True
        except asyncio.TimeoutError:
            code = None
            exited = False
        current_mtime = XRAY_CFG.stat().st_mtime_ns if XRAY_CFG.exists() else 0
        changed = current_mtime != seen_mtime
        if changed and not exited:
            print("Xray config changed by panel; restarting Xray to apply user changes", flush=True)
            if proc.returncode is None:
                proc.terminate()
                try: await asyncio.wait_for(proc.wait(), timeout=3)
                except asyncio.TimeoutError: proc.kill(); await proc.wait()
            code = proc.returncode
            exited = True
        if not exited:
            continue
        if XRAY_PROC is proc:
            XRAY_PROC = None
        seen_mtime = current_mtime
        if code == 0 and not changed:
            return
        if code not in (0, None) and not XRAY_RESTART:
            return
        if code not in (0, None):
            print(f"Xray exited with code {code}; restarting in {backoff:.1f}s", flush=True)
            await asyncio.sleep(backoff)
        try:
            await _spawn_xray()
            seen_mtime = XRAY_CFG.stat().st_mtime_ns if XRAY_CFG.exists() else seen_mtime
            backoff = XRAY_RESTART_MIN
        except Exception as exc:
            print(f"Xray restart failed: {exc}", flush=True)
            backoff = min(XRAY_RESTART_MAX, backoff * 2)


async def start_xray() -> None:
    global XRAY_MONITOR_TASK
    await _spawn_xray()
    XRAY_MONITOR_TASK = asyncio.create_task(xray_supervisor())


async def stop_xray() -> None:
    global XRAY_PROC, XRAY_MONITOR_TASK
    if XRAY_MONITOR_TASK:
        XRAY_MONITOR_TASK.cancel()
        await asyncio.gather(XRAY_MONITOR_TASK, return_exceptions=True)
        XRAY_MONITOR_TASK = None
    proc = XRAY_PROC
    XRAY_PROC = None
    if proc and proc.returncode is None:
        proc.terminate()
        try:
            await asyncio.wait_for(proc.wait(), timeout=3)
        except asyncio.TimeoutError:
            proc.kill()
            await proc.wait()


def _set_socket_keepalive(sock: socket.socket) -> None:
    # Larger kernel buffers reduce stalls on high-BDP transfers. The kernel may
    # clamp these values; failure is harmless.
    for level, optname, value in (
        (socket.SOL_SOCKET, getattr(socket, "SO_RCVBUF", -1), BRIDGE_SOCKET_BUFFER),
        (socket.SOL_SOCKET, getattr(socket, "SO_SNDBUF", -1), BRIDGE_SOCKET_BUFFER),
    ):
        if optname >= 0:
            try:
                sock.setsockopt(level, optname, value)
            except OSError:
                pass
    try:
        sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
    except OSError:
        pass
    if TCP_KEEPALIVE_IDLE <= 0:
        return
    try:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
        if hasattr(socket, "TCP_KEEPIDLE"):
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, TCP_KEEPALIVE_IDLE)
        if hasattr(socket, "TCP_KEEPINTVL") and TCP_KEEPALIVE_INTERVAL > 0:
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, TCP_KEEPALIVE_INTERVAL)
        if hasattr(socket, "TCP_KEEPCNT") and TCP_KEEPALIVE_COUNT > 0:
            sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, TCP_KEEPALIVE_COUNT)
    except OSError:
        pass


def _make_session() -> str:
    expires = int(time.time()) + SESSION_TTL
    payload = str(expires).encode("ascii")
    sig = hmac.new(_auth_secret(), payload, hashlib.sha256).digest()
    return base64.urlsafe_b64encode(payload + b"." + sig).decode("ascii").rstrip("=")


def _valid_session(value: str | None) -> bool:
    if not value or not _panel_is_configured():
        return False
    try:
        raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
        expires_raw, sig = raw.split(b".", 1)
        expires = int(expires_raw.decode("ascii"))
    except (ValueError, TypeError, base64.binascii.Error):
        return False
    if expires < int(time.time()):
        return False
    expected = hmac.new(_auth_secret(), expires_raw, hashlib.sha256).digest()
    return hmac.compare_digest(sig, expected)


def _require_panel_auth(request: Request) -> None:
    if not _panel_is_configured():
        raise HTTPException(503, "panel setup is required")
    if not _valid_session(request.cookies.get("hf_panel_session")):
        raise HTTPException(401, "authentication required")


def public_host() -> str:
    return os.getenv("SPACE_HOST") or os.getenv("HOSTNAME") or "YOUR-SPACE.hf.space"


def _xhttp_extra(profile: dict, host: str) -> dict:
    if profile.get("transport") != "xhttp":
        return {}
    mode = profile.get("mode", "auto")
    extra = {
        "mode": mode,
        "scMaxEachPostBytes": 1000000,
        "scMinPostsIntervalMs": 20,
        "scMaxBufferedPosts": 128,
        "xmux": {
            "maxConcurrency": 0,
            "maxConnections": 4,
            "cMaxReuseTimes": 0,
            "hMaxRequestTimes": "600-900",
            "hMaxReusableSecs": "1800-3000",
            "hKeepAlivePeriod": 20,
        },
    }
    if profile.get("split_download"):
        extra["downloadSettings"] = {
            "address": host,
            "port": 443,
            "network": "xhttp",
            "security": "tls",
            "tlsSettings": {
                "serverName": host,
                "fingerprint": "chrome",
                "alpn": ["h2", "http/1.1"],
            },
            "xhttpSettings": {
                "path": profile["path"],
                "mode": mode,
                "extra": {
                    "xmux": {
                        "maxConcurrency": 0,
                        "maxConnections": 4,
                        "cMaxReuseTimes": 0,
                        "hMaxRequestTimes": "600-900",
                        "hMaxReusableSecs": "1800-3000",
                        "hKeepAlivePeriod": 20,
                    }
                },
            },
        }
    return extra


def vless_uri(profile: dict, host: str, creds: dict | None = None) -> str:
    qp = {"encryption": "none", "security": "tls", "sni": host, "type": profile["transport"], "path": profile["path"]}
    if profile["transport"] == "xhttp":
        qp["mode"] = profile.get("mode", "auto")
        if profile.get("split_download"):
            qp["extra"] = json.dumps(_xhttp_extra(profile, host), separators=(",", ":"), ensure_ascii=False)
    else:
        qp["host"] = host
    return f"vless://{(creds or {}).get('vless', VLESS_UUID)}@{host}:443?{urlencode(qp)}#{quote(profile['label'])}"

def trojan_uri(profile: dict, host: str, creds: dict | None = None) -> str:
    qp = {"security": "tls", "sni": host, "type": profile["transport"], "path": profile["path"]}
    if profile["transport"] == "xhttp":
        qp["mode"] = profile.get("mode", "auto")
        if profile.get("split_download"):
            qp["extra"] = json.dumps(_xhttp_extra(profile, host), separators=(",", ":"), ensure_ascii=False)
    else:
        qp["host"] = host
    return f"trojan://{quote((creds or {}).get('trojan', TROJAN_PASSWORD), safe='')}@{host}:443?{urlencode(qp)}#{quote(profile['label'])}"

def vmess_uri(profile: dict, host: str, creds: dict | None = None) -> str:
    data = {
        "v": "2", "ps": profile["label"], "add": host, "port": "443", "id": (creds or {}).get("vmess", VMESS_UUID),
        "aid": "0", "scy": "auto", "net": "ws" if profile["transport"] == "ws" else "xhttp",
        "type": "none", "host": host, "path": profile["path"], "tls": "tls", "sni": host,
    }
    if profile["transport"] == "xhttp":
        data["mode"] = profile.get("mode", "auto")
        if profile.get("split_download"):
            data["extra"] = _xhttp_extra(profile, host)
    raw = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    return "vmess://" + base64.b64encode(raw).decode("ascii")


def build_uri(profile: dict, host: str, creds: dict | None = None) -> str:
    if profile["protocol"] == "vless":
        return vless_uri(profile, host, creds)
    if profile["protocol"] == "trojan":
        return trojan_uri(profile, host, creds)
    return vmess_uri(profile, host, creds)


def client_json(profile: dict, host: str) -> dict:
    return {
        "name": profile["label"], "protocol": profile["protocol"], "transport": profile["transport"],
        "mode": profile.get("mode", "stream"),
        "split_download": bool(profile.get("split_download")),
        "public_endpoint": f"https://{host}{profile['path']}", "uri": build_uri(profile, host),
        "xray_server_inbound": f"127.0.0.1:{profile['port']}", "outbound": "freedom",
        "performance": ("packet-up + split download + XMUX" if profile.get("split_download") else ("packet-up" if profile.get("mode") == "packet-up" else "xhttp")) if profile["transport"] == "xhttp" else "ws",
        "xhttp_extra": _xhttp_extra(profile, host),
    }


LOGIN_HTML = """<!doctype html><html lang='fa' dir='rtl'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>HF Gateway</title><style>:root{font-family:system-ui,-apple-system,Segoe UI,sans-serif;color-scheme:light}body{margin:0;background:#f4f6f8;color:#16181d;min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box}main{width:min(440px,100%);background:#fff;border:1px solid #e2e6ea;border-radius:20px;padding:28px;box-shadow:0 14px 40px rgba(0,0,0,.08)}h1{font-size:24px;margin:0 0 8px}.sub{color:#69727d;margin:0 0 22px}input{width:100%;box-sizing:border-box;padding:13px 14px;border:1px solid #cbd2d9;border-radius:12px;background:#fff;color:inherit;font-size:16px}button{width:100%;margin-top:12px;border:0;border-radius:12px;padding:13px;background:#111827;color:#fff;font-weight:700;font-size:15px;cursor:pointer}.err{color:#b42318;margin:10px 0}.hint{padding:11px 12px;background:#f0f2f5;border-radius:12px;margin-top:16px;color:#59636e;line-height:1.8}small{display:block;color:#7a828c;margin-top:12px;line-height:1.7}</style></head><body><main><h1>HF Gateway</h1><p class='sub'>برای ورود، رمز پنل را وارد کن.</p>{error}<form method='post' action='/login'><input type='password' name='password' autocomplete='current-password' placeholder='رمز پنل' required autofocus><button type='submit'>ورود</button></form><div class='hint'>VLESS UUID، VMess UUID و Trojan password بدون ورود به Settings به‌صورت خودکار و تصادفی ساخته می‌شوند.</div><small>اگر Space تازه باشد، ابتدا ستاپ اولیه نمایش داده می‌شود.</small></main></body></html>"""

SETUP_HTML = """<!doctype html><html lang='fa' dir='rtl'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>HF Gateway Setup</title><style>:root{font-family:system-ui,-apple-system,Segoe UI,sans-serif;color-scheme:light}body{margin:0;background:#f4f6f8;color:#16181d;min-height:100vh;display:grid;place-items:center;padding:24px;box-sizing:border-box}main{width:min(540px,100%);background:#fff;border:1px solid #e2e6ea;border-radius:20px;padding:28px;box-shadow:0 14px 40px rgba(0,0,0,.08)}h1{font-size:25px;margin:0 0 8px}.sub{color:#69727d;margin:0 0 22px}.row{display:grid;gap:9px;margin-bottom:15px}label{font-weight:700}input{width:100%;box-sizing:border-box;padding:13px 14px;border:1px solid #cbd2d9;border-radius:12px;background:#fff;color:inherit;font-size:16px}button{border:0;border-radius:12px;padding:13px;background:#111827;color:#fff;font-weight:700;font-size:15px;cursor:pointer}.secondary{background:#eef1f5;color:#1b2430}.actions{display:flex;gap:8px;margin-top:16px}.actions button{flex:1}.err{color:#b42318;margin:10px 0}.hint{padding:12px 14px;background:#f0f2f5;border-radius:12px;line-height:1.8;margin-top:14px;color:#59636e}.warn{padding:12px 14px;background:#fff7e6;border:1px solid #ffd591;border-radius:12px;line-height:1.8;margin-top:14px;color:#7a4b00}.mono{direction:ltr;text-align:left;font-family:ui-monospace,monospace}</style></head><body><main><h1>راه‌اندازی اولیه HF Gateway</h1><p class='sub'>اینجا فقط رمز پنل را تعیین کن؛ اعتبارهای خودِ کانفیگ‌ها خودکار ساخته می‌شوند.</p>{error}<form method='post' action='/setup'><div class='row'><label>رمز پنل</label><input id='password' type='password' name='password' minlength='12' autocomplete='new-password' placeholder='حداقل ۱۲ کاراکتر' required></div><div class='row'><label>تکرار رمز پنل</label><input id='confirmation' type='password' name='confirmation' minlength='12' autocomplete='new-password' placeholder='تکرار رمز' required></div><div class='actions'><button type='button' class='secondary' onclick='suggestPassword()'>🔐 ساخت رمز قوی</button><button type='submit'>ذخیره و ورود</button></div></form><div class='hint'>برای VLESS و VMess یک UUID تصادفی و برای Trojan یک password تصادفیِ طولانی ساخته می‌شود. نیازی نیست این موارد را دستی در Secrets بنویسی.</div><div class='warn'>نکتهٔ پایداری: دیسک عادی Space موقتی است. برای باقی ماندن ستاپ و credentialها بعد از Restart، Storage Bucket را روی <span class='mono'>/data</span> mount کن.</div><script>function suggestPassword(){const a='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*_-+=?';let s='';const r=new Uint32Array(24);crypto.getRandomValues(r);for(let i=0;i<r.length;i++)s+=a[r[i]%a.length];for(const id of ['password','confirmation']){const e=document.getElementById(id);e.value=s;e.type='text';}}</script></main></body></html>"""


def panel_html(host: str) -> str:
    options = ''.join(f"<option value='{key}'>{p['label']}</option>" for key, p in PROFILES.items())
    profile_json = json.dumps({k: client_json(v, host) for k, v in PROFILES.items()}, ensure_ascii=False)
    credential_meta = {
        "vless": VLESS_UUID,
        "vmess": VMESS_UUID,
        "trojan": TROJAN_PASSWORD,
        "persistent": str(STATE_DIR).startswith("/data"),
    }
    credential_json = json.dumps(credential_meta, ensure_ascii=False)
    persistence_label = 'Credential state روی /data' if credential_meta['persistent'] else 'Credential state موقتی'
    persistence_class = 'ok' if credential_meta['persistent'] else 'warn'
    return f"""<!doctype html><html lang='fa' dir='rtl'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>HF RVG Gateway</title><style>
:root{{font-family:system-ui,-apple-system,Segoe UI,sans-serif;color-scheme:light;--bg:#f4f6f8;--card:#fff;--text:#16181d;--muted:#66707b;--border:#dfe4ea;--accent:#111827;--accentText:#fff;--code:#f0f2f5;--good:#12805c;--warn:#8b5a00}}:root.dark{{color-scheme:dark;--bg:#0b0f14;--card:#131922;--text:#eef2f7;--muted:#9aa6b2;--border:#273140;--accent:#f3f4f6;--accentText:#10151c;--code:#0e141c;--good:#5de2ad;--warn:#ffc968}}*{{box-sizing:border-box}}body{{margin:0;background:var(--bg);color:var(--text);min-height:100vh}}.wrap{{max-width:1120px;margin:0 auto;padding:22px}}header{{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:18px}}h1{{margin:0;font-size:28px}}.sub{{margin:5px 0 0;color:var(--muted)}}.actions,.toolbar{{display:flex;flex-wrap:wrap;gap:8px}}button,.btn{{border:1px solid var(--border);background:var(--card);color:var(--text);padding:9px 12px;border-radius:10px;cursor:pointer;font-weight:700;text-decoration:none}}.primary{{background:var(--accent);color:var(--accentText);border-color:var(--accent)}}.grid{{display:grid;grid-template-columns:1.1fr .9fr;gap:16px}}.card{{background:var(--card);border:1px solid var(--border);border-radius:18px;padding:18px;margin-bottom:16px}}.card h2{{font-size:18px;margin:0 0 12px}}label{{font-weight:700;display:block;margin-bottom:8px}}select,textarea,input{{width:100%;border:1px solid var(--border);border-radius:11px;background:var(--card);color:var(--text);padding:11px;font:inherit}}textarea{{min-height:180px;resize:vertical;direction:ltr;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}}.chips{{display:flex;flex-wrap:wrap;gap:8px;margin-top:14px}}.chip{{padding:7px 10px;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:13px}}.ok{{color:var(--good);font-weight:800}}.warn{{color:var(--warn);font-weight:700}}.mono{{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;direction:ltr;text-align:left;word-break:break-all}}.muted{{color:var(--muted)}}.notice{{padding:12px 14px;border-radius:12px;background:var(--code);color:var(--muted);margin-top:12px;line-height:1.8}}.credential{{padding:12px;border:1px dashed var(--border);border-radius:12px;margin-top:10px}}.credential b{{display:block;margin-bottom:6px}}.credential code{{display:block;word-break:break-all;background:var(--code);padding:9px;border-radius:9px;direction:ltr;text-align:left}}.toast{{position:fixed;z-index:1000;left:50%;bottom:22px;max-width:min(92vw,520px);padding:10px 15px;border:1px solid var(--border);border-radius:12px;background:var(--card);color:var(--text);box-shadow:0 8px 28px rgba(0,0,0,.18);opacity:0;transform:translate(-50%,10px);pointer-events:none;transition:opacity .18s ease,transform .18s ease;text-align:center;font-size:14px}}.toast.show{{opacity:1;transform:translate(-50%,0)}}.toast.error{{border-color:var(--warn);color:var(--warn)}}footer{{margin-top:4px;color:var(--muted);font-size:13px;line-height:1.8}}@media(max-width:760px){{.grid{{grid-template-columns:1fr}}header{{align-items:flex-start;flex-direction:column}}.actions{{width:100%}}.actions button,.actions a{{flex:1;text-align:center}}}}</style></head><body><div class='wrap'>
<header><div><h1>HF RVG Gateway · v7.0</h1><p class='sub'>Xray روی Hugging Face · credentialها خودکار ساخته شده‌اند</p></div><div class='actions'><button onclick='toggleTheme()'>🌓 حالت</button><a class='btn' href='/logout'>خروج</a></div></header>
<div class='grid'><section><section class='card'><label for='profile'>پروفایل اتصال</label><select id='profile' onchange='renderProfile()'>{options}</select><div class='chips'><span class='chip'>TLS از سمت HF</span><span class='chip'>Outbound: freedom</span><span class='chip ok'>Xray: auto-restart</span><span class='chip {persistence_class}'>{persistence_label}</span></div><div class='notice'><b>برای throughput:</b> اول <b>VLESS + XHTTP packet-up + TLS</b> را تست کن. اگر رفتار HF با آن سازگار نبود، XHTTP auto یا WebSocket را امتحان کن.</div><div style='margin-top:16px'><label>Endpoint عمومی</label><input id='endpoint' readonly></div></section>
<section class='card'><h2>اعتبارهای خودکار</h2><div class='credential'><b>VLESS UUID</b><code id='vlessCred'></code></div><div class='credential'><b>VMess UUID</b><code id='vmessCred'></code></div><div class='credential'><b>Trojan password</b><code id='trojanCred'></code></div><div class='notice'>این مقادیر در اولین راه‌اندازی با CSPRNG ساخته می‌شوند. بدون Secret دستی هم کار می‌کنند.</div></section></section>
<section class='card'><label>لینک کانفیگ</label><textarea id='uri' readonly></textarea><div class='toolbar'><button class='primary' onclick='copyUri()'>کپی لینک انتخاب‌شده</button><button onclick='copyAllUris()'>کپی همه کانفیگ‌ها</button><button onclick='downloadJson()'>دانلود JSON</button></div><div style='margin-top:16px'><label>مشخصات</label><div id='details' class='muted'></div></div></section></div>
<section class='card'><h2>وضعیت لحظه‌ای سرویس</h2><div id='runtimeStatus' class='notice'>در حال خواندن وضعیت هسته…</div><div class='toolbar' style='margin-top:10px'><button onclick='refreshStatus()'>به‌روزرسانی وضعیت</button></div></section>
<section class='card'><h2>مدیریت کاربران و اشتراک‌ها</h2><div class='notice'>کاربران این بخش اعتبار جداگانه دارند و فعال/منقضی بودنشان در کانفیگ Xray اعمال می‌شود. در این نسخه، شمارندهٔ مصرف تفکیکی Xray از API هسته در دسترس نیست؛ بنابراین حجم مصرف‌شده یا اعمال سقف حجم به‌صورت ساختگی نمایش داده نمی‌شود.</div><div class='grid' style='grid-template-columns:repeat(auto-fit,minmax(180px,1fr));margin-top:14px'><div><label>نام کاربر</label><input id='newUserName' placeholder='مثلاً user-01'></div><div><label>مدت اعتبار (روز)</label><input id='newUserDays' type='number' min='1' max='3650' value='30'></div><div><label>سقف حجم (GB، صرفاً ثبت‌شده)</label><input id='newUserQuota' type='number' min='0' max='100000' value='0'></div><div style='display:flex;align-items:end'><button class='primary' onclick='createUser()'>ساخت کاربر</button></div></div><div class='toolbar' style='margin:12px 0'><button onclick='refreshUsers()'>به‌روزرسانی فهرست</button><button onclick='backupUsers()'>خروجی پشتیبان</button><label class='btn' for='restoreFile'>انتخاب فایل بازیابی</label><input id='restoreFile' type='file' accept='.json,application/json' style='display:none' onchange='restoreUsers(event)'></div><div id='usersTable' class='muted'>در حال بارگذاری…</div><div id='userSub' style='margin-top:12px'></div></section>
<div id='toast' class='toast' role='status' aria-live='polite'></div>
<footer>رمز پنل به‌صورت هش‌شده ذخیره می‌شود. حالت Dark/Light در LocalStorage همین مرورگر ذخیره می‌شود. برای ماندگاری state سرور بعد از Restart، Storage Bucket روی /data لازم است.</footer></div><script>
const profiles={profile_json};const credentials={credential_json};const root=document.documentElement;
function applyTheme(){{const t=localStorage.getItem('hf-rvg-theme')||'light';root.classList.toggle('dark',t==='dark')}}
function toggleTheme(){{const dark=!root.classList.contains('dark');localStorage.setItem('hf-rvg-theme',dark?'dark':'light');applyTheme()}}
function renderProfile(){{const p=profiles[document.getElementById('profile').value];document.getElementById('uri').value=p.uri;document.getElementById('endpoint').value=p.public_endpoint;document.getElementById('details').innerHTML='<b>Protocol:</b> '+p.protocol+' &nbsp; <b>Transport:</b> '+p.transport+' &nbsp; <b>Path:</b> <span class="mono">'+p.public_endpoint.replace('https://'+location.host,'')+'</span><br><b>Outbound:</b> freedom &nbsp; <b>Performance:</b> '+p.performance;}}
let toastTimer=null;
function showToast(message,isError=false){{const el=document.getElementById('toast');el.textContent=message;el.classList.toggle('error',isError);el.classList.add('show');if(toastTimer)clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('show'),2200)}}
async function copyText(text){{if(!text){{showToast('کانفیگی برای کپی وجود ندارد',true);return false}}try{{if(navigator.clipboard&&window.isSecureContext){{await navigator.clipboard.writeText(text);showToast('کپی شد');return true}}}}catch(e){{/* use legacy fallback below */}}try{{const ta=document.createElement('textarea');ta.value=text;ta.setAttribute('readonly','');ta.style.position='fixed';ta.style.left='-9999px';ta.style.top='0';ta.style.opacity='0';document.body.appendChild(ta);ta.focus();ta.select();ta.setSelectionRange(0,ta.value.length);const ok=document.execCommand('copy');ta.remove();if(ok){{showToast('کپی شد');return true}}}}catch(e){{/* report unobtrusively below */}}showToast('کپی خودکار در این مرورگر در دسترس نیست؛ متن را دستی کپی کن.',true);return false}}
async function copyUri(){{await copyText(document.getElementById('uri').value)}}
async function copyAllUris(){{const all=Object.values(profiles).map(p=>'# '+p.name+'\\n'+p.uri).join('\\n\\n');await copyText(all)}}
function downloadJson(){{const key=document.getElementById('profile').value;const blob=new Blob([JSON.stringify(profiles[key],null,2)],{{type:'application/json'}});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=key+'.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000)}}
async function apiCall(url,opts={{}}){{const r=await fetch(url,{{...opts,headers:{{'Content-Type':'application/json',...(opts.headers||{{}})}}}});let data={{}};try{{data=await r.json()}}catch(e){{}}if(!r.ok)throw new Error(data.detail||('HTTP '+r.status));return data}}
function esc(s){{return String(s??'').replace(/[&<>"']/g,c=>({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}}[c]))}}
async function refreshStatus(){{const box=document.getElementById('runtimeStatus');try{{const d=await apiCall('/api/admin/status');box.innerHTML='<b>هسته Xray:</b> '+(d.xray_running?'<span class="ok">در حال اجرا</span>':'<span class="warn">متوقف</span>')+' &nbsp; <b>کاربران فعال:</b> '+esc(d.active_users)+' / '+esc(d.users_total)+' &nbsp; <b>بیشینه حافظه پنل:</b> '+(d.panel_max_rss_bytes==null?'نامشخص':(d.panel_max_rss_bytes/1024/1024).toFixed(1)+' MiB')+'<br><span class="muted">آمار واقعی ترافیک تفکیکی کاربران در این نسخه در دسترس نیست و نمایش داده نمی‌شود.</span>'}}catch(e){{box.textContent='وضعیت در دسترس نیست: '+e.message}}}}
async function refreshUsers(){{const box=document.getElementById('usersTable');try{{const d=await apiCall('/api/admin/users');if(!d.users.length){{box.textContent='هنوز کاربری ساخته نشده است.';return}}box.innerHTML='<div style="overflow:auto"><table style="width:100%;border-collapse:collapse"><thead><tr><th>نام</th><th>وضعیت</th><th>انقضا</th><th>سقف ثبت‌شده</th><th>عملیات</th></tr></thead><tbody>'+d.users.map(u=>'<tr><td>'+esc(u.name)+'</td><td>'+((u.active)?'<span class="ok">فعال</span>':'<span class="warn">غیرفعال/منقضی</span>')+'</td><td>'+esc(u.expires_at?new Date(u.expires_at*1000).toLocaleString():'—')+'</td><td>'+esc(u.quota_gb||0)+' GB</td><td><div class="toolbar"><button data-action="sub" data-id="'+esc(u.id)+'">اشتراک</button><button data-action="toggle" data-id="'+esc(u.id)+'">'+(u.enabled?'غیرفعال':'فعال')+'</button><button data-action="extend" data-id="'+esc(u.id)+'">تمدید ۳۰ روز</button><button data-action="delete" data-id="'+esc(u.id)+'">حذف</button></div></td></tr>').join('')+'</tbody></table></div>';box.querySelectorAll('button[data-action]').forEach(b=>b.addEventListener('click',()=>{{const id=b.dataset.id;const action=b.dataset.action;if(action==='sub')showSub(id);else if(action==='toggle')toggleUser(id);else if(action==='extend')extendUser(id);else if(action==='delete')deleteUser(id)}}))}}catch(e){{box.textContent='خطا در دریافت کاربران: '+e.message}}}}
async function createUser(){{try{{const name=document.getElementById('newUserName').value.trim();const days=Number(document.getElementById('newUserDays').value||30);const quota=Number(document.getElementById('newUserQuota').value||0);await apiCall('/api/admin/users',{{method:'POST',body:JSON.stringify({{name,days,quota_gb:quota}})}});document.getElementById('newUserName').value='';showToast('کاربر ساخته شد');await refreshUsers()}}catch(e){{showToast(e.message,true)}}}}
async function toggleUser(id){{try{{await apiCall('/api/admin/users/'+encodeURIComponent(id)+'/toggle',{{method:'POST',body:'{{}}'}});await refreshUsers()}}catch(e){{showToast(e.message,true)}}}}
async function extendUser(id){{try{{await apiCall('/api/admin/users/'+encodeURIComponent(id)+'/extend',{{method:'POST',body:JSON.stringify({{days:30}})}});showToast('اعتبار ۳۰ روز تمدید شد');await refreshUsers()}}catch(e){{showToast(e.message,true)}}}}
async function deleteUser(id){{if(!confirm('این کاربر حذف شود؟'))return;try{{await apiCall('/api/admin/users/'+encodeURIComponent(id),{{method:'DELETE'}});await refreshUsers()}}catch(e){{showToast(e.message,true)}}}}
async function showSub(id){{try{{const d=await apiCall('/api/admin/users/'+encodeURIComponent(id)+'/subscription');const el=document.getElementById('userSub');el.innerHTML='<label>لینک اشتراک این کاربر</label><textarea id="subscriptionLink" readonly>'+esc(d.url)+'</textarea><div class="toolbar"><button id="copySubLink">کپی لینک اشتراک</button><button id="copySubConfigs">کپی همه کانفیگ‌های کاربر</button></div><div style="margin:12px 0"><img alt="QR اشتراک" src="'+esc(d.qr_url)+'" style="width:180px;height:180px;max-width:100%;border-radius:10px;background:white;padding:8px"></div><label style="margin-top:12px">پروفایل‌های این کاربر</label><textarea id="subscriptionConfigs" readonly>'+esc(d.content)+'</textarea>';document.getElementById('copySubLink').addEventListener('click',()=>copyText(document.getElementById('subscriptionLink').value));document.getElementById('copySubConfigs').addEventListener('click',()=>copyText(document.getElementById('subscriptionConfigs').value));el.scrollIntoView({{behavior:'smooth',block:'nearest'}})}}catch(e){{showToast(e.message,true)}}}}
async function backupUsers(){{try{{const d=await apiCall('/api/admin/backup');const blob=new Blob([JSON.stringify(d,null,2)],{{type:'application/json'}});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download='hf-rvg-users-backup.json';a.click();setTimeout(()=>URL.revokeObjectURL(a.href),1000);showToast('فایل پشتیبان آماده شد')}}catch(e){{showToast(e.message,true)}}}}
async function restoreUsers(event){{const f=event.target.files?.[0];if(!f)return;try{{const data=JSON.parse(await f.text());const preview=await apiCall('/api/admin/restore/preview',{{method:'POST',body:JSON.stringify(data)}});if(!confirm('پیش‌نمایش بازیابی: '+preview.incoming+' کاربر ورودی، '+preview.existing+' کاربر فعلی. ادغام و ادامه؟'))return;const out=await apiCall('/api/admin/restore',{{method:'POST',body:JSON.stringify(data)}});showToast('بازیابی شد: '+out.imported+' کاربر');await refreshUsers()}}catch(e){{showToast('بازیابی ناموفق: '+e.message,true)}}finally{{event.target.value=''}}}}
refreshUsers();refreshStatus();setInterval(refreshStatus,15000);
document.getElementById('vlessCred').textContent=credentials.vless;document.getElementById('vmessCred').textContent=credentials.vmess;document.getElementById('trojanCred').textContent=credentials.trojan;applyTheme();renderProfile();
</script></body></html>"""


@asynccontextmanager
async def lifespan(app: FastAPI):
    global HTTP_CLIENT
    if not _panel_is_configured():
        print("First-run setup required: open / to set the panel password.", flush=True)
    if os.getenv("HF_RVG_SUPERVISED_XRAY") != "1":
        await start_xray()
    limits = httpx.Limits(
        max_connections=HTTP_MAX_CONNECTIONS,
        max_keepalive_connections=HTTP_MAX_KEEPALIVE,
        keepalive_expiry=HTTP_KEEPALIVE_EXPIRY,
    )
    timeout = httpx.Timeout(connect=10.0, read=None, write=None, pool=None)
    HTTP_CLIENT = httpx.AsyncClient(
        timeout=timeout,
        follow_redirects=False,
        limits=limits,
        trust_env=False,
    )
    try:
        yield
    finally:
        if HTTP_CLIENT:
            await HTTP_CLIENT.aclose()
            HTTP_CLIENT = None
        if os.getenv("HF_RVG_SUPERVISED_XRAY") != "1":
            await stop_xray()


app = FastAPI(title="HF RVG Gateway v7.0", lifespan=lifespan)


@app.get("/health", response_class=PlainTextResponse)
async def health():
    if os.getenv("HF_RVG_SUPERVISED_XRAY") == "1":
        return "ok"
    if XRAY_PROC is None or XRAY_PROC.returncode is not None:
        raise HTTPException(503, "xray is not running")
    return "ok"


@app.get("/api/profiles")
async def api_profiles(request: Request):
    _require_panel_auth(request)
    host = public_host()
    return {k: client_json(v, host) for k, v in PROFILES.items()}


@app.get("/api/admin/users")
async def admin_users(request: Request):
    _require_panel_auth(request)
    users = _users_from_state()
    return {"users": [{"id":u["id"], "name":u.get("name", "user"), "enabled":bool(u.get("enabled", True)), "active":_user_is_active(u), "expires_at":u.get("expires_at"), "quota_gb":u.get("quota_gb", 0), "created_at":u.get("created_at")} for u in users]}


@app.post("/api/admin/users")
async def admin_create_user(request: Request):
    _require_panel_auth(request)
    try:
        body = await request.json()
        name = str(body.get("name", "")).strip()[:80]
        days = max(1, min(3650, int(body.get("days", 30))))
        quota_gb = max(0, min(100000, float(body.get("quota_gb", 0))))
    except (ValueError, TypeError, AttributeError):
        raise HTTPException(400, "اطلاعات ورودی نامعتبر است")
    if not name:
        raise HTTPException(400, "نام کاربر را وارد کن")
    users = _users_from_state()
    user = {"id":secrets.token_hex(8), "name":name, "vless_uuid":str(uuid.uuid4()), "vmess_uuid":str(uuid.uuid4()), "trojan_password":secrets.token_urlsafe(32), "token":secrets.token_urlsafe(32), "enabled":True, "quota_gb":quota_gb, "used_bytes":None, "created_at":int(time.time()), "expires_at":int(time.time())+days*86400, "reset_days":0}
    users.append(user)
    _save_users(users)
    _reload_config_file()
    return {"ok":True,"id":user["id"]}


@app.post("/api/admin/users/{user_id}/toggle")
async def admin_toggle_user(user_id: str, request: Request):
    _require_panel_auth(request)
    users = _users_from_state()
    user = next((u for u in users if u.get("id") == user_id), None)
    if not user: raise HTTPException(404, "کاربر پیدا نشد")
    user["enabled"] = not bool(user.get("enabled", True))
    user.pop("disabled_reason", None)
    _save_users(users); _reload_config_file()
    return {"ok":True,"enabled":user["enabled"]}


@app.post("/api/admin/users/{user_id}/extend")
async def admin_extend_user(user_id: str, request: Request):
    _require_panel_auth(request)
    body = await request.json()
    try: days = max(1, min(3650, int(body.get("days", 30))))
    except (ValueError, TypeError, AttributeError): raise HTTPException(400, "مدت تمدید نامعتبر است")
    users = _users_from_state(); user = next((u for u in users if u.get("id") == user_id), None)
    if not user: raise HTTPException(404, "کاربر پیدا نشد")
    user["expires_at"] = max(int(user.get("expires_at") or time.time()), int(time.time())) + days*86400
    user["enabled"] = True; user.pop("disabled_reason", None)
    _save_users(users); _reload_config_file()
    return {"ok":True,"expires_at":user["expires_at"]}


@app.delete("/api/admin/users/{user_id}")
async def admin_delete_user(user_id: str, request: Request):
    _require_panel_auth(request)
    users = _users_from_state(); updated = [u for u in users if u.get("id") != user_id]
    if len(updated) == len(users): raise HTTPException(404, "کاربر پیدا نشد")
    _save_users(updated); _reload_config_file()
    return {"ok":True}


def _subscription_for_user(user: dict, host: str) -> list[str]:
    creds = {"vless":user["vless_uuid"], "vmess":user["vmess_uuid"], "trojan":user["trojan_password"]}
    return [build_uri(p, host, creds) for p in PROFILES.values()]


@app.get("/sub/{token}", response_class=PlainTextResponse)
async def user_subscription(token: str):
    user = next((u for u in _users_from_state() if hmac.compare_digest(str(u.get("token", "")), token)), None)
    if not user or not _user_is_active(user): raise HTTPException(404, "subscription not found")
    raw = "\n".join(_subscription_for_user(user, public_host()))
    return Response(content=base64.b64encode(raw.encode()).decode(), media_type="text/plain", headers={"Cache-Control":"no-store", "Profile-Title":quote(str(user.get("name", "HF subscription")) )})


@app.get("/qr/{token}")
async def user_subscription_qr(token: str):
    if qrcode is None or BytesIO is None:
        raise HTTPException(503, "QR dependency is not installed")
    user = next((u for u in _users_from_state() if hmac.compare_digest(str(u.get("token", "")), token)), None)
    if not user or not _user_is_active(user): raise HTTPException(404, "subscription not found")
    target = f"https://{public_host()}/sub/{token}"
    img = qrcode.make(target)
    buffer = BytesIO(); img.save(buffer, format="PNG")
    return Response(content=buffer.getvalue(), media_type="image/png", headers={"Cache-Control":"no-store"})


@app.get("/api/admin/users/{user_id}/subscription")
async def admin_user_subscription(user_id: str, request: Request):
    _require_panel_auth(request)
    user = next((u for u in _users_from_state() if u.get("id") == user_id), None)
    if not user: raise HTTPException(404, "کاربر پیدا نشد")
    host = public_host(); content = "\n".join(_subscription_for_user(user, host))
    return {"url":f"https://{host}/sub/{user['token']}","qr_url":f"https://{host}/qr/{user['token']}","content":content}


@app.get("/api/admin/backup")
async def admin_backup(request: Request):
    _require_panel_auth(request)
    return {"format":"hf-rvg-backup-v1","exported_at":int(time.time()),"users":_users_from_state()}


@app.post("/api/admin/restore/preview")
async def admin_restore_preview(request: Request):
    _require_panel_auth(request)
    data = await request.json()
    incoming = data.get("users") if isinstance(data, dict) else None
    if not isinstance(incoming, list): raise HTTPException(400, "فایل پشتیبان معتبر نیست")
    existing = _users_from_state()
    ids = {u.get("id") for u in existing}
    return {"incoming":len(incoming),"existing":len(existing),"duplicates":sum(1 for u in incoming if isinstance(u,dict) and u.get("id") in ids)}


@app.post("/api/admin/restore")
async def admin_restore(request: Request):
    _require_panel_auth(request)
    data = await request.json()
    incoming = data.get("users") if isinstance(data, dict) else None
    if not isinstance(incoming, list): raise HTTPException(400, "فایل پشتیبان معتبر نیست")
    existing = _users_from_state(); by_id = {u.get("id"):u for u in existing if u.get("id")}
    imported = 0
    for u in incoming:
        if not isinstance(u,dict) or not u.get("id"): continue
        # Only accept fields needed by this application; preserve existing users on ID collision.
        if u["id"] in by_id: continue
        required = ("vless_uuid","vmess_uuid","trojan_password","token")
        if not all(isinstance(u.get(k),str) and u.get(k) for k in required): continue
        safe = {k:u.get(k) for k in ("id","name","vless_uuid","vmess_uuid","trojan_password","token","enabled","quota_gb","used_bytes","created_at","expires_at","reset_days")}
        safe.setdefault("enabled",True); safe.setdefault("name","restored-user")
        existing.append(safe); by_id[safe["id"]]=safe; imported+=1
    _save_users(existing); _reload_config_file()
    return {"ok":True,"imported":imported,"total":len(existing)}


@app.get("/api/admin/status")
async def admin_status(request: Request):
    _require_panel_auth(request)
    try:
        import resource
        max_rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
        if platform.system() != "Darwin": max_rss = int(max_rss * 1024)
    except Exception:
        max_rss = None
    active_users = sum(1 for u in _users_from_state() if _user_is_active(u))
    return {"xray_running": bool(XRAY_PROC is not None and XRAY_PROC.returncode is None), "active_users": active_users, "users_total": len(_users_from_state()), "panel_max_rss_bytes": max_rss, "traffic_counters": "unavailable in this build; no fabricated values"}


@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
    if not _panel_is_configured():
        return HTMLResponse(SETUP_HTML.replace("{error}", ""))
    if not _valid_session(request.cookies.get("hf_panel_session")):
        return HTMLResponse(LOGIN_HTML.replace("{error}", ""))
    return HTMLResponse(panel_html(public_host()))


@app.post("/setup")
async def setup(request: Request, password: str = Form(...), confirmation: str = Form(...)):
    if _panel_is_configured():
        return HTMLResponse("Setup is already complete.", status_code=409)
    if not _same_origin(request):
        return HTMLResponse("Invalid origin.", status_code=403)
    error = _password_policy_error(password, confirmation)
    if error:
        return HTMLResponse(SETUP_HTML.replace("{error}", f"<p class='err'>{error}</p>"), status_code=400)
    _set_panel_password(password)
    result = HTMLResponse(status_code=303)
    result.headers["Location"] = "/"
    result.set_cookie("hf_panel_session", _make_session(), max_age=SESSION_TTL, httponly=True, secure=True, samesite="lax", path="/")
    return result


@app.post("/login")
async def login(request: Request, password: str = Form(...)):
    if not _panel_is_configured():
        return HTMLResponse(SETUP_HTML.replace("{error}", ""))
    if not _same_origin(request):
        return HTMLResponse("Invalid origin.", status_code=403)
    if not _verify_panel_password(password):
        return HTMLResponse(LOGIN_HTML.replace("{error}", "<p class='err'>رمز عبور اشتباه است.</p>"), status_code=401)
    result = HTMLResponse(status_code=303)
    result.headers["Location"] = "/"
    result.set_cookie("hf_panel_session", _make_session(), max_age=SESSION_TTL, httponly=True, secure=True, samesite="lax", path="/")
    return result


@app.get("/logout")
async def logout():
    result = HTMLResponse(LOGIN_HTML.replace("{error}", ""))
    result.delete_cookie("hf_panel_session", path="/")
    return result


async def bridge_ws_to_xray(websocket: WebSocket, port: int) -> None:
    await websocket.accept()
    reader, writer = await asyncio.open_connection("127.0.0.1", port)
    raw_sock = writer.transport.get_extra_info("socket") if writer.transport else None
    if raw_sock is not None:
        _set_socket_keepalive(raw_sock)
        transport = writer.transport
        if transport is not None:
            try:
                transport.set_write_buffer_limits(high=BRIDGE_WRITE_HIGH_WATER, low=BRIDGE_WRITE_LOW_WATER)
            except (AttributeError, OSError):
                pass

    async def ws_to_tcp() -> None:
        pending = 0
        try:
            while True:
                message = await websocket.receive()
                if message.get("type") == "websocket.disconnect":
                    return
                data = message.get("bytes")
                if data:
                    writer.write(data)
                    pending += len(data)
                    if pending >= BRIDGE_DRAIN_BYTES:
                        await writer.drain()
                        pending = 0
                elif message.get("text") is not None:
                    # Proxy transport is binary. Do not reinterpret text frames.
                    return
        finally:
            if pending:
                try:
                    await writer.drain()
                except (ConnectionError, BrokenPipeError):
                    pass

    async def tcp_to_ws() -> None:
        while True:
            chunk = await reader.read(BRIDGE_READ_BYTES)
            if not chunk:
                return
            # Use one large binary frame per read. Avoid slicing/copying the payload.
            await websocket.send_bytes(chunk)

    tasks = [asyncio.create_task(ws_to_tcp()), asyncio.create_task(tcp_to_ws())]
    try:
        done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)
        await asyncio.gather(*done, return_exceptions=True)
    finally:
        writer.close()
        try:
            await writer.wait_closed()
        except Exception:
            pass
        try:
            await websocket.close()
        except Exception:
            pass


@app.websocket(WS_VLESS_PATH)
async def ws_vless(websocket: WebSocket):
    try:
        await bridge_ws_to_xray(websocket, PROFILES["vless-ws"]["port"])
    except (WebSocketDisconnect, ConnectionError):
        pass
    except Exception as exc:
        print(f"[ws/vless] {exc}", flush=True)


@app.websocket(WS_TROJAN_PATH)
async def ws_trojan(websocket: WebSocket):
    try:
        await bridge_ws_to_xray(websocket, PROFILES["trojan-ws"]["port"])
    except (WebSocketDisconnect, ConnectionError):
        pass
    except Exception as exc:
        print(f"[ws/trojan] {exc}", flush=True)


@app.websocket(WS_VMESS_PATH)
async def ws_vmess(websocket: WebSocket):
    try:
        await bridge_ws_to_xray(websocket, PROFILES["vmess-ws"]["port"])
    except (WebSocketDisconnect, ConnectionError):
        pass
    except Exception as exc:
        print(f"[ws/vmess] {exc}", flush=True)


HOP_BY_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", "host"}
RESPONSE_HOP_BY_HOP = HOP_BY_HOP | {"content-length"}


async def proxy_xhttp(request: Request, profile: dict) -> StreamingResponse:
    if HTTP_CLIENT is None:
        raise HTTPException(503, "proxy client is not ready")
    suffix = request.path_params.get("tail", "")
    target_path = profile["path"].rstrip("/")
    if suffix:
        target_path += "/" + suffix
    query = request.url.query
    target = f"http://127.0.0.1:{profile['port']}{target_path}"
    if query:
        target += "?" + query

    headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP_BY_HOP}
    # packet-up sends many POST bodies; preserve their Content-Length when the
    # edge supplied one so the local Xray HTTP parser does not have to rely on
    # chunked framing.
    if request.headers.get("content-length"):
        headers["content-length"] = request.headers["content-length"]
    content: AsyncIterator[bytes] | None = None if request.method in {"GET", "HEAD", "OPTIONS"} else request.stream()

    try:
        upstream = HTTP_CLIENT.build_request(request.method, target, headers=headers, content=content)
        upstream_response = await HTTP_CLIENT.send(upstream, stream=True)
    except httpx.HTTPError as exc:
        raise HTTPException(502, f"xhttp upstream error: {exc}") from exc

    response_headers = {k: v for k, v in upstream_response.headers.items() if k.lower() not in RESPONSE_HOP_BY_HOP}
    response_headers.setdefault("Cache-Control", "no-store")
    response_headers.setdefault("X-Accel-Buffering", "no")
    return StreamingResponse(
        upstream_response.aiter_raw(),
        status_code=upstream_response.status_code,
        headers=response_headers,
        background=BackgroundTask(upstream_response.aclose),
    )


@app.api_route(XHTTP_VLESS_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_VLESS_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_vless(request: Request):
    return await proxy_xhttp(request, PROFILES["vless-xhttp"])


@app.api_route(XHTTP_TROJAN_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_TROJAN_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_trojan(request: Request):
    return await proxy_xhttp(request, PROFILES["trojan-xhttp"])


@app.api_route(XHTTP_VMESS_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_VMESS_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_vmess(request: Request):
    return await proxy_xhttp(request, PROFILES["vmess-xhttp"])


@app.api_route(XHTTP_PACKET_VLESS_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_PACKET_VLESS_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_packet_vless(request: Request):
    return await proxy_xhttp(request, PROFILES["vless-packet-up"])


@app.api_route(XHTTP_PACKET_TROJAN_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_PACKET_TROJAN_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_packet_trojan(request: Request):
    return await proxy_xhttp(request, PROFILES["trojan-packet-up"])


@app.api_route(XHTTP_PACKET_VMESS_PATH, methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
@app.api_route(XHTTP_PACKET_VMESS_PATH.rstrip("/") + "/{tail:path}", methods=["GET", "POST", "PUT", "PATCH", "HEAD", "OPTIONS"])
async def xhttp_packet_vmess(request: Request):
    return await proxy_xhttp(request, PROFILES["vmess-packet-up"])


def _report_zerogpu_startup() -> None:
    if spaces is None:
        return
    try:
        from spaces.zero import startup as zero_startup
    except (ImportError, AttributeError):
        return
    zero_startup()
    print("ZeroGPU startup report sent", flush=True)


def _write_nginx_config() -> None:
    NGINX_PREFIX.mkdir(parents=True, exist_ok=True)
    for name in ("client_body_temp", "proxy_temp", "fastcgi_temp", "uwsgi_temp", "scgi_temp"):
        (NGINX_PREFIX / name).mkdir(exist_ok=True)

    ws_locations = []
    for key in ("vless-ws", "trojan-ws", "vmess-ws"):
        p = PROFILES[key]
        ws_locations.append(f"""
        location = {p['path']} {{
            proxy_pass http://127.0.0.1:{p['port']};
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_buffering off;
            proxy_request_buffering off;
            proxy_connect_timeout 10s;
            proxy_read_timeout 1h;
            proxy_send_timeout 1h;
            proxy_socket_keepalive on;
        }}
        """)

    xhttp_locations = []
    for key in ("vless-xhttp", "trojan-xhttp", "vmess-xhttp", "vless-packet-up", "trojan-packet-up", "vmess-packet-up"):
        p = PROFILES[key]
        xhttp_locations.append(f"""
        location ^~ {p['path']} {{
            proxy_pass http://127.0.0.1:{p['port']};
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Content-Length $http_content_length;
            proxy_buffering off;
            proxy_request_buffering off;
            proxy_connect_timeout 10s;
            proxy_read_timeout 1h;
            proxy_send_timeout 1h;
            proxy_socket_keepalive on;
        }}
        """)

    cfg = f"""
worker_processes 2;
worker_rlimit_nofile 65535;
pid {NGINX_PREFIX / 'nginx.pid'};
error_log /dev/stderr warn;

events {{
    worker_connections 8192;
    multi_accept on;
}}

http {{
    access_log off;
    default_type application/octet-stream;
    sendfile off;
    tcp_nodelay on;
    keepalive_timeout 65s;
    keepalive_requests 10000;
    client_max_body_size 64m;
    client_body_timeout 1h;
    send_timeout 1h;
    proxy_http_version 1.1;
    proxy_buffering off;
    proxy_request_buffering off;
    proxy_connect_timeout 10s;
    proxy_read_timeout 1h;
    proxy_send_timeout 1h;

    map $http_upgrade $connection_upgrade {{
        default upgrade;
        '' close;
    }}

    server {{
        listen {PUBLIC_PORT} reuseport;
        server_name _;
        {''.join(ws_locations)}
        {''.join(xhttp_locations)}

        location / {{
            proxy_pass http://127.0.0.1:{PANEL_PORT};
            proxy_http_version 1.1;
            proxy_set_header Host $http_host;
            proxy_set_header X-Forwarded-Host $http_host;
            proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_buffering off;
            proxy_request_buffering off;
            proxy_read_timeout 1h;
            proxy_send_timeout 1h;
        }}
    }}
}}
""".strip() + "\n"
    NGINX_CFG.write_text(cfg, encoding="utf-8")


async def _spawn_panel() -> asyncio.subprocess.Process:
    env = os.environ.copy()
    env["HF_RVG_SUPERVISED_XRAY"] = "1"
    return await asyncio.create_subprocess_exec(
        os.sys.executable, "-m", "uvicorn", "app:app",
        "--host", "127.0.0.1", "--port", str(PANEL_PORT),
        "--loop", "uvloop", "--http", "httptools", "--ws", "wsproto",
        "--ws-max-size", str(64 * 1024 * 1024),
        "--ws-max-queue", str(WS_MAX_QUEUE),
        "--ws-ping-interval", str(WS_PING_INTERVAL),
        "--ws-ping-timeout", str(WS_PING_TIMEOUT),
        "--timeout-keep-alive", "30", "--backlog", str(UVICORN_BACKLOG),
        "--log-level", "warning", "--no-access-log",
        env=env,
    )


async def _spawn_nginx() -> asyncio.subprocess.Process:
    return await asyncio.create_subprocess_exec(
        "nginx", "-c", str(NGINX_CFG), "-g", "daemon off;"
    )


async def _terminate(proc: asyncio.subprocess.Process | None, name: str) -> None:
    if proc is None or proc.returncode is not None:
        return
    try:
        proc.terminate()
        await asyncio.wait_for(proc.wait(), timeout=5)
    except (ProcessLookupError, asyncio.TimeoutError):
        if proc.returncode is None:
            proc.kill()
            try:
                await proc.wait()
            except Exception:
                pass
    print(f"{name} stopped", flush=True)


async def _serve_supervised() -> None:
    global PANEL_PROC, NGINX_PROC
    await start_xray()
    _write_nginx_config()
    PANEL_PROC = await _spawn_panel()
    NGINX_PROC = await _spawn_nginx()
    print(
        f"Native proxy mode: HF:{PUBLIC_PORT} -> nginx -> Xray directly; panel={PANEL_PORT}",
        flush=True,
    )

    panel_delay = 1.0
    nginx_delay = 1.0
    try:
        while True:
            await asyncio.sleep(1.0)
            if PANEL_PROC.returncode is not None:
                print(f"Panel exited ({PANEL_PROC.returncode}); restarting", flush=True)
                await asyncio.sleep(panel_delay)
                PANEL_PROC = await _spawn_panel()
                panel_delay = min(panel_delay * 2, 15.0)
            else:
                panel_delay = 1.0
            if NGINX_PROC.returncode is not None:
                print(f"nginx exited ({NGINX_PROC.returncode}); restarting", flush=True)
                await asyncio.sleep(nginx_delay)
                _write_nginx_config()
                NGINX_PROC = await _spawn_nginx()
                nginx_delay = min(nginx_delay * 2, 15.0)
            else:
                nginx_delay = 1.0
    finally:
        await _terminate(NGINX_PROC, "nginx")
        await _terminate(PANEL_PROC, "panel")
        await stop_xray()


if __name__ == "__main__":
    _report_zerogpu_startup()
    asyncio.run(_serve_supervised())