Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2900 lines (2580 loc) · 108 KB
/
Copy pathserver.js
File metadata and controls
2900 lines (2580 loc) · 108 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
const express = require('express');
const { spawn, execFileSync } = require('child_process');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');
const os = require('os');
const WebSocket = require('ws');
const axios = require('axios');
const store = require('./mysql-store');
const { listRecentEmailsForAdmin } = require('./pool-email-imap');
const runtimeLog = require('./runtime-log');
const { initializeImapAuth, getImapAuthHeaders } = require('./imap-auth');
const app = express();
const PORT = Number(process.env.PORT || 3000);
const ADMIN_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const ADMIN_REFRESH_AFTER_MS = 60 * 60 * 1000;
const PROCESS_IDLE_TIMEOUT_MS = 60 * 1000;
const MAX_PROCESS_ATTEMPTS = 10;
const WS_HEARTBEAT_PING_TYPE = 'ping';
const WS_HEARTBEAT_PONG_TYPE = 'pong';
const ACCESS_DEACTIVATED_MESSAGES_URL = 'https://imap.chiyiyi.cloud/api/admin/access-deactivated-messages';
const ACCESS_DEACTIVATED_SYNC_KEY = 'access_deactivated_messages_last_since';
const ACCESS_DEACTIVATED_SYNC_COOLDOWN_MS = 30 * 1000;
const ADMIN_TOKEN_SECRET = process.env.ADMIN_TOKEN_SECRET || crypto
.createHash('sha256')
.update(`web_redeem:${process.cwd()}:admin-token-secret`)
.digest('hex');
// 追踪活跃的子进程,防止产生僵尸进程
const activeProcesses = new Set();
function cleanupProcesses() {
if (activeProcesses.size > 0) {
console.log(`清理 ${activeProcesses.size} 个活跃子进程...`);
for (const child of activeProcesses) {
try { child.kill('SIGKILL'); } catch (e) { }
}
activeProcesses.clear();
}
}
// WebSocket 客户端映射: jobKey -> Set<WebSocket>
const taskClients = new Map();
const TERMINAL_TASK_STATUSES = new Set(['success', 'failed', 'maintenance']);
const activeForegroundJobs = new Set();
const activeBackgroundJobs = new Set();
/** 后台成品批量生产:job_key -> 停止回调(将批次 aborted 置 true) */
const adminGenerationStopHandlers = new Map();
function registerAdminGenerationStop(jobKey, fn) {
adminGenerationStopHandlers.set(String(jobKey), fn);
}
function unregisterAdminGenerationStop(jobKey) {
adminGenerationStopHandlers.delete(String(jobKey));
}
function requestAdminGenerationStop(jobKey) {
const fn = adminGenerationStopHandlers.get(String(jobKey));
if (typeof fn !== 'function') {
return false;
}
try {
fn();
} catch (_) {
/* ignore */
}
return true;
}
let systemMetricsCache = {
ts: 0,
data: null,
promise: null
};
let accessDeactivatedSyncPromise = null;
let accessDeactivatedLastSyncAt = 0;
let accessDeactivatedSyncTimer = null;
function reserveForegroundSlot(slotKey) {
activeForegroundJobs.add(String(slotKey));
}
function releaseForegroundSlot(slotKey) {
activeForegroundJobs.delete(String(slotKey));
}
function reserveBackgroundSlot(slotKey) {
activeBackgroundJobs.add(String(slotKey));
}
function releaseBackgroundSlot(slotKey) {
activeBackgroundJobs.delete(String(slotKey));
}
function getTotalActiveJobs() {
return activeForegroundJobs.size + activeBackgroundJobs.size;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function getClientIp(req) {
const forwarded = String(req.headers['x-forwarded-for'] || '').trim();
const rawIp = forwarded ? forwarded.split(',')[0].trim() : (req.ip || req.socket?.remoteAddress || '');
return String(rawIp || '')
.replace(/^::ffff:/, '')
.replace(/^::1$/, '127.0.0.1')
.trim();
}
function getRemainingCooldownMinutes(cooldownUntil) {
if (!cooldownUntil) {
return 0;
}
const cooldownDate = new Date(cooldownUntil);
if (!(cooldownDate instanceof Date) || Number.isNaN(cooldownDate.getTime()) || cooldownDate <= new Date()) {
return 0;
}
return Math.ceil((cooldownDate - new Date()) / 60000);
}
function isNoActivationEligibilityMessage(message) {
return String(message || '').includes('无激活权限');
}
function parseFlexibleTimestamp(value) {
if (value == null || value === '') {
return null;
}
if (value instanceof Date) {
const time = value.getTime();
return Number.isFinite(time) ? time : null;
}
if (typeof value === 'number' && Number.isFinite(value)) {
if (value > 1e12) {
return Math.trunc(value);
}
if (value > 1e9) {
return Math.trunc(value * 1000);
}
return null;
}
const normalized = String(value).trim();
if (!normalized) {
return null;
}
if (/^\d{13}$/.test(normalized)) {
return Number(normalized);
}
if (/^\d{10}$/.test(normalized)) {
return Number(normalized) * 1000;
}
const candidate = normalized.includes('T')
? normalized
: normalized.replace(' ', 'T');
const parsed = Date.parse(candidate);
if (Number.isFinite(parsed)) {
return parsed;
}
return null;
}
function collectMessageEmails(message) {
const emails = new Set();
const addEmail = (value) => {
const normalized = String(value || '').trim().toLowerCase();
if (normalized && normalized.includes('@')) {
emails.add(normalized);
}
};
addEmail(message?.targetRecipient);
const recipientList = String(message?.recipientList || '');
const matches = recipientList.match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/ig) || [];
for (const email of matches) {
addEmail(email);
}
return [...emails];
}
async function syncAccessDeactivatedProductStatuses(force = false) {
const now = Date.now();
if (!force && accessDeactivatedSyncPromise) {
return accessDeactivatedSyncPromise;
}
if (!force && (now - accessDeactivatedLastSyncAt) < ACCESS_DEACTIVATED_SYNC_COOLDOWN_MS) {
return { skipped: true, reason: 'cooldown' };
}
accessDeactivatedSyncPromise = (async () => {
const previousSinceValue = await store.getAppConfigValue(ACCESS_DEACTIVATED_SYNC_KEY, '');
const previousSinceTs = parseFlexibleTimestamp(previousSinceValue);
const params = {};
if (previousSinceTs) {
params.since = String(previousSinceTs);
}
try {
const response = await axios.get(ACCESS_DEACTIVATED_MESSAGES_URL, {
headers: await getImapAuthHeaders(),
params,
timeout: 30000
});
const messages = Array.isArray(response?.data?.messages) ? response.data.messages : [];
const emailSet = new Set();
let latestMessageTs = previousSinceTs;
for (const message of messages) {
for (const email of collectMessageEmails(message)) {
emailSet.add(email);
}
const messageTs = parseFlexibleTimestamp(message?.date);
if (messageTs && (!latestMessageTs || messageTs > latestMessageTs)) {
latestMessageTs = messageTs;
}
}
const affectedRows = await store.updateProductStatusByEmails([...emailSet], '封禁');
const nextSinceTs = latestMessageTs || now;
await store.setAppConfigValue(ACCESS_DEACTIVATED_SYNC_KEY, String(nextSinceTs));
accessDeactivatedLastSyncAt = Date.now();
if (messages.length > 0 || affectedRows > 0) {
console.log(`[AccessDeactivated] synced messages=${messages.length} matchedEmails=${emailSet.size} updatedProducts=${affectedRows} since=${previousSinceTs || 'all'} nextSince=${nextSinceTs}`);
}
return {
messagesCount: messages.length,
matchedEmails: emailSet.size,
updatedProducts: affectedRows,
previousSinceTs,
nextSinceTs
};
} catch (error) {
const isUnauthorized = Number(error?.response?.status || 0) === 401;
if (isUnauthorized) {
try {
const retryResponse = await axios.get(ACCESS_DEACTIVATED_MESSAGES_URL, {
headers: await getImapAuthHeaders(true),
params,
timeout: 30000
});
const retryMessages = Array.isArray(retryResponse?.data?.messages) ? retryResponse.data.messages : [];
const retryEmailSet = new Set();
let latestMessageTs = previousSinceTs;
for (const message of retryMessages) {
for (const email of collectMessageEmails(message)) {
retryEmailSet.add(email);
}
const messageTs = parseFlexibleTimestamp(message?.date);
if (messageTs && (!latestMessageTs || messageTs > latestMessageTs)) {
latestMessageTs = messageTs;
}
}
const affectedRows = await store.updateProductStatusByEmails([...retryEmailSet], '封禁');
const nextSinceTs = latestMessageTs || now;
await store.setAppConfigValue(ACCESS_DEACTIVATED_SYNC_KEY, String(nextSinceTs));
accessDeactivatedLastSyncAt = Date.now();
if (retryMessages.length > 0 || affectedRows > 0) {
console.log(`[AccessDeactivated] synced after token refresh messages=${retryMessages.length} matchedEmails=${retryEmailSet.size} updatedProducts=${affectedRows} since=${previousSinceTs || 'all'} nextSince=${nextSinceTs}`);
}
return {
messagesCount: retryMessages.length,
matchedEmails: retryEmailSet.size,
updatedProducts: affectedRows,
previousSinceTs,
nextSinceTs
};
} catch (retryError) {
console.error(`[AccessDeactivated] sync failed after token refresh: ${retryError.message}`);
throw retryError;
}
}
console.error(`[AccessDeactivated] sync failed: ${error.message}`);
throw error;
} finally {
accessDeactivatedSyncPromise = null;
}
})();
return accessDeactivatedSyncPromise;
}
function scheduleAccessDeactivatedSync(delayMs = ACCESS_DEACTIVATED_SYNC_COOLDOWN_MS) {
if (accessDeactivatedSyncTimer) {
clearTimeout(accessDeactivatedSyncTimer);
accessDeactivatedSyncTimer = null;
}
accessDeactivatedSyncTimer = setTimeout(async () => {
try {
await ensureStoreReady();
await syncAccessDeactivatedProductStatuses(true);
} catch (error) {
console.error(`[AccessDeactivated] scheduled sync failed: ${error.message}`);
} finally {
scheduleAccessDeactivatedSync(ACCESS_DEACTIVATED_SYNC_COOLDOWN_MS);
}
}, Math.max(1000, Number(delayMs) || ACCESS_DEACTIVATED_SYNC_COOLDOWN_MS));
}
async function waitForAvailableActivationSlot(jobSet, maxConcurrentActivations, excludedSlotKeys = []) {
const excluded = new Set((excludedSlotKeys || []).map((item) => String(item)));
while (true) {
let occupied = 0;
for (const slot of jobSet) {
if (!excluded.has(String(slot))) {
occupied += 1;
}
}
if (occupied < Math.max(1, Number(maxConcurrentActivations) || 1)) {
return;
}
await sleep(1000);
}
}
function isFatalProductGenerationError(error) {
const message = String(error?.message || error || '');
// 这些是「换代理 / 换号能解决」的临时性问题,绝对不算致命,要让父进程重试
const transientRetry =
message.includes('OpenAI 鉴权服务异常')
|| message.includes('代理或网络持续超时')
|| message.includes('浏览器连接被代理多次关闭')
|| message.includes('user_already_exists')
|| message.includes('该邮箱已被注册')
|| message.includes('个人资料表单校验失败');
if (transientRetry) {
return false;
}
const proxyFatal =
message.includes('代理连接失败')
|| message.includes('代理认证失败')
|| message.includes('代理响应异常')
|| message.includes('代理不可用')
|| message.includes('账号余额');
return message.includes('系统维护中')
|| message.includes('余额不足')
|| message.includes('资产池枯竭')
|| proxyFatal
|| message.includes('无法获取有效的 Access Token')
|| message.includes('页面仍无法正常显示')
// 支付已成功但协议提取失败:终止整个 batch(避免再扣费),管理员后台手动补 RT 即可
|| message.includes('支付已成功但协议提取失败')
|| message.includes('支付已成功并占位入库');
}
function formatGigabytes(bytes) {
return `${(Math.max(0, Number(bytes) || 0) / (1024 ** 3)).toFixed(1)}G`;
}
function formatDuration(ms) {
const totalSeconds = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
const days = Math.floor(totalSeconds / 86400);
const hours = Math.floor((totalSeconds % 86400) / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = totalSeconds % 60;
if (days > 0) {
return `${days}天 ${hours}时 ${minutes}分`;
}
if (hours > 0) {
return `${hours}时 ${minutes}分 ${seconds}秒`;
}
if (minutes > 0) {
return `${minutes}分 ${seconds}秒`;
}
return `${seconds}秒`;
}
function getCpuTimesSnapshot() {
return os.cpus().map((cpu) => {
const times = cpu.times || {};
const idle = Number(times.idle || 0);
const total = Object.values(times).reduce((sum, value) => sum + Number(value || 0), 0);
return { idle, total };
});
}
async function getCpuUsagePercent(sampleMs = 200) {
const start = getCpuTimesSnapshot();
await sleep(sampleMs);
const end = getCpuTimesSnapshot();
let idleDiff = 0;
let totalDiff = 0;
for (let index = 0; index < Math.min(start.length, end.length); index += 1) {
idleDiff += Math.max(0, end[index].idle - start[index].idle);
totalDiff += Math.max(0, end[index].total - start[index].total);
}
if (totalDiff <= 0) {
return 0;
}
return Math.max(0, Math.min(100, Math.round((1 - (idleDiff / totalDiff)) * 100)));
}
function getDiskMetrics() {
const cwdRootWithSlash = path.parse(process.cwd()).root || 'C:\\';
const driveLetter = cwdRootWithSlash.replace(/[\\\/]+$/, '') || 'C:';
const buildDiskMetrics = (totalBytes, freeBytes) => {
const safeTotalBytes = Math.max(0, Number(totalBytes) || 0);
const safeFreeBytes = Math.max(0, Number(freeBytes) || 0);
const usedBytes = Math.max(0, safeTotalBytes - safeFreeBytes);
const percent = safeTotalBytes > 0
? Math.max(0, Math.min(100, Math.round((usedBytes / safeTotalBytes) * 100)))
: 0;
return {
drive: driveLetter,
usedBytes,
totalBytes: safeTotalBytes,
percent,
usedText: formatGigabytes(usedBytes),
totalText: formatGigabytes(safeTotalBytes)
};
};
try {
if (typeof fs.statfsSync === 'function') {
const stats = fs.statfsSync(cwdRootWithSlash);
const blockSize = Math.max(0, Number(stats.bsize) || 0);
const totalBlocks = Math.max(0, Number(stats.blocks) || 0);
const freeBlocks = Math.max(0, Number(stats.bfree ?? stats.bavail) || 0);
const totalBytes = blockSize * totalBlocks;
const freeBytes = blockSize * freeBlocks;
if (totalBytes > 0) {
return buildDiskMetrics(totalBytes, freeBytes);
}
}
} catch (_) {
}
try {
const script = `(Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='${driveLetter}'" | Select-Object Size,FreeSpace) | ConvertTo-Json -Compress`;
const output = execFileSync('powershell', ['-NoProfile', '-Command', script], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
timeout: 4000
}).trim();
if (!output) {
return null;
}
const parsed = JSON.parse(output);
return buildDiskMetrics(parsed.Size, parsed.FreeSpace);
} catch (_) {
return null;
}
}
async function getSystemMetrics() {
const now = Date.now();
if (systemMetricsCache.data && (now - systemMetricsCache.ts) < 5000) {
return systemMetricsCache.data;
}
if (systemMetricsCache.promise) {
return systemMetricsCache.promise;
}
systemMetricsCache.promise = (async () => {
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = Math.max(0, totalMem - freeMem);
const memoryPercent = totalMem > 0 ? Math.max(0, Math.min(100, Math.round((usedMem / totalMem) * 100))) : 0;
const cpuPercent = await getCpuUsagePercent();
const disk = getDiskMetrics();
const data = {
cpu: {
percent: cpuPercent,
text: `${cpuPercent}%`
},
memory: {
percent: memoryPercent,
usedBytes: usedMem,
totalBytes: totalMem,
usedText: formatGigabytes(usedMem),
totalText: formatGigabytes(totalMem),
text: `${formatGigabytes(usedMem)}/${formatGigabytes(totalMem)}`
},
disk: disk || {
drive: path.parse(process.cwd()).root.replace(/[\\\/]+$/, '') || 'C:',
percent: 0,
usedBytes: 0,
totalBytes: 0,
usedText: '0.0G',
totalText: '0.0G'
},
uptime: {
seconds: Math.max(0, Math.floor(process.uptime())),
text: formatDuration(process.uptime() * 1000)
}
};
systemMetricsCache = {
ts: Date.now(),
data,
promise: null
};
return data;
})().catch((error) => {
systemMetricsCache.promise = null;
throw error;
});
return systemMetricsCache.promise;
}
async function startAdminProductGenerationTask(count, options = {}) {
const targetCount = Math.max(1, Math.min(Number(count) || 1, 100));
const maxConcurrentActivations = await store.getMaxBackgroundConcurrent();
const workerCount = Math.min(targetCount, Math.max(1, maxConcurrentActivations));
const resumeFrom = options.resumeFrom || null;
const task = await store.createTaskLog({
tokenPreview: 'ADMIN_PRODUCT_GEN',
cdkCode: `ADMIN_PRODUCT_GEN:${targetCount}`,
status: 'running',
progress: 1
});
const itemProgress = new Map();
let completed = 0;
let successCount = 0;
let failedCount = 0;
let nextIndex = 1;
let lastError = '';
let lastProgress = 1;
let aborted = false;
registerAdminGenerationStop(task.jobKey, () => {
aborted = true;
logTask(task.jobKey, '管理员请求停止:本批次不再排队新的成品生产(当前正在执行的条次会尽快在步骤间隙退出)', 'warn');
});
const buildGenerationSummary = () => JSON.stringify({
kind: 'admin_product_generation',
targetCount,
completedCount: completed,
successCount,
failedCount,
workerCount,
aborted,
lastError,
resumedFromJobKey: resumeFrom?.jobKey || null,
resumedFromTargetCount: resumeFrom?.targetCount || null,
resumedFromCompletedCount: resumeFrom?.completedCount || null
});
const computeBatchProgress = () => {
const inFlightProgress = Array.from(itemProgress.values()).reduce((sum, value) => sum + Math.max(0, Math.min(99, Number(value) || 0)), 0);
const raw = ((completed * 100) + inFlightProgress) / targetCount;
return Math.max(lastProgress, Math.min(99, Math.floor(raw)));
};
const publishBatchProgress = async (message) => {
const progress = computeBatchProgress();
lastProgress = progress;
await store.updateTaskLog(task.jobKey, {
status: 'running',
message,
rawOutput: buildGenerationSummary(),
cdkCode: `ADMIN_PRODUCT_GEN:${targetCount}`,
progress
});
broadcastToTask(task.jobKey, {
type: 'progress',
jobKey: task.jobKey,
progress,
status: 'running',
message
});
};
logTask(task.jobKey, `🎬 后台成品生产启动 count=${targetCount} workerCount=${workerCount}${resumeFrom ? ` resumeFrom=${resumeFrom.jobKey}` : ''}`);
(async () => {
const worker = async () => {
while (true) {
if (aborted) {
return;
}
const currentIndex = nextIndex;
if (currentIndex > targetCount) {
return;
}
nextIndex += 1;
const slotKey = `${task.jobKey}:item:${currentIndex}`;
itemProgress.set(currentIndex, 0);
try {
let produced = false;
let attempt = 0;
while (!produced) {
if (aborted) {
return;
}
attempt += 1;
itemProgress.set(currentIndex, 1);
await publishBatchProgress(
activeBackgroundJobs.size >= maxConcurrentActivations
? `第 ${currentIndex}/${targetCount} 个正在排队等待空闲并发槽位...`
: `正在生产第 ${currentIndex}/${targetCount} 个成品号...`
);
await waitForAvailableActivationSlot(activeBackgroundJobs, maxConcurrentActivations);
reserveBackgroundSlot(slotKey);
try {
await publishBatchProgress(`正在生产第 ${currentIndex}/${targetCount} 个成品号 (尝试 ${attempt})...`);
const result = await startProductCreation('', async (progressData) => {
itemProgress.set(currentIndex, Math.max(0, Math.min(99, Number(progressData.progress) || 0)));
const itemMessage = progressData.message || `正在生产第 ${currentIndex}/${targetCount} 个成品号...`;
await publishBatchProgress(`第 ${currentIndex}/${targetCount} 个: ${itemMessage}`);
}, { jobKey: task.jobKey });
if (result?.success) {
await store.addProduct(result.email, result.sub2apiPath || result.sub2apiFile || '', null, null, result.imapKey || null);
successCount += 1;
produced = true;
logTask(task.jobKey, `第 ${currentIndex}/${targetCount} 个成品号生产成功 email=${result.email}`);
} else {
throw new Error('未返回成功结果');
}
} catch (error) {
lastError = error.message || '未知错误';
if (isFatalProductGenerationError(error)) {
failedCount += 1;
aborted = true;
logTask(task.jobKey, `第 ${currentIndex}/${targetCount} 个遇到致命错误,任务终止: ${lastError}`, 'error');
throw error;
}
logTask(task.jobKey, `第 ${currentIndex}/${targetCount} 个非致命失败,准备重试: ${lastError}`, 'warn');
itemProgress.set(currentIndex, 1);
await publishBatchProgress(`第 ${currentIndex}/${targetCount} 个失败重试中: ${lastError}`);
await sleep(3000);
} finally {
releaseBackgroundSlot(slotKey);
}
}
} finally {
if (!aborted) {
completed += 1;
itemProgress.delete(currentIndex);
await publishBatchProgress(
completed >= targetCount
? '生产任务收尾中...'
: `已完成 ${completed}/${targetCount},继续生产剩余成品号...`
);
}
}
}
};
try {
await Promise.all(Array.from({ length: workerCount }, () => worker()));
const finalStatus = aborted || failedCount > 0 ? 'failed' : 'success';
const finalMessage = finalStatus === 'success'
? `成功生产 ${successCount} 个成品号`
: `生产中止,已成功 ${successCount} 个${lastError ? `,原因:${lastError}` : ''}`;
const finalProgress = 100;
await store.updateTaskLog(task.jobKey, {
status: finalStatus,
message: finalMessage,
rawOutput: buildGenerationSummary(),
cdkCode: `ADMIN_PRODUCT_GEN:${targetCount}`,
progress: finalProgress
});
broadcastToTask(task.jobKey, {
type: 'status',
jobKey: task.jobKey,
progress: finalProgress,
status: finalStatus,
message: finalMessage
});
} catch (error) {
lastError = error.message || lastError || '未知错误';
const finalMessage = `后台成品生产异常: ${lastError}`;
await store.updateTaskLog(task.jobKey, {
status: 'failed',
message: finalMessage,
rawOutput: buildGenerationSummary(),
cdkCode: `ADMIN_PRODUCT_GEN:${targetCount}`,
progress: 100
});
broadcastToTask(task.jobKey, {
type: 'status',
jobKey: task.jobKey,
progress: 100,
status: 'failed',
message: finalMessage
});
} finally {
unregisterAdminGenerationStop(task.jobKey);
}
})();
return { task, workerCount, targetCount };
}
function broadcastToTask(jobKey, data) {
const clients = taskClients.get(jobKey);
if (clients) {
const message = JSON.stringify(data);
for (const client of clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
}
}
}
function unsubscribeTaskClient(jobKey, ws) {
if (!jobKey || !taskClients.has(jobKey)) {
return;
}
const clients = taskClients.get(jobKey);
clients.delete(ws);
if (clients.size === 0) {
taskClients.delete(jobKey);
}
}
async function sendTaskSnapshot(ws, jobKey) {
const task = await store.getTaskStatus(jobKey);
if (!task || ws.readyState !== WebSocket.OPEN) {
return;
}
ws.send(JSON.stringify({
type: 'snapshot',
jobKey,
status: task.status,
message: task.message,
progress: Number(task.progress || 0),
cdkCode: task.cdk_code || null,
phone: task.phone || null,
cardLast4: task.card_last4 || null,
isTerminal: TERMINAL_TASK_STATUSES.has(task.status)
}));
}
function logTask(jobKey, message, level = 'log') {
runtimeLog.push({
jobKey,
level,
source: 'task',
text: String(message || '')
});
const logger = console[level] || console.log;
logger(`[Task ${jobKey}] ${message}`);
}
function logTaskChunk(jobKey, attempt, source, chunk) {
const text = String(chunk || '');
if (!text) {
return;
}
const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const lines = normalized.split('\n');
for (const line of lines) {
if (!line.trim()) {
continue;
}
runtimeLog.push({
jobKey,
level: source === 'stderr' ? 'stderr' : 'stdout',
source: `spawn/a${attempt}/${source}`,
text: line
});
console.log(`[Task ${jobKey}][Attempt ${attempt}][${source}] ${line}`);
}
}
process.on('SIGINT', () => { cleanupProcesses(); process.exit(0); });
process.on('SIGTERM', () => { cleanupProcesses(); process.exit(0); });
process.on('exit', () => cleanupProcesses());
let storeReadyPromise = null;
const JSON_BODY_LIMIT = process.env.JSON_BODY_LIMIT || '15mb';
app.use(express.json({ limit: JSON_BODY_LIMIT }));
app.use(express.static(path.join(__dirname, 'public')));
function ensureStoreReady() {
if (!storeReadyPromise) {
storeReadyPromise = store.ensureReady().catch((error) => {
storeReadyPromise = null;
throw error;
});
}
return storeReadyPromise;
}
function decodeJwtPart(part) {
const normalized = String(part || '').replace(/-/g, '+').replace(/_/g, '/');
const padded = normalized.padEnd(normalized.length + ((4 - normalized.length % 4) % 4), '=');
return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
}
function validateAccessToken(token) {
const value = String(token || '').trim();
if (!value) {
return { valid: false, message: '缺少 AccessToken' };
}
const parts = value.split('.');
if (parts.length !== 3 || parts.some((item) => !item)) {
return { valid: false, message: '该 Token 不合法:格式错误' };
}
let header;
let payload;
try {
header = decodeJwtPart(parts[0]);
payload = decodeJwtPart(parts[1]);
} catch (_) {
return { valid: false, message: '该 Token 不合法:无法解析' };
}
if (header.typ !== 'JWT') {
return { valid: false, message: '该 Token 不合法:类型错误' };
}
if (header.alg !== 'RS256') {
return { valid: false, message: '该 Token 不合法:算法错误' };
}
if (payload.iss !== 'https://auth.openai.com') {
return { valid: false, message: '该 Token 不合法:签发方错误' };
}
const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud].filter(Boolean);
if (!audiences.includes('https://api.openai.com/v1')) {
return { valid: false, message: '该 Token 不合法:aud 不匹配' };
}
const authInfo = payload['https://api.openai.com/auth'];
if (!authInfo || !authInfo.chatgpt_account_id || !authInfo.chatgpt_user_id) {
return { valid: false, message: '该 Token 不合法:缺少账户信息' };
}
const scopes = Array.isArray(payload.scp) ? payload.scp : [];
if (!scopes.includes('model.request')) {
return { valid: false, message: '该 Token 不合法:缺少 model.request 权限' };
}
const exp = Number(payload.exp || 0);
const now = Math.floor(Date.now() / 1000);
if (!exp || !Number.isFinite(exp)) {
return { valid: false, message: '该 Token 不合法:缺少过期时间' };
}
if (exp <= now) {
return { valid: false, message: '该 Token 已过期' };
}
return { valid: true };
}
function encodeBase64Url(input) {
return Buffer.from(input)
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}
function decodeBase64Url(input) {
const normalized = input
.replace(/-/g, '+')
.replace(/_/g, '/')
.padEnd(Math.ceil(input.length / 4) * 4, '=');
return Buffer.from(normalized, 'base64').toString('utf8');
}
function signTokenPayload(encodedPayload) {
return crypto
.createHmac('sha256', ADMIN_TOKEN_SECRET)
.update(encodedPayload)
.digest('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/g, '');
}
function safeEqualString(left, right) {
const leftBuffer = Buffer.from(String(left));
const rightBuffer = Buffer.from(String(right));
if (leftBuffer.length !== rightBuffer.length) {
return false;
}
return crypto.timingSafeEqual(leftBuffer, rightBuffer);
}
function createPasswordHash(password, salt) {
return crypto.scryptSync(String(password), salt, 64).toString('hex');
}
function verifyPassword(password, storedHash) {
const parts = String(storedHash || '').split('$');
if (parts.length !== 3 || parts[0] !== 'scrypt') {
return false;
}
const [, salt, expectedHash] = parts;
const actualHash = createPasswordHash(password, salt);
return safeEqualString(actualHash, expectedHash);
}
function issueAdminToken(passwordVersion) {
const now = Date.now();
const payload = {
sub: 'admin',
permissions: ['admin'],
pv: Math.max(1, Number(passwordVersion || 1)),
iat: now,
exp: now + ADMIN_TOKEN_TTL_MS
};
const encodedPayload = encodeBase64Url(JSON.stringify(payload));
const signature = signTokenPayload(encodedPayload);
return {
token: `${encodedPayload}.${signature}`,
payload
};
}
function verifyAdminToken(token) {
if (!token || typeof token !== 'string') {
return null;
}
const [encodedPayload, signature] = token.split('.');
if (!encodedPayload || !signature) {
return null;
}
const expectedSignature = signTokenPayload(encodedPayload);
if (!safeEqualString(signature, expectedSignature)) {
return null;
}
try {
const payload = JSON.parse(decodeBase64Url(encodedPayload));
if (!payload || payload.sub !== 'admin' || !Array.isArray(payload.permissions)) {
return null;
}
if (!payload.permissions.includes('admin')) {
return null;
}
if (!payload.exp || Date.now() >= Number(payload.exp)) {
return null;
}
return payload;
} catch (error) {
return null;
}
}
function getBearerToken(req) {
const header = req.headers.authorization || '';
const [scheme, token] = header.split(' ');
if (scheme === 'Bearer' && token) {
return token.trim();
}
return (req.query?.token || '').trim() || null;
}
async function authenticateAdmin(req, res, next) {
const token = getBearerToken(req);