forked from zixiwangluo/CF-M365-Admin
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathworker.js
More file actions
1047 lines (932 loc) · 49.3 KB
/
worker.js
File metadata and controls
1047 lines (932 loc) · 49.3 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
/**
* CF-M365-Admin v4.1 (Fix Auth Loop & Add License Query)
* * [环境变量配置]
* AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET: 微软 Graph API 配置
* CF_TURNSTILE_SECRET: Turnstile 后端密钥 (必须)
* TURNSTILE_SITE_KEY: Turnstile 前端 Site Key (必须)
* DEFAULT_DOMAIN: 邮箱后缀 (不带@)
* SKU_MAP: JSON SKU 映射
* ADMIN_TOKEN: 管理员密码
* HIDDEN_USER: (可选) 隐藏管理员账号
* ADMIN_PATH: (可选) 后台路径,默认 "/admin"
* ENABLE_DEBUG: (可选) "true"
* * [KV 绑定]
* Variable Name: INVITE_CODES
*/
const debugLog = (env, ...args) => {
if (env.ENABLE_DEBUG === 'true') console.log('[DEBUG]', ...args);
};
// --- 辅助函数 ---
const getEnv = (val, defaultVal = '') => val ? val.trim() : defaultVal;
function checkPasswordComplexity(pwd) {
if (!pwd || pwd.length < 8) return false;
let score = 0;
if (/[a-z]/.test(pwd)) score++;
if (/[A-Z]/.test(pwd)) score++;
if (/\d/.test(pwd)) score++;
if (/[^a-zA-Z0-9]/.test(pwd)) score++;
return score >= 3;
}
// --- 通用 HTML 头部 (Tailwind + Fonts) ---
const HTML_HEAD = (title) => `
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>${title}</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;800&display=swap" rel="stylesheet">
<script src="https://unpkg.com/lucide@latest"></script>
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: { sans: ['Inter', 'sans-serif'] },
colors: {
ios: {
bg: '#F2F2F7',
card: 'rgba(255, 255, 255, 0.65)',
primary: '#1C1C1E',
secondary: '#FFFFFF',
danger: '#FF3B30',
success: '#34C759',
border: 'rgba(255, 255, 255, 0.6)',
borderOut: 'rgba(0, 0, 0, 0.05)'
}
},
boxShadow: {
'zen': '0 24px 48px -12px rgba(0, 0, 0, 0.08), 0 4px 12px -4px rgba(0,0,0,0.02)',
'inner-light': 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.03)'
},
backdropBlur: {
'xs': '2px',
}
}
}
}
</script>
<style>
body { background-color: #F2F2F7; -webkit-font-smoothing: antialiased; }
.glass-panel {
background-color: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(40px);
-webkit-backdrop-filter: blur(40px);
border: 1px solid rgba(255, 255, 255, 0.6);
box-shadow: 0 0 0 1px rgba(0,0,0,0.03), 0 24px 48px -12px rgba(0, 0, 0, 0.08);
}
.glass-modal {
background-color: rgba(255, 255, 255, 0.85);
backdrop-filter: blur(24px);
-webkit-backdrop-filter: blur(24px);
border: 1px solid rgba(255, 255, 255, 0.8);
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}
.input-zen {
background-color: rgba(243, 244, 246, 0.6);
box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.03);
border: 1px solid transparent;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.input-zen:focus {
background-color: #FFFFFF;
border-color: rgba(0,0,0,0.1);
box-shadow: 0 4px 12px rgba(0,0,0,0.05);
outline: none;
}
.btn-primary {
background-color: #1C1C1E;
color: white;
transition: transform 0.1s;
}
.btn-primary:active { transform: scale(0.98); }
.btn-secondary {
background-color: #FFFFFF;
color: #1C1C1E;
border: 1px solid rgba(0,0,0,0.05);
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
transition: transform 0.1s, background-color 0.2s;
}
.btn-secondary:active { transform: scale(0.98); }
.btn-secondary:hover { background-color: #F9FAFB; }
.no-scrollbar::-webkit-scrollbar { display: none; }
.no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
.loading-spinner {
border: 3px solid rgba(0,0,0,0.1);
border-left-color: #1C1C1E;
border-radius: 50%;
width: 24px; height: 24px;
animation: spin 1s linear infinite;
}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
</style>
</head>
`;
// --- 1. 登录页面 (Login) ---
const HTML_LOGIN_PAGE = (siteKey, adminPath) => `
<!DOCTYPE html>
<html lang="zh-CN">
${HTML_HEAD('Admin Login')}
<body class="flex items-center justify-center min-h-screen p-6">
<div class="glass-panel w-full max-w-[380px] rounded-[40px] p-10 flex flex-col items-center">
<div class="mb-8 p-4 bg-white/50 rounded-[24px] shadow-sm">
<i data-lucide="shield-check" class="w-8 h-8 text-gray-800"></i>
</div>
<h2 class="text-2xl font-extrabold text-gray-900 mb-2 tracking-tight">管理员登录</h2>
<p class="text-gray-500 text-sm mb-8 font-medium">请输入访问令牌以继续</p>
<form id="loginForm" class="w-full space-y-5">
<div class="space-y-2">
<label class="text-[10px] font-bold text-gray-400 uppercase tracking-widest pl-1">Access Token</label>
<input type="password" id="token"
class="input-zen w-full px-4 py-3.5 rounded-2xl text-gray-800 text-sm placeholder-gray-400"
placeholder="••••••••••••" required>
</div>
<div class="flex justify-center pt-2">
<div class="cf-turnstile" data-sitekey="${siteKey}" data-theme="light"></div>
</div>
<button type="submit" id="loginBtn" class="btn-primary w-full py-3.5 rounded-2xl font-semibold text-sm shadow-lg mt-4 flex justify-center items-center gap-2">
<span>进入控制台</span>
<i data-lucide="arrow-right" class="w-4 h-4"></i>
</button>
</form>
<div id="msg" class="mt-4 text-center text-xs font-medium text-red-500 hidden"></div>
</div>
<script>
lucide.createIcons();
// 如果URL中有token参数,自动跳转到干净的URL,防止无限刷新
if(window.location.search.includes('token=')) {
window.history.replaceState({}, document.title, window.location.pathname);
}
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('loginBtn');
const msg = document.getElementById('msg');
const token = document.getElementById('token').value;
const turnstileEl = document.querySelector('[name="cf-turnstile-response"]');
if (!turnstileEl || !turnstileEl.value) {
msg.textContent = '请完成人机验证';
msg.classList.remove('hidden');
return;
}
btn.disabled = true;
btn.innerHTML = '<div class="loading-spinner w-4 h-4 border-2"></div>';
msg.classList.add('hidden');
try {
const res = await fetch('${adminPath}/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token, cf_turnstile: turnstileEl.value })
});
if (res.ok) {
window.location.reload(); // 登录成功,刷新页面进入后台
} else {
const data = await res.json();
throw new Error(data.message || '验证失败');
}
} catch (err) {
msg.textContent = err.message;
msg.classList.remove('hidden');
btn.disabled = false;
btn.innerHTML = '<span>重试</span><i data-lucide="refresh-cw" class="w-4 h-4"></i>';
turnstile.reset();
}
});
</script>
</body>
</html>
`;
// --- 2. 注册页面 (Register) ---
const HTML_REGISTER_PAGE = (siteKey, skuOptions) => `
<!DOCTYPE html>
<html lang="zh-CN">
${HTML_HEAD('Office 365 邀请注册')}
<body class="flex items-center justify-center min-h-screen p-6">
<div class="glass-panel w-full max-w-[420px] rounded-[48px] p-8 md:p-12 relative overflow-hidden">
<!-- 装饰背景 -->
<div class="absolute -top-20 -right-20 w-64 h-64 bg-blue-400/10 rounded-full blur-3xl pointer-events-none"></div>
<div class="absolute -bottom-20 -left-20 w-64 h-64 bg-purple-400/10 rounded-full blur-3xl pointer-events-none"></div>
<div class="relative z-10">
<div class="text-center mb-10">
<div class="inline-flex items-center justify-center w-16 h-16 bg-white/80 rounded-[24px] shadow-sm mb-6">
<i data-lucide="user-plus" class="w-8 h-8 text-gray-800"></i>
</div>
<h2 class="text-3xl font-extrabold text-gray-900 tracking-tight">Create Account</h2>
<p class="text-gray-500 text-sm mt-2 font-medium">使用管理员分发的邀请码激活</p>
</div>
<form id="regForm" class="space-y-6">
<div class="space-y-2">
<label class="text-[10px] font-bold text-gray-400 uppercase tracking-widest pl-1">Invite Code</label>
<div class="relative">
<input type="text" id="inviteCode" class="input-zen w-full pl-11 pr-4 py-3.5 rounded-2xl text-gray-800 text-sm font-mono tracking-wide" placeholder="XXXX-XXXX" required>
<i data-lucide="key" class="w-4 h-4 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2"></i>
</div>
</div>
<div class="space-y-2">
<label class="text-[10px] font-bold text-gray-400 uppercase tracking-widest pl-1">Subscription</label>
<div class="relative">
<select id="skuSelect" class="input-zen w-full pl-11 pr-10 py-3.5 rounded-2xl text-gray-800 text-sm appearance-none bg-transparent">
${skuOptions.map(opt => `<option value="${opt}">${opt}</option>`).join('')}
</select>
<i data-lucide="package" class="w-4 h-4 text-gray-400 absolute left-4 top-1/2 -translate-y-1/2"></i>
<i data-lucide="chevron-down" class="w-4 h-4 text-gray-400 absolute right-4 top-1/2 -translate-y-1/2"></i>
</div>
</div>
<div class="grid grid-cols-2 gap-4">
<div class="space-y-2">
<label class="text-[10px] font-bold text-gray-400 uppercase tracking-widest pl-1">Username</label>
<input type="text" id="username" class="input-zen w-full px-4 py-3.5 rounded-2xl text-gray-800 text-sm" placeholder="Alice" pattern="[a-zA-Z0-9]+" required>
</div>
<div class="space-y-2">
<label class="text-[10px] font-bold text-gray-400 uppercase tracking-widest pl-1">Password</label>
<input type="password" id="password" class="input-zen w-full px-4 py-3.5 rounded-2xl text-gray-800 text-sm" placeholder="********" required>
</div>
</div>
<div class="flex justify-center pt-2">
<div class="cf-turnstile" data-sitekey="${siteKey}"></div>
</div>
<button type="submit" id="btn" class="btn-primary w-full py-4 rounded-2xl font-bold text-sm shadow-xl hover:shadow-2xl transition-all">
立即激活账号
</button>
</form>
<div id="msg" class="mt-6 p-4 rounded-2xl text-sm font-medium hidden"></div>
</div>
</div>
<script>
lucide.createIcons();
document.getElementById('regForm').addEventListener('submit', async (e) => {
e.preventDefault();
const btn = document.getElementById('btn');
const msg = document.getElementById('msg');
// UI Reset
msg.classList.add('hidden');
msg.className = 'mt-6 p-4 rounded-2xl text-sm font-medium hidden';
btn.disabled = true;
const originalBtnText = btn.innerHTML;
btn.innerHTML = '<div class="flex items-center justify-center gap-2"><span>Processing</span><div class="loading-spinner w-4 h-4 border-white/30 border-l-white"></div></div>';
const formData = new FormData();
formData.append('inviteCode', document.getElementById('inviteCode').value.trim());
formData.append('skuName', document.getElementById('skuSelect').value);
formData.append('username', document.getElementById('username').value);
formData.append('password', document.getElementById('password').value);
const turnstileEl = document.querySelector('[name="cf-turnstile-response"]');
if(turnstileEl) formData.append('cf-turnstile-response', turnstileEl.value);
try {
const res = await fetch('/', { method: 'POST', body: formData });
const data = await res.json();
msg.classList.remove('hidden');
if (data.success) {
msg.classList.add('bg-green-100/80', 'text-green-800', 'border', 'border-green-200');
msg.innerHTML = \`<div class="flex flex-col gap-1"><span class="font-bold flex items-center gap-2"><i data-lucide="check-circle" class="w-4 h-4"></i> Success</span><span>账号: \${data.email}</span><a href="https://portal.office.com" target="_blank" class="underline mt-1 opacity-70 hover:opacity-100">前往登录 →</a></div>\`;
lucide.createIcons();
document.getElementById('regForm').reset();
} else {
throw new Error(data.message);
}
} catch (err) {
msg.classList.add('bg-red-50/80', 'text-red-600', 'border', 'border-red-100');
msg.innerHTML = \`<div class="flex items-center gap-2"><i data-lucide="alert-circle" class="w-4 h-4"></i> <span>\${err.message || '网络错误'}</span></div>\`;
lucide.createIcons();
} finally {
btn.disabled = false;
btn.innerHTML = originalBtnText;
if(typeof turnstile !== 'undefined') turnstile.reset();
}
});
</script>
</body>
</html>
`;
// --- 3. 后台管理页面 HTML ---
const HTML_ADMIN_PAGE = (skuMapJson, hiddenUser, adminPath) => `
<!DOCTYPE html>
<html lang="zh-CN">
${HTML_HEAD('M365 Console')}
<body class="p-6 md:p-10 min-h-screen">
<div class="max-w-7xl mx-auto space-y-8">
<!-- Header -->
<div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
<div>
<h1 class="text-3xl font-extrabold text-gray-900 tracking-tight">Dashboard</h1>
<p class="text-gray-500 text-sm font-medium mt-1">M365 Subscription & User Management</p>
</div>
<div class="flex items-center gap-3">
<button onclick="handleLogout()" class="px-4 py-2 bg-white/60 hover:bg-red-50 hover:text-red-600 rounded-full text-xs font-bold text-gray-500 border border-white/60 shadow-sm backdrop-blur-md transition-all flex items-center gap-2">
<i data-lucide="log-out" class="w-3 h-3"></i> 登出
</button>
</div>
</div>
<!-- Navigation Tabs -->
<div class="flex p-1.5 bg-gray-200/50 rounded-[20px] w-fit backdrop-blur-md">
<button onclick="switchTab('users')" id="tab-btn-users" class="px-6 py-2.5 rounded-2xl text-sm font-semibold transition-all shadow-sm bg-white text-gray-900">
用户列表
</button>
<button onclick="switchTab('invites')" id="tab-btn-invites" class="px-6 py-2.5 rounded-2xl text-sm font-semibold text-gray-500 hover:text-gray-700 transition-all ml-1">
邀请码管理
</button>
</div>
<!-- Content Area -->
<div class="glass-panel rounded-[40px] min-h-[600px] relative overflow-hidden">
<!-- Users Tab -->
<div id="view-users" class="p-8 h-full flex flex-col">
<div class="flex flex-wrap items-center justify-between gap-4 mb-8">
<div class="flex items-center gap-3">
<button onclick="loadUsers()" class="btn-secondary w-10 h-10 rounded-xl flex items-center justify-center" title="刷新">
<i data-lucide="refresh-ccw" class="w-4 h-4"></i>
</button>
<button onclick="showLicenses()" class="btn-secondary px-5 py-2.5 rounded-xl text-sm font-semibold text-gray-600 flex items-center gap-2" title="查看订阅用量">
<i data-lucide="pie-chart" class="w-4 h-4"></i> 订阅用量
</button>
<span class="text-sm font-bold text-gray-400 uppercase tracking-widest pl-2" id="user-count-label">Loading...</span>
</div>
<div class="flex items-center gap-3">
<button onclick="toggleDeleteMode()" id="btn-del-mode" class="btn-secondary px-5 py-2.5 rounded-xl text-sm font-semibold text-gray-600">
批量管理
</button>
<button onclick="confirmBatchDelete()" id="btn-del-confirm" class="bg-red-500 text-white px-5 py-2.5 rounded-xl text-sm font-semibold shadow-lg hover:bg-red-600 active:scale-95 transition-all hidden">
确认删除 (<span id="del-count">0</span>)
</button>
</div>
</div>
<div class="flex-1 overflow-auto -mx-8 px-8 no-scrollbar">
<table class="w-full text-left border-collapse">
<thead>
<tr class="border-b border-gray-200/50">
<th class="py-4 pl-2 w-12 del-col hidden">
<input type="checkbox" onchange="toggleSelectAll(this)" class="rounded-md border-gray-300 text-gray-900 focus:ring-0 w-5 h-5 bg-white/50">
</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">User</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Email (UPN)</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Status</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Created</th>
</tr>
</thead>
<tbody id="user-list" class="text-sm text-gray-700">
<!-- JS Render -->
</tbody>
</table>
</div>
</div>
<!-- Invites Tab -->
<div id="view-invites" class="p-8 h-full flex flex-col hidden">
<div class="flex flex-wrap items-center justify-between gap-4 mb-8">
<div class="flex items-center gap-3">
<button onclick="promptGenerate()" class="btn-primary px-5 py-2.5 rounded-xl text-sm font-semibold flex items-center gap-2 shadow-lg">
<i data-lucide="plus" class="w-4 h-4"></i> Generate
</button>
<button onclick="loadInvites()" class="btn-secondary w-10 h-10 rounded-xl flex items-center justify-center">
<i data-lucide="refresh-ccw" class="w-4 h-4"></i>
</button>
<button onclick="copyUnused()" class="btn-secondary px-5 py-2.5 rounded-xl text-sm font-semibold text-gray-600">
复制未使用
</button>
</div>
<div class="flex items-center gap-4">
<span class="text-sm font-bold text-gray-400 uppercase tracking-widest" id="invite-stats">...</span>
<button onclick="clearAllInvites()" class="text-red-500 hover:bg-red-50 px-4 py-2 rounded-xl text-xs font-bold transition-colors">
清空所有
</button>
</div>
</div>
<div class="flex-1 overflow-auto -mx-8 px-8 no-scrollbar">
<table class="w-full text-left border-collapse">
<thead>
<tr class="border-b border-gray-200/50">
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Code</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Status</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Bound User</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest">Created</th>
<th class="py-4 text-[10px] font-bold text-gray-400 uppercase tracking-widest w-20">Action</th>
</tr>
</thead>
<tbody id="invite-list" class="text-sm text-gray-700">
<!-- JS Render -->
</tbody>
</table>
</div>
</div>
<!-- Loading Overlay -->
<div id="loading-overlay" class="absolute inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-50 hidden">
<div class="loading-spinner w-8 h-8 border-gray-400/30 border-l-gray-800"></div>
</div>
<!-- License Modal -->
<div id="license-modal" class="absolute inset-0 z-40 bg-white/60 backdrop-blur-sm hidden flex items-center justify-center p-4">
<div class="glass-modal w-full max-w-2xl rounded-[32px] p-8 relative flex flex-col max-h-[80vh]">
<div class="flex justify-between items-center mb-6">
<h3 class="text-xl font-bold text-gray-900">订阅用量详情</h3>
<button onclick="closeLicenseModal()" class="p-2 hover:bg-gray-100 rounded-full transition-colors">
<i data-lucide="x" class="w-5 h-5 text-gray-500"></i>
</button>
</div>
<div class="overflow-auto flex-1 no-scrollbar">
<table class="w-full text-left">
<thead>
<tr class="border-b border-gray-200">
<th class="py-3 text-[10px] font-bold text-gray-400 uppercase">SKU Name</th>
<th class="py-3 text-[10px] font-bold text-gray-400 uppercase">Total</th>
<th class="py-3 text-[10px] font-bold text-gray-400 uppercase">Used</th>
<th class="py-3 text-[10px] font-bold text-gray-400 uppercase">Available</th>
</tr>
</thead>
<tbody id="license-list" class="text-sm"></tbody>
</table>
</div>
<div class="mt-6 pt-4 border-t border-gray-200/50 text-xs text-gray-500 font-mono break-all">
* SKUID 用于配置 SKU_MAP 环境变量
</div>
</div>
</div>
</div>
</div>
<script>
const API_BASE = '${adminPath}/api';
const AUTH_PATH = '${adminPath}';
const HIDDEN_USER = ${JSON.stringify(hiddenUser || '')}.toLowerCase();
let usersCache = [];
let invitesCache = [];
let deleteMode = false;
// Init
document.addEventListener('DOMContentLoaded', () => {
loadUsers();
loadInvites(true); // silent load
lucide.createIcons();
});
async function handleLogout() {
await fetch(AUTH_PATH + '/logout', { method: 'POST' });
window.location.reload();
}
// Tab Switcher
function switchTab(tab) {
['users', 'invites'].forEach(t => {
const btn = document.getElementById('tab-btn-' + t);
const view = document.getElementById('view-' + t);
if (t === tab) {
btn.className = 'px-6 py-2.5 rounded-2xl text-sm font-semibold transition-all shadow-sm bg-white text-gray-900';
view.classList.remove('hidden');
} else {
btn.className = 'px-6 py-2.5 rounded-2xl text-sm font-semibold text-gray-500 hover:text-gray-700 transition-all ml-1';
view.classList.add('hidden');
}
});
if (tab === 'users') loadUsers();
if (tab === 'invites') loadInvites();
}
// --- License Modal ---
async function showLicenses() {
setLoading(true);
try {
const res = await fetch(API_BASE + '/licenses');
if(!res.ok) throw new Error('Failed');
const data = await res.json();
const tbody = document.getElementById('license-list');
tbody.innerHTML = data.map(l => {
const available = l.total - l.used;
return \`
<tr class="border-b border-gray-100 last:border-0">
<td class="py-3">
<div class="font-medium text-gray-800">\${l.skuPartNumber}</div>
<div class="text-[10px] text-gray-400 font-mono">\${l.skuId}</div>
</td>
<td class="py-3 font-mono">\${l.total}</td>
<td class="py-3 font-mono">\${l.used}</td>
<td class="py-3 font-mono font-bold \${available < 1 ? 'text-red-500' : 'text-green-600'}">\${available}</td>
</tr>
\`;
}).join('');
document.getElementById('license-modal').classList.remove('hidden');
} catch(e) { alert('加载订阅信息失败'); }
setLoading(false);
}
function closeLicenseModal() {
document.getElementById('license-modal').classList.add('hidden');
}
// --- Users Logic ---
async function loadUsers() {
setLoading(true);
try {
const res = await fetch(API_BASE + '/users');
if (res.status === 401) return window.location.reload();
const data = await res.json();
usersCache = data.value || [];
renderUsers();
} catch(e) { console.error(e); alert('Failed to load users'); }
setLoading(false);
}
function renderUsers() {
const tbody = document.getElementById('user-list');
document.getElementById('user-count-label').innerText = \`\${usersCache.length} USERS\`;
tbody.innerHTML = usersCache.map(u => {
const isHidden = u.userPrincipalName.toLowerCase() === HIDDEN_USER;
const checkbox = isHidden ? '' : \`<input type="checkbox" class="user-check rounded border-gray-300 text-gray-900 focus:ring-0 w-5 h-5 bg-white/50" value="\${u.id}" onchange="updateDelCount()">\`;
const badge = isHidden ? '<span class="px-2 py-0.5 bg-gray-200 rounded text-[10px] font-bold text-gray-500 ml-2">ADMIN</span>' : '';
const license = u.assignedLicenses.length
? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">Active</span>'
: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">None</span>';
return \`
<tr class="group hover:bg-white/40 transition-colors border-b border-gray-100/50 last:border-0">
<td class="py-4 pl-2 del-col \${deleteMode ? '' : 'hidden'}">\${checkbox}</td>
<td class="py-4 font-medium text-gray-900">\${u.displayName} \${badge}</td>
<td class="py-4 font-mono text-xs text-gray-500">\${u.userPrincipalName}</td>
<td class="py-4">\${license}</td>
<td class="py-4 text-gray-500 text-xs">\${new Date(u.createdDateTime).toLocaleDateString()}</td>
</tr>
\`;
}).join('');
}
function toggleDeleteMode() {
deleteMode = !deleteMode;
document.querySelectorAll('.del-col').forEach(el => el.classList.toggle('hidden', !deleteMode));
const btnMode = document.getElementById('btn-del-mode');
const btnConfirm = document.getElementById('btn-del-confirm');
if (deleteMode) {
btnMode.innerText = '取消';
btnMode.classList.add('bg-gray-200');
btnConfirm.classList.remove('hidden');
} else {
btnMode.innerText = '批量管理';
btnMode.classList.remove('bg-gray-200');
btnConfirm.classList.add('hidden');
document.querySelectorAll('.user-check').forEach(c => c.checked = false);
updateDelCount();
}
}
function toggleSelectAll(src) {
document.querySelectorAll('.user-check').forEach(c => c.checked = src.checked);
updateDelCount();
}
function updateDelCount() {
document.getElementById('del-count').innerText = document.querySelectorAll('.user-check:checked').length;
}
async function confirmBatchDelete() {
const checks = document.querySelectorAll('.user-check:checked');
if(checks.length === 0) return;
if(!confirm(\`确定要永久删除这 \${checks.length} 个用户吗?关联的邀请码也将被清理。\n此操作不可撤销。\n\nAre you sure?\`)) return;
setLoading(true);
// Sync invites first to ensure cleanup works
if(invitesCache.length === 0) await loadInvites(true);
for(const cb of checks) {
const uid = cb.value;
try {
// 1. Delete User
const res = await fetch(API_BASE + '/users/' + uid, { method: 'DELETE' });
if(res.ok || res.status === 404) {
// 2. Cleanup Invite
const user = usersCache.find(u => u.id === uid);
if(user) {
const invite = invitesCache.find(i => i.user && i.user.toLowerCase() === user.userPrincipalName.toLowerCase());
if(invite) {
await fetch(API_BASE + '/invites?code=' + invite.code, { method: 'DELETE' });
}
}
}
} catch(e) { console.error(e); }
}
toggleDeleteMode();
loadUsers();
setTimeout(() => loadInvites(true), 1000);
setLoading(false);
}
// --- Invites Logic ---
async function loadInvites(silent = false) {
if(!silent) setLoading(true);
try {
const res = await fetch(API_BASE + '/invites');
const data = await res.json();
invitesCache = data;
if(!silent) renderInvites();
} catch(e) {}
if(!silent) setLoading(false);
}
function renderInvites() {
const tbody = document.getElementById('invite-list');
document.getElementById('invite-stats').innerText = \`\${invitesCache.length} CODES\`;
if(invitesCache.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="py-10 text-center text-gray-400">No data</td></tr>';
return;
}
tbody.innerHTML = invitesCache.map(i => {
const isUsed = i.status === 'used';
const status = isUsed
? '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-gray-100 text-gray-500">USED</span>'
: '<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-green-100 text-green-700">UNUSED</span>';
return \`
<tr class="border-b border-gray-100/50 last:border-0 hover:bg-white/40">
<td class="py-4 font-mono font-bold text-gray-800 cursor-pointer hover:text-blue-600 transition-colors" onclick="copyText('\${i.code}')">\${i.code}</td>
<td class="py-4">\${status}</td>
<td class="py-4 text-gray-500 font-mono text-xs">\${i.user || '-'}</td>
<td class="py-4 text-gray-400 text-xs">\${new Date(i.createdAt).toLocaleDateString()}</td>
<td class="py-4">
<button onclick="deleteInvite('\${i.code}')" class="text-red-400 hover:text-red-600 p-2 rounded-lg hover:bg-red-50 transition-all">
<i data-lucide="trash-2" class="w-4 h-4"></i>
</button>
</td>
</tr>
\`;
}).join('');
lucide.createIcons();
}
async function promptGenerate() {
const count = prompt('生成数量 (1-50):', '1');
if(!count) return;
setLoading(true);
try {
await fetch(API_BASE + '/invites', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({count: parseInt(count)})
});
loadInvites();
} catch(e) { alert('Error'); }
setLoading(false);
}
async function deleteInvite(code) {
if(!confirm('Delete this invite code?')) return;
await fetch(API_BASE + '/invites?code=' + code, { method: 'DELETE' });
loadInvites();
}
async function clearAllInvites() {
if(!confirm('DANGER: Clear ALL invite codes?')) return;
setLoading(true);
await fetch(API_BASE + '/invites?action=clear_all', { method: 'DELETE' });
loadInvites();
setLoading(false);
}
function copyUnused() {
const codes = invitesCache.filter(i => i.status !== 'used').map(i => i.code).join('\\n');
if(!codes) return alert('No unused codes');
navigator.clipboard.writeText(codes).then(() => alert('Copied!'));
}
function copyText(t) {
navigator.clipboard.writeText(t).then(() => alert('Code copied: ' + t));
}
function setLoading(state) {
const el = document.getElementById('loading-overlay');
if(state) el.classList.remove('hidden');
else el.classList.add('hidden');
}
</script>
</body>
</html>
`;
export default {
async fetch(request, env) {
const url = new URL(request.url);
const adminPath = getEnv(env.ADMIN_PATH, '/admin').replace(/\/$/, ''); // 移除尾部斜杠
// --- 0. 路由分发 ---
// 静态资源 (注册页)
if (url.pathname === '/' && request.method === 'GET') {
let skuOptions = [];
try { skuOptions = Object.keys(JSON.parse(env.SKU_MAP || '{}')); } catch (e) {}
return new Response(HTML_REGISTER_PAGE(env.TURNSTILE_SITE_KEY, skuOptions), {
headers: { 'Content-Type': 'text/html;charset=UTF-8' },
});
}
// 注册 API
if (url.pathname === '/' && request.method === 'POST') {
return handleRegister(request, env);
}
// --- 后台相关路由 ---
if (url.pathname.startsWith(adminPath)) {
// 登录页面 & API
if (url.pathname === adminPath || url.pathname === `${adminPath}/`) {
// 检查 Cookie
if (await checkAuth(request, env)) {
return new Response(HTML_ADMIN_PAGE(env.SKU_MAP, getEnv(env.HIDDEN_USER), adminPath), {
headers: { 'Content-Type': 'text/html;charset=UTF-8' }
});
}
return new Response(HTML_LOGIN_PAGE(env.TURNSTILE_SITE_KEY, adminPath), {
headers: { 'Content-Type': 'text/html;charset=UTF-8' }
});
}
// 登录提交 API
if (url.pathname === `${adminPath}/login` && request.method === 'POST') {
const body = await request.json();
// 1. Turnstile 验证
const turnstileRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
secret: env.CF_TURNSTILE_SECRET,
response: body.cf_turnstile,
remoteip: request.headers.get('CF-Connecting-IP')
})
});
const turnstileData = await turnstileRes.json();
if (!turnstileData.success) {
return Response.json({ success: false, message: 'Turnstile verification failed' }, { status: 403 });
}
// 2. 密码验证
if (body.token === env.ADMIN_TOKEN) {
// 设置 HttpOnly Cookie, 有效期 1 天
const headers = new Headers();
headers.append('Set-Cookie', `m365_admin_token=${env.ADMIN_TOKEN}; Path=/; Max-Age=86400; HttpOnly; SameSite=Strict; Secure`);
return new Response(JSON.stringify({ success: true }), { status: 200, headers });
}
return Response.json({ success: false, message: 'Invalid Token' }, { status: 401 });
}
// 登出 API
if (url.pathname === `${adminPath}/logout` && request.method === 'POST') {
const headers = new Headers();
headers.append('Set-Cookie', `m365_admin_token=; Path=/; Max-Age=0; HttpOnly; SameSite=Strict; Secure`);
return new Response(JSON.stringify({ success: true }), { status: 200, headers });
}
// --- API 路由 (需要鉴权) ---
if (url.pathname.startsWith(`${adminPath}/api`)) {
if (!(await checkAuth(request, env))) return Response.json({ error: 'Unauthorized' }, { status: 401 });
// Users API
if (url.pathname === `${adminPath}/api/users`) {
if (request.method === 'GET') return handleGetUsers(env);
}
// Single User Delete
if (url.pathname.startsWith(`${adminPath}/api/users/`) && request.method === 'DELETE') {
const uid = url.pathname.split('/').pop();
return handleDeleteUser(uid, env);
}
// Invites API
if (url.pathname === `${adminPath}/api/invites`) {
if (request.method === 'GET') return handleGetInvites(env);
if (request.method === 'POST') return handleCreateInvites(request, env);
if (request.method === 'DELETE') return handleDeleteInvites(request, env);
}
// Licenses API (New)
if (url.pathname === `${adminPath}/api/licenses`) {
if (request.method === 'GET') return handleGetLicenses(env);
}
}
}
return new Response('404 Not Found', { status: 404 });
}
};
// --- 业务逻辑处理器 ---
async function checkAuth(req, env) {
// 仅检查 Cookie
const cookie = req.headers.get('Cookie');
if (cookie && cookie.includes(`m365_admin_token=${env.ADMIN_TOKEN}`)) return true;
return false;
}
// 注册逻辑 (未改动核心逻辑,仅适配新结构)
async function handleRegister(req, env) {
try {
const formData = await req.formData();
const inviteCode = formData.get('inviteCode');
// 1. Verify Turnstile
if (env.CF_TURNSTILE_SECRET) {
const tRes = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ secret: env.CF_TURNSTILE_SECRET, response: formData.get('cf-turnstile-response'), remoteip: req.headers.get('CF-Connecting-IP') })
});
if (!(await tRes.json()).success) return Response.json({ success: false, message: '人机验证失败' });
}
// 2. Verify Invite Code
if (!env.INVITE_CODES) return Response.json({ success: false, message: '系统配置错误(KV)' });
const kvKey = `invite:${inviteCode}`;
const inviteData = await env.INVITE_CODES.get(kvKey, { type: 'json' });
if (!inviteData) return Response.json({ success: false, message: '邀请码无效' });
if (inviteData.status === 'used') return Response.json({ success: false, message: '邀请码已被使用' });
// 3. Create User
const username = formData.get('username');
const password = formData.get('password');
const skuName = formData.get('skuName');
let skuId = null;
try { skuId = JSON.parse(env.SKU_MAP || '{}')[skuName]; } catch(e){}
if (!skuId) return Response.json({ success: false, message: '订阅类型无效' });
if (!checkPasswordComplexity(password)) return Response.json({ success: false, message: '密码需包含大小写字母和数字,且长度>8' });
const accessToken = await getAccessToken(env);
const userEmail = `${username}@${getEnv(env.DEFAULT_DOMAIN)}`;
const hiddenUser = getEnv(env.HIDDEN_USER);
if (hiddenUser && userEmail.toLowerCase() === hiddenUser.toLowerCase()) return Response.json({ success: false, message: '用户名不可用' });
const createReq = await fetch('https://graph.microsoft.com/v1.0/users', {
method: 'POST',
headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify({
accountEnabled: true,
displayName: username,
mailNickname: username,
userPrincipalName: userEmail,
passwordProfile: { forceChangePasswordNextSignIn: false, password: password },
usageLocation: "CN"
})
});
if (!createReq.ok) {
const err = await createReq.json();
return Response.json({ success: false, message: err.error?.message || '创建用户失败' });
}
const newUser = await createReq.json();
// 4. Assign License
await fetch(`https://graph.microsoft.com/v1.0/users/${newUser.id}/assignLicense`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ addLicenses: [{ disabledPlans: [], skuId: skuId }], removeLicenses: [] })
});
// 5. Update Invite Status
inviteData.status = 'used';
inviteData.user = userEmail;
inviteData.usedAt = Date.now();
await env.INVITE_CODES.put(kvKey, JSON.stringify(inviteData));
return Response.json({ success: true, email: userEmail });
} catch (e) {
return Response.json({ success: false, message: e.message });
}
}
async function handleGetUsers(env) {
try {
const token = await getAccessToken(env);
// Fallback sort
const res = await fetch('https://graph.microsoft.com/v1.0/users?$select=id,displayName,userPrincipalName,createdDateTime,assignedLicenses&$top=100', {
headers: { 'Authorization': `Bearer ${token}` }
});
const data = await res.json();
if (data.value) data.value.sort((a, b) => new Date(b.createdDateTime) - new Date(a.createdDateTime));
return Response.json(data);
} catch (e) { return Response.json({ error: e.message }, { status: 500 }); }
}
async function handleDeleteUser(uid, env) {
try {
const token = await getAccessToken(env);
// Check Hidden
const hiddenUser = getEnv(env.HIDDEN_USER);
if (hiddenUser) {
const check = await fetch(`https://graph.microsoft.com/v1.0/users/${uid}?$select=userPrincipalName`, { headers: { Authorization: `Bearer ${token}` } });
if (check.ok) {
const u = await check.json();
if (u.userPrincipalName.toLowerCase() === hiddenUser.toLowerCase()) return Response.json({ error: 'Protected' }, { status: 403 });
}
}
await fetch(`https://graph.microsoft.com/v1.0/users/${uid}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
return Response.json({ success: true });
} catch (e) { return Response.json({ error: e.message }, { status: 500 }); }
}
async function handleGetInvites(env) {
const list = await env.INVITE_CODES.list({ prefix: 'invite:', limit: 1000 });
const invites = [];
for (const key of list.keys) {
const v = await env.INVITE_CODES.get(key.name, { type: 'json' });
if (v) invites.push(v);
}
invites.sort((a, b) => b.createdAt - a.createdAt);
return Response.json(invites);
}
async function handleCreateInvites(req, env) {
const body = await req.json();
const count = Math.min(Math.max(parseInt(body.count) || 1, 1), 50);
const created = [];
for (let i = 0; i < count; i++) {
const code = generateRandomString(10);
const data = { code, status: 'unused', createdAt: Date.now(), user: null, usedAt: null };
await env.INVITE_CODES.put(`invite:${code}`, JSON.stringify(data));
created.push(data);
}
return Response.json(created);
}
async function handleDeleteInvites(req, env) {
const url = new URL(req.url);
const action = url.searchParams.get('action');
const code = url.searchParams.get('code');
if (action === 'clear_all') {
const list = await env.INVITE_CODES.list({ prefix: 'invite:', limit: 1000 });
for (const k of list.keys) await env.INVITE_CODES.delete(k.name);
return Response.json({ success: true });
}
if (code) {