-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.js
1392 lines (1169 loc) · 55.9 KB
/
server.js
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
require('dotenv').config()
const express = require('express'); const app = express();
const fileUpload = require('express-fileupload');
const fs = require('fs');
var AdmZip = require("adm-zip");
var { accounts_clct, panels_clct, users_clct, logs_clct } = require('./db_interface');
const amnezia_sub_page_html = fs.readFileSync("custom_sub/amnezia.html").toString();
const not_found_page_html = fs.readFileSync("custom_sub/404.html").toString();
const AMNEZIA_COEFFICIENT = 1.33;
var SD_VARIABLE = 0;
const {
uid,
uidv2,
insert_to_accounts,
get_accounts,
get_account,
update_account,
insert_to_panels,
get_panels,
get_panel,
update_panel,
insert_to_users,
get_users,
get_all_users,
get_user1,
username_to_id,
get_user2,
update_user,
insert_to_logs,
get_logs,
b2gb,
gb2b,
format_number,
add_token,
token_to_account,
get_panel_info,
make_vpn,
delete_vpn,
disable_vpn,
enable_vpn,
edit_vpn,
reload_agents,
reset_marzban_user,
unlock_marzban_user,
delete_folder_content,
enable_panel,
disable_panel,
get_sub_url,
switch_countries,
proxy_obj_maker,
update_user_links_bg,
deep_equal,
token_to_sub_account,
delete_vpn_group,
enable_vpn_group,
disable_vpn_group,
notify_tgb,
get_user_data_graph,
get_agent_data_graph,
get_agents,
get_backup_from_everything,
make_zarinpal_gateway,
verify_zarinpal_payment,
get_last_payment,
} = require("./utils");
app.use(express.static('public'));
app.use(express.json());
app.use(fileUpload());
app.use(auth_middleware);
// --- MIDDLEWARE --- //
async function auth_middleware(req, res, next) {
if( req.body.service_access_api_key == process.env.ACCESS_API_KEY ) return next();
if (SD_VARIABLE == 1) return res.status(500).send({ message: 'Service unavailable' });
if (req.url == "/login" || req.url.startsWith("/sub") || req.url.startsWith("/confirm_payment") || req.url.startsWith("/ping") ) return next();
var { access_token } = req.body;
var account = await token_to_account(access_token);
if (!account) return res.send({ status: "ERR", msg: 'Token is either expired or invalid' });
else
{
var endpoints =
{
sub_accounts_perms:["/add_sub_account","/edit_sub_account","/delete_sub_account"],
users_perms:["/create_user","/delete_user","/disable_user","/enable_user","/edit_user","/reset_user","/switch_countries","/checkout"],
agents_perms:["/create_agent","/delete_agent","/disable_agent","/enable_agent","/edit_agent","/enable_edit_access","/enable_create_access","/enable_delete_access","/disable_edit_access","/disable_create_access","/disable_delete_access","/disable_all_agent_users","/enable_all_agent_users","/delete_all_agent_users"],
panels_perms:["/create_panel","/delete_panel","/disable_panel","/enable_panel","/edit_panel"]
};
if(access_token.includes("#") && [...endpoints.agents_perms,...endpoints.panels_perms,"/dldb","/uldb"].includes(req.url)) res.send({ status: "ERR", msg: 'access denied' });
else if(access_token.includes("@") && endpoints.sub_accounts_perms.includes(req.url)) res.send({ status: "ERR", msg: 'access denied' });
else if(access_token.includes("@") && !access_token.includes("$") && endpoints.panels_perms.includes(req.url)) res.send({ status: "ERR", msg: 'access denied' });
else if(access_token.includes("@") && !access_token.includes("%") && endpoints.agents_perms.includes(req.url)) res.send({ status: "ERR", msg: 'access denied' });
else if(access_token.includes("@") && !access_token.includes("^") && endpoints.users_perms.includes(req.url)) res.send({ status: "ERR", msg: 'access denied' });
else next();
}
}
// --- ENDPOINTS --- //
app.post("/ping", async (req, res) =>
{
res.send("OK");
});
app.post("/get_agents", async (req, res) => {
await reload_agents();
var obj_arr = await get_agents();
res.send(obj_arr);
});
app.post("/get_panels", async (req, res) => {
var obj_arr = await (await panels_clct()).find({}).toArray();
res.send(obj_arr);
});
app.post("/get_users", async (req, res) => {
var { access_token,number_of_rows,current_page,search_filter,status_filter,panel_type } = req.body;
await reload_agents();
var agent_id = (await token_to_account(access_token)).id
var obj_arr = await get_users(agent_id);
if(process.env.RELEASE == "ALI" || process.env.RELEASE == "V" || process.env.RELEASE == "AHWAZGSM" || process.env.RELEASE == "REZA") obj_arr = obj_arr.map(x => {x.subscription_url = x.real_subscription_url;return x;});
obj_arr = obj_arr.reverse();
if(search_filter) obj_arr = obj_arr.filter(x => x.username.toLowerCase().includes(search_filter.toLowerCase()));
if(status_filter) obj_arr = obj_arr.filter(x => x.status == status_filter.toLowerCase());
if(panel_type)
{
var panels = await get_panels();
obj_arr = obj_arr.filter(x => panels.filter(y => y.id == x.corresponding_panel_id)[0].panel_type == panel_type);
}
if(!number_of_rows && !current_page) {current_page = 1;number_of_rows = 10;}
var total_pages = Math.ceil(obj_arr.length / number_of_rows);
obj_arr = obj_arr.slice((current_page - 1) * number_of_rows, current_page * number_of_rows);
res.send({ obj_arr, total_pages });
});
app.post("/get_agent", async (req, res) => {
var { access_token } = req.body;
var agent = await token_to_account(access_token);
var filteredCountries = await Promise.all(agent.country.split(",").map(async (x) =>
{
return x;
var panel_obj = (await (await panels_clct()).find({ panel_country: x }).toArray())[0];
if (panel_obj.disable || panel_obj.active_users >= panel_obj.panel_user_max_count || panel_obj.panel_traffic <= panel_obj.panel_data_usage ) return null;
else return x;
}));
agent.last_payment = await get_last_payment(agent.id);
agent.country = filteredCountries.filter(Boolean).join(",");
res.send(agent);
});
app.post("/get_agent_logs", async (req, res) => {
const { access_token, number_of_rows, current_page, actions,start_date,end_date,accounts } = req.body;
var obj = await get_logs();
var account_id = (await token_to_account(access_token)).id;
obj.sort((a, b) => b.time - a.time);
obj = obj.filter(x => x.account_id == account_id);
if (actions.length) obj = obj.filter(x => actions.includes(x.action));
if (accounts.length)
{
var id_arr = await Promise.all(accounts.map(async (x) => await username_to_id(x)));
obj = obj.filter(x => id_arr.includes(x.account_id));
}
if (start_date) obj = obj.filter(x => x.time >= start_date);
if (end_date) obj = obj.filter(x => x.time <= end_date);
var total_pages = Math.ceil(obj.length / number_of_rows);
obj = obj.slice((current_page - 1) * number_of_rows, current_page * number_of_rows);
res.send({ obj, total_pages });
});
app.post("/get_admin_logs", async (req, res) =>
{
const { number_of_rows, current_page, actions, accounts,start_date,end_date,syslog } = req.body;
var obj = await get_logs();
obj.sort((a, b) => b.time - a.time);
if (actions.length) obj = obj.filter(x => actions.includes(x.action) || x.is_syslog);
if (accounts.length)
{
var id_arr = await Promise.all(accounts.map(async (x) => await username_to_id(x)));
obj = obj.filter(x => id_arr.includes(x.account_id) || x.is_syslog);
}
if (start_date) obj = obj.filter(x => x.time >= start_date);
if (end_date) obj = obj.filter(x => x.time <= end_date);
if (!syslog) obj = obj.filter(x=>x.is_syslog == null)
var total_pages = Math.ceil(obj.length / number_of_rows);
obj = obj.slice((current_page - 1) * number_of_rows, current_page * number_of_rows);
res.send({ obj, total_pages });
});
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const accounts = await get_accounts();
const account = accounts.filter(x => x.username == username && x.password == password)[0];
const sub_account_parent = accounts.filter(x => x.sub_accounts.filter(y => y.username == username && y.password == password).length)[0]
if (account)
{
var access_token = await add_token(account.id,account.id,account.is_admin);
await insert_to_logs(account.id, "LOGIN", "logged in",access_token);
res.send({ is_admin: account.is_admin, access_token });
}
else if(sub_account_parent)
{
var sub_account = sub_account_parent.sub_accounts.filter(y => y.username == username && y.password == password)[0];
var access_token = await add_token(sub_account_parent.id,sub_account.id,sub_account_parent.is_admin,sub_account.perms);
await insert_to_logs(sub_account_parent.id, "LOGIN", "logged in",access_token);
res.send({ is_admin: sub_account_parent.is_admin, access_token });
}
else
{
res.status(401).send({ message: 'NOT FOUND' });
}
var all_accounts = await get_accounts();
all_accounts.forEach(async (account_obj) =>
{
var tokens = account_obj.tokens;
var new_tokens = tokens.filter( x => x.expire > Math.floor(Date.now()/1000) );
await update_account(account_obj.id,{tokens:new_tokens});
});
});
app.post("/create_agent", async (req, res) => {
const { name,
username,
password,
volume,
min_vol,
max_users,
max_days,
prefix,
country,
max_non_active_days,
business_mode,
access_token,
vrate } = req.body;
var agents_arr = await get_agents();
var prefix_arr = agents_arr.map(x => x.prefix);
var name_arr = agents_arr.map(x => x.name);
var username_arr = agents_arr.map(x => x.username);
if (!name || !username || !password || !volume || !min_vol || !max_users || !max_days || !prefix || !country || !max_non_active_days || !vrate) res.send({ status: "ERR", msg: "fill all of the inputs" })
else if(prefix_arr.includes(prefix)) res.send({ status: "ERR", msg: "prefix already exists" });
else if(name_arr.includes(name)) res.send({ status: "ERR", msg: "name already exists" });
else if(username_arr.includes(username)) res.send({ status: "ERR", msg: "username already exists" });
else if(isNaN(vrate)) res.send({ status: "ERR", msg: "invalid vrate" });
else if(vrate < 5_000) res.send({ status: "ERR", msg: "volume rate is too low" });
else {
await insert_to_accounts({
id: uid(),
is_admin: 0,
disable: 0,
create_access:1,
edit_access:1,
delete_access:1,
name,
username,
password,
volume: gb2b(volume),
lifetime_volume: gb2b(volume),
allocatable_data: (process.env.RELEASE == "ALI" || process.env.RELEASE == "REZA") ? 100000 : format_number(volume),
min_vol: format_number(min_vol),
max_users: parseInt(max_users),
max_days: parseInt(max_days),
max_non_active_days:parseInt(max_non_active_days),
vrate:parseInt(vrate),
gateway_status:{zarinpal:0,nowpayments:0},
prefix,
country,
used_traffic: 0.00,
active_users: 0,
total_users: 0,
business_mode:business_mode?1:0,
tokens: [],
sub_accounts:[],
daily_usage_logs:[]
});
var account_id = (await token_to_account(access_token)).id;
await insert_to_logs(account_id, "CREATE_AGENT", `created agent !${name} with !${volume} GB data`,access_token)
res.send("DONE");
}
});
app.post("/create_panel", async (req, res) => {
const { panel_name,
panel_url,
panel_username,
panel_password,
panel_country,
panel_user_max_count,
panel_traffic,
access_token } = req.body;
var panel_info = await get_panel_info(panel_url, panel_username, panel_password);
var available_panels = await get_panels();
var panel_countries_arr = available_panels.map(x => x.panel_country);
var panel_urls_arr = available_panels.map(x => x.panel_url);
var panel_names_arr = available_panels.map(x => x.panel_name);
if (!panel_name || !panel_url || !panel_username || !panel_password || !panel_country || !panel_user_max_count || !panel_traffic) res.send({ status: "ERR", msg: "fill all of the inputs" })
else if (panel_info == "ERR") res.send({ status: "ERR", msg: "Failed to connect to panel" });
else if (panel_urls_arr.includes(panel_url)) res.send({ status: "ERR", msg: "panel url already exists" });
else if (panel_names_arr.includes(panel_name)) res.send({ status: "ERR", msg: "panel name already exists" });
else {
await insert_to_panels({
id: uid(),
disable: 0,
panel_name,
panel_username,
panel_password,
panel_url,
panel_country: panel_country + (panel_countries_arr.filter(x => x.replace(/\d+$/, '') == panel_country).length + 1),
panel_user_max_count: parseInt(panel_user_max_count),
panel_traffic: format_number(panel_traffic),
panel_data_usage: format_number(panel_info.panel_data_usage),
active_users: panel_info.active_users,
total_users: panel_info.total_users,
panel_type:panel_info.panel_type,
});
var account_id = (await token_to_account(access_token)).id;
await insert_to_logs(account_id, "CREATE_PANEL", `created panel !${panel_name}`,access_token);
res.send("DONE");
}
});
app.post("/create_user", async (req, res) => {
var { username,
expire,
data_limit,
country,
access_token,
protocols,
flow_status,
desc,
safu,
inbounds,
ip_limit,
} = req.body;
// TEMP
ip_limit = 1;
if(process.env.RELEASE == "ARMAN") flow_status = "xtls-rprx-vision";
if (!username || !expire || !data_limit || !country || !ip_limit || protocols.length == 0)
{
res.send({ status: "ERR", msg: "fill all of the inputs" })
return;
}
var corresponding_agent = await token_to_account(access_token);
var agent_id = corresponding_agent.id;
var all_usernames = [...(await get_all_users()).map(x => x.username)];
var panels_arr = await get_panels();
var selected_panel = panels_arr.filter(x => x.panel_country == country )[0];
var agent_user_count = (await get_all_users()).filter(x => x.agent_id == agent_id).length;
if (corresponding_agent.disable) res.send({ status: "ERR", msg: "your account is disabled" })
else if (!corresponding_agent.create_access) res.send({ status: "ERR", msg: "access denied" })
else if (!corresponding_agent.country.split(",").includes(country)) res.send({ status: "ERR", msg: "country access denied" })
else if (isNaN(expire) || isNaN(data_limit) || isNaN(ip_limit)) res.send({ status: "ERR", msg: "invalid inputs" })
else if (ip_limit % 1 != 0) res.send({ status: "ERR", msg: "ip limit must be an integer" })
else if (ip_limit < 1) res.send({ status: "ERR", msg: "minimum allowed ip limit is 1" })
else if (!selected_panel) res.send({ status: "ERR", msg: "no available server" });
else if (selected_panel.total_users >= selected_panel.panel_user_max_count) res.send({ status: "ERR", msg: "panel is full" })
else if (selected_panel.disable) res.send({ status: "ERR", msg: "panel is disabled" })
else if (selected_panel.panel_traffic <= selected_panel.panel_data_usage) res.send({ status: "ERR", msg: "panel is out of traffic" })
else if (selected_panel.panel_traffic - selected_panel.panel_data_usage < data_limit) res.send({ status: "ERR", msg: "insufficient traffic on server" });
else if (selected_panel.panel_type != "AMN" && data_limit > corresponding_agent.allocatable_data) res.send({ status: "ERR", msg: "not enough allocatable data" })
else if (selected_panel.panel_type == "AMN" && expire % 30 != 0) res.send({ status: "ERR", msg: "invalid expire time" })
else if (selected_panel.panel_type == "AMN" && expire * ip_limit * AMNEZIA_COEFFICIENT > corresponding_agent.allocatable_data) res.send({ status: "ERR", msg: "not enough allocatable data" })
else if (expire > corresponding_agent.max_days) res.send({ status: "ERR", msg: "maximum allowed days is " + corresponding_agent.max_days })
else if (selected_panel.panel_type != "AMN" && corresponding_agent.min_vol > data_limit) res.send({ status: "ERR", msg: "minimum allowed data is " + corresponding_agent.min_vol })
else if (corresponding_agent.max_users <= agent_user_count) res.send({ status: "ERR", msg: "maximum allowed users is " + corresponding_agent.max_users })
else if (all_usernames.includes(corresponding_agent.prefix + "_" + username)) res.send({ status: "ERR", msg: "username already exists" })
else {
for (let protocol in inbounds)
{
if(inbounds[protocol].length == 0)
{
protocols = protocols.filter(x => x != protocol);
}
}
var mv = await make_vpn
(
selected_panel.panel_url,
selected_panel.panel_username,
selected_panel.panel_password,
corresponding_agent.prefix + "_" + username,
gb2b(data_limit),
Math.floor(Date.now() / 1000) + expire * 24 * 60 * 60,
protocols,
flow_status,
inbounds,
ip_limit
)
if (mv == "ERR") res.send({ status: "ERR", msg: "failed to connect to marzban" })
else {
var inbounds = proxy_obj_maker(protocols,flow_status,2)
await insert_to_users({
id: uid(),
agent_id,
status: "active",
disable: 0,
username: corresponding_agent.prefix + "_" + username,
expire: Math.floor(Date.now() / 1000) + expire * 24 * 60 * 60,
data_limit: gb2b(data_limit),
used_traffic: 0.00,
lifetime_used_traffic: 0.00,
country,
corresponding_panel_id: selected_panel.id,
corresponding_panel: selected_panel.panel_url,
real_subscription_url: (mv.subscription_url.startsWith("/")?selected_panel.panel_url:"") + mv.subscription_url,
subscription_url: "https://" + get_sub_url() + "/sub/" + uidv2(10),
links: mv.links,
created_at:Math.floor(Date.now()/1000),
disable_counter:{value:0,last_update:Math.floor(Date.now() / 1000)},
inbounds,
safu:/*safu?1:0*/0,
desc,
ip_limit,
});
if(selected_panel.panel_type == "MZ") await update_account(agent_id, { allocatable_data: format_number(corresponding_agent.allocatable_data - data_limit) });
else if(selected_panel.panel_type == "AMN") await update_account(agent_id, { allocatable_data: format_number(corresponding_agent.allocatable_data - expire * ip_limit * AMNEZIA_COEFFICIENT)});
await insert_to_logs(agent_id, "CREATE_USER", `created user !${username} with !${data_limit} GB data and !${expire} days of expire time on !${selected_panel.panel_name}`,access_token);
res.send("DONE");
}
}
});
app.post("/delete_agent", async (req, res) => {
var { access_token, agent_id } = req.body;
var account_id = (await token_to_account(access_token)).id;
var agent_obj = await get_account(agent_id);
await (await accounts_clct()).deleteOne({ id: agent_id });
await insert_to_logs(account_id, "DELETE_AGENT", `deleted agent !${agent_obj.username}`,access_token);
res.send("DONE");
});
app.post("/delete_panel", async (req, res) => {
var { access_token, panel_id } = req.body;
var account_id = (await token_to_account(access_token)).id;
var panel_obj = await get_panel(panel_id);
var agents_arr = await get_agents();
for (let agent of agents_arr) {
var cindex = agent.country.split(",").indexOf(panel_obj.panel_country);
if (cindex != -1) {
var old_countries = agent.country.split(",");
old_countries.splice(cindex, 1);
var new_countries = old_countries.join(",");
await update_account(agent.id, { country: new_countries });
}
}
await (await panels_clct()).deleteOne({ id: panel_id });
await insert_to_logs(account_id, "DELETE_PANEL", `deleted panel !${panel_obj.panel_name}`,access_token);
res.send("DONE");
});
app.post("/delete_user", async (req, res) => {
var { access_token, username } = req.body;
var user_obj = await get_user2(username);
var agent_obj = await get_account(user_obj.agent_id);
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
if (agent_obj.disable) {res.send({ status: "ERR", msg: "your account is disabled" });return;}
else if(!agent_obj.delete_access) {res.send({ status: "ERR", msg: "access denied" });return;}
else if(!agent_obj.country.split(",").includes(user_obj.country)) {res.send({ status: "ERR", msg: "country access denied" });return;}
var result = await delete_vpn(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, username);
if (result == "ERR") res.send({ status: "ERR", msg: "failed to connect to marzban" })
else {
if(panel_obj.panel_type == "MZ")
{
if(process.env.RELEASE == "ALI")
{
if(user_obj.used_traffic == 0)
await update_account(agent_obj.id, { allocatable_data: format_number(agent_obj.allocatable_data + b2gb(user_obj.data_limit - user_obj.used_traffic)) });
}
else if(process.env.RELEASE != "REZA")
{
if( !(agent_obj.business_mode == 1 && (user_obj.used_traffic > user_obj.data_limit/4 || 7*86400 < (Math.floor(Date.now()/1000) - user_obj.created_at) )) ) await update_account(agent_obj.id, { allocatable_data: format_number(agent_obj.allocatable_data + b2gb(user_obj.data_limit - user_obj.used_traffic)) });
}
}
else if(panel_obj.panel_type == "AMN")
{
if(user_obj.used_traffic < gb2b(0.15))
await update_account(agent_obj.id, { allocatable_data: format_number(agent_obj.allocatable_data + (Math.floor((user_obj.expire-user_obj.created_at)/86400)+1) * user_obj.ip_limit * AMNEZIA_COEFFICIENT )});
}
await (await users_clct()).deleteOne({ username });
await insert_to_logs(agent_obj.id, "DELETE_USER", `deleted user !${username}`,access_token);
res.send("DONE");
}
});
app.post("/disable_panel", async (req, res) => {
var { access_token, panel_id } = req.body;
await disable_panel(panel_id);
var panel_obj = await get_panel(panel_id);
var account_id = (await token_to_account(access_token)).id;
await insert_to_logs(account_id, "DISABLE_PANEL", `disabled panel !${panel_obj.panel_name}`,access_token);
res.send("DONE");
});
app.post("/disable_agent", async (req, res) => {
var { access_token, agent_id } = req.body;
await update_account(agent_id, { disable: 1 });
var agent_obj = await get_account(agent_id);
var account_id = (await token_to_account(access_token)).id;
await insert_to_logs(account_id, "DISABLE_AGENT", `disabled agent !${agent_obj.username}`,access_token);
res.send("DONE");
});
app.post("/disable_user", async (req, res) => {
var { access_token, user_id } = req.body;
var user_obj = await get_user1(user_id);
var account = await token_to_account(access_token);
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
if (account.disable) {res.send({ status: "ERR", msg: "your account is disabled" });return;}
else if(!account.edit_access) {res.send({ status: "ERR", msg: "access denied" });return;}
var result = await disable_vpn(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") res.send({ status: "ERR", msg: "failed to connect to marzban" });
else {
await update_user(user_id, { status: "disable", disable: 1 });
await insert_to_logs(account.id, "DISABLE_USER", `disabled user !${user_obj.username}`,access_token);
res.send("DONE");
}
});
app.post("/enable_agent", async (req, res) => {
var { access_token, agent_id } = req.body;
await update_account(agent_id, { disable: 0 });
var account = await token_to_account(access_token);
var agent_obj = await get_account(agent_id);
await insert_to_logs(account.id, "ENABLE_AGENT", `enabled agent !${agent_obj.username}`,access_token);
res.send("DONE");
});
app.post("/enable_panel", async (req, res) => {
var { access_token, panel_id } = req.body;
await enable_panel(panel_id);
var account = await token_to_account(access_token);
var panel_obj = await get_panel(panel_id);
await insert_to_logs(account.id, "ENABLE_PANEL", `enabled panel !${panel_obj.panel_name}`,access_token);
res.send("DONE");
});
app.post("/enable_user", async (req, res) => {
var { access_token, user_id } = req.body;
var user_obj = await get_user1(user_id);
var account = await token_to_account(access_token);
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
if (account.disable) {res.send({ status: "ERR", msg: "your account is disabled" });return;}
else if(!account.edit_access) {res.send({ status: "ERR", msg: "access denied" });return;}
else if(!account.country.split(",").includes(user_obj.country)) {res.send({ status: "ERR", msg: "country access denied" });return;}
var result = await enable_vpn(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") res.send({ status: "ERR", msg: "failed to connect to marzban" });
else {
await update_user(user_id, { status: "active", disable: 0 });
await insert_to_logs(account.id, "ENABLE_USER", `enabled user !${user_obj.username}`,access_token);
res.send("DONE");
}
});
app.post("/edit_agent", async (req, res) => {
const { agent_id,
name,
username,
password,
volume,
min_vol,
max_users,
max_days,
prefix,
country,
max_non_active_days,
business_mode,
access_token,
vrate,
gateway_status
} = req.body;
var agent = await get_account(agent_id);
var agents_arr = await get_agents();
var prefix_arr = agents_arr.map(x => x.prefix);
var name_arr = agents_arr.map(x => x.name);
var username_arr = agents_arr.map(x => x.username);
var [old_prefix, old_name, old_username] = [agent.prefix, agent.name, agent.username];
if (!name || !username || !password || !volume || !min_vol || !max_users || !max_days || !prefix || !country || !max_non_active_days || !vrate || !gateway_status) res.send({ status: "ERR", msg: "fill all of the inputs" })
else if(prefix_arr.includes(prefix) && old_prefix != prefix) res.send({ status: "ERR", msg: "prefix already exists" });
else if(name_arr.includes(name) && old_name != name) res.send({ status: "ERR", msg: "name already exists" });
else if(username_arr.includes(username) && old_username != username) res.send({ status: "ERR", msg: "username already exists" });
else if(isNaN(vrate)) res.send({ status: "ERR", msg: "invalid vrate" });
else if(vrate < 5_000) res.send({ status: "ERR", msg: "volume rate is too low" });
else if (gateway_status.zarinpal == 1 && !process.env.ZARINPAL_TOKEN) res.send({ status: "ERR", msg: "Zarinpal token is not set" });
else if (gateway_status.nowpayments == 1 && !process.env.NOWPAYMENTS_TOKEN) res.send({ status: "ERR", msg: "NOWPayments token is not set" });
else {
var old_volume = agent.volume;
var old_alloc = agent.allocatable_data;
var update_obj =
{
name,
username,
password,
volume: gb2b(volume),
lifetime_volume: agent.lifetime_volume + gb2b(volume) - old_volume,
allocatable_data: format_number(format_number(old_alloc) + format_number(volume) - format_number(b2gb(old_volume))),
min_vol: format_number(min_vol),
max_users: parseInt(max_users),
max_days: parseInt(max_days),
prefix,
vrate:parseInt(vrate),
gateway_status,
max_non_active_days:parseInt(max_non_active_days),
business_mode:business_mode?1:0,
country
};
if(process.env.RELEASE == "REZA" || process.env.RELEASE == "ALI")
{
if(update_obj.business_mode == 0) delete update_obj.allocatable_data;
else update_obj.allocatable_data = format_number(volume);
}
await update_account(agent_id, update_obj);
var account = await token_to_account(access_token);
var log_msg = `edited agent !${name} `
if(Math.abs(Math.floor(old_volume) - Math.floor(gb2b(volume)))>gb2b(0.3))
{
log_msg += `and added !${b2gb(gb2b(volume) - old_volume)} GB data`
await insert_to_logs(agent_id,"RECEIVE_DATA",`received !${b2gb(gb2b(volume) - old_volume)} GB data`,access_token)
}
await insert_to_logs(account.id, "EDIT_AGENT", log_msg,access_token);
res.send("DONE");
}
});
app.post("/edit_panel", async (req, res) => {
const { panel_id,
panel_name,
panel_username,
panel_url,
panel_password,
panel_user_max_count,
panel_traffic,
access_token } = req.body;
var panel_info = await get_panel_info(panel_url, panel_username, panel_password);
var old_panel_obj = await get_panel(panel_id);
if (!panel_name || !panel_username || !panel_password || !panel_user_max_count || !panel_traffic || !panel_url) res.send({ status: "ERR", msg: "fill all of the inputs" })
else if (panel_info == "ERR") res.send({ status: "ERR", msg: "Failed to connect to panel" });
else {
await update_panel(panel_id, {
panel_name,
panel_username,
panel_password,
panel_url,
panel_user_max_count: parseInt(panel_user_max_count),
panel_traffic: format_number(panel_traffic),
});
if(old_panel_obj.panel_url != panel_url)
{
await (await users_clct()).updateMany({corresponding_panel_id:panel_id},{$set:{corresponding_panel:panel_url}});
var all_users = await get_all_users();
for(let user of all_users)
{
if(user.corresponding_panel_id == panel_id) await update_user(user.id,{real_subscription_url:panel_url + user.real_subscription_url.split(old_panel_obj.panel_url)[1]});
}
}
var account = await token_to_account(access_token);
await insert_to_logs(account.id, "EDIT_PANEL", `edited panel !${panel_name}`,access_token);
res.send("DONE");
}
});
app.post("/edit_user", async (req, res) => {
var { user_id,
expire,
data_limit,
country,
access_token,
protocols,
flow_status,
desc,
safu,
} = req.body;
if(process.env.RELEASE == "ARMAN") flow_status = "xtls-rprx-vision";
if (!user_id || !expire || !data_limit || !country || protocols.length == 0)
{
res.send({ status: "ERR", msg: "fill all of the inputs" });
return;
}
var user_obj = await get_user1(user_id);
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
var corresponding_agent = await token_to_account(access_token);
var old_data_limit = b2gb(user_obj.data_limit);
var old_expire = Math.floor((user_obj.expire - Math.floor(Date.now() / 1000)) / 86400) + 1;
var old_country = user_obj.country;
if (corresponding_agent.disable) res.send({ status: "ERR", msg: "your account is disabled" })
else if(!corresponding_agent.edit_access) res.send({ status: "ERR", msg: "access denied" })
else if (!corresponding_agent.country.split(",").includes(country)) res.send({ status: "ERR", msg: "country access denied" })
else if(b2gb(user_obj.used_traffic) > data_limit) res.send({ status: "ERR", msg: "data limit can't be reduced" })
else if (panel_obj.panel_type != "AMN" && data_limit - old_data_limit > corresponding_agent.allocatable_data) res.send({ status: "ERR", msg: "not enough allocatable data" })
else if (panel_obj.panel_type == "AMN" && expire * user_obj.ip_limit * AMNEZIA_COEFFICIENT > corresponding_agent.allocatable_data) res.send({ status: "ERR", msg: "not enough allocatable data" })
else if (panel_obj.panel_type == "AMN" && expire % 30 != 0) res.send({ status: "ERR", msg: "invalid expire time" })
else if (expire > corresponding_agent.max_days) res.send({ status: "ERR", msg: "maximum allowed days is " + corresponding_agent.max_days })
else if (corresponding_agent.min_vol > data_limit) res.send({ status: "ERR", msg: "minimum allowed data is " + corresponding_agent.min_vol })
else {
var is_changing_country = old_country != country;
var is_changing_protocols = !deep_equal(proxy_obj_maker(protocols,flow_status,2),user_obj.inbounds)
var result = await edit_vpn(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username, data_limit * ((2 ** 10) ** 3), Math.floor(Date.now() / 1000) + expire * 24 * 60 * 60, protocols, flow_status,is_changing_country,is_changing_protocols);
if (result == "ERR") res.send({ status: "ERR", msg: "failed to connect to marzban" });
else {
var inbounds = proxy_obj_maker(protocols,flow_status,2)
if(is_changing_country)
{
for(let inbound in inbounds)
{
if(!Object.keys(user_obj.inbounds).includes(inbound)) delete inbounds[inbound];
}
}
await update_user(user_id, {
expire: Math.floor(Date.now() / 1000) + expire * 24 * 60 * 60,
data_limit: data_limit * ((2 ** 10) ** 3),
inbounds,
safu:/*safu?1:0*/0,
desc
});
if(panel_obj.panel_type == "MZ")
{
if((
(corresponding_agent.business_mode == 1)
//(user_obj.used_traffic > user_obj.data_limit/4 || (user_obj.expire - user_obj.created_at) < (Math.floor(Date.now()/1000) - user_obj.created_at)*4 ) /*&&
//(old_data_limit > data_limit)
)) await update_account(corresponding_agent.id, { allocatable_data: format_number(corresponding_agent.allocatable_data - data_limit + old_data_limit) });
}
else if(panel_obj.panel_type == "AMN")
if(old_expire != expire)
{
await update_account(corresponding_agent.id,
{
allocatable_data: format_number(corresponding_agent.allocatable_data - user_obj.ip_limit * AMNEZIA_COEFFICIENT * expire),
});
await update_user(user_id, { used_traffic: 0 });
}
var account = await token_to_account(access_token);
await insert_to_logs(account.id, "EDIT_USER", `edited user !${user_obj.username} with !${data_limit} GB data and !${expire} days of expire time`,access_token);
if(old_country == country)
{
if(user_obj.protocols != protocols || user_obj.flow_status != flow_status) update_user_links_bg(panel_obj.panel_url,panel_obj.panel_username,panel_obj.panel_password,user_obj.username,user_obj.id)
res.send("DONE");
}
else
{
var switch_process = await switch_countries(old_country,country,[user_obj.username]);
if(switch_process == "ERR") res.send({ status: "ERR", msg: "edited user but didn't switched country" });
else
{
await insert_to_logs(account.id, "SWITCH_COUNTRY", `switched country of user !${user_obj.username} from !${old_country} to !${country}`,access_token);
res.send("DONE")
}
}
}
}
});
app.post("/edit_self", async (req, res) => {
const { username, password, access_token } = req.body;
var corresponding_account = await token_to_account(access_token);
var account_id = corresponding_account.id;
var username_arr = await get_accounts();
username_arr = username_arr.map(x => x.username);
var old_username = corresponding_account.username;
if(username_arr.includes(username) && old_username != username) res.send({ status: "ERR", msg: "username already exists" });
else
{
if(access_token.includes("@"))
{
var sub_account_id = (await token_to_sub_account(access_token)).id;
await (await accounts_clct()).updateOne({id:account_id,"sub_accounts.id":sub_account_id},{$set:{"sub_accounts.$.username":username,"sub_accounts.$.password":password}});
}
else await update_account(account_id, { username, password });
var account = await token_to_account(access_token);
await insert_to_logs(account.id, "EDIT_SELF", `was self edited`,access_token);
res.send("DONE");
}
});
app.post("/reset_user", async (req, res) => {
const { username, access_token } = req.body;
var user_obj = await get_user2(username);
var user_id = user_obj.id;
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
var corresponding_agent = await token_to_account(access_token);
if (corresponding_agent.disable) res.send({ status: "ERR", msg: "your account is disabled" })
else if(!corresponding_agent.edit_access) res.send({ status: "ERR", msg: "access denied" })
else if (!corresponding_agent.country.split(",").includes(panel_obj.panel_country)) res.send({ status: "ERR", msg: "country access denied" })
else
{
if(panel_obj.panel_type == "MZ")
{
if( ( corresponding_agent.business_mode == 1 && (user_obj.used_traffic > user_obj.data_limit/4 || (user_obj.expire - user_obj.created_at) < (Math.floor(Date.now()/1000) - user_obj.created_at)*4 )) )
{
if(corresponding_agent.allocatable_data < b2gb(user_obj.data_limit)) {res.send({ status: "ERR", msg: "not enough allocatable data" }); return;}
var result = await reset_marzban_user(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") {res.send({ status: "ERR", msg: "failed to connect to marzban" });return;}
await update_account(corresponding_agent.id, { allocatable_data: format_number(corresponding_agent.allocatable_data - b2gb(user_obj.data_limit)) });
}
else
{
if(corresponding_agent.allocatable_data < b2gb(Math.min(user_obj.used_traffic,user_obj.data_limit))) {res.send({ status: "ERR", msg: "not enough allocatable data" }); return;}
var result = await reset_marzban_user(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") {res.send({ status: "ERR", msg: "failed to connect to marzban" });return;}
await update_account(corresponding_agent.id, { allocatable_data: format_number(corresponding_agent.allocatable_data - b2gb(user_obj.data_limit)) });
}
}
else if(panel_obj.panel_type == "AMN")
{
if(corresponding_agent.allocatable_data < Math.floor( (user_obj.expire - user_obj.created_at) / 86400 ) * user_obj.ip_limit * AMNEZIA_COEFFICIENT) {res.send({ status: "ERR", msg: "not enough allocatable data" }); return;}
var result = await reset_marzban_user(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") {res.send({ status: "ERR", msg: "failed to connect to marzban" });return;}
await update_account(corresponding_agent.id, { allocatable_data: format_number(corresponding_agent.allocatable_data - Math.floor( (user_obj.expire - user_obj.created_at) / 86400 ) * user_obj.ip_limit * AMNEZIA_COEFFICIENT) });
}
await update_user(user_id, { used_traffic: 0 });
if(user_obj.status=="limited") await update_user(user_id, { status: "active" });
var account = await token_to_account(access_token);
await insert_to_logs(account.id, "RESET_USER", `reseted user !${user_obj.username}`,access_token);
res.send("DONE");
}
});
app.post("/unlock_user", async (req, res) => {
const { username, access_token } = req.body;
var user_obj = await get_user2(username);
var user_id = user_obj.id;
var panel_obj = await get_panel(user_obj.corresponding_panel_id);
var corresponding_agent = await token_to_account(access_token);
if (corresponding_agent.disable) res.send({ status: "ERR", msg: "your account is disabled" })
else if(!corresponding_agent.edit_access) res.send({ status: "ERR", msg: "access denied" })
else if (!corresponding_agent.country.split(",").includes(panel_obj.panel_country)) res.send({ status: "ERR", msg: "country access denied" })
else
{
var result = await unlock_marzban_user(panel_obj.panel_url, panel_obj.panel_username, panel_obj.panel_password, user_obj.username);
if (result == "ERR") {res.send({ status: "ERR", msg: "failed to connect to marzban" });return;}
var account = await token_to_account(access_token);
await insert_to_logs(account.id, "UNLOCK_USER", `unlocked user !${user_obj.username}`,access_token);
res.send("DONE");
}
});
app.post("/dldb", async (req, res) =>
{
const account = await token_to_account(req.body.access_token);
if( req.body.service_access_api_key != process.env.ACCESS_API_KEY && account.is_admin == 0 ) res.send({status:"ERR",msg:"you are not admin"});
else
{
const db_url = await get_backup_from_everything()
res.send("DONE>"+get_sub_url()+db_url);
}
});
app.post("/uldb", async (req, res) =>
{
try
{
var { access_token } = req.body;
var account = await token_to_account(access_token);
await delete_folder_content("dbrs");
await fs.promises.mkdir("dbrs");
var db_file = req.files.file;
await db_file.mv("dbrs/db.zip");
var zip = new AdmZip("dbrs/db.zip");
zip.extractAllTo("dbrs",true);
var panels_clct_rs = JSON.parse(await fs.promises.readFile("dbrs/main/panels.json"));
var accounts_clct_rs = JSON.parse(await fs.promises.readFile("dbrs/main/accounts.json"));
var users_clct_rs = JSON.parse(await fs.promises.readFile("dbrs/main/users.json"));
var logs_clct_rs = JSON.parse(await fs.promises.readFile("dbrs/main/logs.json"));
// backward compatibility
for(let account of accounts_clct_rs)
{
if(account.is_admin) continue;
if(!account.daily_usage_logs) account.daily_usage_logs = [];
if(!account.vrate) account.vrate = 500_000;
if(!account.gateway_status) account.gateway_status = {zarinpal:0,nowpayments:0};
}