forked from baianquanzu/Bai-codeagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1470 lines (1311 loc) · 58.9 KB
/
server.js
File metadata and controls
1470 lines (1311 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import http from "node:http";
import { promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { FrameworkScoutAgent } from "./src/agents/frameworkScoutAgent.js";
import { LocalRepoScoutAgent } from "./src/agents/localRepoScoutAgent.js";
import { GitUrlScoutAgent } from "./src/agents/gitUrlScoutAgent.js";
import { ZipUploadScoutAgent } from "./src/agents/zipUploadScoutAgent.js";
import { AuditAnalystAgent } from "./src/agents/auditAnalystAgent.js";
import { getAuditSkillCatalog, getAllProfiles, getSkillsByProfile, getProfileConfig } from "./src/config/auditSkills.js";
import { getProviderPreset, maskSecret, resolveLlmConfig, getProviderCatalog } from "./src/config/llmProviders.js";
import { buildEnvironmentReport } from "./src/services/environmentReport.js";
import { DefensiveLlmReviewer } from "./src/services/llmReviewService.js";
import { createMemoryStore } from "./src/services/memoryStore.js";
import { createFingerprintService } from "./src/services/fingerprintService.js";
import { writeAuditHtmlReport, writeSarifReport } from "./src/services/reportWriter.js";
import { createSettingsStore } from "./src/services/settingsStore.js";
import { createTaskStore } from "./src/store/taskStore.js";
import { recordRequest, getPerformanceMetrics } from "./src/core/performance.js";
import { stripTrailingSlash } from "./src/utils/fileUtils.js";
import { streamService, EventType } from "./src/services/streamService.js";
import { globalVulnValidator } from "./src/services/sandbox.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, "public");
const downloadsDir = path.join(__dirname, "workspace", "downloads");
const reportsDir = path.join(__dirname, "workspace", "reports");
const memoryFile = path.join(__dirname, "workspace", "memory", "project-memory.json");
const MAX_SSE_CONNECTIONS = 10;
let sseConnectionCount = 0;
const settingsFile = path.join(__dirname, "workspace", "settings", "app-settings.json");
const settingsStore = createSettingsStore({ filePath: settingsFile });
const scoutAgent = new FrameworkScoutAgent({
downloadsDir,
getGithubConfig: async () => (await settingsStore.read()).github
});
const localScoutAgent = new LocalRepoScoutAgent({ downloadsDir });
const gitUrlScoutAgent = new GitUrlScoutAgent({ downloadsDir });
const zipUploadScoutAgent = new ZipUploadScoutAgent({ downloadsDir });
const llmReviewer = new DefensiveLlmReviewer();
const auditAgent = new AuditAnalystAgent({ llmReviewer });
const tasks = createTaskStore({ workspaceDir: path.join(__dirname, "workspace") });
const memoryStore = createMemoryStore({ filePath: memoryFile });
const fingerprintService = createFingerprintService({ downloadsDir });
await fs.mkdir(downloadsDir, { recursive: true });
await fs.mkdir(reportsDir, { recursive: true });
// 初始化沙箱(需要 Docker,不可用时静默跳过)
globalVulnValidator.initialize().then(() => {
console.log('[启动] 沙箱:', globalVulnValidator.isAvailable ? '可用' : '不可用 — 跳过运行时漏洞验证');
});
const server = http.createServer(async (req, res) => {
const start = performance.now();
const url = new URL(req.url, `http://${req.headers.host}`);
try {
console.log(`[请求] ${req.method} ${url.pathname}`);
if (req.method === "GET" && url.pathname === "/api/health") {
const settings = await settingsStore.read();
const environment = await buildEnvironmentReport({ rootDir: __dirname, downloadsDir, settings });
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, { status: "ok", now: new Date().toISOString(), safeMode: true, environment });
}
if (req.method === "GET" && url.pathname === "/api/performance") {
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, getPerformanceMetrics());
}
if (req.method === "GET" && url.pathname === "/api/environment") {
const settings = await settingsStore.read();
const environment = await buildEnvironmentReport({ rootDir: __dirname, downloadsDir, settings });
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, environment);
}
if (req.method === "GET" && url.pathname === "/api/settings") {
const result = sanitizeSettings(await settingsStore.read());
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, result);
}
if (req.method === "GET" && url.pathname === "/api/audit-skills") {
const skills = getAuditSkillCatalog();
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, skills);
}
if (req.method === "GET" && url.pathname === "/api/provider-defaults") {
return sendJson(res, 200, getProviderCatalog());
}
if (req.method === "GET" && url.pathname === "/api/profiles") {
const profiles = getAllProfiles();
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, profiles);
}
if (req.method === "GET" && url.pathname === "/api/profile-config") {
const profileName = url.searchParams.get("name") || "default";
const config = getProfileConfig(profileName);
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, config);
}
if (req.method === "GET" && url.pathname === "/api/skills-by-profile") {
const profile = url.searchParams.get("profile") || null;
const skills = getSkillsByProfile(profile);
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, skills);
}
if (req.method === "POST" && url.pathname === "/api/settings") {
const body = await readJson(req);
const current = await settingsStore.read();
const updated = await settingsStore.write({
llm: {
providerId: body?.llm?.providerId || current.llm.providerId,
baseUrl: body?.llm?.baseUrl ?? current.llm.baseUrl,
model: body?.llm?.model ?? current.llm.model,
apiKey: body?.llm?.apiKey ? body.llm.apiKey : current.llm.apiKey
},
github: {
token: body?.github?.token ? body.github.token : current.github.token,
ownerFilter: body?.github?.ownerFilter ?? current.github.ownerFilter,
notes: body?.github?.notes ?? current.github.notes
},
fofa: {
email: body?.fofa?.email ?? current.fofa.email,
apiKey: body?.fofa?.apiKey ? body.fofa.apiKey : current.fofa.apiKey,
notes: body?.fofa?.notes ?? current.fofa.notes
}
});
return sendJson(res, 200, sanitizeSettings(updated));
}
if (req.method === "POST" && url.pathname === "/api/settings/clear-secrets") {
const body = await readJson(req);
return sendJson(res, 200, sanitizeSettings(await settingsStore.clearSecrets(Array.isArray(body?.targets) ? body.targets : [])));
}
if (req.method === "POST" && url.pathname === "/api/settings/test") {
return sendJson(res, 200, await testConnections(await settingsStore.read()));
}
if (req.method === "GET" && url.pathname === "/api/memory") {
return sendJson(res, 200, await memoryStore.read());
}
if (req.method === "GET" && url.pathname === "/api/fingerprint/projects") {
return sendJson(res, 200, await fingerprintService.listProjects());
}
if (req.method === "POST" && url.pathname === "/api/fingerprint/analyze") {
const body = await readJson(req);
return sendJson(res, 200, await fingerprintService.analyzeProject(String(body?.projectId || "")));
}
if (req.method === "POST" && url.pathname === "/api/fingerprint/match") {
const body = await readJson(req);
return sendJson(res, 200, await fingerprintService.matchAssets({
projectId: String(body?.projectId || ""),
assetText: String(body?.assetText || "")
}));
}
if (req.method === "DELETE" && /\/api\/fingerprint\/projects\/[^/]+$/.test(url.pathname)) {
const [, , , , projectId] = url.pathname.split("/");
if (!projectId) {
return sendJson(res, 400, { error: "Project ID is required" });
}
const result = await fingerprintService.deleteProject(projectId);
if (!result.success) {
return sendJson(res, 400, { error: result.message });
}
return sendJson(res, 200, result);
}
if (req.method === "POST" && url.pathname === "/api/memory") {
const body = await readJson(req);
return sendJson(res, 200, await memoryStore.write({ preferences: body.preferences || {}, rules: Array.isArray(body.rules) ? body.rules : undefined }));
}
if (req.method === "POST" && url.pathname === "/api/tasks/upload") {
console.log("[ZIP上传] 开始处理上传请求");
try {
const uploadResult = await parseMultipartForm(req);
console.log("[ZIP上传] 解析完成,fields:", JSON.stringify(uploadResult.fields));
console.log("[ZIP上传] 解析完成,文件数:", uploadResult.files.length);
const selectedSkillIds = JSON.parse(uploadResult.fields.selectedSkillIds || "[]");
const useMemory = uploadResult.fields.useMemory === "true";
const useReAct = uploadResult.fields.useReAct === "true";
const reactConfig = uploadResult.fields.reactConfig ? JSON.parse(uploadResult.fields.reactConfig) : {};
const enableLlmAudit = uploadResult.fields.enableLlmAudit !== "false";
const memory = await memoryStore.read();
const taskData = {
sourceType: "zip-upload",
selectedSkillIds,
useMemory,
useReAct,
reactConfig,
enableLlmAudit,
zipFiles: uploadResult.files
};
const created = await tasks.createTask(taskData);
console.log("[ZIP上传] 创建任务成功:", created.id);
if (useMemory) {
await tasks.updateTask(created.id, { memorySnapshot: buildMemorySnapshot(memory) });
}
runScout(created.id).catch((error) => {
console.error("[ZIP上传] 运行scout失败:", error);
tasks.failTask(created.id, error instanceof Error ? error.message : String(error));
});
const task = tasks.getTask(created.id);
return sendJson(res, 202, task);
} catch (uploadError) {
console.error("[ZIP上传] 错误:", uploadError);
return sendJson(res, 500, { error: "ZIP上传失败", detail: uploadError instanceof Error ? uploadError.message : String(uploadError) });
}
}
if (req.method === "POST" && url.pathname === "/api/tasks") {
console.log("[任务创建] 开始创建任务");
const body = await readJson(req);
console.log("[任务创建] 请求体:", JSON.stringify(body, null, 2));
try {
const memory = await memoryStore.read();
console.log("[任务创建] 读取内存成功");
const defaults = applyMemoryDefaults(body, memory);
console.log("[任务创建] 应用默认值成功:", JSON.stringify(defaults, null, 2));
const created = await tasks.createTask(defaults);
console.log("[任务创建] 创建任务成功:", created.id);
if (created.useMemory) {
await tasks.updateTask(created.id, { memorySnapshot: buildMemorySnapshot(memory) });
console.log("[任务创建] 更新内存快照成功");
}
runScout(created.id).catch((error) => {
console.error("[任务创建] 运行scout失败:", error);
tasks.failTask(created.id, error instanceof Error ? error.message : String(error));
});
const task = tasks.getTask(created.id);
console.log("[任务创建] 返回任务:", task.id);
return sendJson(res, 202, task);
} catch (taskError) {
console.error("[任务创建] 错误:", taskError);
return sendJson(res, 500, { error: "任务创建失败", detail: taskError instanceof Error ? taskError.message : String(taskError), stack: taskError instanceof Error ? taskError.stack : undefined });
}
}
if (req.method === "POST" && /\/api\/tasks\/[^/]+\/audit$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const body = await readJson(req);
const selectedProjectIds = Array.isArray(body?.selectedProjectIds) ? body.selectedProjectIds : [];
const task = tasks.getTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found" });
}
if (!task.scoutResult?.projects?.length) {
return sendJson(res, 400, { error: "Targets are not ready yet" });
}
runAudit(taskId, selectedProjectIds).catch((error) => tasks.failTask(taskId, error instanceof Error ? error.message : String(error)));
return sendJson(res, 202, tasks.getTask(taskId));
}
if (req.method === "POST" && /\/api\/tasks\/[^/]+\/resume$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
console.log(`[恢复请求] 收到恢复任务请求: ${taskId}`);
const task = await tasks.resumeTask(taskId);
console.log(`[恢复请求] resumeTask 返回: ${task ? `status=${task.status}, phase=${task.phase}` : 'null'}`);
if (!task) {
return sendJson(res, 404, { error: "Task not found" });
}
// 根据当前阶段继续执行
if (task.phase === "framework-scout" || task.phase === "scout") {
runScout(taskId).catch((error) => tasks.failTask(taskId, error instanceof Error ? error.message : String(error)));
} else if (task.phase === "audit" || task.phase === "audit-analyst") {
console.log(`[恢复请求] 调用 runAudit,selectedProjectIds=${JSON.stringify(task.selectedProjectIds)}`);
runAudit(taskId, task.selectedProjectIds).catch((error) => tasks.failTask(taskId, error instanceof Error ? error.message : String(error)));
}
return sendJson(res, 202, task);
}
if (req.method === "POST" && /\/api\/tasks\/[^/]+\/restart$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const originalTask = tasks.getTask(taskId);
if (!originalTask) {
return sendJson(res, 404, { error: "Task not found" });
}
if (originalTask.status !== "completed" && originalTask.status !== "failed" && originalTask.status !== "cancelled") {
return sendJson(res, 400, { error: "Only completed/failed/cancelled tasks can be restarted" });
}
const restartData = {
sourceType: originalTask.sourceType,
selectedSkillIds: originalTask.selectedSkillIds || [],
useMemory: originalTask.useMemory !== false,
useReAct: originalTask.useReAct || false,
reactConfig: originalTask.reactConfig || {},
enableLlmAudit: originalTask.enableLlmAudit !== false
};
const newTask = await tasks.createTask(restartData);
tasks.updateTask(newTask.id, {
scoutResult: originalTask.scoutResult,
selectedProjectIds: originalTask.selectedProjectIds || [],
memorySnapshot: originalTask.memorySnapshot,
memorySummary: originalTask.memorySummary,
phase: "audit",
status: "queued",
message: "重新审计任务已创建",
progress: {
stage: "audit",
label: "等待开始",
detail: "",
percent: 0,
current: 0,
total: originalTask.selectedProjectIds?.length || 0
}
});
runAudit(newTask.id, newTask.selectedProjectIds).catch((error) =>
tasks.failTask(newTask.id, error instanceof Error ? error.message : String(error))
);
return sendJson(res, 202, tasks.getTask(newTask.id));
}
if (req.method === "POST" && /\/api\/tasks\/[^/]+\/pause$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const task = await tasks.pauseTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found or cannot be paused" });
}
return sendJson(res, 200, task);
}
if (req.method === "POST" && /\/api\/tasks\/[^/]+\/stop$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const task = await tasks.stopTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found or already completed" });
}
return sendJson(res, 200, task);
}
if (req.method === "DELETE" && /\/api\/tasks\/[^/]+\/report$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const reportFile = path.join(reportsDir, `audit-report-${taskId}.html`);
try {
await fs.unlink(reportFile);
} catch (error) {
// 文件不存在时忽略
}
return sendJson(res, 200, { status: "ok", message: "Report deleted" });
}
if (req.method === "DELETE" && /\/api\/tasks\/[^/]+$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const task = tasks.getTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found" });
}
// 从内存中移除任务
tasks.deleteTask(taskId);
// 清理任务文件
const tasksDir = path.join(__dirname, "workspace", "tasks");
try {
const taskFile = path.join(tasksDir, `${taskId}.json`);
await fs.unlink(taskFile);
} catch (error) {
// 文件不存在时忽略
}
// 清理关联的报告文件
const reportFile = path.join(reportsDir, `audit-report-${taskId}.html`);
try {
await fs.unlink(reportFile);
} catch (error) {
// 文件不存在时忽略
}
return sendJson(res, 200, { status: "ok", message: "Task deleted" });
}
if (req.method === "GET" && url.pathname === "/api/tasks") {
let result = tasks.listTasks();
const statusFilter = url.searchParams.get("status");
if (statusFilter) {
const statuses = statusFilter.split(",");
result = result.filter(t => statuses.includes(t.status));
}
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, result);
}
if (req.method === "GET" && url.pathname.startsWith("/api/tasks/")) {
const id = url.pathname.split("/")[3];
const task = tasks.getTask(id);
if (!task) {
recordRequest(url.pathname, performance.now() - start, false);
return sendJson(res, 404, { error: "Task not found" });
}
recordRequest(url.pathname, performance.now() - start, true);
return sendJson(res, 200, task);
}
if (req.method === "GET" && /\/api\/tasks\/[^/]+\/react-steps$/.test(url.pathname)) {
const [, , , taskId] = url.pathname.split("/");
const task = tasks.getTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found" });
}
const projects = task.auditResult?.projects || [];
const reactStepsData = projects.map(p => {
const reactResult = p.reactAudit || p.reactResult;
return {
projectId: p.id,
projectName: p.name,
steps: reactResult?.steps || [],
finalAnswer: reactResult?.finalAnswer || reactResult?.summary || "",
issues: reactResult?.issues || []
};
});
return sendJson(res, 200, { taskId, useReAct: task.useReAct, reactConfig: task.reactConfig, projects: reactStepsData });
}
if (req.method === "GET" && url.pathname.startsWith("/downloads/")) {
return serveFile(res, path.join(downloadsDir, decodeURIComponent(url.pathname.replace("/downloads/", ""))));
}
if (req.method === "GET" && url.pathname.startsWith("/reports/")) {
return serveFile(res, path.join(reportsDir, decodeURIComponent(url.pathname.replace("/reports/", ""))));
}
if (req.method === "GET" && url.pathname === "/api/export-json") {
const taskId = url.searchParams.get("taskId");
if (!taskId) return sendJson(res, 400, { error: "Missing taskId parameter" });
const task = tasks.getTask(taskId);
if (!task) return sendJson(res, 404, { error: "Task not found" });
const auditResult = task.auditResult;
if (!auditResult) return sendJson(res, 404, { error: "Audit result not found" });
const allFindings = collectExportFindings(auditResult);
const jsonFileName = `audit-report-${taskId}.json`;
const jsonFilePath = path.join(reportsDir, jsonFileName);
await fs.writeFile(jsonFilePath, JSON.stringify({ taskId, query: task.query, findingsCount: allFindings.length, findings: allFindings }, null, 2), "utf8");
return sendJson(res, 200, { success: true, fileName: jsonFileName, downloadPath: `/reports/${jsonFileName}`, findingsCount: allFindings.length });
}
if (req.method === "GET" && url.pathname === "/api/export-markdown") {
const taskId = url.searchParams.get("taskId");
if (!taskId) return sendJson(res, 400, { error: "Missing taskId parameter" });
const task = tasks.getTask(taskId);
if (!task) return sendJson(res, 404, { error: "Task not found" });
const auditResult = task.auditResult;
if (!auditResult) return sendJson(res, 404, { error: "Audit result not found" });
const allFindings = collectExportFindings(auditResult);
const md = buildMarkdownReport(task, auditResult, allFindings);
const mdFileName = `audit-report-${taskId}.md`;
const mdFilePath = path.join(reportsDir, mdFileName);
await fs.writeFile(mdFilePath, md, "utf8");
return sendJson(res, 200, { success: true, fileName: mdFileName, downloadPath: `/reports/${mdFileName}`, findingsCount: allFindings.length });
}
if (req.method === "GET" && url.pathname === "/api/export-sarif") {
const taskId = url.searchParams.get("taskId");
if (!taskId) {
return sendJson(res, 400, { error: "Missing taskId parameter" });
}
const task = tasks.getTask(taskId);
if (!task) {
return sendJson(res, 404, { error: "Task not found" });
}
const auditResult = task.auditResult;
if (!auditResult) {
return sendJson(res, 404, { error: "Audit result not found" });
}
const allFindings = collectExportFindings(auditResult);
const sarifFileName = `sarif-report-${taskId}.json`;
const sarifFilePath = path.join(reportsDir, sarifFileName);
try {
await writeSarifReport(allFindings, sarifFilePath, {
toolName: 'GBT CodeAgent',
toolVersion: '1.0.0',
toolInformationUri: 'https://gbt-codeagent.com'
});
return sendJson(res, 200, {
success: true,
fileName: sarifFileName,
downloadPath: `/reports/${sarifFileName}`,
findingsCount: allFindings.length
});
} catch (err) {
return sendJson(res, 500, { error: "Failed to generate SARIF report", detail: err.message });
}
}
if (req.method === "POST" && url.pathname === "/api/regenerate-report") {
const body = await readJson(req);
const taskId = body.taskId;
if (!taskId) return sendJson(res, 400, { error: "Missing taskId" });
const task = tasks.getTask(taskId);
if (!task) return sendJson(res, 404, { error: "Task not found" });
const auditResult = task.auditResult;
if (!auditResult) return sendJson(res, 404, { error: "Audit result not found" });
const selectedProjects = task.selectedProjects || [];
await fs.mkdir(reportsDir, { recursive: true });
const htmlReport = await writeAuditHtmlReport({
reportsDir,
task: { ...task, selectedProjectIds: task.selectedProjectIds || [] },
selectedProjects,
auditResult,
architectureAnalysis: auditResult.architectureAnalysis
});
const allFindings = collectExportFindings(auditResult);
await fs.writeFile(
path.join(reportsDir, `audit-report-${taskId}.json`),
JSON.stringify({ taskId, query: task.query, findingsCount: allFindings.length, findings: allFindings }, null, 2),
"utf8"
);
return sendJson(res, 200, {
success: true,
reportPath: htmlReport.downloadPath,
findingsCount: allFindings.length,
ruleFindings: auditResult.heuristicFindingsCount || 0,
llmFindings: auditResult.llmFindingsCount || 0
});
}
if (req.method === "GET" && url.pathname.startsWith("/api/stream/tasks/")) {
const taskId = url.pathname.split("/").pop();
if (!taskId) {
return sendJson(res, 400, { error: "Task ID is required" });
}
if (sseConnectionCount >= MAX_SSE_CONNECTIONS) {
return sendJson(res, 503, { error: "SSE 连接数已满,请稍后重试" });
}
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no"
});
sseConnectionCount++;
const heartbeatTimer = setInterval(() => {
res.write(`event: heartbeat\ndata: ${JSON.stringify({ timestamp: Date.now() })}\n\n`);
}, 15000);
const listenerRemovers = [];
console.log(`[SSE] 客户端连接,taskId: ${taskId},当前连接数: ${sseConnectionCount + 1}`);
const listenAndSSE = (eventType) => {
const remover = streamService.addListener(eventType, (event) => {
try {
if (event.data._taskId && event.data._taskId !== taskId) return;
const sse = event.toSSE();
res.write(sse);
} catch (err) { /* client disconnected */ }
});
listenerRemovers.push(remover);
};
listenAndSSE(EventType.LLM_START);
listenAndSSE(EventType.LLM_STREAM_TOKEN);
listenAndSSE(EventType.LLM_COMPLETE);
listenAndSSE(EventType.LLM_THINKING);
listenAndSSE(EventType.LLM_DECISION);
listenAndSSE(EventType.FINDING_NEW);
listenAndSSE(EventType.FINDING_VERIFIED);
listenAndSSE(EventType.PROGRESS);
listenAndSSE(EventType.INFO);
listenAndSSE(EventType.WARNING);
listenAndSSE(EventType.ERROR);
listenAndSSE(EventType.HEARTBEAT);
req.on("close", () => {
sseConnectionCount = Math.max(0, sseConnectionCount - 1);
clearInterval(heartbeatTimer);
listenerRemovers.forEach(remove => remove());
});
return;
}
if (req.method === "GET") {
const target = url.pathname === "/" ? "index.html" : url.pathname.slice(1);
return serveFile(res, path.join(publicDir, target));
}
return sendJson(res, 404, { error: "Not found" });
} catch (error) {
console.error("[服务器错误]", error);
return sendJson(res, 500, {
error: "Internal server error",
detail: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined
});
}
});
async function runScout(taskId) {
try {
tasks.updateTask(taskId, {
status: "running",
phase: "framework-scout",
message: "正在发现候选目标…",
progress: {
stage: "framework-scout",
label: "正在发现候选目标",
detail: "",
percent: 12,
current: 0,
total: 0
}
});
const task = tasks.getTask(taskId);
let scoutResult;
if (task.sourceType === "local") {
scoutResult = await localScoutAgent.run({ localRepoPaths: task.localRepoPaths });
} else if (task.sourceType === "git-url") {
scoutResult = await gitUrlScoutAgent.cloneFromUrls(task.gitUrls, (progress) => {
updateTaskProgress(taskId, progress);
});
} else if (task.sourceType === "zip-upload") {
scoutResult = await zipUploadScoutAgent.processZipFiles(task.zipFiles, (progress) => {
updateTaskProgress(taskId, progress);
});
} else {
scoutResult = await scoutAgent.run({
query: task.query,
cmsType: task.cmsType,
industry: task.industry,
minAdoption: task.minAdoption
});
}
const projectIds = scoutResult.projects?.map(p => p.id) || [];
if (task.sourceType === "git-url" || task.sourceType === "local" || task.sourceType === "zip-upload") {
// 直接导入类型,无需选择,直接开始审计
if (projectIds.length > 0) {
// 先保存 scoutResult 到任务中,供 runAudit 使用
await tasks.updateTask(taskId, { scoutResult });
runAudit(taskId, projectIds).catch((error) => tasks.failTask(taskId, error instanceof Error ? error.message : String(error)));
} else {
tasks.failTask(taskId, "没有找到可审计的项目");
}
} else {
// GitHub 查询类型,需要用户选择
tasks.updateTask(taskId, {
status: "awaiting_selection",
phase: "target-selection",
message: scoutResult.summary || "请选择需要审计的目标。",
scoutResult,
progress: {
stage: "target-selection",
label: "请选择要审计的目标",
detail: "",
percent: 20,
current: scoutResult.projects?.length || 0,
total: scoutResult.projects?.length || 0
}
});
}
} catch (error) {
console.error(`[任务失败] scout阶段失败 - 任务ID: ${taskId}`, error);
tasks.failTask(taskId, {
message: "发现候选目标时失败",
detail: error instanceof Error ? error.message : String(error),
stage: "framework-scout"
});
}
}
async function runAudit(taskId, selectedProjectIds) {
try {
const task = tasks.getTask(taskId);
const selectedProjects = (task.scoutResult?.projects || []).filter((project) => selectedProjectIds.includes(project.id));
if (!selectedProjects.length) {
throw new Error("No targets selected for audit.");
}
// 检查是否已有审计结果(从暂停恢复的情况)
const existingAuditResult = task.auditResult;
console.log(`[审计流程] existingAuditResult:`, existingAuditResult ? `projects=${existingAuditResult.projects?.length}` : 'null');
// 调试:打印 existingAuditResult 的详细结构
if (existingAuditResult) {
console.log(`[审计流程] existingAuditResult.projects 结构:`);
existingAuditResult.projects?.forEach((p, i) => {
console.log(` [${i}] projectId=${p.projectId}, findings.length=${p.findings?.length || 0}, heuristicFindings.length=${p.heuristicFindings?.length || 0}`);
});
}
const completedProjectIds = existingAuditResult?.projects?.map(p => p.projectId) || [];
const remainingProjects = selectedProjects.filter(p => !completedProjectIds.includes(p.id));
console.log(`[审计流程] 任务 ${taskId} - 已完成项目: ${completedProjectIds.length}, completedProjectIds=${JSON.stringify(completedProjectIds)}`);
console.log(`[审计流程] 任务 ${taskId} - 剩余项目: ${remainingProjects.length}, remainingProjects=${JSON.stringify(remainingProjects.map(p => p.id))}`);
// 如果是从暂停恢复,保持当前进度,只更新状态为 running
if (existingAuditResult && completedProjectIds.length > 0) {
console.log(`[审计流程] 任务 ${taskId} 从暂停点恢复,继续审计剩余项目`);
tasks.updateTask(taskId, {
status: "running",
message: "正在继续审计..."
});
} else {
// 完全从头开始
tasks.updateTask(taskId, {
status: "running",
phase: "audit-analyst",
message: "正在下载审计镜像并审计你选中的目标…",
selectedProjectIds,
progress: {
stage: "mirror",
label: "正在准备审计镜像",
detail: "",
percent: 24,
current: 0,
total: selectedProjects.length
}
});
}
// 只对剩余项目确保镜像
for (const [projectIndex, project] of remainingProjects.entries()) {
if (project.sourceType === "local" || project.sourceType === "git-url" || project.sourceType === "zip-upload") {
updateTaskProgress(taskId, {
stage: "mirror",
label: `正在生成本地镜像:${project.name}`,
detail: "",
percent: calculateMirrorPercent(projectIndex + 1, remainingProjects.length, 1, 1),
current: projectIndex + 1,
total: remainingProjects.length
});
await localScoutAgent.ensureProjectMirror(project);
} else {
await scoutAgent.ensureProjectMirror(project, {
onProgress: (detail) =>
updateTaskProgress(taskId, {
stage: "mirror",
label: `正在下载审计镜像:${project.name}`,
detail: detail.currentPath || "",
percent: calculateMirrorPercent(projectIndex + 1, remainingProjects.length, detail.processed || 0, detail.total || 1),
current: detail.processed || 0,
total: detail.total || 0
})
});
}
}
const settings = await settingsStore.read();
const llmConfig = resolveLlmConfig(process.env, settings.llm);
console.log(`[审计流程] LLM配置 - 提供商: ${llmConfig.providerId}, 模型: ${llmConfig.model}, 端点: ${llmConfig.baseUrl}, API Key配置: ${Boolean(llmConfig.apiKey)}`);
console.log(`[审计流程] ReAct模式: ${task.useReAct ? '启用' : '禁用'}, 最大步数: ${task.reactConfig?.maxSteps || 15}`);
let auditResult;
if (remainingProjects.length > 0) {
// 只对剩余项目进行审计
const newAuditResult = await auditAgent.run({
taskId,
projects: remainingProjects,
selectedSkillIds: task.selectedSkillIds,
llmConfig,
useReAct: task.useReAct || false,
useStreaming: true,
reactConfig: task.reactConfig || {},
enableLlmAudit: task.enableLlmAudit !== false && !!llmConfig?.apiKey,
tasks,
onProgress: (detail) => {
const adjustedDetail = {
...detail,
current: (detail.current || 0) + completedProjectIds.length,
total: selectedProjects.length,
projectIndex: (detail.projectIndex || 0) + completedProjectIds.length
};
updateTaskProgress(taskId, buildAuditProgress(adjustedDetail, selectedProjects.length));
},
onProjectGroupComplete: (partialResult) => {
const merged = existingAuditResult
? {
...existingAuditResult,
projects: [
...(existingAuditResult.projects || []),
...partialResult.projects
]
}
: partialResult;
tasks.updateTask(taskId, { auditResult: merged });
console.log(`[审计流程] 已保存部分结果: ${partialResult.projects.length} 个项目, ${partialResult.findingsCount} 个发现`);
},
shouldCancel: () => {
const currentTask = tasks.getTask(taskId);
return currentTask?.status === 'cancelled' || currentTask?.status === 'paused';
}
});
// 合并已有结果和新结果
if (existingAuditResult) {
auditResult = {
...existingAuditResult,
projects: [
...(existingAuditResult.projects || []),
...newAuditResult.projects
]
};
} else {
auditResult = newAuditResult;
}
// 立即检查任务状态,如果是暂停或取消,保存当前进度并停止
const currentTaskAfterRun = tasks.getTask(taskId);
if (currentTaskAfterRun?.status === 'paused' || currentTaskAfterRun?.status === 'cancelled') {
console.log(`[审计流程] 任务 ${taskId} 被暂停/取消,保存当前进度并停止`);
console.log(`[审计流程] 暂停时已有 ${auditResult?.projects?.length || 0} 个项目的结果`);
tasks.updateTask(taskId, {
auditResult,
progress: {
...currentTaskAfterRun.progress,
stage: currentTaskAfterRun.status === 'paused' ? "paused" : "cancelled",
label: currentTaskAfterRun.status === 'paused' ? "审计已暂停" : "任务已取消"
}
});
return;
}
} else {
auditResult = existingAuditResult;
}
updateTaskProgress(taskId, {
stage: "report",
label: "正在生成审计报告",
detail: "",
percent: 98,
current: selectedProjects.length,
total: selectedProjects.length
});
const finalTaskSnapshot = {
...tasks.getTask(taskId),
phase: "completed",
message: "审计完成,可下载审计报告。",
selectedProjectIds
};
// 生成 HTML 报告
const htmlReport = await writeAuditHtmlReport({
reportsDir,
task: finalTaskSnapshot,
selectedProjects,
auditResult,
architectureAnalysis: auditResult.architectureAnalysis
});
const memorySummary = buildMemorySummary(finalTaskSnapshot, { projects: selectedProjects }, auditResult);
if (task.useMemory) {
await memoryStore.appendRunSummary(memorySummary);
}
tasks.completeTask(taskId, {
phase: "completed",
message: "审计完成,可下载审计报告。",
selectedProjectIds,
auditResult,
report: {
html: htmlReport
},
memorySummary,
progress: {
stage: "completed",
label: "审计完成",
detail: "",
percent: 100,
current: selectedProjects.length,
total: selectedProjects.length
}
});
} catch (error) {
console.error(`[任务失败] audit阶段失败 - 任务ID: ${taskId}`, error);
tasks.failTask(taskId, {
message: "审计过程中失败",
detail: error instanceof Error ? error.message : String(error),
stage: "audit-analyst"
});
}
}
function updateTaskProgress(taskId, progress) {
const current = tasks.getTask(taskId);
tasks.updateTask(taskId, {
progress: {
...(current?.progress || {}),
...progress
}
});
}
function calculateMirrorPercent(projectIndex, totalProjects, processedFiles, totalFiles) {
const safeProjects = Math.max(totalProjects || 1, 1);
const safeTotalFiles = Math.max(totalFiles || 1, 1);
const projectOffset = (projectIndex - 1) / safeProjects;
const fileOffset = Math.min(processedFiles / safeTotalFiles, 1) / safeProjects;
return Math.min(60, Math.max(24, Math.round(24 + (projectOffset + fileOffset) * 36)));
}
function buildAuditProgress(detail, totalProjects) {
const safeProjects = Math.max(totalProjects || 1, 1);
if (detail.stage === "ast-enhance") {
return {
stage: "ast-enhance",
label: detail.label || `正在进行 AST 增强分析`,
detail: detail.detail || "",
percent: 70,
current: detail.projectIndex || 0,
total: detail.totalProjects || safeProjects
};
}
if (detail.stage === "heuristic") {
return {
stage: "heuristic",
label: detail.label || `正在分析规则层:${detail.projectName || ""}`,
detail: "",
percent: Math.min(68, Math.round(60 + ((detail.projectIndex - 1) / safeProjects) * 8)),
current: detail.projectIndex || 0,
total: detail.totalProjects || safeProjects
};
}
if (detail.stage === "llm-review") {
const totalBatches = Math.max(detail.totalBatches || 1, 1);
const totalFiles = detail.totalFiles || 0;
const completedFiles = detail.reviewedFiles || 0;
const completedBatches = detail.currentBatch || 0;
const batchProgress = completedBatches ? Math.min(completedBatches / totalBatches, 1) : 0;
const projectOffset = (Math.max((detail.projectIndex || 1) - 1, 0) / safeProjects) * 24;
const fileDetail = totalFiles > 0
? `第 ${completedBatches} / ${totalBatches} 批`
: "正在初始化...";
return {
stage: "llm-review",
label: detail.label || `正在进行 LLM 复核:${detail.projectName || ""}`,
detail: fileDetail,
percent: Math.min(95, Math.round(68 + projectOffset + batchProgress * (24 / safeProjects))),
current: totalFiles > 0 ? completedFiles : completedBatches || 0,
total: totalFiles > 0 ? totalFiles : totalBatches
};
}
if (detail.stage === "llm-audit") {
const totalBatches = Math.max(detail.totalBatches || 1, 1);
const totalFiles = detail.totalFiles || 0;
const completedFiles = detail.auditedFiles || 0;
const completedBatches = detail.currentBatch || 0;
const batchProgress = completedBatches ? Math.min(completedBatches / totalBatches, 1) : 0;
const projectOffset = (Math.max((detail.projectIndex || 1) - 1, 0) / safeProjects) * 24;
let fileDetail;
if (detail.type === "llm-indexing") {
fileDetail = `索引中 ${detail.indexedFiles || 0} / ${detail.totalFiles || 0} 个文件`;
} else if (totalFiles > 0) {
fileDetail = `第 ${completedBatches} / ${totalBatches} 批`;
} else {