-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path_worker.js
More file actions
2736 lines (2484 loc) · 105 KB
/
_worker.js
File metadata and controls
2736 lines (2484 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { connect } from 'cloudflare:sockets';
// 基础配置
let 配置路径 = "config";
let 优选节点 = [];
let 反代地址 = 'ProxyIP.JP.CMLiussss.net';
let SOCKS5账号 = '';
let 节点名称 = '🌸樱花';
let 伪装域名 = 'lkssite.vip';
let 最大失败次数 = 5;
let 锁定时间 = 5 * 60 * 1000;
// 默认壁纸地址
const 默认白天背景图 = 'https://i.meee.com.tw/el91luR.png';
const 默认暗黑背景图 = 'https://i.meee.com.tw/QPWx8nX.png';
// ====================== 辅助函数 ======================
function 创建HTML响应(内容, 状态码 = 200) {
return new Response(内容, {
status: 状态码,
headers: {
"Content-Type": "text/html;charset=utf-8",
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"
}
});
}
function 创建重定向响应(路径, 额外头 = {}) {
return new Response(null, {
status: 302,
headers: {
"Location": 路径,
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
...额外头
}
});
}
function 创建JSON响应(数据, 状态码 = 200, 额外头 = {}) {
return new Response(JSON.stringify(数据), {
status: 状态码,
headers: {
"Content-Type": "application/json;charset=utf-8",
"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0",
...额外头
}
});
}
function 生成UUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
async function 加密密码(密码) {
const encoder = new TextEncoder();
const data = encoder.encode(密码);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
async function 检查锁定(env, 设备标识) {
const 锁定时间戳 = await env.KV数据库.get(`lock_${设备标识}`);
const 当前时间 = Date.now();
const 被锁定 = 锁定时间戳 && 当前时间 < Number(锁定时间戳);
return {
被锁定,
剩余时间: 被锁定 ? Math.ceil((Number(锁定时间戳) - 当前时间) / 1000) : 0
};
}
function 生成登录注册界面(类型, 额外参数 = {}) {
const 界面数据 = {
注册: {
title: '🌸首次使用注册🌸',
表单: `
<form class="auth-form" action="/register/submit" method="POST" enctype="application/x-www-form-urlencoded">
<input type="text" name="username" placeholder="设置账号" required pattern="^[a-zA-Z0-9]{4,20}$" title="4-20位字母数字">
<input type="password" name="password" placeholder="设置密码" required minlength="6">
<input type="password" name="confirm" placeholder="确认密码" required>
<button type="submit">立即注册</button>
</form>
${额外参数.错误信息 ? `<div class="error-message">${额外参数.错误信息}</div>` : ''}
`
},
登录: {
title: '🌸欢迎回来🌸',
表单: `
<form class="auth-form" action="/login/submit" method="POST" enctype="application/x-www-form-urlencoded">
<input type="text" name="username" placeholder="登录账号" required>
<input type="password" name="password" placeholder="登录密码" required>
<button type="submit" id="loginButton" ${额外参数.锁定状态 ? 'disabled' : ''}>立即登录</button>
</form>
${额外参数.输错密码 ? `<div class="error-message">密码错误,剩余尝试次数:${额外参数.剩余次数}</div>` : ''}
${额外参数.锁定状态 ? `
<div class="lock-message">
账户锁定,请<span id="countdown">${额外参数.剩余时间}</span>秒后重试
</div>` : ''}
${额外参数.错误信息 ? `<div class="error-message">${额外参数.错误信息}</div>` : ''}
`
}
};
return `
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@400;500;600;700&display=swap');
body {
font-family: 'Quicksand', 'Comic Sans MS', 'Arial', sans-serif;
color: #ff6f91;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
position: relative;
overflow: hidden;
transition: background 0.5s ease;
}
@media (prefers-color-scheme: light) {
body { background: linear-gradient(135deg, #ffe6f0, #fff0f5); }
.auth-container { background: rgba(255, 245, 247, 0.85); box-shadow: 0 8px 20px rgba(255, 182, 193, 0.2); }
.floating-petals { background: rgba(255, 255, 255, 0.3); }
}
@media (prefers-color-scheme: dark) {
body { background: linear-gradient(135deg, #1e1e2f, #2a2a3b); }
.auth-container { background: rgba(30, 30, 30, 0.9); color: #ffd1dc; box-shadow: 0 8px 20px rgba(255, 133, 162, 0.2); }
.floating-petals { background: rgba(255, 255, 255, 0.1); }
h1 { color: #ff85a2; }
.auth-form button {
background: linear-gradient(to right, #ff85a2, #ff1493);
color: #ffffff;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}
.auth-form button:hover {
box-shadow: 0 8px 20px rgba(255, 133, 162, 0.6);
}
}
.background-media {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: -1;
transition: opacity 0.5s ease;
}
/* 漂浮花瓣效果 */
.floating-petals {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
overflow: hidden;
}
.petal {
position: absolute;
width: 10px;
height: 10px;
border-radius: 50% 0;
opacity: 0.7;
animation: float linear infinite;
}
@keyframes float {
0% {
transform: translateY(0) rotate(0deg);
opacity: 0.7;
}
100% {
transform: translateY(100vh) rotate(360deg);
opacity: 0;
}
}
/* 可爱装饰元素 */
.cute-decoration {
position: absolute;
width: 60px;
height: 60px;
opacity: 0.8;
z-index: 0;
animation: bounce 3s infinite alternate ease-in-out;
}
.cute-decoration:nth-child(odd) {
animation-delay: 0.5s;
}
@keyframes bounce {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
}
.auth-container {
padding: 40px;
border-radius: 30px;
max-width: 400px;
width: 90%;
text-align: center;
position: relative;
z-index: 1;
backdrop-filter: blur(8px);
animation: fadeIn 0.8s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
h1 {
font-size: 2em;
color: #ff69b4;
margin-bottom: 30px;
text-shadow: 2px 2px 4px rgba(255, 105, 180, 0.3);
animation: pulse 2s infinite alternate;
}
@keyframes pulse {
0% {
transform: scale(1);
}
100% {
transform: scale(1.05);
}
}
.auth-form {
display: flex;
flex-direction: column;
gap: 20px;
width: 100%;
max-width: 300px;
margin: 0 auto;
}
.auth-form input {
padding: 15px;
border-radius: 25px;
border: 2px solid #ffb6c1;
font-size: 1em;
width: 100%;
box-sizing: border-box;
transition: all 0.3s ease;
background-color: rgba(255, 240, 245, 0.9);
}
.auth-form input:focus {
border-color: #ff69b4;
box-shadow: 0 0 10px rgba(255, 105, 180, 0.3);
transform: scale(1.02);
outline: none;
}
.auth-form button {
padding: 15px;
background: linear-gradient(to right, #ff69b4, #ff1493);
color: white;
border: none;
border-radius: 30px;
cursor: pointer;
font-size: 1.1em;
font-weight: bold;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}
.auth-form button:before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(to right, transparent, rgba(255, 255, 255, 0.3), transparent);
transition: left 0.5s;
}
.auth-form button:hover:before {
left: 100%;
}
.auth-form button:hover {
transform: scale(1.05);
box-shadow: 0 8px 20px rgba(255, 105, 180, 0.4);
}
.auth-form button:active {
transform: scale(0.98);
}
.auth-form button:disabled {
background: #ccc;
cursor: not-allowed;
box-shadow: none;
transform: none;
}
.error-message {
color: #ff6666;
margin-top: 20px;
font-size: 0.9em;
animation: shake 0.5s;
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
.lock-message {
color: #ff6666;
margin-top: 20px;
font-size: 1.1em;
display: flex;
align-items: center;
justify-content: center;
gap: 5px;
}
#countdown {
color: #ff1493;
font-weight: bold;
min-width: 50px;
text-align: center;
animation: pulse 1s infinite alternate;
}
/* 可爱图标 */
.cute-icon {
position: absolute;
font-size: 1.5em;
animation: float-icon 3s infinite ease-in-out;
}
.cute-icon:nth-child(1) {
top: -20px;
left: 20px;
animation-delay: 0.2s;
}
.cute-icon:nth-child(2) {
top: -20px;
right: 20px;
animation-delay: 0.7s;
}
@keyframes float-icon {
0%, 100% {
transform: translateY(0) rotate(0deg);
}
50% {
transform: translateY(-10px) rotate(10deg);
}
}
@media (max-width: 600px) {
.auth-container { padding: 25px; }
h1 { font-size: 1.7em; }
.auth-form input, .auth-form button { padding: 12px; font-size: 1em; }
}
</style>
</head>
<body>
<img id="backgroundImage" class="background-media">
<div class="floating-petals" id="petalsContainer"></div>
<div class="auth-container">
<div class="cute-icon">🌸</div>
<div class="cute-icon">🌺</div>
<h1>${界面数据[类型].title}</h1>
${界面数据[类型].表单}
</div>
<script>
// 背景图片切换
const lightBg = '${默认白天背景图}';
const darkBg = '${默认暗黑背景图}';
const bgImage = document.getElementById('backgroundImage');
async function 获取壁纸地址() {
try {
const response = await fetch('/get-wallpaper-public');
if (response.ok) {
const data = await response.json();
return {
light: data.lightWallpaper || '${默认白天背景图}',
dark: data.darkWallpaper || '${默认暗黑背景图}'
};
}
} catch (error) {
console.error('获取壁纸地址失败:', error);
}
return {
light: '${默认白天背景图}',
dark: '${默认暗黑背景图}'
};
}
async function updateBackground() {
const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
const wallpaper = await 获取壁纸地址();
bgImage.src = isDarkMode ? wallpaper.dark : wallpaper.light;
bgImage.onerror = () => { bgImage.style.display = 'none'; };
}
updateBackground();
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateBackground);
// 创建漂浮花瓣效果
function createPetal() {
const petalsContainer = document.getElementById('petalsContainer');
const petal = document.createElement('div');
petal.className = 'petal';
// 随机花瓣颜色
const colors = ['#ffb6c1', '#ff69b4', '#ffc0cb', '#ff1493', '#ffd1dc'];
const color = colors[Math.floor(Math.random() * colors.length)];
// 随机大小
const size = Math.random() * 15 + 5;
// 随机位置
const left = Math.random() * 100;
// 随机动画时长
const duration = Math.random() * 10 + 10;
petal.style.backgroundColor = color;
petal.style.width = size + 'px';
petal.style.height = size + 'px';
petal.style.left = left + '%';
petal.style.animationDuration = duration + 's';
petalsContainer.appendChild(petal);
// 动画结束后移除花瓣
setTimeout(() => {
petal.remove();
}, duration * 1000);
}
// 定期创建花瓣
setInterval(createPetal, 500);
// 初始创建一些花瓣
for (let i = 0; i < 20; i++) {
setTimeout(createPetal, i * 200);
}
// 倒计时逻辑
let remainingTime = ${(额外参数.锁定状态 ? 额外参数.剩余时间 : 0)};
const countdownElement = document.getElementById('countdown');
const loginButton = document.getElementById('loginButton');
function startCountdown() {
if (!countdownElement) return;
const interval = setInterval(() => {
if (remainingTime <= 0) {
clearInterval(interval);
countdownElement.textContent = '0';
loginButton.disabled = false;
document.querySelector('.lock-message').textContent = '锁定已解除,请重新尝试登录';
fetch('/reset-login-failures', { method: 'POST' });
return;
}
countdownElement.textContent = remainingTime;
remainingTime--;
}, 1000);
}
function syncWithServer() {
fetch('/check-lock')
.then(response => response.json())
.then(data => {
if (data.locked) {
remainingTime = data.remainingTime;
countdownElement.textContent = remainingTime;
loginButton.disabled = true;
} else {
remainingTime = 0;
countdownElement.textContent = '0';
loginButton.disabled = false;
document.querySelector('.lock-message').textContent = '锁定已解除,请重新尝试登录';
}
})
.catch(error => {
console.error('同步锁定状态失败:', error);
});
}
if (${额外参数.锁定状态 ? 'true' : 'false'}) {
startCountdown();
setInterval(syncWithServer, 10000);
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
syncWithServer();
}
});
}
// 防止 UA 切换触发表单提交
document.querySelector('.auth-form')?.addEventListener('submit', function(event) {
if (!event.isTrusted) {
event.preventDefault();
console.log('阻止非用户触发的表单提交');
}
});
// 监听 UA 变化并平滑处理
let lastUA = navigator.userAgent;
function checkUAChange() {
const currentUA = navigator.userAgent;
if (currentUA !== lastUA) {
console.log('UA 已切换,从', lastUA, '到', currentUA);
lastUA = currentUA;
}
}
setInterval(checkUAChange, 500);
// 添加输入框聚焦效果
const inputs = document.querySelectorAll('.auth-form input');
inputs.forEach(input => {
input.addEventListener('focus', function() {
this.parentElement.style.transform = 'scale(1.02)';
});
input.addEventListener('blur', function() {
this.parentElement.style.transform = 'scale(1)';
});
});
</script>
</body>
</html>
`;
}
// ====================== 节点配置相关 ======================
async function 获取或初始化UUID(env) {
let uuid = await env.KV数据库.get('current_uuid');
if (!uuid) {
uuid = 生成UUID();
await env.KV数据库.put('current_uuid', uuid);
}
return uuid;
}
async function 获取壁纸地址(env) {
const 白天壁纸 = await env.KV数据库.get('custom_light_bg');
const 暗黑壁纸 = await env.KV数据库.get('custom_dark_bg');
return {
白天: 白天壁纸 || 默认白天背景图,
暗黑: 暗黑壁纸 || 默认暗黑背景图
};
}
async function 加载节点和配置(env, hostName) {
try {
const 节点路径缓存 = await env.KV数据库.get('node_file_paths');
let 节点文件路径 = 节点路径缓存
? JSON.parse(节点路径缓存)
: ['https://raw.githubusercontent.com/Alien-Et/SakuraPanel/refs/heads/main/ips.txt', 'https://raw.githubusercontent.com/Alien-Et/SakuraPanel/refs/heads/main/url.txt'];
const 手动节点缓存 = await env.KV数据库.get('manual_preferred_ips');
let 手动节点列表 = [];
if (手动节点缓存) {
手动节点列表 = JSON.parse(手动节点缓存).map(line => line.trim()).filter(Boolean);
}
const 响应列表 = await Promise.all(
节点文件路径.map(async (路径) => {
try {
const 响应 = await fetch(路径);
if (!响应.ok) throw new Error(`请求 ${路径} 失败,状态码: ${响应.status}`);
const 文本 = await 响应.text();
return 文本.split('\n').map(line => line.trim()).filter(Boolean);
} catch (错误) {
console.error(`拉取 ${路径} 失败: ${错误.message}`);
return [];
}
})
);
const 域名节点列表 = [...new Set(响应列表.flat())];
const 合并节点列表 = [...new Set([...手动节点列表, ...域名节点列表])];
const 缓存节点 = await env.KV数据库.get('ip_preferred_ips');
const 当前节点列表 = 缓存节点 ? JSON.parse(缓存节点) : [];
const 列表相同 = JSON.stringify(合并节点列表) === JSON.stringify(当前节点列表);
if (合并节点列表.length > 0) {
优选节点 = 合并节点列表;
if (!列表相同) {
const 新版本 = String(Date.now());
await env.KV数据库.put('ip_preferred_ips', JSON.stringify(合并节点列表));
await env.KV数据库.put('ip_preferred_ips_version', 新版本);
await env.KV数据库.put('config_' + atob('Y2xhc2g='), await 生成猫咪(env, hostName));
await env.KV数据库.put('config_' + atob('Y2xhc2g=') + '_version', 新版本);
await env.KV数据库.put('config_' + atob('djJyYXk='), await 生成通用(env, hostName));
await env.KV数据库.put('config_' + atob('djJyYXk=') + '_version', 新版本);
}
} else {
优选节点 = 当前节点列表.length > 0 ? 当前节点列表 : [`${hostName}:443`];
}
await env.KV数据库.put('node_file_paths', JSON.stringify(节点文件路径));
} catch (错误) {
const 缓存节点 = await env.KV数据库.get('ip_preferred_ips');
优选节点 = 缓存节点 ? JSON.parse(缓存节点) : [`${hostName}:443`];
await env.KV数据库.put('ip_error_log', JSON.stringify({ time: Date.now(), error: '所有路径拉取失败或手动上传为空' }), { expirationTtl: 86400 });
}
}
async function 获取配置(env, 类型, hostName) {
const 缓存键 = 类型 === atob('Y2xhc2g=') ? 'config_' + atob('Y2xhc2g=') : 'config_' + atob('djJyYXk=');
const 版本键 = `${缓存键}_version`;
const 缓存配置 = await env.KV数据库.get(缓存键);
const 配置版本 = await env.KV数据库.get(版本键) || '0';
const 节点版本 = await env.KV数据库.get('ip_preferred_ips_version') || '0';
if (缓存配置 && 配置版本 === 节点版本) {
return 缓存配置;
}
const 新配置 = 类型 === atob('Y2xhc2g=') ? await 生成猫咪(env, hostName) : await 生成通用(env, hostName);
await env.KV数据库.put(缓存键, 新配置);
await env.KV数据库.put(版本键, 节点版本);
return 新配置;
}
// ====================== 主逻辑 ======================
export default {
async fetch(请求, env) {
try {
if (!env.KV数据库) {
return 创建HTML响应(生成KV未绑定提示页面());
}
const 请求头 = 请求.headers.get('Upgrade');
const url = new URL(请求.url);
const hostName = 请求.headers.get('Host');
const UA = 请求.headers.get('User-Agent') || 'unknown';
const IP = 请求.headers.get('CF-Connecting-IP') || 'unknown';
const 设备标识 = `${UA}_${IP}`;
let formData;
if (请求头 && 请求头 === 'websocket') {
反代地址 = env.PROXYIP || 反代地址;
SOCKS5账号 = env.SOCKS5 || SOCKS5账号;
return await 升级请求(请求, env);
}
if (url.pathname === '/login/submit' || url.pathname === '/register/submit') {
const contentType = 请求.headers.get('Content-Type') || '';
if (!contentType.includes('application/x-www-form-urlencoded') && !contentType.includes('multipart/form-data')) {
console.log(`无效请求: UA=${UA}, IP=${IP}, Path=${url.pathname}, Headers=${JSON.stringify([...请求.headers])}`);
return 创建HTML响应(生成登录注册界面(url.pathname === '/login/submit' ? '登录' : '注册', {
错误信息: '请通过正常表单提交'
}), 400);
}
try {
formData = await 请求.formData();
} catch (错误) {
return 创建HTML响应(生成登录注册界面(url.pathname === '/login/submit' ? '登录' : '注册', {
错误信息: '提交数据格式错误,请重试'
}), 400);
}
}
if (url.pathname === '/register/submit') {
const 用户名 = formData.get('username');
const 密码 = formData.get('password');
const 确认密码 = formData.get('confirm');
if (!用户名 || !密码 || 密码 !== 确认密码) {
return 创建HTML响应(生成登录注册界面('注册', {
错误信息: 密码 !== 确认密码 ? '两次密码不一致' : '请填写完整信息'
}), 400);
}
const 已有用户 = await env.KV数据库.get('stored_credentials');
if (已有用户) {
return 创建重定向响应('/login');
}
const 加密密码值 = await 加密密码(密码);
await env.KV数据库.put('stored_credentials', JSON.stringify({
用户名, 密码: 加密密码值
}));
const 新Token = Math.random().toString(36).substring(2);
await env.KV数据库.put('current_token', 新Token, { expirationTtl: 300 });
return 创建重定向响应(`/${配置路径}`, {
'Set-Cookie': `token=${新Token}; Path=/; HttpOnly; SameSite=Strict`
});
}
if (url.pathname === '/login/submit') {
const 锁定状态 = await 检查锁定(env, 设备标识);
if (锁定状态.被锁定) {
return 创建HTML响应(生成登录注册界面('登录', {
锁定状态: true,
剩余时间: 锁定状态.剩余时间
}), 403);
}
const 存储凭据 = await env.KV数据库.get('stored_credentials');
if (!存储凭据) {
return 创建重定向响应('/register');
}
const 输入用户名 = formData.get('username');
const 输入密码 = formData.get('password');
const 凭据对象 = JSON.parse(存储凭据 || '{}');
const 密码匹配 = (await 加密密码(输入密码)) === 凭据对象.密码;
if (输入用户名 === 凭据对象.用户名 && 密码匹配) {
const 新Token = Math.random().toString(36).substring(2);
await env.KV数据库.put('current_token', 新Token, { expirationTtl: 300 });
await env.KV数据库.put(`fail_${设备标识}`, '0');
return 创建重定向响应(`/${配置路径}`, {
'Set-Cookie': `token=${新Token}; Path=/; HttpOnly; SameSite=Strict`
});
}
let 失败次数 = Number(await env.KV数据库.get(`fail_${设备标识}`) || 0) + 1;
await env.KV数据库.put(`fail_${设备标识}`, String(失败次数));
if (失败次数 >= 最大失败次数) {
await env.KV数据库.put(`lock_${设备标识}`, String(Date.now() + 锁定时间), { expirationTtl: 300 });
const 新锁定状态 = await 检查锁定(env, 设备标识);
return 创建HTML响应(生成登录注册界面('登录', {
锁定状态: true,
剩余时间: 新锁定状态.剩余时间
}), 403);
}
return 创建HTML响应(生成登录注册界面('登录', {
输错密码: true,
剩余次数: 最大失败次数 - 失败次数
}), 401);
}
const 是否已注册 = await env.KV数据库.get('stored_credentials');
if (!是否已注册 && url.pathname !== '/register') {
return 创建HTML响应(生成登录注册界面('注册'));
}
switch (url.pathname) {
case '/login':
const 存储凭据 = await env.KV数据库.get('stored_credentials');
if (!存储凭据) {
return 创建重定向响应('/register');
}
const 锁定状态 = await 检查锁定(env, 设备标识);
if (锁定状态.被锁定) {
return 创建HTML响应(生成登录注册界面('登录', { 锁定状态: true, 剩余时间: 锁定状态.剩余时间 }));
}
if (请求.headers.get('Cookie')?.split('=')[1] === await env.KV数据库.get('current_token')) {
return 创建重定向响应(`/${配置路径}`);
}
const 失败次数 = Number(await env.KV数据库.get(`fail_${设备标识}`) || 0);
return 创建HTML响应(生成登录注册界面('登录', { 输错密码: 失败次数 > 0, 剩余次数: 最大失败次数 - 失败次数 }));
case '/reset-login-failures':
await env.KV数据库.put(`fail_${设备标识}`, '0');
await env.KV数据库.delete(`lock_${设备标识}`);
return new Response(null, { status: 200 });
case '/check-lock':
const 锁定检查 = await 检查锁定(env, 设备标识);
return 创建JSON响应({
locked: 锁定检查.被锁定,
remainingTime: 锁定检查.剩余时间
});
case `/${配置路径}`:
const Token = 请求.headers.get('Cookie')?.split('=')[1];
const 有效Token = await env.KV数据库.get('current_token');
if (!Token || Token !== 有效Token) return 创建重定向响应('/login');
const uuid = await 获取或初始化UUID(env);
return 创建HTML响应(生成订阅页面(配置路径, hostName, uuid));
case `/${配置路径}/logout`:
await env.KV数据库.delete('current_token');
return 创建重定向响应('/login', { 'Set-Cookie': 'token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; HttpOnly; SameSite=Strict' });
case `/${配置路径}/` + atob('Y2xhc2g='):
await 加载节点和配置(env, hostName);
const config = await 获取配置(env, atob('Y2xhc2g='), hostName);
// 获取机场名称用于文件名,atob('54yr5ZKq6YWN572u')配置使用atob('LnlhbWw=')后缀
const 机场名称 = await env.KV数据库.get('airportName') || '樱花订阅';
const cleanAirportName = 机场名称.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, '');
const fileName = cleanAirportName + atob('LnlhbWw=');
return new Response(config, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Content-Disposition": `inline; filename="${cleanAirportName}"; filename*=utf-8''${encodeURIComponent(cleanAirportName)}`
}
});
case `/${配置路径}/` + atob('djJyYXk='):
await 加载节点和配置(env, hostName);
const 通用配置 = await 获取配置(env, atob('djJyYXk='), hostName);
// 获取机场名称用于文件名,atob('6YCa55So6YWN572u')配置使用atob('LnR4dA==')后缀
const 机场名称v2 = await env.KV数据库.get('airportName') || '樱花订阅';
const cleanAirportNamev2 = 机场名称v2.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, '');
const fileNamev2 = cleanAirportNamev2 + atob('LnR4dA==');
return new Response(通用配置, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Content-Disposition": `inline; filename="${cleanAirportNamev2}"; filename*=utf-8''${encodeURIComponent(cleanAirportNamev2)}`
}
});
case `/${配置路径}/` + atob('djJyYXluZw=='):
await 加载节点和配置(env, hostName);
const 手机通用配置 = await 获取配置(env, atob('djJyYXk='), hostName);
// 获取机场名称用于文件名,atob('VjJSYXlOR+mFjee9rg==')配置使用atob('LnR4dA==')后缀
const 机场名称ng = await env.KV数据库.get('airportName') || '樱花订阅';
const cleanAirportNameng = 机场名称ng.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, '');
const fileNameng = cleanAirportNameng + atob('LnR4dA==');
return new Response(手机通用配置, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Content-Disposition": `attachment; filename="${cleanAirportNameng}"; filename*=utf-8''${encodeURIComponent(cleanAirportNameng)}`
}
});
case `/${配置路径}/` + atob('djJyYXlu'):
await 加载节点和配置(env, hostName);
const 电脑通用配置 = await 获取配置(env, atob('djJyYXk='), hostName);
// 获取机场名称用于文件名,atob('6YCa55So6YWN572u')使用atob('LnR4dA==')后缀
const 机场名称n = await env.KV数据库.get('airportName') || '樱花订阅';
const cleanAirportNamen = 机场名称n.replace(/[^\u4e00-\u9fa5a-zA-Z0-9_-]/g, '');
const fileNamen = cleanAirportNamen + atob('LnR4dA==');
return new Response(电脑通用配置, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Content-Disposition": `attachment; filename="${cleanAirportNamen}"; filename*=utf-8''${encodeURIComponent(cleanAirportNamen)}`
}
});
case `/${配置路径}/upload`:
const uploadToken = 请求.headers.get('Cookie')?.split('=')[1];
const 有效UploadToken = await env.KV数据库.get('current_token');
if (!uploadToken || uploadToken !== 有效UploadToken) {
return 创建JSON响应({ error: '未登录或Token无效,请重新登录' }, 401);
}
formData = await 请求.formData();
const ipFiles = formData.getAll('ipFiles');
if (!ipFiles || ipFiles.length === 0) {
return 创建JSON响应({ error: '未选择任何文件' }, 400);
}
let allIpList = [];
try {
for (const ipFile of ipFiles) {
if (!ipFile || !ipFile.text) throw new Error(`文件 ${ipFile.name} 无效`);
// 验证文件格式
if (!ipFile.name.toLowerCase().endsWith('.txt')) {
throw new Error(`文件 ${ipFile.name} 不是txt格式,仅允许上传txt格式文件`);
}
// 验证文件大小(限制为1MB)
if (ipFile.size > 1024 * 1024) {
throw new Error(`文件 ${ipFile.name} 超过大小限制(1MB)`);
}
const ipText = await ipFile.text();
// 验证文件内容格式
const lines = ipText.split('\n').map(line => line.trim()).filter(Boolean);
if (lines.length === 0) {
console.warn(`文件 ${ipFile.name} 内容为空`);
continue;
}
// 验证每行是否符合节点格式:[地址]:端口#节点名称@tls 或 [地址]:端口#节点名称@notls
const validLines = [];
for (const line of lines) {
// 基本格式验证
// 更灵活的节点格式验证,允许以下格式:
// 1. 完整格式:[地址]:端口#节点名称@tls/notls
// 2. 不带端口:[地址]#节点名称@tls/notls
// 3. 不带tls/notls:[地址]:端口#节点名称
// 4. 最简格式:[地址]#节点名称
// 现在支持IP地址(IPv4/IPv6)和域名
const nodePattern = /^(\[[0-9a-fA-F:]+\]|[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9](?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])*)(?::([0-9]{1,5}))?(?:#(.+?))?(?:@(tls|notls))?$/;
const match = nodePattern.exec(line);
if (!match) {
console.warn(`文件 ${ipFile.name} 中的行格式不正确,将被忽略: ${line}`);
continue;
}
const address = match[1];
const port = match[2];
const nodeName = match[3] || 节点名称; // 使用全局变量节点名称作为默认值
const protocol = match[4] || 'tls'; // 默认使用tls
// 如果有端口,验证端口范围
if (port) {
const portNum = parseInt(port);
if (portNum < 1 || portNum > 65535) {
console.warn(`文件 ${ipFile.name} 中的端口无效,将被忽略: ${line}`);
continue;
}
}
// 验证IP地址格式(如果是IPv4)
const ipv4Pattern = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/;
if (ipv4Pattern.test(address)) {
const ipParts = address.split('.');
let isValidIPv4 = true;
for (const part of ipParts) {
const num = parseInt(part);
if (num < 0 || num > 255) {
isValidIPv4 = false;
break;
}
}
if (!isValidIPv4) {
console.warn(`文件 ${ipFile.name} 中的IPv4地址无效,将被忽略: ${line}`);
continue;
}
}
// 标准化节点格式
const standardPort = port || '443'; // 默认端口443
const standardizedLine = `${address}:${standardPort}#${nodeName}@${protocol}`;
validLines.push(standardizedLine);
}
if (validLines.length === 0) {
throw new Error(`文件 ${ipFile.name} 中没有符合格式要求的节点`);
}
console.log(`文件 ${ipFile.name} 验证通过,有效节点数: ${validLines.length}`);
allIpList = allIpList.concat(validLines);
}
if (allIpList.length === 0) {
return 创建JSON响应({ error: '所有上传文件中没有符合格式要求的节点' }, 400);
}
const uniqueIpList = [...new Set(allIpList)];
const 当前手动节点 = await env.KV数据库.get('manual_preferred_ips');
const 当前节点列表 = 当前手动节点 ? JSON.parse(当前手动节点) : [];
const 是重复上传 = JSON.stringify(当前节点列表.sort()) === JSON.stringify(uniqueIpList.sort());
if (是重复上传) {
return 创建JSON响应({ message: '上传内容与现有节点相同,无需更新' }, 200);
}
await env.KV数据库.put('manual_preferred_ips', JSON.stringify(uniqueIpList));
const 新版本 = String(Date.now());
await env.KV数据库.put('ip_preferred_ips_version', 新版本);
await env.KV数据库.put('config_' + atob('Y2xhc2g='), await 生成猫咪(env, hostName));
await env.KV数据库.put('config_' + atob('Y2xhc2g=') + '_version', 新版本);
await env.KV数据库.put('config_' + atob('djJyYXk='), await 生成通用(env, hostName));
await env.KV数据库.put('config_' + atob('djJyYXk=') + '_version', 新版本);
return 创建JSON响应({ message: '上传成功,即将跳转' }, 200, { 'Location': `/${配置路径}` });
} catch (错误) {
console.error(`上传处理失败: ${错误.message}`);
return 创建JSON响应({ error: `上传处理失败: ${错误.message}` }, 500);
}