forked from InconigtoVPN/INCONIGTO
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_worker.js
More file actions
1780 lines (1553 loc) · 56.9 KB
/
Copy path_worker.js
File metadata and controls
1780 lines (1553 loc) · 56.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { connect } from "cloudflare:sockets";
let cachedProxyList = [];
let proxyIP = "";
const DEFAULT_PROXY_BANK_URL = "https://raw.githubusercontent.com/InconigtoVPN/ProxyIP/refs/heads/main/proxyList.txt";
const TELEGRAM_BOT_TOKEN = '';
const TELEGRAM_API_URL = `https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}`;
const apiCheck = 'https://proxyip.biz.id/';
const ChatID = '';
const Chanell = '';
const Group = '';
const Owner = '';
const FAKE_HOSTNAME = '';
const pathinfo = "t.me/Inconigto_Mode";
const watermark = "Inconigto-MODE";
async function handleActive(request) {
const host = request.headers.get('Host');
const webhookUrl = `https://${host}/webhook`;
const response = await fetch(`${TELEGRAM_API_URL}/setWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: webhookUrl }),
});
if (response.ok) {
return new Response('Webhook set successfully', { status: 200 });
}
return new Response('Failed to set webhook', { status: 500 });
}
// Fungsi untuk menangani `/delete` (menghapus webhook)
async function handleDelete(request) {
const response = await fetch(`${TELEGRAM_API_URL}/deleteWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
return new Response('Webhook deleted successfully', { status: 200 });
}
return new Response('Failed to delete webhook', { status: 500 });
}
// Fungsi untuk menangani `/info` (mendapatkan info webhook)
async function handleInfo(request) {
const response = await fetch(`${TELEGRAM_API_URL}/getWebhookInfo`);
if (response.ok) {
const data = await response.json();
return new Response(JSON.stringify(data), { status: 200 });
}
return new Response('Failed to retrieve webhook info', { status: 500 });
}
// Fungsi untuk menangani `/webhook`
async function handleWebhook(request) {
const update = await request.json();
if (update.callback_query) {
return await handleCallbackQuery(update.callback_query);
} else if (update.message) {
return await handleMessage(update.message);
}
return new Response('OK', { status: 200 });
}
// Fungsi untuk menangani `/sendMessage`
async function handleSendMessage(request) {
const { chat_id, text } = await request.json();
const response = await fetch(`${TELEGRAM_API_URL}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id, text }),
});
if (response.ok) {
return new Response('Message sent successfully', { status: 200 });
}
return new Response('Failed to send message', { status: 500 });
}
// Fungsi untuk menangani `/getUpdates`
async function handleGetUpdates(request) {
const response = await fetch(`${TELEGRAM_API_URL}/getUpdates`);
if (response.ok) {
const data = await response.json();
return new Response(JSON.stringify(data), { status: 200 });
}
return new Response('Failed to get updates', { status: 500 });
}
// Fungsi untuk menangani `/deletePending` - menarik pembaruan yang tertunda
async function handleDeletePending(request) {
// Hapus webhook untuk menghindari pembaruan tertunda
const deleteResponse = await fetch(`${TELEGRAM_API_URL}/deleteWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
if (deleteResponse.ok) {
// Setelah menghapus webhook, atur webhook kembali
const host = request.headers.get('Host');
const webhookUrl = `https://${host}/webhook`;
const setResponse = await fetch(`${TELEGRAM_API_URL}/setWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: webhookUrl }),
});
if (setResponse.ok) {
return new Response('Pending updates deleted by resetting webhook', { status: 200 });
}
return new Response('Failed to set webhook after deletion', { status: 500 });
}
return new Response('Failed to delete webhook', { status: 500 });
}
// Routing utama sebelum mencapai handler default
async function routeRequest(request) {
const url = new URL(request.url);
if (url.pathname === '/active') {
return await handleActive(request);
}
if (url.pathname === '/delete') {
return await handleDelete(request);
}
if (url.pathname === '/info') {
return await handleInfo(request);
}
if (url.pathname === '/webhook' && request.method === 'POST') {
return await handleWebhook(request);
}
if (url.pathname === '/sendMessage') {
return await handleSendMessage(request);
}
if (url.pathname === '/getUpdates') {
return await handleGetUpdates(request);
}
if (url.pathname === '/deletePending') {
return await handleDeletePending(request);
}
return null;
}
const getEmojiFlag = (countryCode) => {
if (!countryCode || countryCode.length !== 2) return ''; // Validasi input
return String.fromCodePoint(
...[...countryCode.toUpperCase()].map(char => 0x1F1E6 + char.charCodeAt(0) - 65)
);
};
async function handleCallbackQuery(callbackQuery) {
const callbackData = callbackQuery.data;
const chatId = callbackQuery.message.chat.id;
const HostBot = FAKE_HOSTNAME; // Ganti dengan host default yang benar
try {
if (callbackData.startsWith('create_vless')) {
const [_, ip, port, isp] = callbackData.split('|');
await handleVlessCreation(chatId, ip, port, isp, HostBot);
} else if (callbackData.startsWith('create_trojan')) {
const [_, ip, port, isp] = callbackData.split('|');
await handleTrojanCreation(chatId, ip, port, isp, HostBot);
} else if (callbackData.startsWith('create_ss')) {
const [_, ip, port, isp] = callbackData.split('|');
await handleShadowSocksCreation(chatId, ip, port, isp, HostBot);
}
// Konfirmasi callback query ke Telegram
await fetch(`${TELEGRAM_API_URL}/answerCallbackQuery`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
callback_query_id: callbackQuery.id,
}),
});
} catch (error) {
console.error('Error handling callback query:', error);
}
return new Response('OK', { status: 200 });
}
let userChatIds = [];
// Function to handle incoming messages
async function handleMessage(message) {
const text = message.text;
const chatId = message.chat.id;
try {
// Menangani perintah /start
if (text === '/start') {
await handleStartCommand(chatId);
// Menambahkan pengguna ke daftar jika belum ada
if (!userChatIds.includes(chatId)) {
userChatIds.push(chatId);
}
// Menangani perintah /info
} else if (text === '/info') {
await handleGetInfo(chatId);
// Menangani perintah /listwildcard
} else if (text === '/listwildcard') {
await handleListWildcard(chatId);
// Menangani perintah /getrandomip
} else if (text === '/getrandomip') {
await handleGetRandomIPCommand(chatId);
// Menangani perintah /getrandom <CountryCode>
} else if (text.startsWith('/getrandom')) {
const countryId = text.split(' ')[1]; // Mengambil kode negara setelah "/getrandom"
if (countryId) {
await handleGetRandomCountryCommand(chatId, countryId);
} else {
await sendTelegramMessage(chatId, '⚠️ Harap tentukan kode negara setelah `/getrandom` (contoh: `/getrandom ID`, `/getrandom US`).');
}
// Menangani perintah /broadcast
} else if (text.startsWith('/broadcast')) {
await handleBroadcastCommand(message);
// Menangani format IP:Port
} else if (isValidIPPortFormat(text)) {
// Jika input adalah satu pasangan IP:Port, langsung periksa
await handleIPPortCheck(text, chatId);
} else {
// Cek jika input mengandung beberapa pasangan IP:Port yang dipisahkan oleh koma atau baris baru
const ipPortList = text.split(/[\n,]+/).map(item => item.trim()); // Split berdasarkan koma atau baris baru
let isValid = true;
for (let ipPortText of ipPortList) {
// Periksa format setiap pasangan IP:Port
if (!isValidIPPortFormat(ipPortText)) {
isValid = false;
break; // Jika ada yang tidak valid, berhenti memeriksa dan kirimkan pesan kesalahan
}
}
if (isValid) {
// Jika semua format IP:Port valid, lakukan pengecekan untuk setiap pasangan
for (let ipPortText of ipPortList) {
await handleIPPortCheck(ipPortText, chatId);
}
} else {
// Jika format salah, beri pesan kesalahan
await sendTelegramMessage(chatId, '⚠️ Format tidak valid. Gunakan format IP:Port yang benar (contoh: 192.168.1.1:80).');
}
}
return new Response('OK', { status: 200 });
} catch (error) {
// Log the error and send an error message to the user
console.error('Error processing message:', error);
await sendTelegramMessage(chatId, '⚠️ Terjadi kesalahan dalam memproses perintah. Silakan coba lagi nanti.');
return new Response('Error', { status: 500 });
}
}
// Fungsi untuk menangani perintah /broadcast
async function handleBroadcastCommand(message) {
const chatId = message.chat.id;
const text = message.text;
// Memeriksa apakah pengirim adalah pemilik bot
if (chatId !== ChatID) {
await sendTelegramMessage(chatId, '⚠️ Anda bukan pemilik bot ini.');
return;
}
// Mengambil pesan setelah perintah /broadcast
const broadcastMessage = text.replace('/broadcast', '').trim();
if (!broadcastMessage) {
await sendTelegramMessage(chatId, '⚠️ Harap masukkan pesan setelah perintah /broadcast.');
return;
}
// Mengirim pesan ke semua pengguna yang terdaftar
if (userChatIds.length === 0) {
await sendTelegramMessage(chatId, '⚠️ Tidak ada pengguna untuk menerima pesan broadcast.');
return;
}
for (const userChatId of userChatIds) {
try {
await sendTelegramMessage(userChatId, broadcastMessage);
} catch (error) {
console.error(`Error mengirim pesan ke ${userChatId}:`, error);
}
}
await sendTelegramMessage(chatId, `✅ Pesan telah disebarkan ke ${userChatIds.length} pengguna.`);
}
// Fungsi untuk mengirim pesan ke pengguna melalui Telegram API
async function sendTelegramMessage(chatId, message) {
const url = `${TELEGRAM_API_URL}/sendMessage`;
const payload = {
chat_id: chatId,
text: message,
parse_mode: 'Markdown', // Untuk memformat teks
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
const result = await response.json();
if (!result.ok) {
console.error('Gagal mengirim pesan:', result);
}
} catch (error) {
console.error('Error saat mengirim pesan:', error);
}
}
// Function to handle the /start command
async function handleStartCommand(chatId) {
const welcomeMessage = `
🎉 Selamat datang di Inconigto Mode || YūshaBot ! 🎉
💡 Cara Penggunaan:
1️⃣ Kirimkan Proxy IP:Port dalam format yang benar.
Contoh: \`192.168.1.1:8080\`
2️⃣ Bot akan mengecek status Proxy untuk Anda.
✨ Anda bisa memilih opsi untuk membuat VPN Tunnel CloudFlare Gratis Menggunakan ProxyIP yang sudah di Cek dengan format:
- 🌐 VLESS
- 🔐 TROJAN
- 🛡️ Shadowsocks
🚀 Mulai sekarang dengan mengirimkan Proxy IP:Port Anda!
📌 Daftar Commands : /info
👨💻 ME : [Incognito Mode](${Owner})
📺 CHANNEL : [Inconigto Mode || Seishin](${Chanell})
👥 GROUP : [Incognito Mode || Kuragari](${Group})
`;
await sendTelegramMessage(chatId, welcomeMessage);
}
async function handleGetInfo(chatId) {
const InfoMessage = `
🎉 Commands di Incognito Bot! 🎉
1️⃣ \`/getrandomip\`
2️⃣ \`/getrandom <Country>\`
3️⃣ \`/listwildcard\`
📌 Daftar Commands : /info
👨💻 ME : [Incognito Mode](${Owner})
📺 CHANNEL : [Inconigto Mode || Seishin](${Chanell})
👥 GROUP : [Incognito Mode || Kuragari](${Group})
`;
await sendTelegramMessage(chatId, InfoMessage);
}
async function handleListWildcard(chatId) {
const HostBot = `${FAKE_HOSTNAME}`;
const infoMessage = `
🎉 List Wildcard VPN Tunnel Incognito Bot! 🎉
1️⃣ \`graph.instagram.com.${HostBot}\`
2️⃣ \`ava.game.naver.com.${HostBot}\`
3️⃣ \`support.zoom.us.${HostBot}\`
4️⃣ \`cache.netflix.com.${HostBot}\`
5️⃣ \`zaintest.vuclip.com.${HostBot}\`
6️⃣ \`cdn.appsflayer.com.${HostBot}\`
7️⃣
8️⃣
9️⃣
🔟
📌 Daftar Commands : /info
👨💻 ME : [Incognito Mode](${Owner})
📺 CHANNEL : [Inconigto Mode || Seishin](${Chanell})
👥 GROUP : [Incognito Mode || Kuragari](${Group})
`;
await sendTelegramMessage(chatId, infoMessage);
}
// Function to handle the /getrandomip command
async function handleGetRandomIPCommand(chatId) {
try {
// Fetching the Proxy IP list from the GitHub raw URL
const proxyBankUrl = DEFAULT_PROXY_BANK_URL;
const response = await fetch(proxyBankUrl);
const data = await response.text();
// Split the data into an array of Proxy IPs
const proxyList = data.split('\n').filter(line => line.trim() !== '');
// Randomly select 10 Proxy IPs
const randomIPs = [];
for (let i = 0; i < 20 && proxyList.length > 0; i++) {
const randomIndex = Math.floor(Math.random() * proxyList.length);
randomIPs.push(proxyList[randomIndex]);
proxyList.splice(randomIndex, 1); // Remove the selected item from the list
}
// Format the random IPs into a message
const message = `🔑 **Here are 20 random Proxy IPs:**\n\n` +
randomIPs.map(ip => {
const [ipAddress, port, country, provider] = ip.split(',');
// Replace dots with spaces in the provider name
const formattedProvider = provider.replace(/\./g, ' ');
return `📍**IP:PORT : **\`${ipAddress}:${port}\`**\n🌍 **Country :** ${country}\n💻 **ISP :** ${formattedProvider}\n`;
}).join('\n');
await sendTelegramMessage(chatId, message);
} catch (error) {
console.error('Error fetching proxy list:', error);
await sendTelegramMessage(chatId, '⚠️ There was an error fetching the Proxy list. Please try again later.');
}
}
// Function to handle the /getrandom <Country> command
async function handleGetRandomCountryCommand(chatId, countryId) {
try {
const proxyBankUrl = DEFAULT_PROXY_BANK_URL;
const response = await fetch(proxyBankUrl);
const data = await response.text();
const proxyList = data.split('\n').filter(line => line.trim() !== '');
const filteredProxies = proxyList.filter(ip => {
const [ipAddress, port, country, provider] = ip.split(',');
return country.toUpperCase() === countryId.toUpperCase(); // Country case-insensitive comparison
});
const randomIPs = [];
for (let i = 0; i < 20 && filteredProxies.length > 0; i++) {
const randomIndex = Math.floor(Math.random() * filteredProxies.length);
randomIPs.push(filteredProxies[randomIndex]);
filteredProxies.splice(randomIndex, 1); // Remove the selected item from the list
}
if (randomIPs.length === 0) {
await sendTelegramMessage(chatId, `⚠️ No proxies found for country code **${countryId}**.`);
return;
}
const message = `🔑 **Here are 20 random Proxy IPs for country ${countryId}:**\n\n` +
randomIPs.map(ip => {
const [ipAddress, port, country, provider] = ip.split(',');
// Replace dots with spaces in the provider name
const formattedProvider = provider.replace(/\./g, ' ');
return `📍**IP:PORT : **\`${ipAddress}:${port}\`**\n🌍 **Country :** ${country}\n💻 **ISP :** ${formattedProvider}\n`;
}).join('\n');
await sendTelegramMessage(chatId, message);
} catch (error) {
console.error('Error fetching proxy list:', error);
await sendTelegramMessage(chatId, '⚠️ There was an error fetching the Proxy list. Please try again later.');
}
}
async function handleIPPortCheck(ipPortText, chatId) {
// Mengganti semua karakter baris baru (\n) dengan koma (,) untuk mempermudah pemrosesan
const normalizedText = ipPortText.replace(/\n/g, ',').replace(/\s+/g, '');
// Pisahkan input berdasarkan koma
const ipPortList = normalizedText.split(',');
// Periksa setiap pasangan ip:port
for (let ipPortText of ipPortList) {
const [ip, port] = ipPortText.trim().split(':');
// Validasi format ip:port
if (isValidIPPortFormat(ipPortText.trim())) {
const result = await checkIPPort(ip, port, chatId);
await sendTelegramMessage(chatId, result); // Kirim hasil ke Telegram
} else {
await sendTelegramMessage(chatId, `⚠️ Format ip:port tidak valid: ${ipPortText.trim()}`);
}
}
}
function isValidIPPortFormat(input) {
const regex = /^(\d{1,3}\.){3}\d{1,3}:\d{1,5}$/;
return regex.test(input);
}
async function checkIPPort(ip, port, chatId) {
try {
const response = await fetch(`${apiCheck}${ip}:${port}`);
if (!response.ok) throw new Error(`Error: ${response.statusText}`);
const data = await response.json();
// Ekstrak informasi dari respon API
const { proxy, port: p, org, asn, country = "Unknown", flag = "🏳️", latitude, longitude, timezone } = data;
const status = data.proxyip ? "✅ Active" : "❌ Inactive";
// Format pesan hasil pengecekan
const resultMessage = `
🌍 **IP & Port Check Result**:
━━━━━━━━━━━━━━━━━━━━━━━
📡 **IP**: ${proxy}
🔌 **Port**: ${p}
💻 **ISP**: ${org}
🏢 **ASN**: ${asn}
🌏 **Country**: ${country} ${flag}
🚦 **Status**: ${status}
📍 **Coordinates**: ${latitude}, ${longitude}
🕰️ **Timezone**: ${timezone}
━━━━━━━━━━━━━━━━━━━━━━━
[Incognito Mode](${Owner})
`;
await sendTelegramMessage(chatId, resultMessage);
// Send an inline keyboard with the details
await sendInlineKeyboard(chatId, proxy, p, org, flag );
} catch (error) {
// Error handling
await sendTelegramMessage(chatId, `⚠️ Error: ${error.message}`);
}
}
async function handleShadowSocksCreation(chatId, ip, port,isp, HostBot) {
const path = `/${pathinfo}/${ip}/${port}`;
const ssname = `${isp}-[Tls]-[SS]-[${watermark}]`
const ssname2 = `${isp}-[NTls]-[SS]-[${watermark}]`
const ssTls = `ss://${btoa(`none:${crypto.randomUUID()}`)}@${HostBot}:443?encryption=none&type=ws&host=${HostBot}&path=${encodeURIComponent(path)}&security=tls&sni=${HostBot}#${encodeURIComponent(ssname)}`;
const ssNTls = `ss://${btoa(`none:${crypto.randomUUID()}`)}@${HostBot}:80?encryption=none&type=ws&host=${HostBot}&path=${encodeURIComponent(path)}&security=none&sni=${HostBot}#${encodeURIComponent(ssname2)}`;
const proxies = `
proxies:
- name: ${ssname}
server: ${HostBot}
port: 443
type: ss
cipher: none
password: ${crypto.randomUUID()}
plugin: v2ray-plugin
client-fingerprint: chrome
udp: true
plugin-opts:
mode: websocket
host: ${HostBot}
path: ${path}
tls: true
mux: false
skip-cert-verify: true
headers:
custom: value
ip-version: dual
v2ray-http-upgrade: false
v2ray-http-upgrade-fast-open: false
`;
const message = `
⚜️ Success Create ShadowSocks ⚜️
Type : ShadowSocks
ISP : \`${isp}\`
ProxyIP : \`${ip}:${port}\`
🔗 **Links Vless** :\n
1️⃣ **TLS** : \`${ssTls}\`\n
2️⃣ **Non-TLS** : \`${ssNTls}\`
📄 **Proxies Config**:
\`\`\`
${proxies}
\`\`\`
[Incognito Mode](${Owner})
`;
// Kirim pesan melalui Telegram
await sendTelegramMessage(chatId, message);
}
async function handleVlessCreation(chatId, ip, port, isp, HostBot) {
const path = `/${pathinfo}/${ip}/${port}`;
const vlname = `${isp}-[Tls]-[VL]-[${watermark}]`
const vlname2 = `${isp}-[NTls]-[VL]-[${watermark}]`
const vlessTLS = `vless://${crypto.randomUUID()}@${HostBot}:443?path=${encodeURIComponent(path)}&security=tls&host=${HostBot}&type=ws&sni=${HostBot}#${encodeURIComponent(vlname)}`;
const vlessNTLS = `vless://${crypto.randomUUID()}@${HostBot}:80?path=${encodeURIComponent(path)}&security=none&host=${HostBot}&type=ws&sni=${HostBot}#${encodeURIComponent(vlname2)}`;
const message = `
⚜️ Success Create VLESS ⚜️
Type : VLESS
ISP : \`${isp}\`
ProxyIP : \`${ip}:${port}\`
🔗 **Links Vless** :\n
1️⃣ **TLS** : \`${vlessTLS}\`\n
2️⃣ **Non-TLS** : \`${vlessNTLS}\`
📄 **Proxies Config** :
\`\`\`
proxies:
- name: ${vlname}
server: ${HostBot}
port: 443
type: vless
uuid: ${crypto.randomUUID()}
cipher: auto
tls: true
client-fingerprint: chrome
udp: true
skip-cert-verify: true
network: ws
servername: ${HostBot}
alpn:
- h2
- h3
- http/1.1
ws-opts:
path: ${path}
headers:
Host: ${HostBot}
max-early-data: 0
early-data-header-name: Sec-WebSocket-Protocol
ip-version: dual
v2ray-http-upgrade: false
v2ray-http-upgrade-fast-open: false
\`\`\`
[Incognito Mode](${Owner})
`;
await sendTelegramMessage(chatId, message);
}
async function handleTrojanCreation(chatId, ip, port, isp, HostBot) {
const path = `/${pathinfo}/${ip}/${port}`;;
const trname = `${isp}-[Tls]-[TR]-[${watermark}]`
const trname2 = `${isp}-[NTls]-[TR]-[${watermark}]`
const trojanTLS = `trojan://${crypto.randomUUID()}@${HostBot}:443?path=${encodeURIComponent(path)}&security=tls&host=${HostBot}&type=ws&sni=${HostBot}#${encodeURIComponent(trname)}`;
const trojanNTLS = `trojan://${crypto.randomUUID()}@${HostBot}:80?path=${encodeURIComponent(path)}&security=none&host=${HostBot}&type=ws&sni=${HostBot}${encodeURIComponent(trname2)}`;
const message = `
⚜️ Success Create Trojan ⚜️
Type : Trojan
ISP : \`${isp}\`
ProxyIP : \`${ip}:${port}\`
🔗 **Links Trojan** :\n
1️⃣ **TLS** : \`${trojanTLS}\`\n
2️⃣ **Non-TLS** : \`${trojanNTLS}\`
📄 **Proxies Config** :
\`\`\`
proxies:
- name: ${trname}
server: ${HostBot}
port: 443
type: trojan
password: ${crypto.randomUUID()}
tls: true
client-fingerprint: chrome
udp: true
skip-cert-verify: true
network: ws
sni: ${HostBot}
alpn:
- h2
- h3
- http/1.1
ws-opts:
path: ${path}
headers:
Host: ${HostBot}
max-early-data: 0
early-data-header-name: Sec-WebSocket-Protocol
ip-version: dual
v2ray-http-upgrade: false
v2ray-http-upgrade-fast-open: false
\`\`\`
[Incognito Mode](${Owner})
`;
await sendTelegramMessage(chatId, message);
}
async function sendInlineKeyboard(chatId, ip, port, isp, flag) {
try {
const response = await fetch(`${TELEGRAM_API_URL}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text: 'Pilih opsi berikut untuk membuat VPN Tunnel:',
reply_markup: {
inline_keyboard: [
[
{ text: 'Create VLESS', callback_data: `create_vless|${ip}|${port}|${isp}|${flag}` },
{ text: 'Create Trojan', callback_data: `create_trojan|${ip}|${port}|${isp}|${flag}` },
],
[
{ text: 'Create ShadowSocks', callback_data: `create_ss|${ip}|${port}|${isp}|${flag}` },
],
],
},
}),
});
if (!response.ok) {
const errorText = await response.text();
console.error('Failed to send inline keyboard:', errorText);
} else {
console.log('Inline keyboard sent successfully.');
}
} catch (error) {
console.error('Error sending inline keyboard:', error);
}
}
// Konstanta WebSocket
const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
async function getProxyList(env, forceReload = false) {
try {
// Cek apakah cache kosong atau ada permintaan untuk memuat ulang
if (!cachedProxyList.length || forceReload) {
const proxyBankUrl = env.PROXY_BANK_URL || DEFAULT_PROXY_BANK_URL;
const response = await fetch(proxyBankUrl);
if (!response.ok) {
throw new Error(`Failed to fetch proxy list: ${response.status}`);
}
// Parsing daftar proxy
const proxyLines = (await response.text()).split("\n").filter(Boolean);
cachedProxyList = proxyLines.map((line) => {
const [proxyIP, proxyPort, country, org] = line.split(",");
return { proxyIP, proxyPort, country, org };
});
}
return cachedProxyList;
} catch (error) {
console.error("Error fetching proxy list:", error);
return []; // Mengembalikan array kosong jika terjadi error
}
}
export default {
async fetch(request, env, ctx) {
try {
const routeResponse = await routeRequest(request);
if (routeResponse) {
return routeResponse;
}
const url = new URL(request.url);
const upgradeHeader = request.headers.get("Upgrade");
const inconigto = url.hostname;
const type = url.searchParams.get("type") || "mix";
const tls = url.searchParams.get("tls") !== "false";
const wildcard = url.searchParams.get("wildcard") === "true";
const bugs = url.searchParams.get("bug") || inconigto;
const bugwildcard = wildcard ? `${bugs}.${inconigto}` : inconigto;
const country = url.searchParams.get("country");
const limit = parseInt(url.searchParams.get("limit"), 10);
let configs;
// Map untuk menyimpan proxy per kode negara
const proxyState = new Map();
// Fungsi untuk memperbarui proxy setiap menit
async function updateProxies() {
const proxies = await getProxyList(env);
const groupedProxies = groupBy(proxies, "country");
for (const [countryCode, proxies] of Object.entries(groupedProxies)) {
const randomIndex = Math.floor(Math.random() * proxies.length);
proxyState.set(countryCode, proxies[randomIndex]);
}
}
// Jalankan pembaruan proxy setiap menit
ctx.waitUntil(
(async function periodicUpdate() {
await updateProxies();
setInterval(updateProxies, 60000);
})()
);
// Penanganan WebSocket
if (upgradeHeader === "websocket") {
if (!url.pathname.startsWith(`/${pathinfo}/`)) {
console.log(`Blocked request (Invalid Path): ${url.pathname}`);
return new Response(null, { status: 403 });
}
const cleanPath = url.pathname.replace(`/${pathinfo}/`, "");
const pathMatch = cleanPath.match(/^([A-Z]{2})(\d+)?$/);
if (pathMatch) {
const countryCode = pathMatch[1];
const index = pathMatch[2] ? parseInt(pathMatch[2], 10) - 1 : null;
const proxies = await getProxyList(env);
const filteredProxies = proxies.filter((proxy) => proxy.country === countryCode);
if (filteredProxies.length === 0) {
return new Response(null, { status: 403 });
}
let selectedProxy =
index === null ? proxyState.get(countryCode) || filteredProxies[0] : filteredProxies[index];
proxyIP = `${selectedProxy.proxyIP}:${selectedProxy.proxyPort}`;
return await websockerHandler(request);
}
const ipPortMatch = cleanPath.match(/^(.+[^.\d\w]\d+)$/);
if (ipPortMatch) {
proxyIP = ipPortMatch[1].replace(/[^.\d\w]+/g, ":");
return await websockerHandler(request);
}
return new Response(null, { status: 403 });
}
const ping = await getLatency(url.href);
async function getLatency(url) {
const start = Date.now(); // waktu mulai
await fetch(url); // kirim permintaan ke server
const end = Date.now(); // waktu selesai
return end - start; // latency dalam milidetik
}
async function getIpInfo(ip) {
const apiUrl = `https://ipinfo.io/${ip}/json`; // API endpoint untuk ipinfo.io
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Failed to fetch IP information');
}
const data = await response.json();
return data;
} catch (error) {
return { error: 'Unable to fetch IP information' };
}
}
const myIp = request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For') || 'IP tidak ditemukan';
const ipInfo = await getIpInfo(myIp);
// Routing untuk subscription generator
switch (url.pathname) {
case "/sub/clash":
configs = await generateClashSub(type, bugs, bugwildcard, tls, country, limit);
break;
case "/sub/v2rayng":
configs = await generateV2rayngSub(type, bugs, bugwildcard, tls, country, limit);
break;
case "/sub/v2ray":
configs = await generateV2raySub(type, bugs, bugwildcard, tls, country, limit);
break;
default:
const inconigto = url.hostname;
return new Response(
`Hostname: ${inconigto}\nPath Info: ${pathinfo}\nPing: ${ping}ms\nMy IP: ${myIp}\n\n` +
`IP Info: \n` +
`IP: ${ipInfo.ip || 'N/A'}\n` +
`City: ${ipInfo.city || 'N/A'}\n` +
`Region: ${ipInfo.region || 'N/A'}\n` +
`Country: ${ipInfo.country || 'N/A'}\n` +
`ISP: ${ipInfo.org || 'N/A'}\n\n` +
`====================\n` +
`Cara Penggunaan Bot Telegram:\n` +
`====================\n` +
`1. /active\n` +
` - Tujuan: Mengaktifkan bot atau webhook. Misalnya, menghubungkan bot dengan webhook.\n` +
` - Contoh: https://${inconigto}/active\n\n` +
`2. /delete\n` +
` - Tujuan: Menghapus data atau entitas tertentu. Biasanya digunakan untuk menghapus pesan atau pengaturan.\n` +
` - Contoh: https://${inconigto}/delete\n\n` +
`3. /info\n` +
` - Tujuan: Mendapatkan informasi tentang status bot atau webhook.\n` +
` - Contoh: https://${inconigto}/info\n\n` +
`4. /deletePending\n` +
` - Tujuan: Menghapus data atau entitas yang masih dalam status "pending".\n` +
` - Contoh: https://${inconigto}/deletePending\n\n` +
`====================\n` +
`Cara Penggunaan Url Subs API:\n` +
`====================\n` +
`API ini menyediakan tiga jenis sub-endpoint yang dapat digunakan untuk mengakses konfigurasi yang berbeda: /sub/clash, /sub/v2ray, dan /sub/v2rayng.\n` +
`Penjelasan parameter URL:\n` +
`- sub/clash: Endpoint yang digunakan, bisa diganti dengan /sub/v2ray atau /sub/v2rayng.\n` +
`- type: Pilih protokol, tersedia vless, trojan, shadowshocks dan mix.\n` +
`- bug: Alamat bug report yang digunakan, misalnya google.com.\n` +
`- tls: Aktifkan TLS, pilih true untuk aktif dan false untuk nonaktif.\n` +
`- wildcard: Aktifkan atau nonaktifkan wildcard, pilih true atau false.\n` +
`- limit: Jumlah konfigurasi yang ingin diambil, antara 1 hingga 20.\n` +
`- country: Pilih negara dengan kode negara yang sesuai, misalnya id untuk Indonesia, sg untuk Singapura.\n\n` +
`Contoh URL Lengkap:\n\n` +
`- Clash Vless : https://${inconigto}/sub/clash?type=vless&bug=google.com&tls=true&wildcard=false&limit=10&country=id\n` +
`- V2Ray Trojan : https://${inconigto}/sub/v2ray?type=trojan&bug=google.com&tls=true&wildcard=false&limit=10&country=id\n` +
`- V2rayNG Shadowsocks : https://${inconigto}/sub/v2rayng?type=shadowsocks&bug=google.com&tls=true&wildcard=false&limit=10&country=id\n` +
`====================\n`,
{
status: 200,
headers: { "Content-Type": "text/plain;charset=utf-8" },
}
);
}
return new Response(configs);
} catch (err) {
return new Response(`An error occurred: ${err.toString()}`, {
status: 500,
});
}
},
};
// Helper function: Group proxies by country
function groupBy(array, key) {
return array.reduce((result, item) => {
if (!result[item[key]]) {
result[item[key]] = [];
}
result[item[key]].push(item);
return result;
}, {});
}
async function websockerHandler(request) {
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let addressLog = "";
let portLog = "";
const log = (info, event) => {
console.log(`[${addressLog}:${portLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
let remoteSocketWrapper = {
value: null,
};
let udpStreamWrite = null;
let isDNS = false;
readableWebSocketStream
.pipeTo(
new WritableStream({
async write(chunk, controller) {
if (isDNS && udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWrapper.value) {
const writer = remoteSocketWrapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();