Compare commits
85 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e54815e018 | |||
| 9baa99ea40 | |||
| 83a8c46db1 | |||
| 4b2619e1fe | |||
| 3fffee80f4 | |||
| 41d7afcf99 | |||
| 6431dcb240 | |||
| 665b1d553a | |||
| fd3a52af01 | |||
| 8368ee7712 | |||
| dd883677b8 | |||
| 2edd5ffe95 | |||
| ae588dbfe4 | |||
| 93be113a79 | |||
| d3fb14f72d | |||
| af715e23cb | |||
| 3aecdc275f | |||
| 660d95a787 | |||
| 01271fd8eb | |||
| 8c6e044f84 | |||
| cb2defd0cc | |||
| 88ab73e422 | |||
| 5404d95db7 | |||
| 32d0e98cfb | |||
| e4b1e10a42 | |||
| 870715fc8f | |||
| 772a04b715 | |||
| 2455bde7ab | |||
| dbdfc18d57 | |||
| 82daad3b56 | |||
| 9eee820096 | |||
| fae912b79c | |||
| 9b48daf795 | |||
| bfbb8b31d3 | |||
| 8b2dfea884 | |||
| 7447e82c39 | |||
| 44b8d0b427 | |||
| 3a26d77c94 | |||
| 0be6746794 | |||
| 06bfed508a | |||
| 0d617ebd66 | |||
| 9a52ec25ea | |||
| 594b7676e1 | |||
| fd5d1dff10 | |||
| b8218d9f77 | |||
| 7b7c689efd | |||
| 27b16e0d54 | |||
| 2b6b678439 | |||
| be104d1a05 | |||
| f64bda3678 | |||
| 4b8dbb1bd6 | |||
| 783d80ee37 | |||
| a27c13b734 | |||
| 3cbf398636 | |||
| 84d54b1ea9 | |||
| 91230f273e | |||
| 81fca5b2dd | |||
| 01b6b226eb | |||
| efd7a0aadd | |||
| 895061911c | |||
| a99387fd6d | |||
| 068dbc1209 | |||
| 7c35c93f23 | |||
| 79fa951da8 | |||
| 3ce9c42333 | |||
| f3b8f231dd | |||
| 6815e03842 | |||
| 42e9ad3bda | |||
| 6321df417b | |||
| 7f1ebe5c3d | |||
| bb68f341d9 | |||
| 232fd9184a | |||
| 38571c7e82 | |||
| 8347244d62 | |||
| b25f455ca6 | |||
| 49a9b57500 | |||
| 06c9bb3bd8 | |||
| d50fa3d633 | |||
| 7a1fc8313c | |||
| 7e145aecf5 | |||
| 3634bf40b4 | |||
| d317e6f13f | |||
| 18fa0ad9e7 | |||
| 15a713743f | |||
| 4926335c71 |
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img src="web/static/logo.png" alt="CyberStrikeAI Logo" width="300">
|
||||
<img src="web/static/logo.png" alt="CyberStrikeAI Logo" width="200">
|
||||
</div>
|
||||
|
||||
# CyberStrikeAI
|
||||
@@ -14,47 +14,55 @@ CyberStrikeAI is an **AI-native security testing platform** built in Go. It inte
|
||||
|
||||
<div align="center">
|
||||
|
||||
### System Dashboard Overview
|
||||
|
||||
<img src="./images/dashboard.png" alt="System Dashboard" width="100%">
|
||||
|
||||
*The dashboard provides a comprehensive overview of system runtime status, security vulnerabilities, tool usage, and knowledge base, helping users quickly understand the platform's core features and current state.*
|
||||
|
||||
### Core Features Overview
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Web Console</strong><br/>
|
||||
<img src="./img/效果.png" alt="Web Console" width="100%">
|
||||
<img src="./images/web-console.png" alt="Web Console" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>MCP Integration</strong><br/>
|
||||
<img src="./img/MCP管理.png" alt="MCP management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Attack Chain Visualization</strong><br/>
|
||||
<img src="./img/攻击链.png" alt="Attack Chain" width="100%">
|
||||
<img src="./images/attack-chain.png" alt="Attack Chain" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>Vulnerability Management</strong><br/>
|
||||
<img src="./img/漏洞管理.png" alt="Vulnerability Management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Task Management</strong><br/>
|
||||
<img src="./img/任务.png" alt="Task Management" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>Role Management</strong><br/>
|
||||
<img src="./img/角色管理.png" alt="Role Management" width="100%">
|
||||
<img src="./images/task-management.png" alt="Task Management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<strong>Skills Management</strong><br/>
|
||||
<img src="./img/skills.png" alt="Skills Management" width="100%">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Vulnerability Management</strong><br/>
|
||||
<img src="./images/vulnerability-management.png" alt="Vulnerability Management" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP Management</strong><br/>
|
||||
<img src="./images/mcp-management.png" alt="MCP management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP stdio Mode</strong><br/>
|
||||
<img src="./img/mcp-stdio2.png" alt="MCP stdio mode" width="100%">
|
||||
<img src="./images/mcp-stdio2.png" alt="MCP stdio mode" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Knowledge Base</strong><br/>
|
||||
<img src="./images/knowledge-base.png" alt="Knowledge Base" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Skills Management</strong><br/>
|
||||
<img src="./images/skills.png" alt="Skills Management" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Role Management</strong><br/>
|
||||
<img src="./images/role-management.png" alt="Role Management" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -174,7 +182,7 @@ go build -o cyberstrike-ai cmd/server/main.go
|
||||
- **Predefined roles** – System includes 12+ predefined security testing roles (Penetration Testing, CTF, Web App Scanning, API Security Testing, Binary Analysis, Cloud Security Audit, etc.) in the `roles/` directory.
|
||||
- **Custom prompts** – Each role can define a `user_prompt` that prepends to user messages, guiding the AI to adopt specialized testing methodologies and focus areas.
|
||||
- **Tool restrictions** – Roles can specify a `tools` list to limit available tools, ensuring focused testing workflows (e.g., CTF role restricts to CTF-specific utilities).
|
||||
- **Skills integration** – Roles can attach security testing skills that are automatically injected into system prompts.
|
||||
- **Skills integration** – Roles can attach security testing skills. Skill names are added to system prompts as hints, and AI agents can access skill content on-demand using the `read_skill` tool.
|
||||
- **Easy role creation** – Create custom roles by adding YAML files to the `roles/` directory. Each role defines `name`, `description`, `user_prompt`, `icon`, `tools`, `skills`, and `enabled` fields.
|
||||
- **Web UI integration** – Select roles from a dropdown in the chat interface. Role selection affects both AI behavior and available tool suggestions.
|
||||
|
||||
@@ -198,7 +206,7 @@ go build -o cyberstrike-ai cmd/server/main.go
|
||||
|
||||
### Skills System
|
||||
- **Predefined skills** – System includes 20+ predefined security testing skills (SQL injection, XSS, API security, cloud security, container security, etc.) in the `skills/` directory.
|
||||
- **Automatic injection** – When a role is selected, all skills attached to that role are automatically loaded and injected into the system prompt, providing AI with specialized knowledge and methodologies.
|
||||
- **Skill hints in prompts** – When a role is selected, skill names attached to that role are added to the system prompt as recommendations. Skill content is not automatically injected; AI agents must use the `read_skill` tool to access skill details when needed.
|
||||
- **On-demand access** – AI agents can also access skills on-demand using built-in tools (`list_skills`, `read_skill`), allowing dynamic skill retrieval during task execution.
|
||||
- **Structured format** – Each skill is a directory containing a `SKILL.md` file with detailed testing methods, tool usage, best practices, and examples. Skills support YAML front matter for metadata.
|
||||
- **Custom skills** – Create custom skills by adding directories to the `skills/` directory. Each skill directory should contain a `SKILL.md` file with the skill content.
|
||||
@@ -462,7 +470,7 @@ CyberStrikeAI/
|
||||
├── tools/ # YAML tool recipes (100+ examples provided)
|
||||
├── roles/ # Role configurations (12+ predefined security testing roles)
|
||||
├── skills/ # Skills directory (20+ predefined security testing skills)
|
||||
├── img/ # Docs screenshots & diagrams
|
||||
├── images/ # Docs screenshots & diagrams
|
||||
├── config.yaml # Runtime configuration
|
||||
├── run.sh # Convenience launcher
|
||||
└── README*.md
|
||||
@@ -489,10 +497,9 @@ Build an attack chain for the latest engagement and export the node list with se
|
||||
|
||||
## Changelog
|
||||
|
||||
See [CHANGELOG.md](CHANGELOG.md) for detailed version history and all changes.
|
||||
|
||||
### Recent Highlights
|
||||
|
||||
- **2026-01-27** – OpenAPI documentation with interactive testing interface, supporting conversation management, message interaction, and result querying
|
||||
- **2026-01-15** – Skills system with 20+ predefined security testing skills
|
||||
- **2026-01-11** – Role-based testing with predefined security testing roles
|
||||
- **2026-01-08** – SSE transport mode support for external MCP servers
|
||||
@@ -504,17 +511,19 @@ See [CHANGELOG.md](CHANGELOG.md) for detailed version history and all changes.
|
||||
|
||||
## 404Starlink
|
||||
|
||||
<img src="./img/404StarLinkLogo.png" width="30%">
|
||||
<img src="./images/404StarLinkLogo.png" width="30%">
|
||||
|
||||
CyberStrikeAI has joined [404Starlink](https://github.com/knownsec/404StarLink)
|
||||
|
||||
## TCH Top-Ranked Intelligent Pentest Project
|
||||
<div align="left">
|
||||
<a href="https://zc.tencent.com/competition/competitionHackathon?code=cha004" target="_blank">
|
||||
<img src="./img/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
<img src="./images/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Stargazers over time
|
||||

|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img src="web/static/logo.png" alt="CyberStrikeAI Logo" width="300">
|
||||
<img src="web/static/logo.png" alt="CyberStrikeAI Logo" width="200">
|
||||
</div>
|
||||
|
||||
# CyberStrikeAI
|
||||
@@ -13,47 +13,55 @@ CyberStrikeAI 是一款 **AI 原生安全测试平台**,基于 Go 构建,集
|
||||
|
||||
<div align="center">
|
||||
|
||||
### 系统仪表盘概览
|
||||
|
||||
<img src="./images/dashboard.png" alt="系统仪表盘" width="100%">
|
||||
|
||||
*仪表盘提供系统运行状态、安全漏洞、工具使用情况和知识库的全面概览,帮助用户快速了解平台核心功能和当前状态。*
|
||||
|
||||
### 核心功能概览
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Web 控制台</strong><br/>
|
||||
<img src="./img/效果.png" alt="Web 控制台" width="100%">
|
||||
<img src="./images/web-console.png" alt="Web 控制台" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>MCP 集成</strong><br/>
|
||||
<img src="./img/MCP管理.png" alt="MCP 管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>攻击链可视化</strong><br/>
|
||||
<img src="./img/攻击链.png" alt="攻击链" width="100%">
|
||||
<img src="./images/attack-chain.png" alt="攻击链" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>漏洞管理</strong><br/>
|
||||
<img src="./img/漏洞管理.png" alt="漏洞管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>任务管理</strong><br/>
|
||||
<img src="./img/任务.png" alt="任务管理" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<strong>角色管理</strong><br/>
|
||||
<img src="./img/角色管理.png" alt="角色管理" width="100%">
|
||||
<img src="./images/task-management.png" alt="任务管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%" align="center">
|
||||
<strong>Skills 管理</strong><br/>
|
||||
<img src="./img/skills.png" alt="Skills 管理" width="100%">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>漏洞管理</strong><br/>
|
||||
<img src="./images/vulnerability-management.png" alt="漏洞管理" width="100%">
|
||||
</td>
|
||||
<td width="50%" align="center">
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP 管理</strong><br/>
|
||||
<img src="./images/mcp-management.png" alt="MCP 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>MCP stdio 模式</strong><br/>
|
||||
<img src="./img/mcp-stdio2.png" alt="MCP stdio 模式" width="100%">
|
||||
<img src="./images/mcp-stdio2.png" alt="MCP stdio 模式" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>知识库</strong><br/>
|
||||
<img src="./images/knowledge-base.png" alt="知识库" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>Skills 管理</strong><br/>
|
||||
<img src="./images/skills.png" alt="Skills 管理" width="100%">
|
||||
</td>
|
||||
<td width="33.33%" align="center">
|
||||
<strong>角色管理</strong><br/>
|
||||
<img src="./images/role-management.png" alt="角色管理" width="100%">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@@ -173,7 +181,7 @@ go build -o cyberstrike-ai cmd/server/main.go
|
||||
- **预设角色**:系统内置 12+ 个预设的安全测试角色(渗透测试、CTF、Web 应用扫描、API 安全测试、二进制分析、云安全审计等),位于 `roles/` 目录。
|
||||
- **自定义提示词**:每个角色可定义 `user_prompt`,会在用户消息前自动添加,引导 AI 采用特定的测试方法和关注重点。
|
||||
- **工具限制**:角色可指定 `tools` 列表,限制可用工具,实现聚焦的测试流程(如 CTF 角色限制为 CTF 专用工具)。
|
||||
- **Skills 集成**:角色可附加安全测试技能,选择角色时自动注入到系统提示词中。
|
||||
- **Skills 集成**:角色可附加安全测试技能。技能名称会作为提示添加到系统提示词中,AI 智能体可通过 `read_skill` 工具按需获取技能内容。
|
||||
- **轻松创建角色**:通过在 `roles/` 目录添加 YAML 文件即可创建自定义角色。每个角色定义 `name`、`description`、`user_prompt`、`icon`、`tools`、`skills`、`enabled` 字段。
|
||||
- **Web 界面集成**:在聊天界面通过下拉菜单选择角色。角色选择会影响 AI 行为和可用工具建议。
|
||||
|
||||
@@ -197,7 +205,7 @@ go build -o cyberstrike-ai cmd/server/main.go
|
||||
|
||||
### Skills 技能系统
|
||||
- **预设技能**:系统内置 20+ 个预设的安全测试技能(SQL 注入、XSS、API 安全、云安全、容器安全等),位于 `skills/` 目录。
|
||||
- **自动注入**:当选择某个角色时,该角色附加的所有技能会自动加载并注入到系统提示词中,为 AI 提供专业知识和测试方法。
|
||||
- **提示词中的技能提示**:当选择某个角色时,该角色附加的技能名称会作为推荐添加到系统提示词中。技能内容不会自动注入,AI 智能体需要时需使用 `read_skill` 工具获取技能详情。
|
||||
- **按需调用**:AI 智能体也可以通过内置工具(`list_skills`、`read_skill`)按需访问技能,允许在执行任务过程中动态获取相关技能。
|
||||
- **结构化格式**:每个技能是一个目录,包含一个 `SKILL.md` 文件,详细描述测试方法、工具使用、最佳实践和示例。技能支持 YAML front matter 格式用于元数据。
|
||||
- **自定义技能**:通过在 `skills/` 目录添加目录即可创建自定义技能。每个技能目录应包含一个 `SKILL.md` 文件。
|
||||
@@ -461,7 +469,7 @@ CyberStrikeAI/
|
||||
├── tools/ # YAML 工具目录(含 100+ 示例)
|
||||
├── roles/ # 角色配置文件目录(含 12+ 预设安全测试角色)
|
||||
├── skills/ # Skills 目录(含 20+ 预设安全测试技能)
|
||||
├── img/ # 文档配图
|
||||
├── images/ # 文档配图
|
||||
├── config.yaml # 运行配置
|
||||
├── run.sh # 启动脚本
|
||||
└── README*.md
|
||||
@@ -488,10 +496,9 @@ CyberStrikeAI/
|
||||
|
||||
## 更新日志
|
||||
|
||||
详细版本历史和所有变更请查看 [CHANGELOG.md](CHANGELOG.md)。
|
||||
|
||||
### 近期亮点
|
||||
|
||||
- **2026-01-27** – 新增 OpenAPI 文档,提供交互式测试界面,支持对话管理、消息交互和结果查询
|
||||
- **2026-01-15** – 新增 Skills 技能系统,内置 20+ 预设安全测试技能
|
||||
- **2026-01-11** – 新增角色化测试功能,支持预设安全测试角色
|
||||
- **2026-01-08** – 新增 SSE 传输模式支持,外部 MCP 联邦支持三种模式
|
||||
@@ -501,17 +508,20 @@ CyberStrikeAI/
|
||||
|
||||
|
||||
## 404星链计划
|
||||
<img src="./img/404StarLinkLogo.png" width="30%">
|
||||
<img src="./images/404StarLinkLogo.png" width="30%">
|
||||
|
||||
CyberStrikeAI 现已加入 [404星链计划](https://github.com/knownsec/404StarLink)
|
||||
|
||||
## TCH Top-Ranked Intelligent Pentest Project
|
||||
<div align="left">
|
||||
<a href="https://zc.tencent.com/competition/competitionHackathon?code=cha004" target="_blank">
|
||||
<img src="./img/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
<img src="./images/tch.png" alt="TCH Top-Ranked Intelligent Pentest Project" width="30%">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## Stargazers over time
|
||||

|
||||
|
||||
---
|
||||
|
||||
欢迎提交 Issue/PR 贡献新的工具模版或优化建议!
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
# 系统设置
|
||||
# ============================================
|
||||
|
||||
# 前端显示的版本号(可选,不填则显示默认版本)
|
||||
version: "v1.3.9"
|
||||
|
||||
# 服务器配置
|
||||
server:
|
||||
host: 0.0.0.0 # 监听地址,0.0.0.0 表示监听所有网络接口
|
||||
@@ -41,6 +44,16 @@ openai:
|
||||
model: deepseek-chat # 模型名称(必填)
|
||||
max_total_tokens: 120000 # LLM 相关上下文的最大 Token 数限制(内存压缩和攻击链构建会共用此配置)
|
||||
|
||||
# ============================================
|
||||
# 信息收集(FOFA)配置(可选)
|
||||
# ============================================
|
||||
# 用于「信息收集」页面调用 FOFA API(后端代理,避免前端暴露 key)
|
||||
# 也可通过环境变量配置:FOFA_EMAIL / FOFA_API_KEY(优先级更高)
|
||||
fofa:
|
||||
base_url: "https://fofa.info/api/v1/search/all" # 可选,留空则使用默认
|
||||
email: "" # FOFA 账号邮箱(可选,建议在系统设置中填写)
|
||||
api_key: "" # FOFA API Key(可选,建议在系统设置中填写)
|
||||
|
||||
# Agent 配置
|
||||
# 达到最大迭代次数时,AI 会自动总结测试结果
|
||||
agent:
|
||||
@@ -67,6 +80,10 @@ database:
|
||||
# 推荐方式:在 tools/ 目录下为每个工具创建独立的配置文件
|
||||
security:
|
||||
tools_dir: tools # 工具配置文件目录(相对于配置文件所在目录)
|
||||
# 工具描述模式:加载 tools 下工具时,暴露给 AI/API 使用的描述来源
|
||||
# short - 优先使用 short_description(简短描述,省 token),为空时用 description
|
||||
# full - 使用 description(详细描述)
|
||||
tool_description_mode: full
|
||||
|
||||
# ============================================
|
||||
# MCP 相关配置
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
module cyberstrike-ai
|
||||
|
||||
go 1.21
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.24.4
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/google/uuid v1.5.0
|
||||
github.com/mattn/go-sqlite3 v1.14.18
|
||||
github.com/modelcontextprotocol/go-sdk v1.2.0
|
||||
github.com/pkoukk/tiktoken-go v0.1.8
|
||||
go.uber.org/zap v1.26.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
@@ -21,6 +24,7 @@ require (
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/google/jsonschema-go v0.3.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
@@ -30,10 +34,12 @@ require (
|
||||
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/net v0.17.0 // indirect
|
||||
golang.org/x/oauth2 v0.30.0 // indirect
|
||||
golang.org/x/sys v0.13.0 // indirect
|
||||
golang.org/x/text v0.13.0 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
|
||||
@@ -25,10 +25,15 @@ github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/jsonschema-go v0.3.0 h1:6AH2TxVNtk3IlvkkhjrtbUc4S8AvO0Xii0DxIygDg+Q=
|
||||
github.com/google/jsonschema-go v0.3.0/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
|
||||
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
@@ -42,6 +47,8 @@ github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APP
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI=
|
||||
github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||
github.com/modelcontextprotocol/go-sdk v1.2.0 h1:Y23co09300CEk8iZ/tMxIX1dVmKZkzoSBZOpJwUnc/s=
|
||||
github.com/modelcontextprotocol/go-sdk v1.2.0/go.mod h1:6fM3LCm3yV7pAs8isnKLn07oKtB0MP9LHd3DfAcKw10=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -68,6 +75,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
|
||||
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
@@ -81,13 +90,16 @@ golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng=
|
||||
|
||||
|
Before Width: | Height: | Size: 9.0 KiB After Width: | Height: | Size: 9.0 KiB |
|
Before Width: | Height: | Size: 1.8 MiB After Width: | Height: | Size: 1.8 MiB |
|
After Width: | Height: | Size: 832 KiB |
|
After Width: | Height: | Size: 499 KiB |
|
After Width: | Height: | Size: 477 KiB |
|
Before Width: | Height: | Size: 839 KiB After Width: | Height: | Size: 839 KiB |
|
After Width: | Height: | Size: 711 KiB |
|
Before Width: | Height: | Size: 317 KiB After Width: | Height: | Size: 317 KiB |
|
After Width: | Height: | Size: 656 KiB |
|
After Width: | Height: | Size: 326 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 493 KiB |
|
After Width: | Height: | Size: 598 KiB |
|
Before Width: | Height: | Size: 305 KiB |
|
Before Width: | Height: | Size: 280 KiB |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 468 KiB |
|
Before Width: | Height: | Size: 273 KiB |
|
Before Width: | Height: | Size: 543 KiB |
|
Before Width: | Height: | Size: 382 KiB |
|
Before Width: | Height: | Size: 506 KiB |
|
Before Width: | Height: | Size: 246 KiB |
@@ -391,6 +391,17 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
- 将低影响问题串联成高影响攻击路径
|
||||
- 牢记:单个高影响漏洞比几十个低严重度更有价值。
|
||||
|
||||
思考与推理要求:
|
||||
调用工具前,在消息内容中提供5-10句话(50-150字)的思考,包含:
|
||||
1. 当前测试目标和工具选择原因
|
||||
2. 基于之前结果的上下文关联
|
||||
3. 期望获得的测试结果
|
||||
|
||||
要求:
|
||||
- ✅ 2-4句话清晰表达
|
||||
- ✅ 包含关键决策依据
|
||||
- ❌ 不要只写一句话
|
||||
- ❌ 不要超过10句话
|
||||
|
||||
重要:当工具调用失败时,请遵循以下原则:
|
||||
1. 仔细分析错误信息,理解失败的具体原因
|
||||
@@ -518,8 +529,10 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
|
||||
maxIterations := a.maxIterations
|
||||
for i := 0; i < maxIterations; i++ {
|
||||
// 每轮调用前先尝试压缩,防止历史消息持续膨胀
|
||||
messages = a.applyMemoryCompression(ctx, messages)
|
||||
// 先获取本轮可用工具并统计 tools token,再压缩,以便压缩时预留 tools 占用的空间
|
||||
tools := a.getAvailableTools(roleTools)
|
||||
toolsTokens := a.countToolsTokens(tools)
|
||||
messages = a.applyMemoryCompression(ctx, messages, toolsTokens)
|
||||
|
||||
// 检查是否是最后一次迭代
|
||||
isLastIteration := (i == maxIterations-1)
|
||||
@@ -551,17 +564,17 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
default:
|
||||
}
|
||||
|
||||
// 获取可用工具
|
||||
tools := a.getAvailableTools(roleTools)
|
||||
|
||||
// 记录当前上下文的Token用量,展示压缩器运行状态
|
||||
// 记录当前上下文的 Token 用量(messages + tools),展示压缩器运行状态
|
||||
if a.memoryCompressor != nil {
|
||||
totalTokens, systemCount, regularCount := a.memoryCompressor.totalTokensFor(messages)
|
||||
messagesTokens, systemCount, regularCount := a.memoryCompressor.totalTokensFor(messages)
|
||||
totalTokens := messagesTokens + toolsTokens
|
||||
a.logger.Info("memory compressor context stats",
|
||||
zap.Int("iteration", i+1),
|
||||
zap.Int("messagesCount", len(messages)),
|
||||
zap.Int("systemMessages", systemCount),
|
||||
zap.Int("regularMessages", regularCount),
|
||||
zap.Int("messagesTokens", messagesTokens),
|
||||
zap.Int("toolsTokens", toolsTokens),
|
||||
zap.Int("totalTokens", totalTokens),
|
||||
zap.Int("maxTotalTokens", a.memoryCompressor.maxTotalTokens),
|
||||
)
|
||||
@@ -777,7 +790,7 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
Role: "user",
|
||||
Content: "这是最后一次迭代。请总结到目前为止的所有测试结果、发现的问题和已完成的工作。如果需要继续测试,请提供详细的下一步执行计划。请直接回复,不要调用工具。",
|
||||
})
|
||||
messages = a.applyMemoryCompression(ctx, messages)
|
||||
messages = a.applyMemoryCompression(ctx, messages, 0) // 总结时不带 tools,不预留
|
||||
// 立即调用OpenAI获取总结
|
||||
summaryResponse, err := a.callOpenAI(ctx, messages, []Tool{}) // 不提供工具,强制AI直接回复
|
||||
if err == nil && summaryResponse != nil && len(summaryResponse.Choices) > 0 {
|
||||
@@ -817,7 +830,7 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
Role: "user",
|
||||
Content: "这是最后一次迭代。请总结到目前为止的所有测试结果、发现的问题和已完成的工作。如果需要继续测试,请提供详细的下一步执行计划。请直接回复,不要调用工具。",
|
||||
})
|
||||
messages = a.applyMemoryCompression(ctx, messages)
|
||||
messages = a.applyMemoryCompression(ctx, messages, 0) // 总结时不带 tools,不预留
|
||||
// 立即调用OpenAI获取总结
|
||||
summaryResponse, err := a.callOpenAI(ctx, messages, []Tool{}) // 不提供工具,强制AI直接回复
|
||||
if err == nil && summaryResponse != nil && len(summaryResponse.Choices) > 0 {
|
||||
@@ -856,7 +869,7 @@ func (a *Agent) AgentLoopWithProgress(ctx context.Context, userInput string, his
|
||||
Content: fmt.Sprintf("已达到最大迭代次数(%d轮)。请总结到目前为止的所有测试结果、发现的问题和已完成的工作。如果需要继续测试,请提供详细的下一步执行计划。请直接回复,不要调用工具。", a.maxIterations),
|
||||
}
|
||||
messages = append(messages, finalSummaryPrompt)
|
||||
messages = a.applyMemoryCompression(ctx, messages)
|
||||
messages = a.applyMemoryCompression(ctx, messages, 0) // 总结时不带 tools,不预留
|
||||
|
||||
summaryResponse, err := a.callOpenAI(ctx, messages, []Tool{}) // 不提供工具,强制AI直接回复
|
||||
if err == nil && summaryResponse != nil && len(summaryResponse.Choices) > 0 {
|
||||
@@ -1414,13 +1427,13 @@ func (a *Agent) formatToolError(toolName string, args map[string]interface{}, er
|
||||
return errorMsg
|
||||
}
|
||||
|
||||
// applyMemoryCompression 在调用LLM前对消息进行压缩,避免超过token限制
|
||||
func (a *Agent) applyMemoryCompression(ctx context.Context, messages []ChatMessage) []ChatMessage {
|
||||
// applyMemoryCompression 在调用LLM前对消息进行压缩,避免超过 token 限制。reservedTokens 为预留给 tools 的 token 数,传 0 表示不预留。
|
||||
func (a *Agent) applyMemoryCompression(ctx context.Context, messages []ChatMessage, reservedTokens int) []ChatMessage {
|
||||
if a.memoryCompressor == nil {
|
||||
return messages
|
||||
}
|
||||
|
||||
compressed, changed, err := a.memoryCompressor.CompressHistory(ctx, messages)
|
||||
compressed, changed, err := a.memoryCompressor.CompressHistory(ctx, messages, reservedTokens)
|
||||
if err != nil {
|
||||
a.logger.Warn("上下文压缩失败,将使用原始消息继续", zap.Error(err))
|
||||
return messages
|
||||
@@ -1436,6 +1449,18 @@ func (a *Agent) applyMemoryCompression(ctx context.Context, messages []ChatMessa
|
||||
return messages
|
||||
}
|
||||
|
||||
// countToolsTokens 统计 tools 序列化后的 token 数,用于日志与压缩时预留空间。mc 为 nil 时返回 0。
|
||||
func (a *Agent) countToolsTokens(tools []Tool) int {
|
||||
if len(tools) == 0 || a.memoryCompressor == nil {
|
||||
return 0
|
||||
}
|
||||
data, err := json.Marshal(tools)
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return a.memoryCompressor.CountTextTokens(string(data))
|
||||
}
|
||||
|
||||
// handleMissingToolError 当LLM调用不存在的工具时,向其追加提示消息并允许继续迭代
|
||||
func (a *Agent) handleMissingToolError(errMsg string, messages *[]ChatMessage) (bool, string) {
|
||||
lowerMsg := strings.ToLower(errMsg)
|
||||
|
||||
@@ -158,8 +158,8 @@ func (mc *MemoryCompressor) UpdateConfig(cfg *config.OpenAIConfig) {
|
||||
}
|
||||
}
|
||||
|
||||
// CompressHistory 根据Token限制压缩历史消息。
|
||||
func (mc *MemoryCompressor) CompressHistory(ctx context.Context, messages []ChatMessage) ([]ChatMessage, bool, error) {
|
||||
// CompressHistory 根据 Token 限制压缩历史消息。reservedTokens 为预留给 tools 等非消息内容的 token 数,压缩时使用 (maxTotalTokens - reservedTokens) 作为消息上限。
|
||||
func (mc *MemoryCompressor) CompressHistory(ctx context.Context, messages []ChatMessage, reservedTokens int) ([]ChatMessage, bool, error) {
|
||||
if len(messages) == 0 {
|
||||
return messages, false, nil
|
||||
}
|
||||
@@ -171,8 +171,13 @@ func (mc *MemoryCompressor) CompressHistory(ctx context.Context, messages []Chat
|
||||
return messages, false, nil
|
||||
}
|
||||
|
||||
effectiveMax := mc.maxTotalTokens
|
||||
if reservedTokens > 0 && reservedTokens < mc.maxTotalTokens {
|
||||
effectiveMax = mc.maxTotalTokens - reservedTokens
|
||||
}
|
||||
|
||||
totalTokens := mc.countTotalTokens(systemMsgs, regularMsgs)
|
||||
if totalTokens <= int(float64(mc.maxTotalTokens)*0.9) {
|
||||
if totalTokens <= int(float64(effectiveMax)*0.9) {
|
||||
return messages, false, nil
|
||||
}
|
||||
|
||||
@@ -184,6 +189,8 @@ func (mc *MemoryCompressor) CompressHistory(ctx context.Context, messages []Chat
|
||||
mc.logger.Info("memory compression triggered",
|
||||
zap.Int("total_tokens", totalTokens),
|
||||
zap.Int("max_total_tokens", mc.maxTotalTokens),
|
||||
zap.Int("reserved_tokens", reservedTokens),
|
||||
zap.Int("effective_max", effectiveMax),
|
||||
zap.Int("system_messages", len(systemMsgs)),
|
||||
zap.Int("regular_messages", len(regularMsgs)),
|
||||
zap.Int("old_messages", len(oldMsgs)),
|
||||
@@ -282,6 +289,11 @@ func (mc *MemoryCompressor) countTokens(text string) int {
|
||||
return count
|
||||
}
|
||||
|
||||
// CountTextTokens 对外暴露的文本 Token 计数,用于统计 tools 等非消息内容的 token(如 agent 侧序列化 tools 后计数)。
|
||||
func (mc *MemoryCompressor) CountTextTokens(text string) int {
|
||||
return mc.countTokens(text)
|
||||
}
|
||||
|
||||
// totalTokensFor provides token statistics without mutating the message list.
|
||||
func (mc *MemoryCompressor) totalTokensFor(messages []ChatMessage) (totalTokens int, systemCount int, regularCount int) {
|
||||
if len(messages) == 0 {
|
||||
|
||||
@@ -309,7 +309,6 @@ func New(cfg *config.Config, log *logger.Logger) (*App, error) {
|
||||
}
|
||||
monitorHandler := handler.NewMonitorHandler(mcpServer, executor, db, log.Logger)
|
||||
monitorHandler.SetExternalMCPManager(externalMCPMgr) // 设置外部MCP管理器,以便获取外部MCP执行记录
|
||||
conversationHandler := handler.NewConversationHandler(db, log.Logger)
|
||||
groupHandler := handler.NewGroupHandler(db, log.Logger)
|
||||
authHandler := handler.NewAuthHandler(authManager, cfg, configPath, log.Logger)
|
||||
attackChainHandler := handler.NewAttackChainHandler(db, &cfg.OpenAI, log.Logger)
|
||||
@@ -319,10 +318,15 @@ func New(cfg *config.Config, log *logger.Logger) (*App, error) {
|
||||
roleHandler := handler.NewRoleHandler(cfg, configPath, log.Logger)
|
||||
roleHandler.SetSkillsManager(skillsManager) // 设置Skills管理器到RoleHandler
|
||||
skillsHandler := handler.NewSkillsHandler(skillsManager, cfg, configPath, log.Logger)
|
||||
fofaHandler := handler.NewFofaHandler(cfg, log.Logger)
|
||||
if db != nil {
|
||||
skillsHandler.SetDB(db) // 设置数据库连接以便获取调用统计
|
||||
}
|
||||
|
||||
// 创建OpenAPI处理器
|
||||
conversationHandler := handler.NewConversationHandler(db, log.Logger)
|
||||
openAPIHandler := handler.NewOpenAPIHandler(db, log.Logger, resultStorage, conversationHandler, agentHandler)
|
||||
|
||||
// 创建 App 实例(部分字段稍后填充)
|
||||
app := &App{
|
||||
config: cfg,
|
||||
@@ -349,6 +353,18 @@ func New(cfg *config.Config, log *logger.Logger) (*App, error) {
|
||||
}
|
||||
configHandler.SetVulnerabilityToolRegistrar(vulnerabilityRegistrar)
|
||||
|
||||
// 设置Skills工具注册器(内置工具,必须设置)
|
||||
skillsRegistrar := func() error {
|
||||
// 创建一个适配器,将database.DB适配为SkillStatsStorage接口
|
||||
var skillStatsStorage skills.SkillStatsStorage
|
||||
if db != nil {
|
||||
skillStatsStorage = &skillStatsDBAdapter{db: db}
|
||||
}
|
||||
skills.RegisterSkillsToolWithStorage(mcpServer, skillsManager, skillStatsStorage, log.Logger)
|
||||
return nil
|
||||
}
|
||||
configHandler.SetSkillsToolRegistrar(skillsRegistrar)
|
||||
|
||||
// 设置知识库初始化器(用于动态初始化,需要在 App 创建后设置)
|
||||
configHandler.SetKnowledgeInitializer(func() (*handler.KnowledgeHandler, error) {
|
||||
knowledgeHandler, err := initializeKnowledge(cfg, db, knowledgeDBConn, mcpServer, agentHandler, app, log.Logger)
|
||||
@@ -400,8 +416,10 @@ func New(cfg *config.Config, log *logger.Logger) (*App, error) {
|
||||
vulnerabilityHandler,
|
||||
roleHandler,
|
||||
skillsHandler,
|
||||
fofaHandler,
|
||||
mcpServer,
|
||||
authManager,
|
||||
openAPIHandler,
|
||||
)
|
||||
|
||||
return app, nil
|
||||
@@ -462,8 +480,10 @@ func setupRoutes(
|
||||
vulnerabilityHandler *handler.VulnerabilityHandler,
|
||||
roleHandler *handler.RoleHandler,
|
||||
skillsHandler *handler.SkillsHandler,
|
||||
fofaHandler *handler.FofaHandler,
|
||||
mcpServer *mcp.Server,
|
||||
authManager *security.AuthManager,
|
||||
openAPIHandler *handler.OpenAPIHandler,
|
||||
) {
|
||||
// API路由
|
||||
api := router.Group("/api")
|
||||
@@ -489,6 +509,11 @@ func setupRoutes(
|
||||
protected.GET("/agent-loop/tasks", agentHandler.ListAgentTasks)
|
||||
protected.GET("/agent-loop/tasks/completed", agentHandler.ListCompletedTasks)
|
||||
|
||||
// 信息收集 - FOFA 查询(后端代理)
|
||||
protected.POST("/fofa/search", fofaHandler.Search)
|
||||
// 信息收集 - 自然语言解析为 FOFA 语法(需人工确认后再查询)
|
||||
protected.POST("/fofa/parse", fofaHandler.ParseNaturalLanguage)
|
||||
|
||||
// 批量任务管理
|
||||
protected.POST("/batch-tasks", agentHandler.CreateBatchQueue)
|
||||
protected.GET("/batch-tasks", agentHandler.ListBatchQueues)
|
||||
@@ -677,6 +702,18 @@ func setupRoutes(
|
||||
}
|
||||
app.knowledgeHandler.Search(c)
|
||||
})
|
||||
knowledgeRoutes.GET("/stats", func(c *gin.Context) {
|
||||
if app.knowledgeHandler == nil {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": false,
|
||||
"total_categories": 0,
|
||||
"total_items": 0,
|
||||
"message": "知识库功能未启用,请前往系统设置启用知识检索功能",
|
||||
})
|
||||
return
|
||||
}
|
||||
app.knowledgeHandler.GetStats(c)
|
||||
})
|
||||
}
|
||||
|
||||
// 漏洞管理
|
||||
@@ -710,15 +747,30 @@ func setupRoutes(
|
||||
protected.POST("/mcp", func(c *gin.Context) {
|
||||
mcpServer.HandleHTTP(c.Writer, c.Request)
|
||||
})
|
||||
|
||||
// OpenAPI结果聚合端点(可选,用于获取对话的完整结果)
|
||||
protected.GET("/conversations/:id/results", openAPIHandler.GetConversationResults)
|
||||
}
|
||||
|
||||
// OpenAPI规范(需要认证,避免暴露API结构信息)
|
||||
protected.GET("/openapi/spec", openAPIHandler.GetOpenAPISpec)
|
||||
|
||||
// API文档页面(公开访问,但需要登录后才能使用API)
|
||||
router.GET("/api-docs", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "api-docs.html", nil)
|
||||
})
|
||||
|
||||
// 静态文件
|
||||
router.Static("/static", "./web/static")
|
||||
router.LoadHTMLGlob("web/templates/*")
|
||||
|
||||
// 前端页面
|
||||
router.GET("/", func(c *gin.Context) {
|
||||
c.HTML(http.StatusOK, "index.html", nil)
|
||||
version := app.config.Version
|
||||
if version == "" {
|
||||
version = "v1.0.0"
|
||||
}
|
||||
c.HTML(http.StatusOK, "index.html", gin.H{"Version": version})
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -13,19 +13,21 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Server ServerConfig `yaml:"server"`
|
||||
Log LogConfig `yaml:"log"`
|
||||
MCP MCPConfig `yaml:"mcp"`
|
||||
OpenAI OpenAIConfig `yaml:"openai"`
|
||||
Agent AgentConfig `yaml:"agent"`
|
||||
Security SecurityConfig `yaml:"security"`
|
||||
Database DatabaseConfig `yaml:"database"`
|
||||
Auth AuthConfig `yaml:"auth"`
|
||||
ExternalMCP ExternalMCPConfig `yaml:"external_mcp,omitempty"`
|
||||
Knowledge KnowledgeConfig `yaml:"knowledge,omitempty"`
|
||||
RolesDir string `yaml:"roles_dir,omitempty" json:"roles_dir,omitempty"` // 角色配置文件目录(新方式)
|
||||
Roles map[string]RoleConfig `yaml:"roles,omitempty" json:"roles,omitempty"` // 向后兼容:支持在主配置文件中定义角色
|
||||
SkillsDir string `yaml:"skills_dir,omitempty" json:"skills_dir,omitempty"` // Skills配置文件目录
|
||||
Version string `yaml:"version,omitempty" json:"version,omitempty"` // 前端显示的版本号,如 v1.3.3
|
||||
Server ServerConfig `yaml:"server"`
|
||||
Log LogConfig `yaml:"log"`
|
||||
MCP MCPConfig `yaml:"mcp"`
|
||||
OpenAI OpenAIConfig `yaml:"openai"`
|
||||
FOFA FofaConfig `yaml:"fofa,omitempty" json:"fofa,omitempty"`
|
||||
Agent AgentConfig `yaml:"agent"`
|
||||
Security SecurityConfig `yaml:"security"`
|
||||
Database DatabaseConfig `yaml:"database"`
|
||||
Auth AuthConfig `yaml:"auth"`
|
||||
ExternalMCP ExternalMCPConfig `yaml:"external_mcp,omitempty"`
|
||||
Knowledge KnowledgeConfig `yaml:"knowledge,omitempty"`
|
||||
RolesDir string `yaml:"roles_dir,omitempty" json:"roles_dir,omitempty"` // 角色配置文件目录(新方式)
|
||||
Roles map[string]RoleConfig `yaml:"roles,omitempty" json:"roles,omitempty"` // 向后兼容:支持在主配置文件中定义角色
|
||||
SkillsDir string `yaml:"skills_dir,omitempty" json:"skills_dir,omitempty"` // Skills配置文件目录
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -51,9 +53,17 @@ type OpenAIConfig struct {
|
||||
MaxTotalTokens int `yaml:"max_total_tokens,omitempty" json:"max_total_tokens,omitempty"`
|
||||
}
|
||||
|
||||
type FofaConfig struct {
|
||||
// Email 为 FOFA 账号邮箱;APIKey 为 FOFA API Key(建议使用只读权限的 Key)
|
||||
Email string `yaml:"email,omitempty" json:"email,omitempty"`
|
||||
APIKey string `yaml:"api_key,omitempty" json:"api_key,omitempty"`
|
||||
BaseURL string `yaml:"base_url,omitempty" json:"base_url,omitempty"` // 默认 https://fofa.info/api/v1/search/all
|
||||
}
|
||||
|
||||
type SecurityConfig struct {
|
||||
Tools []ToolConfig `yaml:"tools,omitempty"` // 向后兼容:支持在主配置文件中定义工具
|
||||
ToolsDir string `yaml:"tools_dir,omitempty"` // 工具配置文件目录(新方式)
|
||||
Tools []ToolConfig `yaml:"tools,omitempty"` // 向后兼容:支持在主配置文件中定义工具
|
||||
ToolsDir string `yaml:"tools_dir,omitempty"` // 工具配置文件目录(新方式)
|
||||
ToolDescriptionMode string `yaml:"tool_description_mode,omitempty"` // 工具描述模式: "short" | "full",默认 short
|
||||
}
|
||||
|
||||
type DatabaseConfig struct {
|
||||
@@ -83,13 +93,14 @@ type ExternalMCPConfig struct {
|
||||
// ExternalMCPServerConfig 外部MCP服务器配置
|
||||
type ExternalMCPServerConfig struct {
|
||||
// stdio模式配置
|
||||
Command string `yaml:"command,omitempty" json:"command,omitempty"`
|
||||
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
|
||||
Command string `yaml:"command,omitempty" json:"command,omitempty"`
|
||||
Args []string `yaml:"args,omitempty" json:"args,omitempty"`
|
||||
Env map[string]string `yaml:"env,omitempty" json:"env,omitempty"` // 环境变量(用于stdio模式)
|
||||
|
||||
// HTTP模式配置
|
||||
Transport string `yaml:"transport,omitempty" json:"transport,omitempty"` // "http" 或 "stdio"
|
||||
URL string `yaml:"url,omitempty" json:"url,omitempty"`
|
||||
Transport string `yaml:"transport,omitempty" json:"transport,omitempty"` // "stdio" | "sse" | "http"(Streamable) | "simple_http"(自建/简单POST端点,如本机 http://127.0.0.1:8081/mcp)
|
||||
URL string `yaml:"url,omitempty" json:"url,omitempty"`
|
||||
Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"` // HTTP/SSE 请求头(如 x-api-key)
|
||||
|
||||
// 通用配置
|
||||
Description string `yaml:"description,omitempty" json:"description,omitempty"`
|
||||
@@ -108,8 +119,8 @@ type ToolConfig struct {
|
||||
ShortDescription string `yaml:"short_description,omitempty"` // 简短描述(用于工具列表,减少token消耗)
|
||||
Description string `yaml:"description"` // 详细描述(用于工具文档)
|
||||
Enabled bool `yaml:"enabled"`
|
||||
Parameters []ParameterConfig `yaml:"parameters,omitempty"` // 参数定义(可选)
|
||||
ArgMapping string `yaml:"arg_mapping,omitempty"` // 参数映射方式: "auto", "manual", "template"(可选)
|
||||
Parameters []ParameterConfig `yaml:"parameters,omitempty"` // 参数定义(可选)
|
||||
ArgMapping string `yaml:"arg_mapping,omitempty"` // 参数映射方式: "auto", "manual", "template"(可选)
|
||||
AllowedExitCodes []int `yaml:"allowed_exit_codes,omitempty"` // 允许的退出码列表(某些工具在成功时也返回非零退出码)
|
||||
}
|
||||
|
||||
@@ -467,7 +478,7 @@ func LoadRoleFromFile(path string) (*RoleConfig, error) {
|
||||
icon := role.Icon
|
||||
// 去除可能的引号
|
||||
icon = strings.Trim(icon, `"`)
|
||||
|
||||
|
||||
// 检查是否是 Unicode 转义格式 \U0001F3C6(8位十六进制)或 \uXXXX(4位十六进制)
|
||||
if len(icon) >= 3 && icon[0] == '\\' {
|
||||
if icon[1] == 'U' && len(icon) >= 10 {
|
||||
@@ -576,12 +587,12 @@ type RolesConfig struct {
|
||||
|
||||
// RoleConfig 单个角色配置
|
||||
type RoleConfig struct {
|
||||
Name string `yaml:"name" json:"name"` // 角色名称
|
||||
Description string `yaml:"description" json:"description"` // 角色描述
|
||||
UserPrompt string `yaml:"user_prompt" json:"user_prompt"` // 用户提示词(追加到用户消息前)
|
||||
Icon string `yaml:"icon,omitempty" json:"icon,omitempty"` // 角色图标(可选)
|
||||
Tools []string `yaml:"tools,omitempty" json:"tools,omitempty"` // 关联的工具列表(toolKey格式,如 "toolName" 或 "mcpName::toolName")
|
||||
MCPs []string `yaml:"mcps,omitempty" json:"mcps,omitempty"` // 向后兼容:关联的MCP服务器列表(已废弃,使用tools替代)
|
||||
Name string `yaml:"name" json:"name"` // 角色名称
|
||||
Description string `yaml:"description" json:"description"` // 角色描述
|
||||
UserPrompt string `yaml:"user_prompt" json:"user_prompt"` // 用户提示词(追加到用户消息前)
|
||||
Icon string `yaml:"icon,omitempty" json:"icon,omitempty"` // 角色图标(可选)
|
||||
Tools []string `yaml:"tools,omitempty" json:"tools,omitempty"` // 关联的工具列表(toolKey格式,如 "toolName" 或 "mcpName::toolName")
|
||||
MCPs []string `yaml:"mcps,omitempty" json:"mcps,omitempty"` // 向后兼容:关联的MCP服务器列表(已废弃,使用tools替代)
|
||||
Skills []string `yaml:"skills,omitempty" json:"skills,omitempty"` // 关联的skills列表(skill名称列表,在执行任务前会读取这些skills的内容)
|
||||
Enabled bool `yaml:"enabled" json:"enabled"` // 是否启用
|
||||
Enabled bool `yaml:"enabled" json:"enabled"` // 是否启用
|
||||
}
|
||||
|
||||
@@ -223,12 +223,30 @@ func (db *DB) UpdateConversationTime(id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteConversation 删除对话
|
||||
// DeleteConversation 删除对话及其所有相关数据
|
||||
// 由于数据库外键约束设置了 ON DELETE CASCADE,删除对话时会自动删除:
|
||||
// - messages(消息)
|
||||
// - process_details(过程详情)
|
||||
// - attack_chain_nodes(攻击链节点)
|
||||
// - attack_chain_edges(攻击链边)
|
||||
// - vulnerabilities(漏洞)
|
||||
// - conversation_group_mappings(分组映射)
|
||||
// 注意:knowledge_retrieval_logs 使用 ON DELETE SET NULL,记录会保留但 conversation_id 会被设为 NULL
|
||||
func (db *DB) DeleteConversation(id string) error {
|
||||
_, err := db.Exec("DELETE FROM conversations WHERE id = ?", id)
|
||||
// 显式删除知识检索日志(虽然外键是SET NULL,但为了彻底清理,我们手动删除)
|
||||
_, err := db.Exec("DELETE FROM knowledge_retrieval_logs WHERE conversation_id = ?", id)
|
||||
if err != nil {
|
||||
db.logger.Warn("删除知识检索日志失败", zap.String("conversationId", id), zap.Error(err))
|
||||
// 不返回错误,继续删除对话
|
||||
}
|
||||
|
||||
// 删除对话(外键CASCADE会自动删除其他相关数据)
|
||||
_, err = db.Exec("DELETE FROM conversations WHERE id = ?", id)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除对话失败: %w", err)
|
||||
}
|
||||
|
||||
db.logger.Info("对话及其所有相关数据已删除", zap.String("conversationId", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -147,6 +147,14 @@ func (h *AgentHandler) AgentLoop(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
conversationID = conv.ID
|
||||
} else {
|
||||
// 验证对话是否存在
|
||||
_, err := h.db.GetConversation(conversationID)
|
||||
if err != nil {
|
||||
h.logger.Error("对话不存在", zap.String("conversationId", conversationID), zap.Error(err))
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "对话不存在"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 优先尝试从保存的ReAct数据恢复历史上下文
|
||||
@@ -203,6 +211,8 @@ func (h *AgentHandler) AgentLoop(c *gin.Context) {
|
||||
_, err = h.db.AddMessage(conversationID, "user", req.Message, nil)
|
||||
if err != nil {
|
||||
h.logger.Error("保存用户消息失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存用户消息失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 执行Agent Loop,传入历史消息和对话ID(使用包含角色提示词的finalMessage和角色工具列表)
|
||||
@@ -228,6 +238,8 @@ func (h *AgentHandler) AgentLoop(c *gin.Context) {
|
||||
_, err = h.db.AddMessage(conversationID, "assistant", result.Response, result.MCPExecutionIDs)
|
||||
if err != nil {
|
||||
h.logger.Error("保存助手消息失败", zap.Error(err))
|
||||
// 即使保存失败,也返回响应,但记录错误
|
||||
// 因为AI已经生成了回复,用户应该能看到
|
||||
}
|
||||
|
||||
// 保存最后一轮ReAct的输入和输出
|
||||
@@ -479,12 +491,19 @@ func (h *AgentHandler) AgentLoopStream(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
conversationID = conv.ID
|
||||
sendEvent("conversation", "会话已创建", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
})
|
||||
} else {
|
||||
// 验证对话是否存在
|
||||
_, err := h.db.GetConversation(conversationID)
|
||||
if err != nil {
|
||||
h.logger.Error("对话不存在", zap.String("conversationId", conversationID), zap.Error(err))
|
||||
sendEvent("error", "对话不存在", nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
sendEvent("conversation", "会话已创建", map[string]interface{}{
|
||||
"conversationId": conversationID,
|
||||
})
|
||||
|
||||
// 优先尝试从保存的ReAct数据恢复历史上下文
|
||||
agentHistoryMessages, err := h.loadHistoryFromReActData(conversationID)
|
||||
if err != nil {
|
||||
|
||||
@@ -28,6 +28,9 @@ type KnowledgeToolRegistrar func() error
|
||||
// VulnerabilityToolRegistrar 漏洞工具注册器接口
|
||||
type VulnerabilityToolRegistrar func() error
|
||||
|
||||
// SkillsToolRegistrar Skills工具注册器接口
|
||||
type SkillsToolRegistrar func() error
|
||||
|
||||
// RetrieverUpdater 检索器更新接口
|
||||
type RetrieverUpdater interface {
|
||||
UpdateConfig(config *knowledge.RetrievalConfig)
|
||||
@@ -52,6 +55,7 @@ type ConfigHandler struct {
|
||||
externalMCPMgr *mcp.ExternalMCPManager // 外部MCP管理器
|
||||
knowledgeToolRegistrar KnowledgeToolRegistrar // 知识库工具注册器(可选)
|
||||
vulnerabilityToolRegistrar VulnerabilityToolRegistrar // 漏洞工具注册器(可选)
|
||||
skillsToolRegistrar SkillsToolRegistrar // Skills工具注册器(可选)
|
||||
retrieverUpdater RetrieverUpdater // 检索器更新器(可选)
|
||||
knowledgeInitializer KnowledgeInitializer // 知识库初始化器(可选)
|
||||
appUpdater AppUpdater // App更新器(可选)
|
||||
@@ -110,6 +114,13 @@ func (h *ConfigHandler) SetVulnerabilityToolRegistrar(registrar VulnerabilityToo
|
||||
h.vulnerabilityToolRegistrar = registrar
|
||||
}
|
||||
|
||||
// SetSkillsToolRegistrar 设置Skills工具注册器
|
||||
func (h *ConfigHandler) SetSkillsToolRegistrar(registrar SkillsToolRegistrar) {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.skillsToolRegistrar = registrar
|
||||
}
|
||||
|
||||
// SetRetrieverUpdater 设置检索器更新器
|
||||
func (h *ConfigHandler) SetRetrieverUpdater(updater RetrieverUpdater) {
|
||||
h.mu.Lock()
|
||||
@@ -134,6 +145,7 @@ func (h *ConfigHandler) SetAppUpdater(updater AppUpdater) {
|
||||
// GetConfigResponse 获取配置响应
|
||||
type GetConfigResponse struct {
|
||||
OpenAI config.OpenAIConfig `json:"openai"`
|
||||
FOFA config.FofaConfig `json:"fofa"`
|
||||
MCP config.MCPConfig `json:"mcp"`
|
||||
Tools []ToolConfigInfo `json:"tools"`
|
||||
Agent config.AgentConfig `json:"agent"`
|
||||
@@ -163,18 +175,10 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
||||
configToolMap[tool.Name] = true
|
||||
tools = append(tools, ToolConfigInfo{
|
||||
Name: tool.Name,
|
||||
Description: tool.ShortDescription,
|
||||
Description: h.pickToolDescription(tool.ShortDescription, tool.Description),
|
||||
Enabled: tool.Enabled,
|
||||
IsExternal: false,
|
||||
})
|
||||
// 如果没有简短描述,使用详细描述的前100个字符
|
||||
if tools[len(tools)-1].Description == "" {
|
||||
desc := tool.Description
|
||||
if len(desc) > 100 {
|
||||
desc = desc[:100] + "..."
|
||||
}
|
||||
tools[len(tools)-1].Description = desc
|
||||
}
|
||||
}
|
||||
|
||||
// 从MCP服务器获取所有已注册的工具(包括直接注册的工具,如知识检索工具)
|
||||
@@ -190,8 +194,8 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
||||
if description == "" {
|
||||
description = mcpTool.Description
|
||||
}
|
||||
if len(description) > 100 {
|
||||
description = description[:100] + "..."
|
||||
if len(description) > 10000 {
|
||||
description = description[:10000] + "..."
|
||||
}
|
||||
tools = append(tools, ToolConfigInfo{
|
||||
Name: mcpTool.Name,
|
||||
@@ -204,66 +208,16 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
||||
|
||||
// 获取外部MCP工具
|
||||
if h.externalMCPMgr != nil {
|
||||
// 增加超时时间到30秒,因为通过代理连接远程服务器可能需要更长时间
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
externalTools, err := h.externalMCPMgr.GetAllTools(ctx)
|
||||
if err == nil {
|
||||
externalMCPConfigs := h.externalMCPMgr.GetConfigs()
|
||||
for _, externalTool := range externalTools {
|
||||
var mcpName, actualToolName string
|
||||
if idx := strings.Index(externalTool.Name, "::"); idx > 0 {
|
||||
mcpName = externalTool.Name[:idx]
|
||||
actualToolName = externalTool.Name[idx+2:]
|
||||
} else {
|
||||
continue
|
||||
}
|
||||
|
||||
enabled := false
|
||||
if cfg, exists := externalMCPConfigs[mcpName]; exists {
|
||||
// 首先检查外部MCP是否启用
|
||||
if !cfg.ExternalMCPEnable && !(cfg.Enabled && !cfg.Disabled) {
|
||||
enabled = false // MCP未启用,所有工具都禁用
|
||||
} else {
|
||||
// MCP已启用,检查单个工具的启用状态
|
||||
// 如果ToolEnabled为空或未设置该工具,默认为启用(向后兼容)
|
||||
if cfg.ToolEnabled == nil {
|
||||
enabled = true // 未设置工具状态,默认为启用
|
||||
} else if toolEnabled, exists := cfg.ToolEnabled[actualToolName]; exists {
|
||||
enabled = toolEnabled // 使用配置的工具状态
|
||||
} else {
|
||||
enabled = true // 工具未在配置中,默认为启用
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
client, exists := h.externalMCPMgr.GetClient(mcpName)
|
||||
if !exists || !client.IsConnected() {
|
||||
enabled = false
|
||||
}
|
||||
|
||||
description := externalTool.ShortDescription
|
||||
if description == "" {
|
||||
description = externalTool.Description
|
||||
}
|
||||
if len(description) > 100 {
|
||||
description = description[:100] + "..."
|
||||
}
|
||||
|
||||
tools = append(tools, ToolConfigInfo{
|
||||
Name: actualToolName,
|
||||
Description: description,
|
||||
Enabled: enabled,
|
||||
IsExternal: true,
|
||||
ExternalMCP: mcpName,
|
||||
})
|
||||
}
|
||||
ctx := context.Background()
|
||||
externalTools := h.getExternalMCPTools(ctx)
|
||||
for _, toolInfo := range externalTools {
|
||||
tools = append(tools, toolInfo)
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, GetConfigResponse{
|
||||
OpenAI: h.config.OpenAI,
|
||||
FOFA: h.config.FOFA,
|
||||
MCP: h.config.MCP,
|
||||
Tools: tools,
|
||||
Agent: h.config.Agent,
|
||||
@@ -331,18 +285,10 @@ func (h *ConfigHandler) GetTools(c *gin.Context) {
|
||||
configToolMap[tool.Name] = true
|
||||
toolInfo := ToolConfigInfo{
|
||||
Name: tool.Name,
|
||||
Description: tool.ShortDescription,
|
||||
Description: h.pickToolDescription(tool.ShortDescription, tool.Description),
|
||||
Enabled: tool.Enabled,
|
||||
IsExternal: false,
|
||||
}
|
||||
// 如果没有简短描述,使用详细描述的前100个字符
|
||||
if toolInfo.Description == "" {
|
||||
desc := tool.Description
|
||||
if len(desc) > 100 {
|
||||
desc = desc[:100] + "..."
|
||||
}
|
||||
toolInfo.Description = desc
|
||||
}
|
||||
|
||||
// 根据角色配置标注工具状态
|
||||
if roleName != "" {
|
||||
@@ -394,8 +340,8 @@ func (h *ConfigHandler) GetTools(c *gin.Context) {
|
||||
if description == "" {
|
||||
description = mcpTool.Description
|
||||
}
|
||||
if len(description) > 100 {
|
||||
description = description[:100] + "..."
|
||||
if len(description) > 10000 {
|
||||
description = description[:10000] + "..."
|
||||
}
|
||||
|
||||
toolInfo := ToolConfigInfo{
|
||||
@@ -440,99 +386,43 @@ func (h *ConfigHandler) GetTools(c *gin.Context) {
|
||||
|
||||
// 获取外部MCP工具
|
||||
if h.externalMCPMgr != nil {
|
||||
// 增加超时时间到30秒,因为通过代理连接远程服务器可能需要更长时间
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
// 创建context用于获取外部工具
|
||||
ctx := context.Background()
|
||||
externalTools := h.getExternalMCPTools(ctx)
|
||||
|
||||
externalTools, err := h.externalMCPMgr.GetAllTools(ctx)
|
||||
if err != nil {
|
||||
h.logger.Warn("获取外部MCP工具失败", zap.Error(err))
|
||||
} else {
|
||||
// 获取外部MCP配置,用于判断启用状态
|
||||
externalMCPConfigs := h.externalMCPMgr.GetConfigs()
|
||||
|
||||
for _, externalTool := range externalTools {
|
||||
// 解析工具名称:mcpName::toolName
|
||||
var mcpName, actualToolName string
|
||||
if idx := strings.Index(externalTool.Name, "::"); idx > 0 {
|
||||
mcpName = externalTool.Name[:idx]
|
||||
actualToolName = externalTool.Name[idx+2:]
|
||||
} else {
|
||||
continue // 跳过格式不正确的工具
|
||||
// 应用搜索过滤和角色配置
|
||||
for _, toolInfo := range externalTools {
|
||||
// 搜索过滤
|
||||
if searchTermLower != "" {
|
||||
nameLower := strings.ToLower(toolInfo.Name)
|
||||
descLower := strings.ToLower(toolInfo.Description)
|
||||
if !strings.Contains(nameLower, searchTermLower) && !strings.Contains(descLower, searchTermLower) {
|
||||
continue // 不匹配,跳过
|
||||
}
|
||||
|
||||
// 获取外部工具的启用状态
|
||||
enabled := false
|
||||
if cfg, exists := externalMCPConfigs[mcpName]; exists {
|
||||
// 首先检查外部MCP是否启用
|
||||
if !cfg.ExternalMCPEnable && !(cfg.Enabled && !cfg.Disabled) {
|
||||
enabled = false // MCP未启用,所有工具都禁用
|
||||
} else {
|
||||
// MCP已启用,检查单个工具的启用状态
|
||||
// 如果ToolEnabled为空或未设置该工具,默认为启用(向后兼容)
|
||||
if cfg.ToolEnabled == nil {
|
||||
enabled = true // 未设置工具状态,默认为启用
|
||||
} else if toolEnabled, exists := cfg.ToolEnabled[actualToolName]; exists {
|
||||
enabled = toolEnabled // 使用配置的工具状态
|
||||
} else {
|
||||
enabled = true // 工具未在配置中,默认为启用
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查外部MCP是否已连接
|
||||
client, exists := h.externalMCPMgr.GetClient(mcpName)
|
||||
if !exists || !client.IsConnected() {
|
||||
enabled = false // 未连接时视为禁用
|
||||
}
|
||||
|
||||
description := externalTool.ShortDescription
|
||||
if description == "" {
|
||||
description = externalTool.Description
|
||||
}
|
||||
if len(description) > 100 {
|
||||
description = description[:100] + "..."
|
||||
}
|
||||
|
||||
// 如果有关键词,进行搜索过滤
|
||||
if searchTermLower != "" {
|
||||
nameLower := strings.ToLower(actualToolName)
|
||||
descLower := strings.ToLower(description)
|
||||
if !strings.Contains(nameLower, searchTermLower) && !strings.Contains(descLower, searchTermLower) {
|
||||
continue // 不匹配,跳过
|
||||
}
|
||||
}
|
||||
|
||||
toolInfo := ToolConfigInfo{
|
||||
Name: actualToolName, // 显示实际工具名称,不带前缀
|
||||
Description: description,
|
||||
Enabled: enabled,
|
||||
IsExternal: true,
|
||||
ExternalMCP: mcpName,
|
||||
}
|
||||
|
||||
// 根据角色配置标注工具状态
|
||||
if roleName != "" {
|
||||
if roleUsesAllTools {
|
||||
// 角色使用所有工具,标注启用的工具为role_enabled=true
|
||||
toolInfo.RoleEnabled = &enabled
|
||||
} else {
|
||||
// 角色配置了工具列表,检查工具是否在列表中
|
||||
// 外部工具使用 "mcpName::toolName" 格式作为key
|
||||
externalToolKey := externalTool.Name // 这是 "mcpName::toolName" 格式
|
||||
if roleToolsSet[externalToolKey] {
|
||||
roleEnabled := enabled // 工具必须在角色列表中且本身启用
|
||||
toolInfo.RoleEnabled = &roleEnabled
|
||||
} else {
|
||||
// 不在角色列表中,标记为false
|
||||
roleEnabled := false
|
||||
toolInfo.RoleEnabled = &roleEnabled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allTools = append(allTools, toolInfo)
|
||||
}
|
||||
|
||||
// 根据角色配置标注工具状态
|
||||
if roleName != "" {
|
||||
if roleUsesAllTools {
|
||||
// 角色使用所有工具,标注启用的工具为role_enabled=true
|
||||
roleEnabled := toolInfo.Enabled
|
||||
toolInfo.RoleEnabled = &roleEnabled
|
||||
} else {
|
||||
// 角色配置了工具列表,检查工具是否在列表中
|
||||
// 外部工具使用 "mcpName::toolName" 格式作为key
|
||||
externalToolKey := fmt.Sprintf("%s::%s", toolInfo.ExternalMCP, toolInfo.Name)
|
||||
if roleToolsSet[externalToolKey] {
|
||||
roleEnabled := toolInfo.Enabled // 工具必须在角色列表中且本身启用
|
||||
toolInfo.RoleEnabled = &roleEnabled
|
||||
} else {
|
||||
// 不在角色列表中,标记为false
|
||||
roleEnabled := false
|
||||
toolInfo.RoleEnabled = &roleEnabled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allTools = append(allTools, toolInfo)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -584,6 +474,7 @@ func (h *ConfigHandler) GetTools(c *gin.Context) {
|
||||
// UpdateConfigRequest 更新配置请求
|
||||
type UpdateConfigRequest struct {
|
||||
OpenAI *config.OpenAIConfig `json:"openai,omitempty"`
|
||||
FOFA *config.FofaConfig `json:"fofa,omitempty"`
|
||||
MCP *config.MCPConfig `json:"mcp,omitempty"`
|
||||
Tools []ToolEnableStatus `json:"tools,omitempty"`
|
||||
Agent *config.AgentConfig `json:"agent,omitempty"`
|
||||
@@ -618,6 +509,12 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
|
||||
)
|
||||
}
|
||||
|
||||
// 更新FOFA配置
|
||||
if req.FOFA != nil {
|
||||
h.config.FOFA = *req.FOFA
|
||||
h.logger.Info("更新FOFA配置", zap.String("email", h.config.FOFA.Email))
|
||||
}
|
||||
|
||||
// 更新MCP配置
|
||||
if req.MCP != nil {
|
||||
h.config.MCP = *req.MCP
|
||||
@@ -869,6 +766,16 @@ func (h *ConfigHandler) ApplyConfig(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 重新注册Skills工具(内置工具,必须注册)
|
||||
if h.skillsToolRegistrar != nil {
|
||||
h.logger.Info("重新注册Skills工具")
|
||||
if err := h.skillsToolRegistrar(); err != nil {
|
||||
h.logger.Error("重新注册Skills工具失败", zap.Error(err))
|
||||
} else {
|
||||
h.logger.Info("Skills工具已重新注册")
|
||||
}
|
||||
}
|
||||
|
||||
// 如果知识库启用,重新注册知识库工具
|
||||
if h.config.Knowledge.Enabled && h.knowledgeToolRegistrar != nil {
|
||||
h.logger.Info("重新注册知识库工具")
|
||||
@@ -947,6 +854,7 @@ func (h *ConfigHandler) saveConfig() error {
|
||||
updateAgentConfig(root, h.config.Agent.MaxIterations)
|
||||
updateMCPConfig(root, h.config.MCP)
|
||||
updateOpenAIConfig(root, h.config.OpenAI)
|
||||
updateFOFAConfig(root, h.config.FOFA)
|
||||
updateKnowledgeConfig(root, h.config.Knowledge)
|
||||
// 更新外部MCP配置(使用external_mcp.go中的函数,同一包中可直接调用)
|
||||
// 读取原始配置以保持向后兼容
|
||||
@@ -1091,6 +999,14 @@ func updateOpenAIConfig(doc *yaml.Node, cfg config.OpenAIConfig) {
|
||||
setStringInMap(openaiNode, "model", cfg.Model)
|
||||
}
|
||||
|
||||
func updateFOFAConfig(doc *yaml.Node, cfg config.FofaConfig) {
|
||||
root := doc.Content[0]
|
||||
fofaNode := ensureMap(root, "fofa")
|
||||
setStringInMap(fofaNode, "base_url", cfg.BaseURL)
|
||||
setStringInMap(fofaNode, "email", cfg.Email)
|
||||
setStringInMap(fofaNode, "api_key", cfg.APIKey)
|
||||
}
|
||||
|
||||
func updateKnowledgeConfig(doc *yaml.Node, cfg config.KnowledgeConfig) {
|
||||
root := doc.Content[0]
|
||||
knowledgeNode := ensureMap(root, "knowledge")
|
||||
@@ -1238,3 +1154,114 @@ func setFloatInMap(mapNode *yaml.Node, key string, value float64) {
|
||||
valueNode.Value = fmt.Sprintf("%g", value)
|
||||
}
|
||||
}
|
||||
|
||||
// getExternalMCPTools 获取外部MCP工具列表(公共方法)
|
||||
// 返回 ToolConfigInfo 列表,已处理启用状态和描述信息
|
||||
func (h *ConfigHandler) getExternalMCPTools(ctx context.Context) []ToolConfigInfo {
|
||||
var result []ToolConfigInfo
|
||||
|
||||
if h.externalMCPMgr == nil {
|
||||
return result
|
||||
}
|
||||
|
||||
// 使用较短的超时时间(5秒)进行快速失败,避免阻塞页面加载
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
externalTools, err := h.externalMCPMgr.GetAllTools(timeoutCtx)
|
||||
if err != nil {
|
||||
// 记录警告但不阻塞,继续返回已缓存的工具(如果有)
|
||||
h.logger.Warn("获取外部MCP工具失败(可能连接断开),尝试返回缓存的工具",
|
||||
zap.Error(err),
|
||||
zap.String("hint", "如果外部MCP工具未显示,请检查连接状态或点击刷新按钮"),
|
||||
)
|
||||
}
|
||||
|
||||
// 如果获取到了工具(即使有错误),继续处理
|
||||
if len(externalTools) == 0 {
|
||||
return result
|
||||
}
|
||||
|
||||
externalMCPConfigs := h.externalMCPMgr.GetConfigs()
|
||||
|
||||
for _, externalTool := range externalTools {
|
||||
// 解析工具名称:mcpName::toolName
|
||||
mcpName, actualToolName := h.parseExternalToolName(externalTool.Name)
|
||||
if mcpName == "" || actualToolName == "" {
|
||||
continue // 跳过格式不正确的工具
|
||||
}
|
||||
|
||||
// 计算启用状态
|
||||
enabled := h.calculateExternalToolEnabled(mcpName, actualToolName, externalMCPConfigs)
|
||||
|
||||
// 处理描述信息
|
||||
description := h.pickToolDescription(externalTool.ShortDescription, externalTool.Description)
|
||||
|
||||
result = append(result, ToolConfigInfo{
|
||||
Name: actualToolName,
|
||||
Description: description,
|
||||
Enabled: enabled,
|
||||
IsExternal: true,
|
||||
ExternalMCP: mcpName,
|
||||
})
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// parseExternalToolName 解析外部工具名称(格式:mcpName::toolName)
|
||||
func (h *ConfigHandler) parseExternalToolName(fullName string) (mcpName, toolName string) {
|
||||
idx := strings.Index(fullName, "::")
|
||||
if idx > 0 {
|
||||
return fullName[:idx], fullName[idx+2:]
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
// calculateExternalToolEnabled 计算外部工具的启用状态
|
||||
func (h *ConfigHandler) calculateExternalToolEnabled(mcpName, toolName string, configs map[string]config.ExternalMCPServerConfig) bool {
|
||||
cfg, exists := configs[mcpName]
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
|
||||
// 首先检查外部MCP是否启用
|
||||
if !cfg.ExternalMCPEnable && !(cfg.Enabled && !cfg.Disabled) {
|
||||
return false // MCP未启用,所有工具都禁用
|
||||
}
|
||||
|
||||
// MCP已启用,检查单个工具的启用状态
|
||||
// 如果ToolEnabled为空或未设置该工具,默认为启用(向后兼容)
|
||||
if cfg.ToolEnabled == nil {
|
||||
// 未设置工具状态,默认为启用
|
||||
} else if toolEnabled, exists := cfg.ToolEnabled[toolName]; exists {
|
||||
// 使用配置的工具状态
|
||||
if !toolEnabled {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// 工具未在配置中,默认为启用
|
||||
|
||||
// 最后检查外部MCP是否已连接
|
||||
client, exists := h.externalMCPMgr.GetClient(mcpName)
|
||||
if !exists || !client.IsConnected() {
|
||||
return false // 未连接时视为禁用
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// pickToolDescription 根据 security.tool_description_mode 选择 short 或 full 描述并限制长度
|
||||
func (h *ConfigHandler) pickToolDescription(shortDesc, fullDesc string) string {
|
||||
useFull := strings.TrimSpace(strings.ToLower(h.config.Security.ToolDescriptionMode)) == "full"
|
||||
description := shortDesc
|
||||
if useFull {
|
||||
description = fullDesc
|
||||
} else if description == "" {
|
||||
description = fullDesc
|
||||
}
|
||||
if len(description) > 10000 {
|
||||
description = description[:10000] + "..."
|
||||
}
|
||||
return description
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"gopkg.in/yaml.v3"
|
||||
@@ -36,12 +37,12 @@ func NewExternalMCPHandler(manager *mcp.ExternalMCPManager, cfg *config.Config,
|
||||
func (h *ExternalMCPHandler) GetExternalMCPs(c *gin.Context) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
|
||||
configs := h.manager.GetConfigs()
|
||||
|
||||
|
||||
// 获取所有外部MCP的工具数量
|
||||
toolCounts := h.manager.GetToolCounts()
|
||||
|
||||
|
||||
// 转换为响应格式
|
||||
result := make(map[string]ExternalMCPResponse)
|
||||
for name, cfg := range configs {
|
||||
@@ -54,13 +55,13 @@ func (h *ExternalMCPHandler) GetExternalMCPs(c *gin.Context) {
|
||||
} else {
|
||||
status = "disabled"
|
||||
}
|
||||
|
||||
|
||||
toolCount := toolCounts[name]
|
||||
errorMsg := ""
|
||||
if status == "error" {
|
||||
errorMsg = h.manager.GetError(name)
|
||||
}
|
||||
|
||||
|
||||
result[name] = ExternalMCPResponse{
|
||||
Config: cfg,
|
||||
Status: status,
|
||||
@@ -68,7 +69,7 @@ func (h *ExternalMCPHandler) GetExternalMCPs(c *gin.Context) {
|
||||
Error: errorMsg,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"servers": result,
|
||||
"stats": h.manager.GetStats(),
|
||||
@@ -78,17 +79,17 @@ func (h *ExternalMCPHandler) GetExternalMCPs(c *gin.Context) {
|
||||
// GetExternalMCP 获取单个外部MCP配置
|
||||
func (h *ExternalMCPHandler) GetExternalMCP(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
|
||||
|
||||
configs := h.manager.GetConfigs()
|
||||
cfg, exists := configs[name]
|
||||
if !exists {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "外部MCP配置不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
client, clientExists := h.manager.GetClient(name)
|
||||
status := "disconnected"
|
||||
if clientExists {
|
||||
@@ -98,7 +99,7 @@ func (h *ExternalMCPHandler) GetExternalMCP(c *gin.Context) {
|
||||
} else {
|
||||
status = "disabled"
|
||||
}
|
||||
|
||||
|
||||
// 获取工具数量
|
||||
toolCount := 0
|
||||
if clientExists && client.IsConnected() {
|
||||
@@ -106,13 +107,13 @@ func (h *ExternalMCPHandler) GetExternalMCP(c *gin.Context) {
|
||||
toolCount = count
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 获取错误信息
|
||||
errorMsg := ""
|
||||
if status == "error" {
|
||||
errorMsg = h.manager.GetError(name)
|
||||
}
|
||||
|
||||
|
||||
c.JSON(http.StatusOK, ExternalMCPResponse{
|
||||
Config: cfg,
|
||||
Status: status,
|
||||
@@ -128,38 +129,38 @@ func (h *ExternalMCPHandler) AddOrUpdateExternalMCP(c *gin.Context) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
name := c.Param("name")
|
||||
if name == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "名称不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 验证配置
|
||||
if err := h.validateConfig(req.Config); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
|
||||
// 添加或更新配置
|
||||
if err := h.manager.AddOrUpdateConfig(name, req.Config); err != nil {
|
||||
h.logger.Error("添加或更新外部MCP配置失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "添加或更新配置失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 更新内存中的配置
|
||||
if h.config.ExternalMCP.Servers == nil {
|
||||
h.config.ExternalMCP.Servers = make(map[string]config.ExternalMCPServerConfig)
|
||||
}
|
||||
|
||||
|
||||
// 如果用户提供了 disabled 或 enabled 字段,保留它们以保持向后兼容
|
||||
// 同时将值迁移到 external_mcp_enable
|
||||
cfg := req.Config
|
||||
|
||||
|
||||
if req.Config.Disabled {
|
||||
// 用户设置了 disabled: true
|
||||
cfg.ExternalMCPEnable = false
|
||||
@@ -185,16 +186,16 @@ func (h *ExternalMCPHandler) AddOrUpdateExternalMCP(c *gin.Context) {
|
||||
cfg.Enabled = true
|
||||
cfg.Disabled = false
|
||||
}
|
||||
|
||||
|
||||
h.config.ExternalMCP.Servers[name] = cfg
|
||||
|
||||
|
||||
// 保存到配置文件
|
||||
if err := h.saveConfig(); err != nil {
|
||||
h.logger.Error("保存配置失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存配置失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
h.logger.Info("外部MCP配置已更新", zap.String("name", name))
|
||||
c.JSON(http.StatusOK, gin.H{"message": "配置已更新"})
|
||||
}
|
||||
@@ -202,28 +203,28 @@ func (h *ExternalMCPHandler) AddOrUpdateExternalMCP(c *gin.Context) {
|
||||
// DeleteExternalMCP 删除外部MCP配置
|
||||
func (h *ExternalMCPHandler) DeleteExternalMCP(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
|
||||
// 移除配置
|
||||
if err := h.manager.RemoveConfig(name); err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "配置不存在"})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 从内存配置中删除
|
||||
if h.config.ExternalMCP.Servers != nil {
|
||||
delete(h.config.ExternalMCP.Servers, name)
|
||||
}
|
||||
|
||||
|
||||
// 保存到配置文件
|
||||
if err := h.saveConfig(); err != nil {
|
||||
h.logger.Error("保存配置失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存配置失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
h.logger.Info("外部MCP配置已删除", zap.String("name", name))
|
||||
c.JSON(http.StatusOK, gin.H{"message": "配置已删除"})
|
||||
}
|
||||
@@ -231,10 +232,10 @@ func (h *ExternalMCPHandler) DeleteExternalMCP(c *gin.Context) {
|
||||
// StartExternalMCP 启动外部MCP
|
||||
func (h *ExternalMCPHandler) StartExternalMCP(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
|
||||
// 更新配置为启用
|
||||
if h.config.ExternalMCP.Servers == nil {
|
||||
h.config.ExternalMCP.Servers = make(map[string]config.ExternalMCPServerConfig)
|
||||
@@ -242,32 +243,32 @@ func (h *ExternalMCPHandler) StartExternalMCP(c *gin.Context) {
|
||||
cfg := h.config.ExternalMCP.Servers[name]
|
||||
cfg.ExternalMCPEnable = true
|
||||
h.config.ExternalMCP.Servers[name] = cfg
|
||||
|
||||
|
||||
// 保存到配置文件
|
||||
if err := h.saveConfig(); err != nil {
|
||||
h.logger.Error("保存配置失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存配置失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 启动客户端(立即创建客户端并设置状态为connecting,实际连接在后台进行)
|
||||
h.logger.Info("开始启动外部MCP", zap.String("name", name))
|
||||
if err := h.manager.StartClient(name); err != nil {
|
||||
h.logger.Error("启动外部MCP失败", zap.String("name", name), zap.Error(err))
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": err.Error(),
|
||||
"error": err.Error(),
|
||||
"status": "error",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 获取客户端状态(应该是connecting)
|
||||
client, exists := h.manager.GetClient(name)
|
||||
status := "connecting"
|
||||
if exists {
|
||||
status = client.GetStatus()
|
||||
}
|
||||
|
||||
|
||||
// 立即返回,不等待连接完成
|
||||
// 客户端会在后台异步连接,用户可以通过状态查询接口查看连接状态
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -279,16 +280,16 @@ func (h *ExternalMCPHandler) StartExternalMCP(c *gin.Context) {
|
||||
// StopExternalMCP 停止外部MCP
|
||||
func (h *ExternalMCPHandler) StopExternalMCP(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
|
||||
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
|
||||
|
||||
// 停止客户端
|
||||
if err := h.manager.StopClient(name); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 更新配置
|
||||
if h.config.ExternalMCP.Servers == nil {
|
||||
h.config.ExternalMCP.Servers = make(map[string]config.ExternalMCPServerConfig)
|
||||
@@ -296,14 +297,14 @@ func (h *ExternalMCPHandler) StopExternalMCP(c *gin.Context) {
|
||||
cfg := h.config.ExternalMCP.Servers[name]
|
||||
cfg.ExternalMCPEnable = false
|
||||
h.config.ExternalMCP.Servers[name] = cfg
|
||||
|
||||
|
||||
// 保存到配置文件
|
||||
if err := h.saveConfig(); err != nil {
|
||||
h.logger.Error("保存配置失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存配置失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
h.logger.Info("外部MCP已停止", zap.String("name", name))
|
||||
c.JSON(http.StatusOK, gin.H{"message": "外部MCP已停止"})
|
||||
}
|
||||
@@ -327,7 +328,7 @@ func (h *ExternalMCPHandler) validateConfig(cfg config.ExternalMCPServerConfig)
|
||||
return fmt.Errorf("需要指定command(stdio模式)或url(http/sse模式)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
switch transport {
|
||||
case "http":
|
||||
if cfg.URL == "" {
|
||||
@@ -344,7 +345,7 @@ func (h *ExternalMCPHandler) validateConfig(cfg config.ExternalMCPServerConfig)
|
||||
default:
|
||||
return fmt.Errorf("不支持的传输模式: %s,支持的模式: http, stdio, sse", transport)
|
||||
}
|
||||
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -428,17 +429,17 @@ func updateExternalMCPConfig(doc *yaml.Node, cfg config.ExternalMCPConfig, origi
|
||||
root := doc.Content[0]
|
||||
externalMCPNode := ensureMap(root, "external_mcp")
|
||||
serversNode := ensureMap(externalMCPNode, "servers")
|
||||
|
||||
|
||||
// 清空现有服务器配置
|
||||
serversNode.Content = nil
|
||||
|
||||
|
||||
// 添加新的服务器配置
|
||||
for name, serverCfg := range cfg.Servers {
|
||||
// 添加服务器名称键
|
||||
nameNode := &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: name}
|
||||
serverNode := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
serversNode.Content = append(serversNode.Content, nameNode, serverNode)
|
||||
|
||||
|
||||
// 设置服务器配置字段
|
||||
if serverCfg.Command != "" {
|
||||
setStringInMap(serverNode, "command", serverCfg.Command)
|
||||
@@ -459,6 +460,13 @@ func updateExternalMCPConfig(doc *yaml.Node, cfg config.ExternalMCPConfig, origi
|
||||
if serverCfg.URL != "" {
|
||||
setStringInMap(serverNode, "url", serverCfg.URL)
|
||||
}
|
||||
// 保存 headers 字段(HTTP/SSE 请求头)
|
||||
if serverCfg.Headers != nil && len(serverCfg.Headers) > 0 {
|
||||
headersNode := ensureMap(serverNode, "headers")
|
||||
for k, v := range serverCfg.Headers {
|
||||
setStringInMap(headersNode, k, v)
|
||||
}
|
||||
}
|
||||
if serverCfg.Description != "" {
|
||||
setStringInMap(serverNode, "description", serverCfg.Description)
|
||||
}
|
||||
@@ -476,7 +484,7 @@ func updateExternalMCPConfig(doc *yaml.Node, cfg config.ExternalMCPConfig, origi
|
||||
}
|
||||
// 保留旧的 enabled/disabled 字段以保持向后兼容
|
||||
originalFields, hasOriginal := originalConfigs[name]
|
||||
|
||||
|
||||
// 如果原始配置中有 enabled 字段,保留它
|
||||
if hasOriginal {
|
||||
if enabledVal, hasEnabled := originalFields["enabled"]; hasEnabled {
|
||||
@@ -494,7 +502,7 @@ func updateExternalMCPConfig(doc *yaml.Node, cfg config.ExternalMCPConfig, origi
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果用户在当前请求中明确设置了这些字段,也保存它们
|
||||
if serverCfg.Enabled {
|
||||
setBoolInMap(serverNode, "enabled", serverCfg.Enabled)
|
||||
@@ -528,8 +536,7 @@ type AddOrUpdateExternalMCPRequest struct {
|
||||
// ExternalMCPResponse 外部MCP响应
|
||||
type ExternalMCPResponse struct {
|
||||
Config config.ExternalMCPServerConfig `json:"config"`
|
||||
Status string `json:"status"` // "connected", "disconnected", "disabled", "error", "connecting"
|
||||
ToolCount int `json:"tool_count"` // 工具数量
|
||||
Status string `json:"status"` // "connected", "disconnected", "disabled", "error", "connecting"
|
||||
ToolCount int `json:"tool_count"` // 工具数量
|
||||
Error string `json:"error,omitempty"` // 错误信息(仅在status为error时存在)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
"cyberstrike-ai/internal/mcp"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -18,7 +19,7 @@ import (
|
||||
func setupTestRouter() (*gin.Engine, *ExternalMCPHandler, string) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
|
||||
|
||||
// 创建临时配置文件
|
||||
tmpFile, err := os.CreateTemp("", "test-config-*.yaml")
|
||||
if err != nil {
|
||||
@@ -27,7 +28,7 @@ func setupTestRouter() (*gin.Engine, *ExternalMCPHandler, string) {
|
||||
tmpFile.WriteString("server:\n host: 0.0.0.0\n port: 8080\n")
|
||||
tmpFile.Close()
|
||||
configPath := tmpFile.Name()
|
||||
|
||||
|
||||
logger := zap.NewNop()
|
||||
manager := mcp.NewExternalMCPManager(logger)
|
||||
cfg := &config.Config{
|
||||
@@ -35,9 +36,9 @@ func setupTestRouter() (*gin.Engine, *ExternalMCPHandler, string) {
|
||||
Servers: make(map[string]config.ExternalMCPServerConfig),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
handler := NewExternalMCPHandler(manager, cfg, configPath, logger)
|
||||
|
||||
|
||||
api := router.Group("/api")
|
||||
api.GET("/external-mcp", handler.GetExternalMCPs)
|
||||
api.GET("/external-mcp/stats", handler.GetExternalMCPStats)
|
||||
@@ -46,7 +47,7 @@ func setupTestRouter() (*gin.Engine, *ExternalMCPHandler, string) {
|
||||
api.DELETE("/external-mcp/:name", handler.DeleteExternalMCP)
|
||||
api.POST("/external-mcp/:name/start", handler.StartExternalMCP)
|
||||
api.POST("/external-mcp/:name/stop", handler.StopExternalMCP)
|
||||
|
||||
|
||||
return router, handler, configPath
|
||||
}
|
||||
|
||||
@@ -58,7 +59,7 @@ func cleanupTestConfig(configPath string) {
|
||||
func TestExternalMCPHandler_AddOrUpdateExternalMCP_Stdio(t *testing.T) {
|
||||
router, _, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
// 测试添加stdio模式的配置
|
||||
configJSON := `{
|
||||
"command": "python3",
|
||||
@@ -67,41 +68,41 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_Stdio(t *testing.T) {
|
||||
"timeout": 300,
|
||||
"enabled": true
|
||||
}`
|
||||
|
||||
|
||||
var configObj config.ExternalMCPServerConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &configObj); err != nil {
|
||||
t.Fatalf("解析配置JSON失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
reqBody := AddOrUpdateExternalMCPRequest{
|
||||
Config: configObj,
|
||||
}
|
||||
|
||||
|
||||
body, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/test-stdio", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
// 验证配置已添加
|
||||
req2 := httptest.NewRequest("GET", "/api/external-mcp/test-stdio", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(w2, req2)
|
||||
|
||||
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var response ExternalMCPResponse
|
||||
if err := json.Unmarshal(w2.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
if response.Config.Command != "python3" {
|
||||
t.Errorf("期望command为python3,实际%s", response.Config.Command)
|
||||
}
|
||||
@@ -122,48 +123,48 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_Stdio(t *testing.T) {
|
||||
func TestExternalMCPHandler_AddOrUpdateExternalMCP_HTTP(t *testing.T) {
|
||||
router, _, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
// 测试添加HTTP模式的配置
|
||||
configJSON := `{
|
||||
"transport": "http",
|
||||
"url": "http://127.0.0.1:8081/mcp",
|
||||
"enabled": true
|
||||
}`
|
||||
|
||||
|
||||
var configObj config.ExternalMCPServerConfig
|
||||
if err := json.Unmarshal([]byte(configJSON), &configObj); err != nil {
|
||||
t.Fatalf("解析配置JSON失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
reqBody := AddOrUpdateExternalMCPRequest{
|
||||
Config: configObj,
|
||||
}
|
||||
|
||||
|
||||
body, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/test-http", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
// 验证配置已添加
|
||||
req2 := httptest.NewRequest("GET", "/api/external-mcp/test-http", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(w2, req2)
|
||||
|
||||
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var response ExternalMCPResponse
|
||||
if err := json.Unmarshal(w2.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
if response.Config.Transport != "http" {
|
||||
t.Errorf("期望transport为http,实际%s", response.Config.Transport)
|
||||
}
|
||||
@@ -178,7 +179,7 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_HTTP(t *testing.T) {
|
||||
func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidConfig(t *testing.T) {
|
||||
router, _, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
configJSON string
|
||||
@@ -187,7 +188,7 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidConfig(t *testing.T) {
|
||||
{
|
||||
name: "缺少command和url",
|
||||
configJSON: `{"enabled": true}`,
|
||||
expectedErr: "需要指定command(stdio模式)或url(http模式)",
|
||||
expectedErr: "需要指定command(stdio模式)或url(http/sse模式)",
|
||||
},
|
||||
{
|
||||
name: "stdio模式缺少command",
|
||||
@@ -205,34 +206,34 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidConfig(t *testing.T) {
|
||||
expectedErr: "不支持的传输模式",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var configObj config.ExternalMCPServerConfig
|
||||
if err := json.Unmarshal([]byte(tc.configJSON), &configObj); err != nil {
|
||||
t.Fatalf("解析配置JSON失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
reqBody := AddOrUpdateExternalMCPRequest{
|
||||
Config: configObj,
|
||||
}
|
||||
|
||||
|
||||
body, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/test-invalid", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("期望状态码400,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var response map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
errorMsg := response["error"].(string)
|
||||
// 对于stdio模式缺少command的情况,错误信息可能略有不同
|
||||
if tc.name == "stdio模式缺少command" {
|
||||
@@ -249,28 +250,28 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidConfig(t *testing.T) {
|
||||
func TestExternalMCPHandler_DeleteExternalMCP(t *testing.T) {
|
||||
router, handler, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
// 先添加一个配置
|
||||
configObj := config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
Enabled: true,
|
||||
}
|
||||
handler.manager.AddOrUpdateConfig("test-delete", configObj)
|
||||
|
||||
|
||||
// 删除配置
|
||||
req := httptest.NewRequest("DELETE", "/api/external-mcp/test-delete", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
// 验证配置已删除
|
||||
req2 := httptest.NewRequest("GET", "/api/external-mcp/test-delete", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(w2, req2)
|
||||
|
||||
|
||||
if w2.Code != http.StatusNotFound {
|
||||
t.Errorf("期望状态码404,实际%d: %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
@@ -278,7 +279,7 @@ func TestExternalMCPHandler_DeleteExternalMCP(t *testing.T) {
|
||||
|
||||
func TestExternalMCPHandler_GetExternalMCPs(t *testing.T) {
|
||||
router, handler, _ := setupTestRouter()
|
||||
|
||||
|
||||
// 添加多个配置
|
||||
handler.manager.AddOrUpdateConfig("test1", config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
@@ -288,20 +289,20 @@ func TestExternalMCPHandler_GetExternalMCPs(t *testing.T) {
|
||||
URL: "http://127.0.0.1:8081/mcp",
|
||||
Enabled: false,
|
||||
})
|
||||
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/external-mcp", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var response map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
servers := response["servers"].(map[string]interface{})
|
||||
if len(servers) != 2 {
|
||||
t.Errorf("期望2个服务器,实际%d", len(servers))
|
||||
@@ -312,7 +313,7 @@ func TestExternalMCPHandler_GetExternalMCPs(t *testing.T) {
|
||||
if _, ok := servers["test2"]; !ok {
|
||||
t.Error("期望包含test2")
|
||||
}
|
||||
|
||||
|
||||
stats := response["stats"].(map[string]interface{})
|
||||
if int(stats["total"].(float64)) != 2 {
|
||||
t.Errorf("期望总数为2,实际%d", int(stats["total"].(float64)))
|
||||
@@ -321,7 +322,7 @@ func TestExternalMCPHandler_GetExternalMCPs(t *testing.T) {
|
||||
|
||||
func TestExternalMCPHandler_GetExternalMCPStats(t *testing.T) {
|
||||
router, handler, _ := setupTestRouter()
|
||||
|
||||
|
||||
// 添加配置
|
||||
handler.manager.AddOrUpdateConfig("enabled1", config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
@@ -336,20 +337,20 @@ func TestExternalMCPHandler_GetExternalMCPStats(t *testing.T) {
|
||||
Enabled: false,
|
||||
Disabled: true,
|
||||
})
|
||||
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/external-mcp/stats", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var stats map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &stats); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
if int(stats["total"].(float64)) != 3 {
|
||||
t.Errorf("期望总数为3,实际%d", int(stats["total"].(float64)))
|
||||
}
|
||||
@@ -364,19 +365,19 @@ func TestExternalMCPHandler_GetExternalMCPStats(t *testing.T) {
|
||||
func TestExternalMCPHandler_StartStopExternalMCP(t *testing.T) {
|
||||
router, handler, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
// 添加一个禁用的配置
|
||||
handler.manager.AddOrUpdateConfig("test-start-stop", config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
Enabled: false,
|
||||
Disabled: true,
|
||||
})
|
||||
|
||||
|
||||
// 测试启动(可能会失败,因为没有真实的服务器)
|
||||
req := httptest.NewRequest("POST", "/api/external-mcp/test-start-stop/start", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
// 启动可能会失败,但应该返回合理的状态码
|
||||
if w.Code != http.StatusOK {
|
||||
// 如果启动失败,应该是400或500
|
||||
@@ -384,12 +385,12 @@ func TestExternalMCPHandler_StartStopExternalMCP(t *testing.T) {
|
||||
t.Errorf("期望状态码200/400/500,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 测试停止
|
||||
req2 := httptest.NewRequest("POST", "/api/external-mcp/test-start-stop/stop", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(w2, req2)
|
||||
|
||||
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Errorf("期望状态码200,实际%d: %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
@@ -397,11 +398,11 @@ func TestExternalMCPHandler_StartStopExternalMCP(t *testing.T) {
|
||||
|
||||
func TestExternalMCPHandler_GetExternalMCP_NotFound(t *testing.T) {
|
||||
router, _, _ := setupTestRouter()
|
||||
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/external-mcp/nonexistent", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("期望状态码404,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
@@ -410,11 +411,11 @@ func TestExternalMCPHandler_GetExternalMCP_NotFound(t *testing.T) {
|
||||
func TestExternalMCPHandler_DeleteExternalMCP_NotFound(t *testing.T) {
|
||||
router, _, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
req := httptest.NewRequest("DELETE", "/api/external-mcp/nonexistent", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
// 删除不存在的配置可能返回200(幂等操作)或404,都是合理的
|
||||
if w.Code != http.StatusNotFound && w.Code != http.StatusOK {
|
||||
t.Errorf("期望状态码404或200,实际%d: %s", w.Code, w.Body.String())
|
||||
@@ -423,23 +424,23 @@ func TestExternalMCPHandler_DeleteExternalMCP_NotFound(t *testing.T) {
|
||||
|
||||
func TestExternalMCPHandler_AddOrUpdateExternalMCP_EmptyName(t *testing.T) {
|
||||
router, _, _ := setupTestRouter()
|
||||
|
||||
|
||||
configObj := config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
Enabled: true,
|
||||
}
|
||||
|
||||
|
||||
reqBody := AddOrUpdateExternalMCPRequest{
|
||||
Config: configObj,
|
||||
}
|
||||
|
||||
|
||||
body, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
// 空名称应该返回404或400
|
||||
if w.Code != http.StatusNotFound && w.Code != http.StatusBadRequest {
|
||||
t.Errorf("期望状态码404或400,实际%d: %s", w.Code, w.Body.String())
|
||||
@@ -448,15 +449,15 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_EmptyName(t *testing.T) {
|
||||
|
||||
func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidJSON(t *testing.T) {
|
||||
router, _, _ := setupTestRouter()
|
||||
|
||||
|
||||
// 发送无效的JSON
|
||||
body := []byte(`{"config": invalid json}`)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/test", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("期望状态码400,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
@@ -465,49 +466,49 @@ func TestExternalMCPHandler_AddOrUpdateExternalMCP_InvalidJSON(t *testing.T) {
|
||||
func TestExternalMCPHandler_UpdateExistingConfig(t *testing.T) {
|
||||
router, handler, configPath := setupTestRouter()
|
||||
defer cleanupTestConfig(configPath)
|
||||
|
||||
|
||||
// 先添加配置
|
||||
config1 := config.ExternalMCPServerConfig{
|
||||
Command: "python3",
|
||||
Enabled: true,
|
||||
}
|
||||
handler.manager.AddOrUpdateConfig("test-update", config1)
|
||||
|
||||
|
||||
// 更新配置
|
||||
config2 := config.ExternalMCPServerConfig{
|
||||
URL: "http://127.0.0.1:8081/mcp",
|
||||
Enabled: true,
|
||||
}
|
||||
|
||||
|
||||
reqBody := AddOrUpdateExternalMCPRequest{
|
||||
Config: config2,
|
||||
}
|
||||
|
||||
|
||||
body, _ := json.Marshal(reqBody)
|
||||
req := httptest.NewRequest("PUT", "/api/external-mcp/test-update", bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
|
||||
// 验证配置已更新
|
||||
req2 := httptest.NewRequest("GET", "/api/external-mcp/test-update", nil)
|
||||
w2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(w2, req2)
|
||||
|
||||
|
||||
if w2.Code != http.StatusOK {
|
||||
t.Fatalf("期望状态码200,实际%d: %s", w2.Code, w2.Body.String())
|
||||
}
|
||||
|
||||
|
||||
var response ExternalMCPResponse
|
||||
if err := json.Unmarshal(w2.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("解析响应失败: %v", err)
|
||||
}
|
||||
|
||||
|
||||
if response.Config.URL != "http://127.0.0.1:8081/mcp" {
|
||||
t.Errorf("期望url为'http://127.0.0.1:8081/mcp',实际%s", response.Config.URL)
|
||||
}
|
||||
@@ -515,4 +516,3 @@ func TestExternalMCPHandler_UpdateExistingConfig(t *testing.T) {
|
||||
t.Errorf("期望command为空,实际%s", response.Config.Command)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
openaiClient "cyberstrike-ai/internal/openai"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type FofaHandler struct {
|
||||
cfg *config.Config
|
||||
logger *zap.Logger
|
||||
client *http.Client
|
||||
openAIClient *openaiClient.Client
|
||||
}
|
||||
|
||||
func NewFofaHandler(cfg *config.Config, logger *zap.Logger) *FofaHandler {
|
||||
// LLM 请求通常比 FOFA 查询更慢一点,单独给一个更宽松的超时。
|
||||
llmHTTPClient := &http.Client{Timeout: 2 * time.Minute}
|
||||
var llmCfg *config.OpenAIConfig
|
||||
if cfg != nil {
|
||||
llmCfg = &cfg.OpenAI
|
||||
}
|
||||
return &FofaHandler{
|
||||
cfg: cfg,
|
||||
logger: logger,
|
||||
client: &http.Client{Timeout: 30 * time.Second},
|
||||
openAIClient: openaiClient.NewClient(llmCfg, llmHTTPClient, logger),
|
||||
}
|
||||
}
|
||||
|
||||
type fofaSearchRequest struct {
|
||||
Query string `json:"query" binding:"required"`
|
||||
Size int `json:"size,omitempty"`
|
||||
Page int `json:"page,omitempty"`
|
||||
Fields string `json:"fields,omitempty"`
|
||||
Full bool `json:"full,omitempty"`
|
||||
}
|
||||
|
||||
type fofaParseRequest struct {
|
||||
Text string `json:"text" binding:"required"`
|
||||
}
|
||||
|
||||
type fofaParseResponse struct {
|
||||
Query string `json:"query"`
|
||||
Explanation string `json:"explanation,omitempty"`
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
}
|
||||
|
||||
type fofaAPIResponse struct {
|
||||
Error bool `json:"error"`
|
||||
ErrMsg string `json:"errmsg"`
|
||||
Size int `json:"size"`
|
||||
Page int `json:"page"`
|
||||
Total int `json:"total"`
|
||||
Mode string `json:"mode"`
|
||||
Query string `json:"query"`
|
||||
Results [][]interface{} `json:"results"`
|
||||
}
|
||||
|
||||
type fofaSearchResponse struct {
|
||||
Query string `json:"query"`
|
||||
Size int `json:"size"`
|
||||
Page int `json:"page"`
|
||||
Total int `json:"total"`
|
||||
Fields []string `json:"fields"`
|
||||
ResultsCount int `json:"results_count"`
|
||||
Results []map[string]interface{} `json:"results"`
|
||||
}
|
||||
|
||||
func (h *FofaHandler) resolveCredentials() (email, apiKey string) {
|
||||
// 优先环境变量(便于容器部署),其次配置文件
|
||||
email = strings.TrimSpace(os.Getenv("FOFA_EMAIL"))
|
||||
apiKey = strings.TrimSpace(os.Getenv("FOFA_API_KEY"))
|
||||
if email != "" && apiKey != "" {
|
||||
return email, apiKey
|
||||
}
|
||||
if h.cfg != nil {
|
||||
if email == "" {
|
||||
email = strings.TrimSpace(h.cfg.FOFA.Email)
|
||||
}
|
||||
if apiKey == "" {
|
||||
apiKey = strings.TrimSpace(h.cfg.FOFA.APIKey)
|
||||
}
|
||||
}
|
||||
return email, apiKey
|
||||
}
|
||||
|
||||
func (h *FofaHandler) resolveBaseURL() string {
|
||||
if h.cfg != nil {
|
||||
if v := strings.TrimSpace(h.cfg.FOFA.BaseURL); v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return "https://fofa.info/api/v1/search/all"
|
||||
}
|
||||
|
||||
// ParseNaturalLanguage 将自然语言解析为 FOFA 查询语法(仅生成,不执行查询)
|
||||
func (h *FofaHandler) ParseNaturalLanguage(c *gin.Context) {
|
||||
var req fofaParseRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数: " + err.Error()})
|
||||
return
|
||||
}
|
||||
req.Text = strings.TrimSpace(req.Text)
|
||||
if req.Text == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "text 不能为空"})
|
||||
return
|
||||
}
|
||||
|
||||
if h.cfg == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "系统配置未初始化"})
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(h.cfg.OpenAI.APIKey) == "" || strings.TrimSpace(h.cfg.OpenAI.Model) == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "未配置 AI 模型:请在系统设置中填写 openai.api_key 与 openai.model(支持 OpenAI 兼容 API,如 DeepSeek)",
|
||||
"need": []string{"openai.api_key", "openai.model"},
|
||||
})
|
||||
return
|
||||
}
|
||||
if h.openAIClient == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "AI 客户端未初始化"})
|
||||
return
|
||||
}
|
||||
|
||||
systemPrompt := strings.TrimSpace(`
|
||||
你是“FOFA 查询语法生成器”。任务:把用户输入的自然语言搜索意图,转换成 FOFA 查询语法。
|
||||
|
||||
输出要求(非常重要):
|
||||
1) 只输出 JSON(不要 markdown、不要代码块、不要额外解释文本)
|
||||
2) JSON 结构必须是:
|
||||
{
|
||||
"query": "string,FOFA查询语法(可直接粘贴到 FOFA 或本系统查询框)",
|
||||
"explanation": "string,可选,解释你如何映射字段/逻辑",
|
||||
"warnings": ["string"...] 可选,列出歧义/风险/需要人工确认的点
|
||||
}
|
||||
3) 如果用户输入本身已经是 FOFA 查询语法(或非常接近 FOFA 语法的表达式),应当“原样返回”为 query:
|
||||
- 不要擅自改写字段名、操作符、括号结构
|
||||
- 不要改写任何字符串值(尤其是地理位置类值),不要做缩写/同义词替换/翻译/音译
|
||||
|
||||
查询语法要点(来自 FOFA 语法参考):
|
||||
- 逻辑连接符:&&(与)、||(或),必要时用 () 包住子表达式以确认优先级(括号优先级最高)
|
||||
- 当同一层级同时出现 && 与 ||(混用)时,用 () 明确优先级(避免歧义)
|
||||
- 比较/匹配:
|
||||
- = 匹配;当字段="" 时,可查询“不存在该字段”或“值为空”的情况
|
||||
- == 完全匹配;当字段=="" 时,可查询“字段存在且值为空”的情况
|
||||
- != 不匹配;当字段!="" 时,可查询“值不为空”的情况
|
||||
- *= 模糊匹配;可使用 * 或 ? 进行搜索
|
||||
- 直接输入关键词(不带字段)会在标题、HTML内容、HTTP头、URL字段中搜索;但当意图明确时优先用字段表达(更可控、更准确)
|
||||
|
||||
字段示例速查(来自用户提供的案例,可直接套用/拼接):
|
||||
- 高级搜索操作符示例:
|
||||
- title="beijing" (= 匹配)
|
||||
- title=="" (== 完全匹配,字段存在且值为空)
|
||||
- title="" (= 匹配,可能表示字段不存在或值为空)
|
||||
- title!="" (!= 不匹配,可用于值不为空)
|
||||
- title*="*Home*" (*= 模糊匹配,用 * 或 ?)
|
||||
- (app="Apache" || app="Nginx") && country="CN" (混用 && / || 时用括号)
|
||||
- 基础类(General):
|
||||
- ip="1.1.1.1"
|
||||
- ip="220.181.111.1/24"
|
||||
- ip="2600:9000:202a:2600:18:4ab7:f600:93a1"
|
||||
- port="6379"
|
||||
- domain="qq.com"
|
||||
- host=".fofa.info"
|
||||
- os="centos"
|
||||
- server="Microsoft-IIS/10"
|
||||
- asn="19551"
|
||||
- org="LLC Baxet"
|
||||
- is_domain=true / is_domain=false
|
||||
- is_ipv6=true / is_ipv6=false
|
||||
- 标记类(Special Label):
|
||||
- app="Microsoft-Exchange"
|
||||
- fid="sSXXGNUO2FefBTcCLIT/2Q=="
|
||||
- product="NGINX"
|
||||
- product="Roundcube-Webmail" && product.version="1.6.10"
|
||||
- category="服务"
|
||||
- type="service" / type="subdomain"
|
||||
- cloud_name="Aliyundun"
|
||||
- is_cloud=true / is_cloud=false
|
||||
- is_fraud=true / is_fraud=false
|
||||
- is_honeypot=true / is_honeypot=false
|
||||
- 协议类(type=service):
|
||||
- protocol="quic"
|
||||
- banner="users"
|
||||
- banner_hash="7330105010150477363"
|
||||
- banner_fid="zRpqmn0FXQRjZpH8MjMX55zpMy9SgsW8"
|
||||
- base_protocol="udp" / base_protocol="tcp"
|
||||
- 网站类(type=subdomain):
|
||||
- title="beijing"
|
||||
- header="elastic"
|
||||
- header_hash="1258854265"
|
||||
- body="网络空间测绘"
|
||||
- body_hash="-2090962452"
|
||||
- js_name="js/jquery.js"
|
||||
- js_md5="82ac3f14327a8b7ba49baa208d4eaa15"
|
||||
- cname="customers.spektrix.com"
|
||||
- cname_domain="siteforce.com"
|
||||
- icon_hash="-247388890"
|
||||
- status_code="402"
|
||||
- icp="京ICP证030173号"
|
||||
- sdk_hash="Are3qNnP2Eqn7q5kAoUO3l+w3mgVIytO"
|
||||
- 地理位置(Location):
|
||||
- country="CN" 或 country="中国"
|
||||
- region="Zhejiang" 或 region="浙江"(仅支持中国地区中文)
|
||||
- city="Hangzhou"
|
||||
- 证书类(Certificate):
|
||||
- cert="baidu"
|
||||
- cert.subject="Oracle Corporation"
|
||||
- cert.issuer="DigiCert"
|
||||
- cert.subject.org="Oracle Corporation"
|
||||
- cert.subject.cn="baidu.com"
|
||||
- cert.issuer.org="cPanel, Inc."
|
||||
- cert.issuer.cn="Synology Inc. CA"
|
||||
- cert.domain="huawei.com"
|
||||
- cert.is_equal=true / cert.is_equal=false
|
||||
- cert.is_valid=true / cert.is_valid=false
|
||||
- cert.is_match=true / cert.is_match=false
|
||||
- cert.is_expired=true / cert.is_expired=false
|
||||
- jarm="2ad2ad0002ad2ad22c2ad2ad2ad2ad2eac92ec34bcc0cf7520e97547f83e81"
|
||||
- tls.version="TLS 1.3"
|
||||
- tls.ja3s="15af977ce25de452b96affa2addb1036"
|
||||
- cert.sn="356078156165546797850343536942784588840297"
|
||||
- cert.not_after.after="2025-03-01" / cert.not_after.before="2025-03-01"
|
||||
- cert.not_before.after="2025-03-01" / cert.not_before.before="2025-03-01"
|
||||
- 时间类(Last update time):
|
||||
- after="2023-01-01"
|
||||
- before="2023-12-01"
|
||||
- after="2023-01-01" && before="2023-12-01"
|
||||
- 独立IP语法(需配合 ip_filter / ip_exclude):
|
||||
- ip_filter(banner="SSH-2.0-OpenSSH_6.7p2") && ip_filter(icon_hash="-1057022626")
|
||||
- ip_filter(banner="SSH-2.0-OpenSSH_6.7p2" && asn="3462") && ip_exclude(title="EdgeOS")
|
||||
- port_size="6" / port_size_gt="6" / port_size_lt="12"
|
||||
- ip_ports="80,161"
|
||||
- ip_country="CN"
|
||||
- ip_region="Zhejiang"
|
||||
- ip_city="Hangzhou"
|
||||
- ip_after="2021-03-18"
|
||||
- ip_before="2019-09-09"
|
||||
|
||||
生成约束与注意事项:
|
||||
- 字符串值一律用英文双引号包裹,例如 title="登录"、country="CN"
|
||||
- 字符串值保持字面一致:不要缩写(例如 city="beijing" 不要变成 city="BJ"),不要用别名(例如 Beijing/Peking),不要擅自翻译/音译/改写大小写
|
||||
- 地理位置字段(country/region/city)更倾向于“按用户给定值输出”;不确定合法取值时,不要猜测,把备选写进 warnings
|
||||
- 不要捏造不存在的 FOFA 字段;不确定时把不确定点写进 warnings,并输出一个保守的 query
|
||||
- 当用户描述里有“多个与/或条件”,优先加 () 明确优先级,例如:(app="Apache" || app="Nginx") && country="CN"
|
||||
- 当用户缺少关键条件导致范围过大或歧义(如地点/协议/端口/服务类型未说明),允许 query 为空字符串,并在 warnings 里明确需要补充的信息
|
||||
`)
|
||||
|
||||
userPrompt := fmt.Sprintf("自然语言意图:%s", req.Text)
|
||||
|
||||
requestBody := map[string]interface{}{
|
||||
"model": h.cfg.OpenAI.Model,
|
||||
"messages": []map[string]interface{}{
|
||||
{"role": "system", "content": systemPrompt},
|
||||
{"role": "user", "content": userPrompt},
|
||||
},
|
||||
"temperature": 0.1,
|
||||
"max_tokens": 1200,
|
||||
}
|
||||
|
||||
// OpenAI 返回结构:只需要 choices[0].message.content
|
||||
var apiResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := h.openAIClient.ChatCompletion(ctx, requestBody, &apiResponse); err != nil {
|
||||
var apiErr *openaiClient.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
h.logger.Warn("FOFA自然语言解析:LLM返回错误", zap.Int("status", apiErr.StatusCode))
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "AI 解析失败(上游返回非 200),请检查模型配置或稍后重试"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "AI 解析失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if len(apiResponse.Choices) == 0 {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "AI 未返回有效结果"})
|
||||
return
|
||||
}
|
||||
|
||||
content := strings.TrimSpace(apiResponse.Choices[0].Message.Content)
|
||||
// 兼容模型偶尔返回 ```json ... ``` 的情况
|
||||
content = strings.TrimPrefix(content, "```json")
|
||||
content = strings.TrimPrefix(content, "```")
|
||||
content = strings.TrimSuffix(content, "```")
|
||||
content = strings.TrimSpace(content)
|
||||
|
||||
var parsed fofaParseResponse
|
||||
if err := json.Unmarshal([]byte(content), &parsed); err != nil {
|
||||
// 直接回传一部分原文,方便排查,但避免太大
|
||||
snippet := content
|
||||
if len(snippet) > 1200 {
|
||||
snippet = snippet[:1200]
|
||||
}
|
||||
c.JSON(http.StatusBadGateway, gin.H{
|
||||
"error": "AI 返回内容无法解析为 JSON,请稍后重试或换个描述方式",
|
||||
"snippet": snippet,
|
||||
})
|
||||
return
|
||||
}
|
||||
parsed.Query = strings.TrimSpace(parsed.Query)
|
||||
if parsed.Query == "" {
|
||||
// query 允许为空(表示需求不明确),但前端需要明确提示
|
||||
if len(parsed.Warnings) == 0 {
|
||||
parsed.Warnings = []string{"需求信息不足,未能生成可用的 FOFA 查询语法,请补充关键条件(如国家/端口/产品/域名等)。"}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, parsed)
|
||||
}
|
||||
|
||||
// Search FOFA 查询(后端代理,避免前端暴露 key)
|
||||
func (h *FofaHandler) Search(c *gin.Context) {
|
||||
var req fofaSearchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
req.Query = strings.TrimSpace(req.Query)
|
||||
if req.Query == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "query 不能为空"})
|
||||
return
|
||||
}
|
||||
if req.Size <= 0 {
|
||||
req.Size = 100
|
||||
}
|
||||
if req.Page <= 0 {
|
||||
req.Page = 1
|
||||
}
|
||||
// FOFA 接口 size 上限和账户权限相关,这里只做一个合理的保护
|
||||
if req.Size > 10000 {
|
||||
req.Size = 10000
|
||||
}
|
||||
if req.Fields == "" {
|
||||
req.Fields = "host,ip,port,domain,title,protocol,country,province,city,server"
|
||||
}
|
||||
|
||||
email, apiKey := h.resolveCredentials()
|
||||
if email == "" || apiKey == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "FOFA 未配置:请在系统设置中填写 FOFA Email/API Key,或设置环境变量 FOFA_EMAIL/FOFA_API_KEY",
|
||||
"need": []string{"fofa.email", "fofa.api_key"},
|
||||
"env_key": []string{"FOFA_EMAIL", "FOFA_API_KEY"},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
baseURL := h.resolveBaseURL()
|
||||
qb64 := base64.StdEncoding.EncodeToString([]byte(req.Query))
|
||||
|
||||
u, err := url.Parse(baseURL)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "FOFA base_url 无效: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
params := u.Query()
|
||||
params.Set("email", email)
|
||||
params.Set("key", apiKey)
|
||||
params.Set("qbase64", qb64)
|
||||
params.Set("size", fmt.Sprintf("%d", req.Size))
|
||||
params.Set("page", fmt.Sprintf("%d", req.Page))
|
||||
params.Set("fields", strings.TrimSpace(req.Fields))
|
||||
if req.Full {
|
||||
params.Set("full", "true")
|
||||
} else {
|
||||
// 明确传 false,便于排查
|
||||
params.Set("full", "false")
|
||||
}
|
||||
u.RawQuery = params.Encode()
|
||||
|
||||
httpReq, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, u.String(), nil)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "创建请求失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.client.Do(httpReq)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "请求 FOFA 失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": fmt.Sprintf("FOFA 返回非 2xx: %d", resp.StatusCode)})
|
||||
return
|
||||
}
|
||||
|
||||
var apiResp fofaAPIResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "解析 FOFA 响应失败: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if apiResp.Error {
|
||||
msg := strings.TrimSpace(apiResp.ErrMsg)
|
||||
if msg == "" {
|
||||
msg = "FOFA 返回错误"
|
||||
}
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": msg})
|
||||
return
|
||||
}
|
||||
|
||||
fields := splitAndCleanCSV(req.Fields)
|
||||
results := make([]map[string]interface{}, 0, len(apiResp.Results))
|
||||
for _, row := range apiResp.Results {
|
||||
item := make(map[string]interface{}, len(fields))
|
||||
for i, f := range fields {
|
||||
if i < len(row) {
|
||||
item[f] = row[i]
|
||||
} else {
|
||||
item[f] = nil
|
||||
}
|
||||
}
|
||||
results = append(results, item)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, fofaSearchResponse{
|
||||
Query: req.Query,
|
||||
Size: apiResp.Size,
|
||||
Page: apiResp.Page,
|
||||
Total: apiResp.Total,
|
||||
Fields: fields,
|
||||
ResultsCount: len(results),
|
||||
Results: results,
|
||||
})
|
||||
}
|
||||
|
||||
func splitAndCleanCSV(s string) []string {
|
||||
parts := strings.Split(s, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
seen := make(map[string]struct{}, len(parts))
|
||||
for _, p := range parts {
|
||||
v := strings.TrimSpace(p)
|
||||
if v == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[v]; ok {
|
||||
continue
|
||||
}
|
||||
seen[v] = struct{}{}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -15,11 +15,11 @@ import (
|
||||
|
||||
// KnowledgeHandler 知识库处理器
|
||||
type KnowledgeHandler struct {
|
||||
manager *knowledge.Manager
|
||||
manager *knowledge.Manager
|
||||
retriever *knowledge.Retriever
|
||||
indexer *knowledge.Indexer
|
||||
db *database.DB
|
||||
logger *zap.Logger
|
||||
indexer *knowledge.Indexer
|
||||
db *database.DB
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewKnowledgeHandler 创建新的知识库处理器
|
||||
@@ -55,7 +55,7 @@ func (h *KnowledgeHandler) GetCategories(c *gin.Context) {
|
||||
func (h *KnowledgeHandler) GetItems(c *gin.Context) {
|
||||
category := c.Query("category")
|
||||
searchKeyword := c.Query("search") // 搜索关键字
|
||||
|
||||
|
||||
// 如果提供了搜索关键字,执行关键字搜索(在所有数据中搜索)
|
||||
if searchKeyword != "" {
|
||||
items, err := h.manager.SearchItemsByKeyword(searchKeyword, category)
|
||||
@@ -102,10 +102,10 @@ func (h *KnowledgeHandler) GetItems(c *gin.Context) {
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 分页模式:categoryPage=true 表示按分类分页,否则按项分页(向后兼容)
|
||||
categoryPageMode := c.Query("categoryPage") != "false" // 默认使用分类分页
|
||||
|
||||
|
||||
// 分页参数
|
||||
limit := 50 // 默认每页50条(分类分页时为分类数,项分页时为项数)
|
||||
offset := 0
|
||||
@@ -192,9 +192,9 @@ func (h *KnowledgeHandler) GetItems(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"items": items,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
} else {
|
||||
@@ -207,9 +207,9 @@ func (h *KnowledgeHandler) GetItems(c *gin.Context) {
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"items": items,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"items": items,
|
||||
"total": total,
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
})
|
||||
}
|
||||
@@ -341,12 +341,12 @@ func (h *KnowledgeHandler) ScanKnowledgeBase(c *gin.Context) {
|
||||
consecutiveFailures := 0
|
||||
var firstFailureItemID string
|
||||
var firstFailureError error
|
||||
|
||||
|
||||
for i, itemID := range itemsToIndex {
|
||||
if err := h.indexer.IndexItem(ctx, itemID); err != nil {
|
||||
failedCount++
|
||||
consecutiveFailures++
|
||||
|
||||
|
||||
// 只在第一个失败时记录详细日志
|
||||
if consecutiveFailures == 1 {
|
||||
firstFailureItemID = itemID
|
||||
@@ -357,7 +357,7 @@ func (h *KnowledgeHandler) ScanKnowledgeBase(c *gin.Context) {
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
// 如果连续失败2次,立即停止增量索引
|
||||
if consecutiveFailures >= 2 {
|
||||
h.logger.Error("连续索引失败次数过多,立即停止增量索引",
|
||||
@@ -371,14 +371,14 @@ func (h *KnowledgeHandler) ScanKnowledgeBase(c *gin.Context) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
|
||||
// 成功时重置连续失败计数
|
||||
if consecutiveFailures > 0 {
|
||||
consecutiveFailures = 0
|
||||
firstFailureItemID = ""
|
||||
firstFailureError = nil
|
||||
}
|
||||
|
||||
|
||||
// 减少进度日志频率
|
||||
if (i+1)%10 == 0 || i+1 == len(itemsToIndex) {
|
||||
h.logger.Info("索引进度", zap.Int("current", i+1), zap.Int("total", len(itemsToIndex)), zap.Int("failed", failedCount))
|
||||
@@ -388,7 +388,7 @@ func (h *KnowledgeHandler) ScanKnowledgeBase(c *gin.Context) {
|
||||
}()
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": fmt.Sprintf("扫描完成,开始索引 %d 个新添加或更新的知识项", len(itemsToIndex)),
|
||||
"message": fmt.Sprintf("扫描完成,开始索引 %d 个新添加或更新的知识项", len(itemsToIndex)),
|
||||
"items_to_index": len(itemsToIndex),
|
||||
})
|
||||
}
|
||||
@@ -470,10 +470,25 @@ func (h *KnowledgeHandler) Search(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"results": results})
|
||||
}
|
||||
|
||||
// GetStats 获取知识库统计信息
|
||||
func (h *KnowledgeHandler) GetStats(c *gin.Context) {
|
||||
totalCategories, totalItems, err := h.manager.GetStats()
|
||||
if err != nil {
|
||||
h.logger.Error("获取知识库统计信息失败", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"enabled": true,
|
||||
"total_categories": totalCategories,
|
||||
"total_items": totalItems,
|
||||
})
|
||||
}
|
||||
|
||||
// 辅助函数:解析整数
|
||||
func parseInt(s string) (int, error) {
|
||||
var result int
|
||||
_, err := fmt.Sscanf(s, "%d", &result)
|
||||
return result, err
|
||||
}
|
||||
|
||||
|
||||
@@ -153,6 +153,25 @@ func (m *Manager) GetCategories() ([]string, error) {
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
// GetStats 获取知识库统计信息
|
||||
func (m *Manager) GetStats() (int, int, error) {
|
||||
// 获取分类总数
|
||||
categories, err := m.GetCategories()
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("获取分类失败: %w", err)
|
||||
}
|
||||
totalCategories := len(categories)
|
||||
|
||||
// 获取知识项总数
|
||||
var totalItems int
|
||||
err = m.db.QueryRow("SELECT COUNT(*) FROM knowledge_base_items").Scan(&totalItems)
|
||||
if err != nil {
|
||||
return totalCategories, 0, fmt.Errorf("获取知识项总数失败: %w", err)
|
||||
}
|
||||
|
||||
return totalCategories, totalItems, nil
|
||||
}
|
||||
|
||||
// GetCategoriesWithItems 按分类分页获取知识项(每个分类包含其下的所有知识项)
|
||||
// limit: 每页分类数量(0表示不限制)
|
||||
// offset: 偏移量(按分类偏移)
|
||||
@@ -359,7 +378,7 @@ func (m *Manager) SearchItemsByKeyword(keyword string, category string) ([]*Know
|
||||
// SQLite的LIKE不区分大小写,使用COLLATE NOCASE或LOWER()函数
|
||||
// 使用%keyword%进行模糊匹配
|
||||
searchPattern := "%" + keyword + "%"
|
||||
|
||||
|
||||
query = `
|
||||
SELECT id, category, title, file_path, created_at, updated_at
|
||||
FROM knowledge_base_items
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
// Package mcp 外部 MCP 客户端 - 基于官方 go-sdk 实现,保证协议兼容性
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
clientName = "CyberStrikeAI"
|
||||
clientVersion = "1.0.0"
|
||||
)
|
||||
|
||||
// sdkClient 基于官方 MCP Go SDK 的外部 MCP 客户端,实现 ExternalMCPClient 接口
|
||||
type sdkClient struct {
|
||||
session *mcp.ClientSession
|
||||
client *mcp.Client
|
||||
logger *zap.Logger
|
||||
mu sync.RWMutex
|
||||
status string // "disconnected", "connecting", "connected", "error"
|
||||
}
|
||||
|
||||
// newSDKClientFromSession 用已连接成功的 session 构造(供 createSDKClient 内部使用)
|
||||
func newSDKClientFromSession(session *mcp.ClientSession, client *mcp.Client, logger *zap.Logger) *sdkClient {
|
||||
return &sdkClient{
|
||||
session: session,
|
||||
client: client,
|
||||
logger: logger,
|
||||
status: "connected",
|
||||
}
|
||||
}
|
||||
|
||||
// lazySDKClient 延迟连接:Initialize() 时才调用官方 SDK 建立连接,对外实现 ExternalMCPClient
|
||||
type lazySDKClient struct {
|
||||
serverCfg config.ExternalMCPServerConfig
|
||||
logger *zap.Logger
|
||||
inner ExternalMCPClient // 连接成功后为 *sdkClient
|
||||
mu sync.RWMutex
|
||||
status string
|
||||
}
|
||||
|
||||
func newLazySDKClient(serverCfg config.ExternalMCPServerConfig, logger *zap.Logger) *lazySDKClient {
|
||||
return &lazySDKClient{
|
||||
serverCfg: serverCfg,
|
||||
logger: logger,
|
||||
status: "connecting",
|
||||
}
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) setStatus(s string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.status = s
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) GetStatus() string {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
if c.inner != nil {
|
||||
return c.inner.GetStatus()
|
||||
}
|
||||
return c.status
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) IsConnected() bool {
|
||||
c.mu.RLock()
|
||||
inner := c.inner
|
||||
c.mu.RUnlock()
|
||||
if inner != nil {
|
||||
return inner.IsConnected()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) Initialize(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
if c.inner != nil {
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
c.mu.Unlock()
|
||||
|
||||
inner, err := createSDKClient(ctx, c.serverCfg, c.logger)
|
||||
if err != nil {
|
||||
c.setStatus("error")
|
||||
return err
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
c.inner = inner
|
||||
c.mu.Unlock()
|
||||
c.setStatus("connected")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) ListTools(ctx context.Context) ([]Tool, error) {
|
||||
c.mu.RLock()
|
||||
inner := c.inner
|
||||
c.mu.RUnlock()
|
||||
if inner == nil {
|
||||
return nil, fmt.Errorf("未连接")
|
||||
}
|
||||
return inner.ListTools(ctx)
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) CallTool(ctx context.Context, name string, args map[string]interface{}) (*ToolResult, error) {
|
||||
c.mu.RLock()
|
||||
inner := c.inner
|
||||
c.mu.RUnlock()
|
||||
if inner == nil {
|
||||
return nil, fmt.Errorf("未连接")
|
||||
}
|
||||
return inner.CallTool(ctx, name, args)
|
||||
}
|
||||
|
||||
func (c *lazySDKClient) Close() error {
|
||||
c.mu.Lock()
|
||||
inner := c.inner
|
||||
c.inner = nil
|
||||
c.mu.Unlock()
|
||||
c.setStatus("disconnected")
|
||||
if inner != nil {
|
||||
return inner.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *sdkClient) setStatus(s string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.status = s
|
||||
}
|
||||
|
||||
func (c *sdkClient) GetStatus() string {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
return c.status
|
||||
}
|
||||
|
||||
func (c *sdkClient) IsConnected() bool {
|
||||
return c.GetStatus() == "connected"
|
||||
}
|
||||
|
||||
func (c *sdkClient) Initialize(ctx context.Context) error {
|
||||
// sdkClient 由 createSDKClient 在 Connect 成功后才创建,因此 Initialize 时已经连接
|
||||
// 此方法仅用于满足 ExternalMCPClient 接口,实际连接在 createSDKClient 中完成
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *sdkClient) ListTools(ctx context.Context) ([]Tool, error) {
|
||||
if c.session == nil {
|
||||
return nil, fmt.Errorf("未连接")
|
||||
}
|
||||
res, err := c.session.ListTools(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return sdkToolsToOur(res.Tools), nil
|
||||
}
|
||||
|
||||
func (c *sdkClient) CallTool(ctx context.Context, name string, args map[string]interface{}) (*ToolResult, error) {
|
||||
if c.session == nil {
|
||||
return nil, fmt.Errorf("未连接")
|
||||
}
|
||||
params := &mcp.CallToolParams{
|
||||
Name: name,
|
||||
Arguments: args,
|
||||
}
|
||||
res, err := c.session.CallTool(ctx, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return sdkCallToolResultToOurs(res), nil
|
||||
}
|
||||
|
||||
func (c *sdkClient) Close() error {
|
||||
c.setStatus("disconnected")
|
||||
if c.session != nil {
|
||||
err := c.session.Close()
|
||||
c.session = nil
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sdkToolsToOur 将 SDK 的 []*mcp.Tool 转为我们的 []Tool
|
||||
func sdkToolsToOur(tools []*mcp.Tool) []Tool {
|
||||
if len(tools) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]Tool, 0, len(tools))
|
||||
for _, t := range tools {
|
||||
if t == nil {
|
||||
continue
|
||||
}
|
||||
schema := make(map[string]interface{})
|
||||
if t.InputSchema != nil {
|
||||
// SDK InputSchema 可能为 *jsonschema.Schema 或 map,统一转为 map
|
||||
if m, ok := t.InputSchema.(map[string]interface{}); ok {
|
||||
schema = m
|
||||
} else {
|
||||
_ = json.Unmarshal(mustJSON(t.InputSchema), &schema)
|
||||
}
|
||||
}
|
||||
desc := t.Description
|
||||
shortDesc := desc
|
||||
if t.Annotations != nil && t.Annotations.Title != "" {
|
||||
shortDesc = t.Annotations.Title
|
||||
}
|
||||
out = append(out, Tool{
|
||||
Name: t.Name,
|
||||
Description: desc,
|
||||
ShortDescription: shortDesc,
|
||||
InputSchema: schema,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sdkCallToolResultToOurs 将 SDK 的 *mcp.CallToolResult 转为我们的 *ToolResult
|
||||
func sdkCallToolResultToOurs(res *mcp.CallToolResult) *ToolResult {
|
||||
if res == nil {
|
||||
return &ToolResult{Content: []Content{}}
|
||||
}
|
||||
content := sdkContentToOurs(res.Content)
|
||||
return &ToolResult{
|
||||
Content: content,
|
||||
IsError: res.IsError,
|
||||
}
|
||||
}
|
||||
|
||||
func sdkContentToOurs(list []mcp.Content) []Content {
|
||||
if len(list) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]Content, 0, len(list))
|
||||
for _, c := range list {
|
||||
switch v := c.(type) {
|
||||
case *mcp.TextContent:
|
||||
out = append(out, Content{Type: "text", Text: v.Text})
|
||||
default:
|
||||
out = append(out, Content{Type: "text", Text: fmt.Sprintf("%v", c)})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func mustJSON(v interface{}) []byte {
|
||||
b, _ := json.Marshal(v)
|
||||
return b
|
||||
}
|
||||
|
||||
// simpleHTTPClient 简单 JSON-RPC over HTTP:每次请求一次 POST、响应在 body。实现 ExternalMCPClient。
|
||||
// 用于自建 MCP(如 http://127.0.0.1:8081/mcp)或其它仅支持简单 POST 的端点。
|
||||
type simpleHTTPClient struct {
|
||||
url string
|
||||
client *http.Client
|
||||
logger *zap.Logger
|
||||
mu sync.RWMutex
|
||||
status string
|
||||
}
|
||||
|
||||
func newSimpleHTTPClient(ctx context.Context, url string, timeout time.Duration, headers map[string]string, logger *zap.Logger) (ExternalMCPClient, error) {
|
||||
c := &simpleHTTPClient{
|
||||
url: url,
|
||||
client: httpClientWithTimeoutAndHeaders(timeout, headers),
|
||||
logger: logger,
|
||||
status: "connecting",
|
||||
}
|
||||
if err := c.initialize(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.status = "connected"
|
||||
c.mu.Unlock()
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) setStatus(s string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.status = s
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) GetStatus() string {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
return c.status
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) IsConnected() bool {
|
||||
return c.GetStatus() == "connected"
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) Initialize(context.Context) error {
|
||||
return nil // 已在 newSimpleHTTPClient 中完成
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) initialize(ctx context.Context) error {
|
||||
params := InitializeRequest{
|
||||
ProtocolVersion: ProtocolVersion,
|
||||
Capabilities: make(map[string]interface{}),
|
||||
ClientInfo: ClientInfo{Name: clientName, Version: clientVersion},
|
||||
}
|
||||
paramsJSON, _ := json.Marshal(params)
|
||||
req := &Message{
|
||||
ID: MessageID{value: "1"},
|
||||
Method: "initialize",
|
||||
Version: "2.0",
|
||||
Params: paramsJSON,
|
||||
}
|
||||
resp, err := c.sendRequest(ctx, req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialize: %w", err)
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return fmt.Errorf("initialize: %s (code %d)", resp.Error.Message, resp.Error.Code)
|
||||
}
|
||||
// 发送 notifications/initialized(协议要求)
|
||||
notify := &Message{
|
||||
ID: MessageID{value: nil},
|
||||
Method: "notifications/initialized",
|
||||
Version: "2.0",
|
||||
Params: json.RawMessage("{}"),
|
||||
}
|
||||
_ = c.sendNotification(notify)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) sendRequest(ctx context.Context, msg *Message) (*Message, error) {
|
||||
body, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))
|
||||
}
|
||||
var out Message
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) sendNotification(msg *Message) error {
|
||||
body, _ := json.Marshal(msg)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
httpReq, _ := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader(body))
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
resp, err := c.client.Do(httpReq)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) ListTools(ctx context.Context) ([]Tool, error) {
|
||||
req := &Message{
|
||||
ID: MessageID{value: uuid.New().String()},
|
||||
Method: "tools/list",
|
||||
Version: "2.0",
|
||||
Params: json.RawMessage("{}"),
|
||||
}
|
||||
resp, err := c.sendRequest(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return nil, fmt.Errorf("tools/list: %s (code %d)", resp.Error.Message, resp.Error.Code)
|
||||
}
|
||||
var listResp ListToolsResponse
|
||||
if err := json.Unmarshal(resp.Result, &listResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return listResp.Tools, nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) CallTool(ctx context.Context, name string, args map[string]interface{}) (*ToolResult, error) {
|
||||
params := CallToolRequest{Name: name, Arguments: args}
|
||||
paramsJSON, _ := json.Marshal(params)
|
||||
req := &Message{
|
||||
ID: MessageID{value: uuid.New().String()},
|
||||
Method: "tools/call",
|
||||
Version: "2.0",
|
||||
Params: paramsJSON,
|
||||
}
|
||||
resp, err := c.sendRequest(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.Error != nil {
|
||||
return nil, fmt.Errorf("tools/call: %s (code %d)", resp.Error.Message, resp.Error.Code)
|
||||
}
|
||||
var callResp CallToolResponse
|
||||
if err := json.Unmarshal(resp.Result, &callResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ToolResult{Content: callResp.Content, IsError: callResp.IsError}, nil
|
||||
}
|
||||
|
||||
func (c *simpleHTTPClient) Close() error {
|
||||
c.setStatus("disconnected")
|
||||
return nil
|
||||
}
|
||||
|
||||
// createSDKClient 根据配置创建并连接外部 MCP 客户端(使用官方 SDK),返回实现 ExternalMCPClient 的 *sdkClient
|
||||
// 若连接失败返回 (nil, error)。ctx 用于连接超时与取消。
|
||||
func createSDKClient(ctx context.Context, serverCfg config.ExternalMCPServerConfig, logger *zap.Logger) (ExternalMCPClient, error) {
|
||||
timeout := time.Duration(serverCfg.Timeout) * time.Second
|
||||
if timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
transport := serverCfg.Transport
|
||||
if transport == "" {
|
||||
if serverCfg.Command != "" {
|
||||
transport = "stdio"
|
||||
} else if serverCfg.URL != "" {
|
||||
transport = "http"
|
||||
} else {
|
||||
return nil, fmt.Errorf("配置缺少 command 或 url")
|
||||
}
|
||||
}
|
||||
|
||||
client := mcp.NewClient(&mcp.Implementation{
|
||||
Name: clientName,
|
||||
Version: clientVersion,
|
||||
}, nil)
|
||||
|
||||
var t mcp.Transport
|
||||
switch transport {
|
||||
case "stdio":
|
||||
if serverCfg.Command == "" {
|
||||
return nil, fmt.Errorf("stdio 模式需要配置 command")
|
||||
}
|
||||
// 必须用 exec.Command 而非 CommandContext:doConnect 返回后 ctx 会被 cancel,
|
||||
// 若用 CommandContext(ctx) 会立刻杀掉子进程,导致 ListTools 等后续请求失败、显示 0 工具
|
||||
cmd := exec.Command(serverCfg.Command, serverCfg.Args...)
|
||||
if len(serverCfg.Env) > 0 {
|
||||
cmd.Env = append(cmd.Env, envMapToSlice(serverCfg.Env)...)
|
||||
}
|
||||
t = &mcp.CommandTransport{Command: cmd}
|
||||
case "sse":
|
||||
if serverCfg.URL == "" {
|
||||
return nil, fmt.Errorf("sse 模式需要配置 url")
|
||||
}
|
||||
httpClient := httpClientWithTimeoutAndHeaders(timeout, serverCfg.Headers)
|
||||
t = &mcp.SSEClientTransport{
|
||||
Endpoint: serverCfg.URL,
|
||||
HTTPClient: httpClient,
|
||||
}
|
||||
case "http":
|
||||
if serverCfg.URL == "" {
|
||||
return nil, fmt.Errorf("http 模式需要配置 url")
|
||||
}
|
||||
httpClient := httpClientWithTimeoutAndHeaders(timeout, serverCfg.Headers)
|
||||
t = &mcp.StreamableClientTransport{
|
||||
Endpoint: serverCfg.URL,
|
||||
HTTPClient: httpClient,
|
||||
}
|
||||
case "simple_http":
|
||||
// 简单 JSON-RPC HTTP:每次请求一次 POST、响应在 body。用于自建 MCP 或兼容旧端点(如 http://127.0.0.1:8081/mcp)
|
||||
if serverCfg.URL == "" {
|
||||
return nil, fmt.Errorf("simple_http 模式需要配置 url")
|
||||
}
|
||||
return newSimpleHTTPClient(ctx, serverCfg.URL, timeout, serverCfg.Headers, logger)
|
||||
default:
|
||||
return nil, fmt.Errorf("不支持的传输模式: %s", transport)
|
||||
}
|
||||
|
||||
session, err := client.Connect(ctx, t, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("连接失败: %w", err)
|
||||
}
|
||||
|
||||
return newSDKClientFromSession(session, client, logger), nil
|
||||
}
|
||||
|
||||
func envMapToSlice(env map[string]string) []string {
|
||||
m := make(map[string]string)
|
||||
for _, s := range os.Environ() {
|
||||
if i := strings.IndexByte(s, '='); i > 0 {
|
||||
m[s[:i]] = s[i+1:]
|
||||
}
|
||||
}
|
||||
for k, v := range env {
|
||||
m[k] = v
|
||||
}
|
||||
out := make([]string, 0, len(m))
|
||||
for k, v := range m {
|
||||
out = append(out, k+"="+v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func httpClientWithTimeoutAndHeaders(timeout time.Duration, headers map[string]string) *http.Client {
|
||||
transport := http.DefaultTransport
|
||||
if len(headers) > 0 {
|
||||
transport = &headerRoundTripper{
|
||||
headers: headers,
|
||||
base: http.DefaultTransport,
|
||||
}
|
||||
}
|
||||
return &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: transport,
|
||||
}
|
||||
}
|
||||
|
||||
type headerRoundTripper struct {
|
||||
headers map[string]string
|
||||
base http.RoundTripper
|
||||
}
|
||||
|
||||
func (h *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
for k, v := range h.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
return h.base.RoundTrip(req)
|
||||
}
|
||||
@@ -25,6 +25,8 @@ type ExternalMCPManager struct {
|
||||
errors map[string]string // 错误信息
|
||||
toolCounts map[string]int // 工具数量缓存
|
||||
toolCountsMu sync.RWMutex // 工具数量缓存的锁
|
||||
toolCache map[string][]Tool // 工具列表缓存:MCP名称 -> 工具列表
|
||||
toolCacheMu sync.RWMutex // 工具列表缓存的锁
|
||||
stopRefresh chan struct{} // 停止后台刷新的信号
|
||||
refreshWg sync.WaitGroup // 等待后台刷新goroutine完成
|
||||
mu sync.RWMutex
|
||||
@@ -46,6 +48,7 @@ func NewExternalMCPManagerWithStorage(logger *zap.Logger, storage MonitorStorage
|
||||
stats: make(map[string]*ToolStats),
|
||||
errors: make(map[string]string),
|
||||
toolCounts: make(map[string]int),
|
||||
toolCache: make(map[string][]Tool),
|
||||
stopRefresh: make(chan struct{}),
|
||||
}
|
||||
// 启动后台刷新工具数量的goroutine
|
||||
@@ -119,6 +122,11 @@ func (m *ExternalMCPManager) RemoveConfig(name string) error {
|
||||
delete(m.toolCounts, name)
|
||||
m.toolCountsMu.Unlock()
|
||||
|
||||
// 清理工具列表缓存
|
||||
m.toolCacheMu.Lock()
|
||||
delete(m.toolCache, name)
|
||||
m.toolCacheMu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -196,8 +204,15 @@ func (m *ExternalMCPManager) StartClient(name string) error {
|
||||
m.mu.Lock()
|
||||
delete(m.errors, name)
|
||||
m.mu.Unlock()
|
||||
// 连接成功,立即刷新工具数量
|
||||
// 立即刷新工具数量和工具列表缓存
|
||||
m.triggerToolCountRefresh()
|
||||
m.refreshToolCache(name, client)
|
||||
// 2 秒后再刷新一次,覆盖 SSE/Streamable 等需稍等就绪的远端
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
m.triggerToolCountRefresh()
|
||||
m.refreshToolCache(name, client)
|
||||
}()
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -253,6 +268,11 @@ func (m *ExternalMCPManager) GetError(name string) string {
|
||||
}
|
||||
|
||||
// GetAllTools 获取所有外部MCP的工具
|
||||
// 优先从已连接的客户端获取,如果连接断开则返回缓存的工具列表
|
||||
// 策略:
|
||||
// - error 状态:不使用缓存,直接跳过(配置错误或服务不可用)
|
||||
// - disconnected/connecting 状态:使用缓存(临时断开)
|
||||
// - connected 状态:正常获取,失败时降级使用缓存
|
||||
func (m *ExternalMCPManager) GetAllTools(ctx context.Context) ([]Tool, error) {
|
||||
m.mu.RLock()
|
||||
clients := make(map[string]ExternalMCPClient)
|
||||
@@ -262,17 +282,21 @@ func (m *ExternalMCPManager) GetAllTools(ctx context.Context) ([]Tool, error) {
|
||||
m.mu.RUnlock()
|
||||
|
||||
var allTools []Tool
|
||||
for name, client := range clients {
|
||||
if !client.IsConnected() {
|
||||
continue
|
||||
}
|
||||
var hasError bool
|
||||
var lastError error
|
||||
|
||||
tools, err := client.ListTools(ctx)
|
||||
// 使用较短的超时时间进行快速检查(3秒),避免阻塞
|
||||
quickCtx, quickCancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer quickCancel()
|
||||
|
||||
for name, client := range clients {
|
||||
tools, err := m.getToolsForClient(name, client, quickCtx)
|
||||
if err != nil {
|
||||
m.logger.Warn("获取外部MCP工具列表失败",
|
||||
zap.String("name", name),
|
||||
zap.Error(err),
|
||||
)
|
||||
// 记录错误,但继续处理其他客户端
|
||||
hasError = true
|
||||
if lastError == nil {
|
||||
lastError = err
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -283,9 +307,97 @@ func (m *ExternalMCPManager) GetAllTools(ctx context.Context) ([]Tool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果有错误但至少返回了一些工具,不返回错误(部分成功)
|
||||
if hasError && len(allTools) == 0 {
|
||||
return nil, fmt.Errorf("获取外部MCP工具失败: %w", lastError)
|
||||
}
|
||||
|
||||
return allTools, nil
|
||||
}
|
||||
|
||||
// getToolsForClient 获取指定客户端的工具列表
|
||||
// 返回工具列表和错误(如果完全无法获取)
|
||||
func (m *ExternalMCPManager) getToolsForClient(name string, client ExternalMCPClient, ctx context.Context) ([]Tool, error) {
|
||||
status := client.GetStatus()
|
||||
|
||||
// error 状态:不使用缓存,直接返回错误
|
||||
if status == "error" {
|
||||
m.logger.Debug("跳过连接失败的外部MCP(不使用缓存)",
|
||||
zap.String("name", name),
|
||||
zap.String("status", status),
|
||||
)
|
||||
return nil, fmt.Errorf("外部MCP连接失败: %s", name)
|
||||
}
|
||||
|
||||
// 已连接:尝试获取最新工具列表
|
||||
if client.IsConnected() {
|
||||
tools, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
// 获取失败,尝试使用缓存
|
||||
return m.getCachedTools(name, "连接正常但获取失败", err)
|
||||
}
|
||||
|
||||
// 获取成功,更新缓存
|
||||
m.updateToolCache(name, tools)
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// 未连接:根据状态决定是否使用缓存
|
||||
if status == "disconnected" || status == "connecting" {
|
||||
return m.getCachedTools(name, fmt.Sprintf("客户端临时断开(状态: %s)", status), nil)
|
||||
}
|
||||
|
||||
// 其他未知状态,不使用缓存
|
||||
m.logger.Debug("跳过外部MCP(未知状态)",
|
||||
zap.String("name", name),
|
||||
zap.String("status", status),
|
||||
)
|
||||
return nil, fmt.Errorf("外部MCP状态未知: %s (状态: %s)", name, status)
|
||||
}
|
||||
|
||||
// getCachedTools 获取缓存的工具列表
|
||||
func (m *ExternalMCPManager) getCachedTools(name, reason string, originalErr error) ([]Tool, error) {
|
||||
m.toolCacheMu.RLock()
|
||||
cachedTools, hasCache := m.toolCache[name]
|
||||
m.toolCacheMu.RUnlock()
|
||||
|
||||
if hasCache && len(cachedTools) > 0 {
|
||||
m.logger.Debug("使用缓存的工具列表",
|
||||
zap.String("name", name),
|
||||
zap.String("reason", reason),
|
||||
zap.Int("count", len(cachedTools)),
|
||||
zap.Error(originalErr),
|
||||
)
|
||||
return cachedTools, nil
|
||||
}
|
||||
|
||||
// 无缓存,返回错误
|
||||
if originalErr != nil {
|
||||
return nil, fmt.Errorf("获取外部MCP工具失败且无缓存: %w", originalErr)
|
||||
}
|
||||
return nil, fmt.Errorf("外部MCP无缓存工具: %s", name)
|
||||
}
|
||||
|
||||
// updateToolCache 更新工具列表缓存
|
||||
func (m *ExternalMCPManager) updateToolCache(name string, tools []Tool) {
|
||||
m.toolCacheMu.Lock()
|
||||
m.toolCache[name] = tools
|
||||
m.toolCacheMu.Unlock()
|
||||
|
||||
// 如果返回空列表,记录警告
|
||||
if len(tools) == 0 {
|
||||
m.logger.Warn("外部MCP返回空工具列表",
|
||||
zap.String("name", name),
|
||||
zap.String("hint", "服务可能暂时不可用,工具列表为空"),
|
||||
)
|
||||
} else {
|
||||
m.logger.Debug("工具列表缓存已更新",
|
||||
zap.String("name", name),
|
||||
zap.Int("count", len(tools)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// CallTool 调用外部MCP工具(返回执行ID)
|
||||
func (m *ExternalMCPManager) CallTool(ctx context.Context, toolName string, args map[string]interface{}) (*ToolResult, string, error) {
|
||||
// 解析工具名称:name::toolName
|
||||
@@ -302,8 +414,18 @@ func (m *ExternalMCPManager) CallTool(ctx context.Context, toolName string, args
|
||||
return nil, "", fmt.Errorf("外部MCP客户端不存在: %s", mcpName)
|
||||
}
|
||||
|
||||
// 检查连接状态,如果未连接或状态为error,不允许调用
|
||||
if !client.IsConnected() {
|
||||
return nil, "", fmt.Errorf("外部MCP客户端未连接: %s", mcpName)
|
||||
status := client.GetStatus()
|
||||
if status == "error" {
|
||||
// 获取错误信息(如果有)
|
||||
errorMsg := m.GetError(mcpName)
|
||||
if errorMsg != "" {
|
||||
return nil, "", fmt.Errorf("外部MCP连接失败: %s (错误: %s)", mcpName, errorMsg)
|
||||
}
|
||||
return nil, "", fmt.Errorf("外部MCP连接失败: %s", mcpName)
|
||||
}
|
||||
return nil, "", fmt.Errorf("外部MCP客户端未连接: %s (状态: %s)", mcpName, status)
|
||||
}
|
||||
|
||||
// 创建执行记录
|
||||
@@ -630,11 +752,20 @@ func (m *ExternalMCPManager) refreshToolCounts() {
|
||||
cancel()
|
||||
|
||||
if err != nil {
|
||||
m.logger.Debug("获取外部MCP工具数量失败",
|
||||
zap.String("name", n),
|
||||
zap.Error(err),
|
||||
)
|
||||
// 如果获取失败,保留旧值(在更新时处理)
|
||||
errStr := err.Error()
|
||||
// SSE 连接 EOF:远端可能关闭了流或未按规范在流上推送响应,仅首次用 Warn 提示
|
||||
if strings.Contains(errStr, "EOF") || strings.Contains(errStr, "client is closing") {
|
||||
m.logger.Warn("获取外部MCP工具数量失败(SSE 流已关闭或服务端未在流上返回 tools/list 响应)",
|
||||
zap.String("name", n),
|
||||
zap.String("hint", "若为 SSE 连接,请确认服务端保持 GET 流打开并按 MCP 规范以 event: message 推送 JSON-RPC 响应"),
|
||||
zap.Error(err),
|
||||
)
|
||||
} else {
|
||||
m.logger.Warn("获取外部MCP工具数量失败,请检查连接或服务端 tools/list",
|
||||
zap.String("name", n),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
resultChan <- countResult{name: n, count: -1} // -1 表示使用旧值
|
||||
return
|
||||
}
|
||||
@@ -680,6 +811,40 @@ func (m *ExternalMCPManager) refreshToolCounts() {
|
||||
m.toolCountsMu.Unlock()
|
||||
}
|
||||
|
||||
// refreshToolCache 刷新指定MCP的工具列表缓存
|
||||
func (m *ExternalMCPManager) refreshToolCache(name string, client ExternalMCPClient) {
|
||||
if !client.IsConnected() {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查状态,如果是error状态,不更新缓存
|
||||
status := client.GetStatus()
|
||||
if status == "error" {
|
||||
m.logger.Debug("跳过刷新工具列表缓存(连接失败)",
|
||||
zap.String("name", name),
|
||||
zap.String("status", status),
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// 使用较短的超时时间(5秒)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
tools, err := client.ListTools(ctx)
|
||||
if err != nil {
|
||||
m.logger.Debug("刷新工具列表缓存失败",
|
||||
zap.String("name", name),
|
||||
zap.Error(err),
|
||||
)
|
||||
// 刷新失败时不更新缓存,保留旧缓存(如果有)
|
||||
return
|
||||
}
|
||||
|
||||
// 使用统一的缓存更新方法
|
||||
m.updateToolCache(name, tools)
|
||||
}
|
||||
|
||||
// startToolCountRefresh 启动后台刷新工具数量的goroutine
|
||||
func (m *ExternalMCPManager) startToolCountRefresh() {
|
||||
m.refreshWg.Add(1)
|
||||
@@ -707,21 +872,13 @@ func (m *ExternalMCPManager) triggerToolCountRefresh() {
|
||||
go m.refreshToolCounts()
|
||||
}
|
||||
|
||||
// createClient 创建客户端(不连接)
|
||||
// createClient 创建客户端(不连接)。统一使用官方 MCP Go SDK 的 lazy 客户端,连接在 Initialize 时完成。
|
||||
func (m *ExternalMCPManager) createClient(serverCfg config.ExternalMCPServerConfig) ExternalMCPClient {
|
||||
timeout := time.Duration(serverCfg.Timeout) * time.Second
|
||||
if timeout <= 0 {
|
||||
timeout = 30 * time.Second
|
||||
}
|
||||
|
||||
// 根据传输模式创建客户端
|
||||
transport := serverCfg.Transport
|
||||
if transport == "" {
|
||||
// 如果没有指定transport,根据是否有command或url判断
|
||||
if serverCfg.Command != "" {
|
||||
transport = "stdio"
|
||||
} else if serverCfg.URL != "" {
|
||||
// 默认使用http,但可以通过transport字段指定sse
|
||||
transport = "http"
|
||||
} else {
|
||||
return nil
|
||||
@@ -733,17 +890,23 @@ func (m *ExternalMCPManager) createClient(serverCfg config.ExternalMCPServerConf
|
||||
if serverCfg.URL == "" {
|
||||
return nil
|
||||
}
|
||||
return NewHTTPMCPClient(serverCfg.URL, timeout, m.logger)
|
||||
return newLazySDKClient(serverCfg, m.logger)
|
||||
case "simple_http":
|
||||
// 简单 HTTP(一次 POST 一次响应),用于自建 MCP 等
|
||||
if serverCfg.URL == "" {
|
||||
return nil
|
||||
}
|
||||
return newLazySDKClient(serverCfg, m.logger)
|
||||
case "stdio":
|
||||
if serverCfg.Command == "" {
|
||||
return nil
|
||||
}
|
||||
return NewStdioMCPClient(serverCfg.Command, serverCfg.Args, serverCfg.Env, timeout, m.logger)
|
||||
return newLazySDKClient(serverCfg, m.logger)
|
||||
case "sse":
|
||||
if serverCfg.URL == "" {
|
||||
return nil
|
||||
}
|
||||
return NewSSEMCPClient(serverCfg.URL, timeout, m.logger)
|
||||
return newLazySDKClient(serverCfg, m.logger)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -773,12 +936,7 @@ func (m *ExternalMCPManager) doConnect(name string, serverCfg config.ExternalMCP
|
||||
|
||||
// setClientStatus 设置客户端状态(通过类型断言)
|
||||
func (m *ExternalMCPManager) setClientStatus(client ExternalMCPClient, status string) {
|
||||
switch c := client.(type) {
|
||||
case *HTTPMCPClient:
|
||||
c.setStatus(status)
|
||||
case *StdioMCPClient:
|
||||
c.setStatus(status)
|
||||
case *SSEMCPClient:
|
||||
if c, ok := client.(*lazySDKClient); ok {
|
||||
c.setStatus(status)
|
||||
}
|
||||
}
|
||||
@@ -819,8 +977,13 @@ func (m *ExternalMCPManager) connectClient(name string, serverCfg config.Externa
|
||||
zap.String("name", name),
|
||||
)
|
||||
|
||||
// 连接成功,触发工具数量刷新
|
||||
// 连接成功,触发工具数量刷新和工具列表缓存刷新
|
||||
m.triggerToolCountRefresh()
|
||||
m.mu.RLock()
|
||||
if client, exists := m.clients[name]; exists {
|
||||
m.refreshToolCache(name, client)
|
||||
}
|
||||
m.mu.RUnlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -926,6 +1089,11 @@ func (m *ExternalMCPManager) StopAll() {
|
||||
m.toolCounts = make(map[string]int)
|
||||
m.toolCountsMu.Unlock()
|
||||
|
||||
// 清理所有工具列表缓存
|
||||
m.toolCacheMu.Lock()
|
||||
m.toolCache = make(map[string][]Tool)
|
||||
m.toolCacheMu.Unlock()
|
||||
|
||||
// 停止后台刷新(使用 select 避免重复关闭 channel)
|
||||
select {
|
||||
case <-m.stopRefresh:
|
||||
|
||||
@@ -151,48 +151,26 @@ func TestExternalMCPManager_LoadConfigs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMCPClient_Initialize(t *testing.T) {
|
||||
// 注意:这个测试需要一个真实的HTTP MCP服务器
|
||||
// 如果没有服务器,这个测试会失败
|
||||
// 在实际测试中,可以使用mock服务器
|
||||
// TestLazySDKClient_InitializeFails 验证无效配置时 SDK 客户端 Initialize 失败并设置 error 状态
|
||||
func TestLazySDKClient_InitializeFails(t *testing.T) {
|
||||
logger := zap.NewNop()
|
||||
client := NewHTTPMCPClient("http://127.0.0.1:8081/mcp", 5*time.Second, logger)
|
||||
|
||||
// 使用不存在的 HTTP 地址,Initialize 应失败
|
||||
cfg := config.ExternalMCPServerConfig{
|
||||
Transport: "http",
|
||||
URL: "http://127.0.0.1:19999/nonexistent",
|
||||
Timeout: 2,
|
||||
}
|
||||
c := newLazySDKClient(cfg, logger)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 这个测试可能会失败,如果没有真实的服务器
|
||||
// 在实际环境中,应该使用mock服务器
|
||||
err := client.Initialize(ctx)
|
||||
if err != nil {
|
||||
t.Logf("初始化失败(可能是没有服务器): %v", err)
|
||||
err := c.Initialize(ctx)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when connecting to invalid server")
|
||||
}
|
||||
|
||||
status := client.GetStatus()
|
||||
if status == "" {
|
||||
t.Error("状态不应该为空")
|
||||
if c.GetStatus() != "error" {
|
||||
t.Errorf("expected status error, got %s", c.GetStatus())
|
||||
}
|
||||
|
||||
client.Close()
|
||||
}
|
||||
|
||||
func TestStdioMCPClient_Initialize(t *testing.T) {
|
||||
// 注意:这个测试需要一个真实的stdio MCP服务器
|
||||
// 如果没有服务器,这个测试会失败
|
||||
logger := zap.NewNop()
|
||||
client := NewStdioMCPClient("echo", []string{"test"}, nil, 5*time.Second, logger)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 这个测试可能会失败,因为echo不是MCP服务器
|
||||
// 在实际环境中,应该使用真实的MCP服务器或mock
|
||||
err := client.Initialize(ctx)
|
||||
if err != nil {
|
||||
t.Logf("初始化失败(echo不是MCP服务器): %v", err)
|
||||
}
|
||||
|
||||
client.Close()
|
||||
c.Close()
|
||||
}
|
||||
|
||||
func TestExternalMCPManager_StartStopClient(t *testing.T) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -125,6 +126,13 @@ func (s *Server) HandleHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// 官方 MCP SSE 规范:带 sessionid 的 POST 表示消息发往该 SSE 会话,响应通过 SSE 流返回
|
||||
if sessionID := r.URL.Query().Get("sessionid"); sessionID != "" {
|
||||
s.serveSSESessionMessage(w, r, sessionID)
|
||||
return
|
||||
}
|
||||
|
||||
// 简单 POST:请求体为 JSON-RPC,响应在 body 中返回
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
s.sendError(w, nil, -32700, "Parse error", err.Error())
|
||||
@@ -137,14 +145,56 @@ func (s *Server) HandleHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// 处理消息
|
||||
response := s.handleMessage(&msg)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// handleSSE 处理SSE连接(用于MCP HTTP传输的事件通道)
|
||||
// serveSSESessionMessage 处理发往 SSE 会话的 POST:读取 JSON-RPC 请求,处理后将响应通过该会话的 SSE 流推送
|
||||
func (s *Server) serveSSESessionMessage(w http.ResponseWriter, r *http.Request, sessionID string) {
|
||||
s.mu.RLock()
|
||||
client, exists := s.sseClients[sessionID]
|
||||
s.mu.RUnlock()
|
||||
if !exists || client == nil {
|
||||
http.Error(w, "session not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
var msg Message
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
http.Error(w, "failed to parse body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
response := s.handleMessage(&msg)
|
||||
if response == nil {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
return
|
||||
}
|
||||
|
||||
respBytes, err := json.Marshal(response)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case client.send <- respBytes:
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
default:
|
||||
http.Error(w, "session send buffer full", http.StatusServiceUnavailable)
|
||||
}
|
||||
}
|
||||
|
||||
// handleSSE 处理 SSE 连接,兼容官方 MCP 2024-11-05 SSE 规范:
|
||||
// 1. 首个事件必须为 event: endpoint,data 为客户端 POST 消息的 URL(含 sessionid)
|
||||
// 2. 后续事件为 event: message,data 为 JSON-RPC 响应
|
||||
func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
flusher, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
@@ -157,16 +207,25 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Connection", "keep-alive")
|
||||
w.Header().Set("X-Accel-Buffering", "no")
|
||||
|
||||
sessionID := uuid.New().String()
|
||||
client := &sseClient{
|
||||
id: uuid.New().String(),
|
||||
send: make(chan []byte, 8),
|
||||
id: sessionID,
|
||||
send: make(chan []byte, 32),
|
||||
}
|
||||
|
||||
s.addSSEClient(client)
|
||||
defer s.removeSSEClient(client.id)
|
||||
|
||||
// 发送初始ready事件,告知客户端连接成功
|
||||
fmt.Fprintf(w, "event: message\ndata: {\"type\":\"ready\",\"status\":\"ok\"}\n\n")
|
||||
// 官方规范:首个事件为 endpoint,data 为消息端点 URL(客户端将向该 URL POST 请求)
|
||||
scheme := "http"
|
||||
if r.TLS != nil {
|
||||
scheme = "https"
|
||||
}
|
||||
if r.URL.Scheme != "" {
|
||||
scheme = r.URL.Scheme
|
||||
}
|
||||
endpointURL := fmt.Sprintf("%s://%s%s?sessionid=%s", scheme, r.Host, r.URL.Path, sessionID)
|
||||
fmt.Fprintf(w, "event: endpoint\ndata: %s\n\n", endpointURL)
|
||||
flusher.Flush()
|
||||
|
||||
ticker := time.NewTicker(15 * time.Second)
|
||||
@@ -183,7 +242,6 @@ func (s *Server) handleSSE(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "event: message\ndata: %s\n\n", msg)
|
||||
flusher.Flush()
|
||||
case <-ticker.C:
|
||||
// 心跳保持连接
|
||||
fmt.Fprintf(w, ": ping\n\n")
|
||||
flusher.Flush()
|
||||
}
|
||||
@@ -311,6 +369,7 @@ func (s *Server) handleListTools(msg *Message) *Message {
|
||||
tools = append(tools, tool)
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
s.logger.Debug("tools/list 请求", zap.Int("返回工具数", len(tools)))
|
||||
|
||||
response := ListToolsResponse{Tools: tools}
|
||||
result, _ := json.Marshal(response)
|
||||
@@ -1110,10 +1169,11 @@ func (s *Server) RegisterResource(resource *Resource) {
|
||||
}
|
||||
|
||||
// HandleStdio 处理标准输入输出(用于 stdio 传输模式)
|
||||
// MCP 协议使用换行分隔的 JSON-RPC 消息
|
||||
// MCP 协议使用换行分隔的 JSON-RPC 消息;管道下需每次写入后 Flush,否则客户端会读不到响应
|
||||
func (s *Server) HandleStdio() error {
|
||||
decoder := json.NewDecoder(os.Stdin)
|
||||
encoder := json.NewEncoder(os.Stdout)
|
||||
stdout := bufio.NewWriter(os.Stdout)
|
||||
encoder := json.NewEncoder(stdout)
|
||||
// 注意:不设置缩进,MCP 协议期望紧凑的 JSON 格式
|
||||
|
||||
for {
|
||||
@@ -1134,6 +1194,9 @@ func (s *Server) HandleStdio() error {
|
||||
if err := encoder.Encode(errorMsg); err != nil {
|
||||
return fmt.Errorf("发送错误响应失败: %w", err)
|
||||
}
|
||||
if err := stdout.Flush(); err != nil {
|
||||
return fmt.Errorf("刷新 stdout 失败: %w", err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1149,6 +1212,9 @@ func (s *Server) HandleStdio() error {
|
||||
if err := encoder.Encode(response); err != nil {
|
||||
return fmt.Errorf("发送响应失败: %w", err)
|
||||
}
|
||||
if err := stdout.Flush(); err != nil {
|
||||
return fmt.Errorf("刷新 stdout 失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ExternalMCPClient 外部 MCP 客户端接口(由 client_sdk.go 基于官方 SDK 实现)
|
||||
type ExternalMCPClient interface {
|
||||
Initialize(ctx context.Context) error
|
||||
ListTools(ctx context.Context) ([]Tool, error)
|
||||
CallTool(ctx context.Context, name string, args map[string]interface{}) (*ToolResult, error)
|
||||
Close() error
|
||||
IsConnected() bool
|
||||
GetStatus() string
|
||||
}
|
||||
|
||||
// MCP消息类型
|
||||
const (
|
||||
MessageTypeRequest = "request"
|
||||
@@ -29,21 +40,21 @@ func (m *MessageID) UnmarshalJSON(data []byte) error {
|
||||
m.value = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// 尝试解析为字符串
|
||||
var str string
|
||||
if err := json.Unmarshal(data, &str); err == nil {
|
||||
m.value = str
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
// 尝试解析为数字
|
||||
var num json.Number
|
||||
if err := json.Unmarshal(data, &num); err == nil {
|
||||
m.value = num
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
return fmt.Errorf("invalid id type")
|
||||
}
|
||||
|
||||
@@ -81,15 +92,15 @@ type Message struct {
|
||||
|
||||
// Error 表示MCP错误
|
||||
type Error struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// Tool 表示MCP工具定义
|
||||
type Tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"` // 详细描述
|
||||
Description string `json:"description"` // 详细描述
|
||||
ShortDescription string `json:"shortDescription,omitempty"` // 简短描述(用于工具列表,减少token消耗)
|
||||
InputSchema map[string]interface{} `json:"inputSchema"`
|
||||
}
|
||||
@@ -127,9 +138,9 @@ type ClientInfo struct {
|
||||
|
||||
// InitializeResponse 初始化响应
|
||||
type InitializeResponse struct {
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
Capabilities ServerCapabilities `json:"capabilities"`
|
||||
ServerInfo ServerInfo `json:"serverInfo"`
|
||||
ProtocolVersion string `json:"protocolVersion"`
|
||||
Capabilities ServerCapabilities `json:"capabilities"`
|
||||
ServerInfo ServerInfo `json:"serverInfo"`
|
||||
}
|
||||
|
||||
// ServerCapabilities 服务器能力
|
||||
@@ -178,31 +189,31 @@ type CallToolResponse struct {
|
||||
|
||||
// ToolExecution 工具执行记录
|
||||
type ToolExecution struct {
|
||||
ID string `json:"id"`
|
||||
ToolName string `json:"toolName"`
|
||||
Arguments map[string]interface{} `json:"arguments"`
|
||||
Status string `json:"status"` // pending, running, completed, failed
|
||||
Result *ToolResult `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
StartTime time.Time `json:"startTime"`
|
||||
EndTime *time.Time `json:"endTime,omitempty"`
|
||||
Duration time.Duration `json:"duration,omitempty"`
|
||||
ID string `json:"id"`
|
||||
ToolName string `json:"toolName"`
|
||||
Arguments map[string]interface{} `json:"arguments"`
|
||||
Status string `json:"status"` // pending, running, completed, failed
|
||||
Result *ToolResult `json:"result,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
StartTime time.Time `json:"startTime"`
|
||||
EndTime *time.Time `json:"endTime,omitempty"`
|
||||
Duration time.Duration `json:"duration,omitempty"`
|
||||
}
|
||||
|
||||
// ToolStats 工具统计信息
|
||||
type ToolStats struct {
|
||||
ToolName string `json:"toolName"`
|
||||
TotalCalls int `json:"totalCalls"`
|
||||
SuccessCalls int `json:"successCalls"`
|
||||
FailedCalls int `json:"failedCalls"`
|
||||
ToolName string `json:"toolName"`
|
||||
TotalCalls int `json:"totalCalls"`
|
||||
SuccessCalls int `json:"successCalls"`
|
||||
FailedCalls int `json:"failedCalls"`
|
||||
LastCallTime *time.Time `json:"lastCallTime,omitempty"`
|
||||
}
|
||||
|
||||
// Prompt 提示词模板
|
||||
type Prompt struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Arguments []PromptArgument `json:"arguments,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Arguments []PromptArgument `json:"arguments,omitempty"`
|
||||
}
|
||||
|
||||
// PromptArgument 提示词参数
|
||||
@@ -257,11 +268,11 @@ type ResourceContent struct {
|
||||
|
||||
// SamplingRequest 采样请求
|
||||
type SamplingRequest struct {
|
||||
Messages []SamplingMessage `json:"messages"`
|
||||
Model string `json:"model,omitempty"`
|
||||
MaxTokens int `json:"maxTokens,omitempty"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
TopP float64 `json:"topP,omitempty"`
|
||||
Messages []SamplingMessage `json:"messages"`
|
||||
Model string `json:"model,omitempty"`
|
||||
MaxTokens int `json:"maxTokens,omitempty"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
TopP float64 `json:"topP,omitempty"`
|
||||
}
|
||||
|
||||
// SamplingMessage 采样消息
|
||||
@@ -272,9 +283,9 @@ type SamplingMessage struct {
|
||||
|
||||
// SamplingResponse 采样响应
|
||||
type SamplingResponse struct {
|
||||
Content []SamplingContent `json:"content"`
|
||||
Model string `json:"model,omitempty"`
|
||||
StopReason string `json:"stopReason,omitempty"`
|
||||
Content []SamplingContent `json:"content"`
|
||||
Model string `json:"model,omitempty"`
|
||||
StopReason string `json:"stopReason,omitempty"`
|
||||
}
|
||||
|
||||
// SamplingContent 采样内容
|
||||
@@ -282,4 +293,3 @@ type SamplingContent struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
@@ -224,22 +224,25 @@ func (e *Executor) RegisterTools(mcpServer *mcp.Server) {
|
||||
toolName := toolConfig.Name
|
||||
toolConfigCopy := toolConfig
|
||||
|
||||
// 使用简短描述(如果存在),否则使用详细描述的前100个字符
|
||||
// 根据配置决定暴露给 AI/API 的描述:short_description 或 description
|
||||
useFullDescription := strings.TrimSpace(strings.ToLower(e.config.ToolDescriptionMode)) == "full"
|
||||
shortDesc := toolConfigCopy.ShortDescription
|
||||
if shortDesc == "" {
|
||||
// 如果没有简短描述,从详细描述中提取第一行或前100个字符
|
||||
// 如果没有简短描述,从详细描述中提取第一行或前10000个字符
|
||||
desc := toolConfigCopy.Description
|
||||
if len(desc) > 100 {
|
||||
// 尝试找到第一个换行符
|
||||
if idx := strings.Index(desc, "\n"); idx > 0 && idx < 100 {
|
||||
if len(desc) > 10000 {
|
||||
if idx := strings.Index(desc, "\n"); idx > 0 && idx < 10000 {
|
||||
shortDesc = strings.TrimSpace(desc[:idx])
|
||||
} else {
|
||||
shortDesc = desc[:100] + "..."
|
||||
shortDesc = desc[:10000] + "..."
|
||||
}
|
||||
} else {
|
||||
shortDesc = desc
|
||||
}
|
||||
}
|
||||
if useFullDescription {
|
||||
shortDesc = "" // 使用 description 时清空 ShortDescription,下游会回退到 Description
|
||||
}
|
||||
|
||||
tool := mcp.Tool{
|
||||
Name: toolConfigCopy.Name,
|
||||
@@ -303,7 +306,23 @@ func (e *Executor) buildCommandArgs(toolName string, toolConfig *config.ToolConf
|
||||
}
|
||||
}
|
||||
|
||||
// 先处理标志参数(对于大多数命令,标志应该在位置参数之前)
|
||||
// 对于需要子命令的工具(如 gobuster dir),position 0 必须紧跟在命令名后、所有 flag 之前
|
||||
for _, param := range positionalParams {
|
||||
if param.Name == "additional_args" || param.Name == "scan_type" || param.Name == "action" {
|
||||
continue
|
||||
}
|
||||
if param.Position != nil && *param.Position == 0 {
|
||||
value := e.getParamValue(args, param)
|
||||
if value == nil && param.Default != nil {
|
||||
value = param.Default
|
||||
}
|
||||
if value != nil {
|
||||
cmdArgs = append(cmdArgs, e.formatParamValue(param, value))
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 处理标志参数
|
||||
for _, param := range flagParams {
|
||||
// 跳过特殊参数,它们会在后面单独处理
|
||||
@@ -416,7 +435,11 @@ func (e *Executor) buildCommandArgs(toolName string, toolConfig *config.ToolConf
|
||||
}
|
||||
|
||||
// 按位置顺序处理参数,确保即使某些位置没有参数或使用默认值,也能正确传递
|
||||
// position 0 已在前面插入(子命令优先),此处从 1 开始
|
||||
for i := 0; i <= maxPosition; i++ {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
for _, param := range positionalParams {
|
||||
// 跳过特殊参数,它们会在后面单独处理
|
||||
// action 参数仅用于工具内部逻辑,不传递给命令
|
||||
@@ -1190,7 +1213,15 @@ func (e *Executor) buildInputSchema(toolConfig *config.ToolConfig) map[string]in
|
||||
required := []string{}
|
||||
|
||||
for _, param := range toolConfig.Parameters {
|
||||
// 转换类型为OpenAI/JSON Schema标准类型
|
||||
// 跳过 name 为空的参数(避免 YAML 中 name: null 或空导致非法 schema)
|
||||
if strings.TrimSpace(param.Name) == "" {
|
||||
e.logger.Debug("跳过无名称的参数",
|
||||
zap.String("tool", toolConfig.Name),
|
||||
zap.String("type", param.Type),
|
||||
)
|
||||
continue
|
||||
}
|
||||
// 转换类型为OpenAI/JSON Schema标准类型(空类型默认为 string)
|
||||
openAIType := e.convertToOpenAIType(param.Type)
|
||||
|
||||
prop := map[string]interface{}{
|
||||
@@ -1232,6 +1263,10 @@ func (e *Executor) buildInputSchema(toolConfig *config.ToolConfig) map[string]in
|
||||
|
||||
// convertToOpenAIType 将配置中的类型转换为OpenAI/JSON Schema标准类型
|
||||
func (e *Executor) convertToOpenAIType(configType string) string {
|
||||
// 空或 null 类型统一视为 string,避免非法 schema 导致工具调用失败
|
||||
if strings.TrimSpace(configType) == "" {
|
||||
return "string"
|
||||
}
|
||||
switch configType {
|
||||
case "bool":
|
||||
return "boolean"
|
||||
|
||||
@@ -5,10 +5,13 @@ charset-normalizer>=3.3.2
|
||||
chardet>=5.2.0
|
||||
|
||||
# Python exploitation / analysis frameworks referenced by tool recipes
|
||||
angr>=9.2.96
|
||||
# angr>=9.2.96
|
||||
# pwntools>=4.12.0
|
||||
arjun>=2.2.0
|
||||
uro>=1.0.2
|
||||
|
||||
bloodhound>=1.6.1
|
||||
impacket>=0.11.0
|
||||
|
||||
# MCP (Model Context Protocol) SDK
|
||||
mcp>=1.0.0
|
||||
|
||||
@@ -11,6 +11,7 @@ RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
CYAN='\033[0;36m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# 打印带颜色的消息
|
||||
@@ -18,6 +19,47 @@ info() { echo -e "${BLUE}ℹ️ $1${NC}"; }
|
||||
success() { echo -e "${GREEN}✅ $1${NC}"; }
|
||||
warning() { echo -e "${YELLOW}⚠️ $1${NC}"; }
|
||||
error() { echo -e "${RED}❌ $1${NC}"; }
|
||||
note() { echo -e "${CYAN}ℹ️ $1${NC}"; }
|
||||
|
||||
# 临时源配置(仅在此脚本中生效)
|
||||
PIP_INDEX_URL="${PIP_INDEX_URL:-https://pypi.tuna.tsinghua.edu.cn/simple}"
|
||||
GOPROXY="${GOPROXY:-https://goproxy.cn,direct}"
|
||||
|
||||
# 保存原始环境变量(用于恢复)
|
||||
ORIGINAL_PIP_INDEX_URL="${PIP_INDEX_URL:-}"
|
||||
ORIGINAL_GOPROXY="${GOPROXY:-}"
|
||||
|
||||
# 进度显示函数
|
||||
show_progress() {
|
||||
local pid=$1
|
||||
local message=$2
|
||||
local i=0
|
||||
local dots=""
|
||||
|
||||
# 检查进程是否存在
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
# 进程已经结束,立即返回
|
||||
return 0
|
||||
fi
|
||||
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
i=$((i + 1))
|
||||
case $((i % 4)) in
|
||||
0) dots="." ;;
|
||||
1) dots=".." ;;
|
||||
2) dots="..." ;;
|
||||
3) dots="...." ;;
|
||||
esac
|
||||
printf "\r${BLUE}⏳ %s%s${NC}" "$message" "$dots"
|
||||
sleep 0.5
|
||||
|
||||
# 再次检查进程是否还存在
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
done
|
||||
printf "\r"
|
||||
}
|
||||
|
||||
echo ""
|
||||
echo "=========================================="
|
||||
@@ -25,6 +67,19 @@ echo " CyberStrikeAI 一键部署启动脚本"
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
|
||||
# 显示临时源配置信息
|
||||
echo ""
|
||||
warning "⚠️ 注意:此脚本将使用临时镜像源加速下载"
|
||||
echo ""
|
||||
info "Python pip 临时镜像源:"
|
||||
echo " ${PIP_INDEX_URL}"
|
||||
info "Go Proxy 临时镜像源:"
|
||||
echo " ${GOPROXY}"
|
||||
echo ""
|
||||
note "这些设置仅在脚本运行期间生效,不会修改系统配置"
|
||||
echo ""
|
||||
sleep 1
|
||||
|
||||
CONFIG_FILE="$ROOT_DIR/config.yaml"
|
||||
VENV_DIR="$ROOT_DIR/venv"
|
||||
REQUIREMENTS_FILE="$ROOT_DIR/requirements.txt"
|
||||
@@ -101,12 +156,55 @@ setup_python_env() {
|
||||
source "$VENV_DIR/bin/activate"
|
||||
|
||||
if [ -f "$REQUIREMENTS_FILE" ]; then
|
||||
info "安装/更新 Python 依赖..."
|
||||
pip install --quiet --upgrade pip >/dev/null 2>&1 || true
|
||||
echo ""
|
||||
note "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
note "⚠️ 使用临时 pip 镜像源(仅本次脚本运行有效)"
|
||||
note " 镜像地址: ${PIP_INDEX_URL}"
|
||||
note " 如需永久配置,请设置环境变量 PIP_INDEX_URL"
|
||||
note "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
|
||||
# 尝试安装依赖,捕获错误输出
|
||||
info "升级 pip..."
|
||||
pip install --index-url "$PIP_INDEX_URL" --upgrade pip >/dev/null 2>&1 || true
|
||||
|
||||
info "安装 Python 依赖包..."
|
||||
echo ""
|
||||
|
||||
# 尝试安装依赖,捕获错误输出并显示进度
|
||||
PIP_LOG=$(mktemp)
|
||||
if pip install -r "$REQUIREMENTS_FILE" >"$PIP_LOG" 2>&1; then
|
||||
(
|
||||
set +e # 在子shell中禁用错误退出
|
||||
pip install --index-url "$PIP_INDEX_URL" -r "$REQUIREMENTS_FILE" >"$PIP_LOG" 2>&1
|
||||
echo $? > "${PIP_LOG}.exit"
|
||||
) &
|
||||
PIP_PID=$!
|
||||
|
||||
# 等待一小段时间,确保进程启动
|
||||
sleep 0.1
|
||||
|
||||
# 显示进度(如果进程还在运行)
|
||||
if kill -0 "$PIP_PID" 2>/dev/null; then
|
||||
show_progress "$PIP_PID" "正在安装依赖包"
|
||||
else
|
||||
# 进程已经结束,等待一下确保退出码文件已写入
|
||||
sleep 0.2
|
||||
fi
|
||||
|
||||
# 等待进程完成,忽略 wait 的退出码
|
||||
wait "$PIP_PID" 2>/dev/null || true
|
||||
|
||||
PIP_EXIT_CODE=0
|
||||
if [ -f "${PIP_LOG}.exit" ]; then
|
||||
PIP_EXIT_CODE=$(cat "${PIP_LOG}.exit" 2>/dev/null || echo "1")
|
||||
rm -f "${PIP_LOG}.exit" 2>/dev/null || true
|
||||
else
|
||||
# 如果没有退出码文件,检查日志中是否有错误
|
||||
if [ -f "$PIP_LOG" ] && grep -q -i "error\|failed\|exception" "$PIP_LOG" 2>/dev/null; then
|
||||
PIP_EXIT_CODE=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $PIP_EXIT_CODE -eq 0 ]; then
|
||||
success "Python 依赖安装完成"
|
||||
else
|
||||
# 检查是否是 angr 安装失败(需要 Rust)
|
||||
@@ -138,17 +236,102 @@ setup_python_env() {
|
||||
|
||||
# 构建 Go 项目
|
||||
build_go_project() {
|
||||
echo ""
|
||||
note "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
note "⚠️ 使用临时 Go Proxy(仅本次脚本运行有效)"
|
||||
note " Proxy 地址: ${GOPROXY}"
|
||||
note " 如需永久配置,请设置环境变量 GOPROXY"
|
||||
note "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||
echo ""
|
||||
|
||||
info "下载 Go 依赖..."
|
||||
go mod download >/dev/null 2>&1 || {
|
||||
GO_DOWNLOAD_LOG=$(mktemp)
|
||||
(
|
||||
set +e # 在子shell中禁用错误退出
|
||||
export GOPROXY="$GOPROXY"
|
||||
go mod download >"$GO_DOWNLOAD_LOG" 2>&1
|
||||
echo $? > "${GO_DOWNLOAD_LOG}.exit"
|
||||
) &
|
||||
GO_DOWNLOAD_PID=$!
|
||||
|
||||
# 等待一小段时间,确保进程启动
|
||||
sleep 0.1
|
||||
|
||||
# 显示进度(如果进程还在运行)
|
||||
if kill -0 "$GO_DOWNLOAD_PID" 2>/dev/null; then
|
||||
show_progress "$GO_DOWNLOAD_PID" "正在下载 Go 依赖"
|
||||
else
|
||||
# 进程已经结束,等待一下确保退出码文件已写入
|
||||
sleep 0.2
|
||||
fi
|
||||
|
||||
# 等待进程完成,忽略 wait 的退出码
|
||||
wait "$GO_DOWNLOAD_PID" 2>/dev/null || true
|
||||
|
||||
GO_DOWNLOAD_EXIT_CODE=0
|
||||
if [ -f "${GO_DOWNLOAD_LOG}.exit" ]; then
|
||||
GO_DOWNLOAD_EXIT_CODE=$(cat "${GO_DOWNLOAD_LOG}.exit" 2>/dev/null || echo "1")
|
||||
rm -f "${GO_DOWNLOAD_LOG}.exit" 2>/dev/null || true
|
||||
else
|
||||
# 如果没有退出码文件,检查日志中是否有错误
|
||||
if [ -f "$GO_DOWNLOAD_LOG" ] && grep -q -i "error\|failed" "$GO_DOWNLOAD_LOG" 2>/dev/null; then
|
||||
GO_DOWNLOAD_EXIT_CODE=1
|
||||
fi
|
||||
fi
|
||||
rm -f "$GO_DOWNLOAD_LOG" 2>/dev/null || true
|
||||
|
||||
if [ $GO_DOWNLOAD_EXIT_CODE -ne 0 ]; then
|
||||
error "Go 依赖下载失败"
|
||||
exit 1
|
||||
}
|
||||
fi
|
||||
success "Go 依赖下载完成"
|
||||
|
||||
info "构建项目..."
|
||||
if go build -o "$BINARY_NAME" cmd/server/main.go 2>&1; then
|
||||
GO_BUILD_LOG=$(mktemp)
|
||||
(
|
||||
set +e # 在子shell中禁用错误退出
|
||||
export GOPROXY="$GOPROXY"
|
||||
go build -o "$BINARY_NAME" cmd/server/main.go >"$GO_BUILD_LOG" 2>&1
|
||||
echo $? > "${GO_BUILD_LOG}.exit"
|
||||
) &
|
||||
GO_BUILD_PID=$!
|
||||
|
||||
# 等待一小段时间,确保进程启动
|
||||
sleep 0.1
|
||||
|
||||
# 显示进度(如果进程还在运行)
|
||||
if kill -0 "$GO_BUILD_PID" 2>/dev/null; then
|
||||
show_progress "$GO_BUILD_PID" "正在构建项目"
|
||||
else
|
||||
# 进程已经结束,等待一下确保退出码文件已写入
|
||||
sleep 0.2
|
||||
fi
|
||||
|
||||
# 等待进程完成,忽略 wait 的退出码
|
||||
wait "$GO_BUILD_PID" 2>/dev/null || true
|
||||
|
||||
GO_BUILD_EXIT_CODE=0
|
||||
if [ -f "${GO_BUILD_LOG}.exit" ]; then
|
||||
GO_BUILD_EXIT_CODE=$(cat "${GO_BUILD_LOG}.exit" 2>/dev/null || echo "1")
|
||||
rm -f "${GO_BUILD_LOG}.exit" 2>/dev/null || true
|
||||
else
|
||||
# 如果没有退出码文件,检查日志中是否有错误
|
||||
if [ -f "$GO_BUILD_LOG" ] && grep -q -i "error\|failed" "$GO_BUILD_LOG" 2>/dev/null; then
|
||||
GO_BUILD_EXIT_CODE=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $GO_BUILD_EXIT_CODE -eq 0 ]; then
|
||||
success "项目构建完成: $BINARY_NAME"
|
||||
rm -f "$GO_BUILD_LOG"
|
||||
else
|
||||
error "项目构建失败"
|
||||
# 显示构建错误
|
||||
echo ""
|
||||
info "构建错误详情:"
|
||||
cat "$GO_BUILD_LOG" | sed 's/^/ /'
|
||||
echo ""
|
||||
rm -f "$GO_BUILD_LOG"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 概述
|
||||
|
||||
Skills系统允许你为角色配置专业知识和技能文档。当角色执行任务时,系统会自动将这些skills的内容注入到系统提示词中,帮助AI更好地理解和执行相关任务。
|
||||
Skills系统允许你为角色配置专业知识和技能文档。当角色执行任务时,系统会将技能名称添加到系统提示词中作为推荐提示,AI智能体可以通过 `read_skill` 工具按需获取技能的详细内容。
|
||||
|
||||
## Skills结构
|
||||
|
||||
@@ -62,16 +62,16 @@ enabled: true
|
||||
|
||||
## 工作原理
|
||||
|
||||
1. **加载阶段**:系统启动时,会扫描`skills_dir`目录下的所有skill
|
||||
1. **加载阶段**:系统启动时,会扫描`skills_dir`目录下的所有skill目录
|
||||
2. **执行阶段**:当使用某个角色执行任务时:
|
||||
- 系统会加载该角色配置的所有skills
|
||||
- 将skills内容合并并注入到系统提示词中
|
||||
- AI在执行任务前会阅读这些skills内容
|
||||
3. **按需调用**:即使角色没有配置skills,AI也可以通过以下工具按需调用:
|
||||
- 系统会将角色配置的skill名称添加到系统提示词中作为推荐提示
|
||||
- **注意**:skill的详细内容不会自动注入到系统提示词中
|
||||
- AI智能体需要根据任务需要,主动调用 `read_skill` 工具获取技能的详细内容
|
||||
3. **按需调用**:AI可以通过以下工具访问skills:
|
||||
- `list_skills`: 获取所有可用的skills列表
|
||||
- `read_skill`: 读取指定skill的详细内容
|
||||
|
||||
这样AI可以在执行任务过程中,根据实际需要自主调用相关skills获取专业知识。
|
||||
这样AI可以在执行任务过程中,根据实际需要自主调用相关skills获取专业知识。即使角色没有配置skills,AI也可以通过这些工具按需访问任何可用的skill。
|
||||
|
||||
## 示例Skills
|
||||
|
||||
@@ -106,10 +106,12 @@ EOF
|
||||
|
||||
## 注意事项
|
||||
|
||||
- Skill内容会被注入到系统提示词中,注意控制长度避免超过token限制
|
||||
- **重要**:Skill的详细内容不会自动注入到系统提示词中,只有技能名称会作为提示添加
|
||||
- AI智能体需要通过 `read_skill` 工具主动获取技能内容,这样可以节省token并提高灵活性
|
||||
- Skill内容应该清晰、结构化,便于AI理解
|
||||
- 可以包含代码示例、命令示例等
|
||||
- 建议每个skill专注于一个特定领域或技能
|
||||
- 建议在skill的YAML front matter中提供清晰的 `description`,帮助AI判断是否需要读取该skill
|
||||
|
||||
## 配置
|
||||
|
||||
|
||||
@@ -407,7 +407,7 @@ go run cmd/test-config/main.go
|
||||
|
||||
### Q: 参数顺序如何控制?
|
||||
|
||||
A: 使用 `position` 字段控制位置参数的顺序。标志参数会按照在 `parameters` 列表中的顺序添加。`additional_args` 会追加到命令末尾。
|
||||
A: 使用 `position` 字段控制位置参数的顺序。**位置 0 的参数(如 gobuster 的 `dir` 子命令)会紧跟在命令名后、所有标志参数之前**,以便兼容需要“子命令 + 选项”形式的 CLI。其余标志参数按在 `parameters` 列表中的顺序添加,再按 position 1、2… 添加其余位置参数。`additional_args` 会追加到命令末尾。
|
||||
|
||||
## 工具配置模板
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
name: "list-files"
|
||||
command: "ls"
|
||||
enabled: true
|
||||
short_description: "列出目录文件工具"
|
||||
description: |
|
||||
列出服务器上指定目录中的文件。
|
||||
|
||||
**主要功能:**
|
||||
- 列出文件
|
||||
- 显示详细信息
|
||||
- 递归列出
|
||||
|
||||
**使用场景:**
|
||||
- 目录浏览
|
||||
- 文件查找
|
||||
- 系统检查
|
||||
parameters:
|
||||
- name: "directory"
|
||||
type: "string"
|
||||
description: "要列出的目录(相对于服务器基础目录)"
|
||||
required: false
|
||||
default: "."
|
||||
position: 0
|
||||
format: "positional"
|
||||
- name: "long_format"
|
||||
type: "bool"
|
||||
description: "显示详细信息(长格式)"
|
||||
required: false
|
||||
flag: "-l"
|
||||
format: "flag"
|
||||
default: false
|
||||
- name: "recursive"
|
||||
type: "bool"
|
||||
description: "递归列出"
|
||||
required: false
|
||||
flag: "-R"
|
||||
format: "flag"
|
||||
default: false
|
||||
- name: "additional_args"
|
||||
type: "string"
|
||||
description: |
|
||||
额外的list-files参数。用于传递未在参数列表中定义的list-files选项。
|
||||
|
||||
**示例值:**
|
||||
- 根据工具特性添加常用参数示例
|
||||
|
||||
**注意事项:**
|
||||
- 多个参数用空格分隔
|
||||
- 确保参数格式正确,避免命令注入
|
||||
- 此参数会直接追加到命令末尾
|
||||
required: false
|
||||
format: "positional"
|
||||
|
Before Width: | Height: | Size: 614 KiB After Width: | Height: | Size: 97 KiB |
@@ -0,0 +1,944 @@
|
||||
// API文档页面JavaScript
|
||||
|
||||
let apiSpec = null;
|
||||
let currentToken = null;
|
||||
|
||||
// 初始化
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
await loadToken();
|
||||
await loadAPISpec();
|
||||
if (apiSpec) {
|
||||
renderAPIDocs();
|
||||
}
|
||||
});
|
||||
|
||||
// 加载token
|
||||
async function loadToken() {
|
||||
try {
|
||||
const authData = localStorage.getItem('cyberstrike-auth');
|
||||
if (authData) {
|
||||
const parsed = JSON.parse(authData);
|
||||
if (parsed && parsed.token) {
|
||||
const expiry = parsed.expiresAt ? new Date(parsed.expiresAt) : null;
|
||||
if (!expiry || expiry.getTime() > Date.now()) {
|
||||
currentToken = parsed.token;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
currentToken = localStorage.getItem('swagger_auth_token');
|
||||
} catch (e) {
|
||||
console.error('加载token失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// 加载OpenAPI规范
|
||||
async function loadAPISpec() {
|
||||
try {
|
||||
let url = '/api/openapi/spec';
|
||||
if (currentToken) {
|
||||
url += '?token=' + encodeURIComponent(currentToken);
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
showError('需要登录才能查看API文档。请先在前端页面登录,然后刷新此页面。');
|
||||
return;
|
||||
}
|
||||
throw new Error('加载API规范失败: ' + response.status);
|
||||
}
|
||||
|
||||
apiSpec = await response.json();
|
||||
} catch (error) {
|
||||
console.error('加载API规范失败:', error);
|
||||
showError('加载API文档失败: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 显示错误
|
||||
function showError(message) {
|
||||
const main = document.getElementById('api-docs-main');
|
||||
main.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<line x1="15" y1="9" x2="9" y2="15"/>
|
||||
<line x1="9" y1="9" x2="15" y2="15"/>
|
||||
</svg>
|
||||
<h3>加载失败</h3>
|
||||
<p>${message}</p>
|
||||
<div style="margin-top: 16px;">
|
||||
<a href="/" style="color: var(--accent-color); text-decoration: none;">返回首页登录</a>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 渲染API文档
|
||||
function renderAPIDocs() {
|
||||
if (!apiSpec || !apiSpec.paths) {
|
||||
showError('API规范格式错误');
|
||||
return;
|
||||
}
|
||||
|
||||
// 显示认证说明
|
||||
renderAuthInfo();
|
||||
|
||||
// 渲染侧边栏分组
|
||||
renderSidebar();
|
||||
|
||||
// 渲染API端点
|
||||
renderEndpoints();
|
||||
}
|
||||
|
||||
// 渲染认证说明
|
||||
function renderAuthInfo() {
|
||||
const authSection = document.getElementById('auth-info-section');
|
||||
if (!authSection) return;
|
||||
|
||||
// 显示认证说明部分
|
||||
authSection.style.display = 'block';
|
||||
|
||||
// 检查是否有token
|
||||
const tokenStatus = document.getElementById('token-status');
|
||||
if (currentToken && tokenStatus) {
|
||||
tokenStatus.style.display = 'block';
|
||||
} else if (tokenStatus) {
|
||||
// 如果没有token,显示提示
|
||||
tokenStatus.style.display = 'block';
|
||||
tokenStatus.style.background = 'rgba(255, 152, 0, 0.1)';
|
||||
tokenStatus.style.borderLeftColor = '#ff9800';
|
||||
tokenStatus.innerHTML = '<p style="margin: 0; font-size: 0.8125rem; color: #ff9800;"><strong>⚠ 未检测到 Token</strong> - 请先在前端页面登录,然后刷新此页面。测试接口时需要在请求头中添加 Authorization: Bearer token</p>';
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染侧边栏
|
||||
function renderSidebar() {
|
||||
const groups = new Set();
|
||||
Object.keys(apiSpec.paths).forEach(path => {
|
||||
Object.keys(apiSpec.paths[path]).forEach(method => {
|
||||
const endpoint = apiSpec.paths[path][method];
|
||||
if (endpoint.tags && endpoint.tags.length > 0) {
|
||||
endpoint.tags.forEach(tag => groups.add(tag));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const groupList = document.getElementById('api-group-list');
|
||||
const allGroups = Array.from(groups).sort();
|
||||
|
||||
allGroups.forEach(group => {
|
||||
const li = document.createElement('li');
|
||||
li.className = 'api-group-item';
|
||||
li.innerHTML = `<a href="#" class="api-group-link" data-group="${group}">${group}</a>`;
|
||||
groupList.appendChild(li);
|
||||
});
|
||||
|
||||
// 绑定点击事件
|
||||
groupList.querySelectorAll('.api-group-link').forEach(link => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
groupList.querySelectorAll('.api-group-link').forEach(l => l.classList.remove('active'));
|
||||
link.classList.add('active');
|
||||
const group = link.dataset.group;
|
||||
renderEndpoints(group === 'all' ? null : group);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 渲染API端点
|
||||
function renderEndpoints(filterGroup = null) {
|
||||
const main = document.getElementById('api-docs-main');
|
||||
main.innerHTML = '';
|
||||
|
||||
const endpoints = [];
|
||||
Object.keys(apiSpec.paths).forEach(path => {
|
||||
Object.keys(apiSpec.paths[path]).forEach(method => {
|
||||
const endpoint = apiSpec.paths[path][method];
|
||||
const tags = endpoint.tags || [];
|
||||
if (!filterGroup || filterGroup === 'all' || tags.includes(filterGroup)) {
|
||||
endpoints.push({
|
||||
path,
|
||||
method,
|
||||
...endpoint
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 按分组排序
|
||||
endpoints.sort((a, b) => {
|
||||
const tagA = a.tags && a.tags.length > 0 ? a.tags[0] : '';
|
||||
const tagB = b.tags && b.tags.length > 0 ? b.tags[0] : '';
|
||||
if (tagA !== tagB) return tagA.localeCompare(tagB);
|
||||
return a.path.localeCompare(b.path);
|
||||
});
|
||||
|
||||
if (endpoints.length === 0) {
|
||||
main.innerHTML = '<div class="empty-state"><h3>暂无API</h3><p>该分组下没有API端点</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
endpoints.forEach(endpoint => {
|
||||
main.appendChild(createEndpointCard(endpoint));
|
||||
});
|
||||
}
|
||||
|
||||
// 创建API端点卡片
|
||||
function createEndpointCard(endpoint) {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'api-endpoint';
|
||||
|
||||
const methodClass = endpoint.method.toLowerCase();
|
||||
const tags = endpoint.tags || [];
|
||||
const tagHtml = tags.map(tag => `<span class="api-tag">${tag}</span>`).join('');
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="api-endpoint-header">
|
||||
<div class="api-endpoint-title">
|
||||
<span class="api-method ${methodClass}">${endpoint.method.toUpperCase()}</span>
|
||||
<span class="api-path">${endpoint.path}</span>
|
||||
${tagHtml}
|
||||
</div>
|
||||
</div>
|
||||
<div class="api-endpoint-body">
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">描述</div>
|
||||
${endpoint.summary ? `<div class="api-description" style="font-weight: 500; margin-bottom: 8px; color: var(--text-primary);">${escapeHtml(endpoint.summary)}</div>` : ''}
|
||||
${endpoint.description ? `
|
||||
<div class="api-description-toggle">
|
||||
<button class="description-toggle-btn" onclick="toggleDescription(this)">
|
||||
<svg class="description-toggle-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="6 9 12 15 18 9"/>
|
||||
</svg>
|
||||
<span>查看详细说明</span>
|
||||
</button>
|
||||
<div class="api-description-detail" style="display: none;">
|
||||
${formatDescription(endpoint.description)}
|
||||
</div>
|
||||
</div>
|
||||
` : endpoint.summary ? '' : '<div class="api-description">无描述</div>'}
|
||||
</div>
|
||||
|
||||
${renderParameters(endpoint)}
|
||||
${renderRequestBody(endpoint)}
|
||||
${renderResponses(endpoint)}
|
||||
${renderTestSection(endpoint)}
|
||||
</div>
|
||||
`;
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// 渲染参数
|
||||
function renderParameters(endpoint) {
|
||||
const params = endpoint.parameters || [];
|
||||
if (params.length === 0) return '';
|
||||
|
||||
const rows = params.map(param => {
|
||||
const required = param.required ? '<span class="api-param-required">必需</span>' : '<span class="api-param-optional">可选</span>';
|
||||
// 处理描述文本,将换行符转换为<br>
|
||||
let descriptionHtml = '-';
|
||||
if (param.description) {
|
||||
const escapedDesc = escapeHtml(param.description);
|
||||
descriptionHtml = escapedDesc.replace(/\n/g, '<br>');
|
||||
}
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td><span class="api-param-name">${param.name}</span></td>
|
||||
<td><span class="api-param-type">${param.schema?.type || 'string'}</span></td>
|
||||
<td>${descriptionHtml}</td>
|
||||
<td>${required}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
return `
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">参数</div>
|
||||
<div class="api-table-wrapper">
|
||||
<table class="api-params-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>参数名</th>
|
||||
<th>类型</th>
|
||||
<th>描述</th>
|
||||
<th>必需</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${rows}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 渲染请求体
|
||||
function renderRequestBody(endpoint) {
|
||||
if (!endpoint.requestBody) return '';
|
||||
|
||||
const content = endpoint.requestBody.content || {};
|
||||
let schema = content['application/json']?.schema || {};
|
||||
|
||||
// 处理 $ref 引用
|
||||
if (schema.$ref) {
|
||||
const refPath = schema.$ref.split('/');
|
||||
const refName = refPath[refPath.length - 1];
|
||||
if (apiSpec.components && apiSpec.components.schemas && apiSpec.components.schemas[refName]) {
|
||||
schema = apiSpec.components.schemas[refName];
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染参数表格
|
||||
let paramsTable = '';
|
||||
if (schema.properties) {
|
||||
const requiredFields = schema.required || [];
|
||||
const rows = Object.keys(schema.properties).map(key => {
|
||||
const prop = schema.properties[key];
|
||||
const required = requiredFields.includes(key)
|
||||
? '<span class="api-param-required">必需</span>'
|
||||
: '<span class="api-param-optional">可选</span>';
|
||||
|
||||
// 处理嵌套类型
|
||||
let typeDisplay = prop.type || 'object';
|
||||
if (prop.type === 'array' && prop.items) {
|
||||
typeDisplay = `array[${prop.items.type || 'object'}]`;
|
||||
} else if (prop.$ref) {
|
||||
const refPath = prop.$ref.split('/');
|
||||
typeDisplay = refPath[refPath.length - 1];
|
||||
}
|
||||
|
||||
// 处理枚举
|
||||
if (prop.enum) {
|
||||
typeDisplay += ` (${prop.enum.join(', ')})`;
|
||||
}
|
||||
|
||||
// 处理描述文本,将换行符转换为<br>,但保持其他格式
|
||||
let descriptionHtml = '-';
|
||||
if (prop.description) {
|
||||
// 转义HTML,然后处理换行
|
||||
const escapedDesc = escapeHtml(prop.description);
|
||||
// 将 \n 转换为 <br>,但不要转换已经转义的换行
|
||||
descriptionHtml = escapedDesc.replace(/\n/g, '<br>');
|
||||
}
|
||||
|
||||
return `
|
||||
<tr>
|
||||
<td><span class="api-param-name">${escapeHtml(key)}</span></td>
|
||||
<td><span class="api-param-type">${escapeHtml(typeDisplay)}</span></td>
|
||||
<td>${descriptionHtml}</td>
|
||||
<td>${required}</td>
|
||||
<td>${prop.example !== undefined ? `<code>${escapeHtml(String(prop.example))}</code>` : '-'}</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
if (rows) {
|
||||
paramsTable = `
|
||||
<div class="api-table-wrapper" style="margin-top: 12px;">
|
||||
<table class="api-params-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>参数名</th>
|
||||
<th>类型</th>
|
||||
<th>描述</th>
|
||||
<th>必需</th>
|
||||
<th>示例</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${rows}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// 生成示例JSON
|
||||
let example = '';
|
||||
if (schema.example) {
|
||||
example = JSON.stringify(schema.example, null, 2);
|
||||
} else if (schema.properties) {
|
||||
const exampleObj = {};
|
||||
Object.keys(schema.properties).forEach(key => {
|
||||
const prop = schema.properties[key];
|
||||
if (prop.example !== undefined) {
|
||||
exampleObj[key] = prop.example;
|
||||
} else {
|
||||
// 根据类型生成默认示例
|
||||
if (prop.type === 'string') {
|
||||
exampleObj[key] = prop.description || 'string';
|
||||
} else if (prop.type === 'number') {
|
||||
exampleObj[key] = 0;
|
||||
} else if (prop.type === 'boolean') {
|
||||
exampleObj[key] = false;
|
||||
} else if (prop.type === 'array') {
|
||||
exampleObj[key] = [];
|
||||
} else {
|
||||
exampleObj[key] = null;
|
||||
}
|
||||
}
|
||||
});
|
||||
example = JSON.stringify(exampleObj, null, 2);
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">请求体</div>
|
||||
${endpoint.requestBody.description ? `<div class="api-description">${endpoint.requestBody.description}</div>` : ''}
|
||||
${paramsTable}
|
||||
${example ? `
|
||||
<div style="margin-top: 16px;">
|
||||
<div style="font-weight: 500; margin-bottom: 8px; color: var(--text-primary);">示例JSON:</div>
|
||||
<div class="api-response-example">
|
||||
<pre>${escapeHtml(example)}</pre>
|
||||
</div>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 渲染响应
|
||||
function renderResponses(endpoint) {
|
||||
const responses = endpoint.responses || {};
|
||||
const responseItems = Object.keys(responses).map(status => {
|
||||
const response = responses[status];
|
||||
const schema = response.content?.['application/json']?.schema || {};
|
||||
let example = '';
|
||||
if (schema.example) {
|
||||
example = JSON.stringify(schema.example, null, 2);
|
||||
}
|
||||
|
||||
return `
|
||||
<div style="margin-bottom: 16px;">
|
||||
<strong style="color: ${status.startsWith('2') ? 'var(--success-color)' : status.startsWith('4') ? 'var(--error-color)' : 'var(--warning-color)'}">${status}</strong>
|
||||
${response.description ? `<span style="color: var(--text-secondary); margin-left: 8px;">${response.description}</span>` : ''}
|
||||
${example ? `
|
||||
<div class="api-response-example" style="margin-top: 8px;">
|
||||
<pre>${escapeHtml(example)}</pre>
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
if (!responseItems) return '';
|
||||
|
||||
return `
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">响应</div>
|
||||
${responseItems}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 渲染测试区域
|
||||
function renderTestSection(endpoint) {
|
||||
const method = endpoint.method.toUpperCase();
|
||||
const path = endpoint.path;
|
||||
const hasBody = endpoint.requestBody && ['POST', 'PUT', 'PATCH'].includes(method);
|
||||
|
||||
let bodyInput = '';
|
||||
if (hasBody) {
|
||||
const schema = endpoint.requestBody.content?.['application/json']?.schema || {};
|
||||
let defaultBody = '';
|
||||
if (schema.example) {
|
||||
defaultBody = JSON.stringify(schema.example, null, 2);
|
||||
} else if (schema.properties) {
|
||||
const exampleObj = {};
|
||||
Object.keys(schema.properties).forEach(key => {
|
||||
const prop = schema.properties[key];
|
||||
exampleObj[key] = prop.example || (prop.type === 'string' ? '' : prop.type === 'number' ? 0 : prop.type === 'boolean' ? false : null);
|
||||
});
|
||||
defaultBody = JSON.stringify(exampleObj, null, 2);
|
||||
}
|
||||
|
||||
const bodyInputId = `test-body-${escapeId(path)}-${method}`;
|
||||
bodyInput = `
|
||||
<div class="api-test-input-group">
|
||||
<label>请求体 (JSON)</label>
|
||||
<textarea id="${bodyInputId}" class="test-body-input" placeholder='请输入JSON格式的请求体'>${defaultBody}</textarea>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 处理路径参数
|
||||
const pathParams = (endpoint.parameters || []).filter(p => p.in === 'path');
|
||||
let pathParamsInput = '';
|
||||
if (pathParams.length > 0) {
|
||||
pathParamsInput = pathParams.map(param => {
|
||||
const inputId = `test-param-${param.name}-${escapeId(path)}-${method}`;
|
||||
return `
|
||||
<div class="api-test-input-group">
|
||||
<label>${param.name} <span style="color: var(--error-color);">*</span></label>
|
||||
<input type="text" id="${inputId}" placeholder="${param.description || param.name}" required>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// 处理查询参数
|
||||
const queryParams = (endpoint.parameters || []).filter(p => p.in === 'query');
|
||||
let queryParamsInput = '';
|
||||
if (queryParams.length > 0) {
|
||||
queryParamsInput = queryParams.map(param => {
|
||||
const inputId = `test-query-${param.name}-${escapeId(path)}-${method}`;
|
||||
const defaultValue = param.schema?.default !== undefined ? param.schema.default : '';
|
||||
const placeholder = param.description || param.name;
|
||||
const required = param.required ? '<span style="color: var(--error-color);">*</span>' : '<span style="color: var(--text-muted);">可选</span>';
|
||||
return `
|
||||
<div class="api-test-input-group">
|
||||
<label>${param.name} ${required}</label>
|
||||
<input type="${param.schema?.type === 'number' || param.schema?.type === 'integer' ? 'number' : 'text'}"
|
||||
id="${inputId}"
|
||||
placeholder="${placeholder}"
|
||||
value="${defaultValue}"
|
||||
${param.required ? 'required' : ''}>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="api-test-section">
|
||||
<div class="api-section-title">测试接口</div>
|
||||
<div class="api-test-form">
|
||||
${pathParamsInput}
|
||||
${queryParamsInput ? `<div style="margin-top: 16px;"><div style="font-weight: 500; margin-bottom: 8px; color: var(--text-primary);">查询参数:</div>${queryParamsInput}</div>` : ''}
|
||||
${bodyInput}
|
||||
<div class="api-test-buttons">
|
||||
<button class="api-test-btn primary" onclick="testAPI('${method}', '${escapeHtml(path)}', '${endpoint.operationId || ''}')">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polygon points="5 3 19 12 5 21 5 3"/>
|
||||
</svg>
|
||||
发送请求
|
||||
</button>
|
||||
<button class="api-test-btn copy-curl" onclick="copyCurlCommand(event, '${method}', '${escapeHtml(path)}')" title="复制curl命令">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" stroke="currentColor" stroke-width="2"/>
|
||||
</svg>
|
||||
复制curl
|
||||
</button>
|
||||
<button class="api-test-btn clear-result" onclick="clearTestResult('${escapeId(path)}-${method}')" title="清除测试结果">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="3 6 5 6 21 6"/>
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
|
||||
</svg>
|
||||
清除结果
|
||||
</button>
|
||||
</div>
|
||||
<div id="test-result-${escapeId(path)}-${method}" class="api-test-result" style="display: none;"></div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 测试API
|
||||
async function testAPI(method, path, operationId) {
|
||||
const resultId = `test-result-${escapeId(path)}-${method}`;
|
||||
const resultDiv = document.getElementById(resultId);
|
||||
if (!resultDiv) return;
|
||||
|
||||
resultDiv.style.display = 'block';
|
||||
resultDiv.className = 'api-test-result loading';
|
||||
resultDiv.textContent = '发送请求中...';
|
||||
|
||||
try {
|
||||
// 替换路径参数
|
||||
let actualPath = path;
|
||||
const pathParams = path.match(/\{([^}]+)\}/g) || [];
|
||||
pathParams.forEach(param => {
|
||||
const paramName = param.slice(1, -1);
|
||||
const inputId = `test-param-${paramName}-${escapeId(path)}-${method}`;
|
||||
const input = document.getElementById(inputId);
|
||||
if (input && input.value) {
|
||||
actualPath = actualPath.replace(param, encodeURIComponent(input.value));
|
||||
} else {
|
||||
throw new Error(`路径参数 ${paramName} 不能为空`);
|
||||
}
|
||||
});
|
||||
|
||||
// 确保路径以/api开头(如果OpenAPI规范中的路径不包含/api)
|
||||
if (!actualPath.startsWith('/api') && !actualPath.startsWith('http')) {
|
||||
actualPath = '/api' + actualPath;
|
||||
}
|
||||
|
||||
// 构建查询参数
|
||||
const queryParams = [];
|
||||
const endpointSpec = apiSpec.paths[path]?.[method.toLowerCase()];
|
||||
if (endpointSpec && endpointSpec.parameters) {
|
||||
endpointSpec.parameters.filter(p => p.in === 'query').forEach(param => {
|
||||
const inputId = `test-query-${param.name}-${escapeId(path)}-${method}`;
|
||||
const input = document.getElementById(inputId);
|
||||
if (input && input.value !== '' && input.value !== null && input.value !== undefined) {
|
||||
queryParams.push(`${encodeURIComponent(param.name)}=${encodeURIComponent(input.value)}`);
|
||||
} else if (param.required) {
|
||||
throw new Error(`查询参数 ${param.name} 不能为空`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 添加查询字符串
|
||||
if (queryParams.length > 0) {
|
||||
actualPath += (actualPath.includes('?') ? '&' : '?') + queryParams.join('&');
|
||||
}
|
||||
|
||||
// 构建请求选项
|
||||
const options = {
|
||||
method: method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
};
|
||||
|
||||
// 添加token
|
||||
if (currentToken) {
|
||||
options.headers['Authorization'] = 'Bearer ' + currentToken;
|
||||
} else {
|
||||
// 如果没有token,提示用户
|
||||
throw new Error('未检测到 Token。请先在前端页面登录,然后刷新此页面。或者手动在请求头中添加 Authorization: Bearer your_token');
|
||||
}
|
||||
|
||||
// 添加请求体
|
||||
if (['POST', 'PUT', 'PATCH'].includes(method)) {
|
||||
const bodyInputId = `test-body-${escapeId(path)}-${method}`;
|
||||
const bodyInput = document.getElementById(bodyInputId);
|
||||
if (bodyInput && bodyInput.value.trim()) {
|
||||
try {
|
||||
options.body = JSON.stringify(JSON.parse(bodyInput.value.trim()));
|
||||
} catch (e) {
|
||||
throw new Error('请求体JSON格式错误: ' + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 发送请求
|
||||
const response = await fetch(actualPath, options);
|
||||
const responseText = await response.text();
|
||||
|
||||
let responseData;
|
||||
try {
|
||||
responseData = JSON.parse(responseText);
|
||||
} catch {
|
||||
responseData = responseText;
|
||||
}
|
||||
|
||||
// 显示结果
|
||||
resultDiv.className = response.ok ? 'api-test-result success' : 'api-test-result error';
|
||||
resultDiv.textContent = `状态码: ${response.status} ${response.statusText}\n\n${typeof responseData === 'string' ? responseData : JSON.stringify(responseData, null, 2)}`;
|
||||
|
||||
} catch (error) {
|
||||
resultDiv.className = 'api-test-result error';
|
||||
resultDiv.textContent = '请求失败: ' + error.message;
|
||||
}
|
||||
}
|
||||
|
||||
// 清除测试结果
|
||||
function clearTestResult(id) {
|
||||
const resultDiv = document.getElementById(`test-result-${id}`);
|
||||
if (resultDiv) {
|
||||
resultDiv.style.display = 'none';
|
||||
resultDiv.textContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// 复制curl命令
|
||||
function copyCurlCommand(event, method, path) {
|
||||
try {
|
||||
// 替换路径参数
|
||||
let actualPath = path;
|
||||
const pathParams = path.match(/\{([^}]+)\}/g) || [];
|
||||
pathParams.forEach(param => {
|
||||
const paramName = param.slice(1, -1);
|
||||
const inputId = `test-param-${paramName}-${escapeId(path)}-${method}`;
|
||||
const input = document.getElementById(inputId);
|
||||
if (input && input.value) {
|
||||
actualPath = actualPath.replace(param, encodeURIComponent(input.value));
|
||||
}
|
||||
});
|
||||
|
||||
// 确保路径以/api开头
|
||||
if (!actualPath.startsWith('/api') && !actualPath.startsWith('http')) {
|
||||
actualPath = '/api' + actualPath;
|
||||
}
|
||||
|
||||
// 构建查询参数
|
||||
const queryParams = [];
|
||||
const endpointSpec = apiSpec.paths[path]?.[method.toLowerCase()];
|
||||
if (endpointSpec && endpointSpec.parameters) {
|
||||
endpointSpec.parameters.filter(p => p.in === 'query').forEach(param => {
|
||||
const inputId = `test-query-${param.name}-${escapeId(path)}-${method}`;
|
||||
const input = document.getElementById(inputId);
|
||||
if (input && input.value !== '' && input.value !== null && input.value !== undefined) {
|
||||
queryParams.push(`${encodeURIComponent(param.name)}=${encodeURIComponent(input.value)}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 添加查询字符串
|
||||
if (queryParams.length > 0) {
|
||||
actualPath += (actualPath.includes('?') ? '&' : '?') + queryParams.join('&');
|
||||
}
|
||||
|
||||
// 构建完整的URL
|
||||
const baseUrl = window.location.origin;
|
||||
const fullUrl = baseUrl + actualPath;
|
||||
|
||||
// 构建curl命令
|
||||
let curlCommand = `curl -X ${method.toUpperCase()} "${fullUrl}"`;
|
||||
|
||||
// 添加请求头
|
||||
curlCommand += ` \\\n -H "Content-Type: application/json"`;
|
||||
|
||||
// 添加Authorization头
|
||||
if (currentToken) {
|
||||
curlCommand += ` \\\n -H "Authorization: Bearer ${currentToken}"`;
|
||||
} else {
|
||||
curlCommand += ` \\\n -H "Authorization: Bearer YOUR_TOKEN_HERE"`;
|
||||
}
|
||||
|
||||
// 添加请求体(如果有)
|
||||
if (['POST', 'PUT', 'PATCH'].includes(method.toUpperCase())) {
|
||||
const bodyInputId = `test-body-${escapeId(path)}-${method}`;
|
||||
const bodyInput = document.getElementById(bodyInputId);
|
||||
if (bodyInput && bodyInput.value.trim()) {
|
||||
try {
|
||||
// 验证JSON格式并格式化
|
||||
const jsonBody = JSON.parse(bodyInput.value.trim());
|
||||
const jsonString = JSON.stringify(jsonBody);
|
||||
// 在单引号内,只需要转义单引号本身
|
||||
const escapedJson = jsonString.replace(/'/g, "'\\''");
|
||||
curlCommand += ` \\\n -d '${escapedJson}'`;
|
||||
} catch (e) {
|
||||
// 如果不是有效JSON,直接使用原始值
|
||||
const escapedBody = bodyInput.value.trim().replace(/'/g, "'\\''");
|
||||
curlCommand += ` \\\n -d '${escapedBody}'`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 复制到剪贴板
|
||||
const button = event ? event.target.closest('button') : null;
|
||||
navigator.clipboard.writeText(curlCommand).then(() => {
|
||||
// 显示成功提示
|
||||
if (button) {
|
||||
const originalText = button.innerHTML;
|
||||
button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>已复制';
|
||||
button.style.color = 'var(--success-color)';
|
||||
setTimeout(() => {
|
||||
button.innerHTML = originalText;
|
||||
button.style.color = '';
|
||||
}, 2000);
|
||||
} else {
|
||||
alert('curl命令已复制到剪贴板!');
|
||||
}
|
||||
}).catch(err => {
|
||||
console.error('复制失败:', err);
|
||||
// 如果clipboard API失败,使用fallback方法
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = curlCommand;
|
||||
textarea.style.position = 'fixed';
|
||||
textarea.style.opacity = '0';
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
if (button) {
|
||||
const originalText = button.innerHTML;
|
||||
button.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>已复制';
|
||||
button.style.color = 'var(--success-color)';
|
||||
setTimeout(() => {
|
||||
button.innerHTML = originalText;
|
||||
button.style.color = '';
|
||||
}, 2000);
|
||||
} else {
|
||||
alert('curl命令已复制到剪贴板!');
|
||||
}
|
||||
} catch (e) {
|
||||
alert('复制失败,请手动复制:\n\n' + curlCommand);
|
||||
}
|
||||
document.body.removeChild(textarea);
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('生成curl命令失败:', error);
|
||||
alert('生成curl命令失败: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 格式化描述文本(处理markdown格式)
|
||||
function formatDescription(text) {
|
||||
if (!text) return '';
|
||||
|
||||
// 先提取代码块(避免代码块内的markdown被处理)
|
||||
let formatted = text;
|
||||
const codeBlocks = [];
|
||||
let codeBlockIndex = 0;
|
||||
|
||||
// 提取代码块(支持语言标识符,如 ```json 或 ```javascript)
|
||||
formatted = formatted.replace(/```(\w+)?\s*\n?([\s\S]*?)```/g, (match, lang, code) => {
|
||||
const placeholder = `__CODE_BLOCK_${codeBlockIndex}__`;
|
||||
codeBlocks[codeBlockIndex] = {
|
||||
lang: (lang && lang.trim()) || '',
|
||||
code: code.trim()
|
||||
};
|
||||
codeBlockIndex++;
|
||||
return placeholder;
|
||||
});
|
||||
|
||||
// 提取行内代码(避免行内代码内的markdown被处理)
|
||||
const inlineCodes = [];
|
||||
let inlineCodeIndex = 0;
|
||||
formatted = formatted.replace(/`([^`\n]+)`/g, (match, code) => {
|
||||
const placeholder = `__INLINE_CODE_${inlineCodeIndex}__`;
|
||||
inlineCodes[inlineCodeIndex] = code;
|
||||
inlineCodeIndex++;
|
||||
return placeholder;
|
||||
});
|
||||
|
||||
// 转义HTML(但保留占位符)
|
||||
formatted = escapeHtml(formatted);
|
||||
|
||||
// 恢复行内代码(需要转义,因为占位符已经被转义了)
|
||||
inlineCodes.forEach((code, index) => {
|
||||
formatted = formatted.replace(
|
||||
`__INLINE_CODE_${index}__`,
|
||||
`<code class="inline-code">${escapeHtml(code)}</code>`
|
||||
);
|
||||
});
|
||||
|
||||
// 恢复代码块(代码块内容已经转义过,直接使用)
|
||||
codeBlocks.forEach((block, index) => {
|
||||
const langLabel = block.lang ? `<span class="code-lang">${escapeHtml(block.lang)}</span>` : '';
|
||||
// 代码块内容已经在提取时保存,不需要再次转义
|
||||
formatted = formatted.replace(
|
||||
`__CODE_BLOCK_${index}__`,
|
||||
`<pre class="code-block">${langLabel}<code>${escapeHtml(block.code)}</code></pre>`
|
||||
);
|
||||
});
|
||||
|
||||
// 处理标题(### 标题)
|
||||
formatted = formatted.replace(/^###\s+(.+)$/gm, '<h3 class="md-h3">$1</h3>');
|
||||
formatted = formatted.replace(/^##\s+(.+)$/gm, '<h2 class="md-h2">$1</h2>');
|
||||
formatted = formatted.replace(/^#\s+(.+)$/gm, '<h1 class="md-h1">$1</h1>');
|
||||
|
||||
// 处理加粗文本(**text** 或 __text__)
|
||||
formatted = formatted.replace(/\*\*([^*]+?)\*\*/g, '<strong>$1</strong>');
|
||||
formatted = formatted.replace(/__([^_]+?)__/g, '<strong>$1</strong>');
|
||||
|
||||
// 处理斜体(*text* 或 _text_,但不与加粗冲突)
|
||||
formatted = formatted.replace(/(?<!\*)\*([^*\n]+?)\*(?!\*)/g, '<em>$1</em>');
|
||||
formatted = formatted.replace(/(?<!_)_([^_\n]+?)_(?!_)/g, '<em>$1</em>');
|
||||
|
||||
// 处理链接 [text](url)
|
||||
formatted = formatted.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer" class="md-link">$1</a>');
|
||||
|
||||
// 处理列表项(有序和无序)
|
||||
const lines = formatted.split('\n');
|
||||
const result = [];
|
||||
let inUnorderedList = false;
|
||||
let inOrderedList = false;
|
||||
let orderedListStart = 1;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
const unorderedMatch = line.match(/^[-*]\s+(.+)$/);
|
||||
const orderedMatch = line.match(/^\d+\.\s+(.+)$/);
|
||||
|
||||
if (unorderedMatch) {
|
||||
if (inOrderedList) {
|
||||
result.push('</ol>');
|
||||
inOrderedList = false;
|
||||
}
|
||||
if (!inUnorderedList) {
|
||||
result.push('<ul class="md-list">');
|
||||
inUnorderedList = true;
|
||||
}
|
||||
result.push(`<li class="md-list-item">${unorderedMatch[1]}</li>`);
|
||||
} else if (orderedMatch) {
|
||||
if (inUnorderedList) {
|
||||
result.push('</ul>');
|
||||
inUnorderedList = false;
|
||||
}
|
||||
if (!inOrderedList) {
|
||||
result.push('<ol class="md-list">');
|
||||
inOrderedList = true;
|
||||
orderedListStart = parseInt(line.match(/^(\d+)\./)[1]) || 1;
|
||||
}
|
||||
result.push(`<li class="md-list-item">${orderedMatch[1]}</li>`);
|
||||
} else {
|
||||
if (inUnorderedList) {
|
||||
result.push('</ul>');
|
||||
inUnorderedList = false;
|
||||
}
|
||||
if (inOrderedList) {
|
||||
result.push('</ol>');
|
||||
inOrderedList = false;
|
||||
}
|
||||
if (line.trim()) {
|
||||
result.push(line);
|
||||
} else if (i < lines.length - 1) {
|
||||
// 只在非最后一行时添加换行
|
||||
result.push('<br>');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (inUnorderedList) {
|
||||
result.push('</ul>');
|
||||
}
|
||||
if (inOrderedList) {
|
||||
result.push('</ol>');
|
||||
}
|
||||
|
||||
formatted = result.join('\n');
|
||||
|
||||
// 处理段落(连续的空行分隔段落)
|
||||
formatted = formatted.replace(/(<br>\s*){2,}/g, '</p><p class="md-paragraph">');
|
||||
formatted = '<p class="md-paragraph">' + formatted + '</p>';
|
||||
|
||||
// 清理多余的<br>标签(在块级元素前后)
|
||||
formatted = formatted.replace(/(<\/?(h[1-6]|ul|ol|li|pre|p)[^>]*>)\s*<br>/gi, '$1');
|
||||
formatted = formatted.replace(/<br>\s*(<\/?(h[1-6]|ul|ol|li|pre|p)[^>]*>)/gi, '$1');
|
||||
|
||||
// 将剩余的单个换行符转换为<br>(但避免在块级元素内)
|
||||
formatted = formatted.replace(/\n(?!<\/?(h[1-6]|ul|ol|li|pre|p|code))/g, '<br>');
|
||||
|
||||
return formatted;
|
||||
}
|
||||
|
||||
// HTML转义
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
// ID转义(用于HTML ID属性)
|
||||
function escapeId(text) {
|
||||
return text.replace(/[{}]/g, '').replace(/\//g, '-');
|
||||
}
|
||||
|
||||
// 切换描述显示/隐藏
|
||||
function toggleDescription(button) {
|
||||
const icon = button.querySelector('.description-toggle-icon');
|
||||
const detail = button.parentElement.querySelector('.api-description-detail');
|
||||
const span = button.querySelector('span');
|
||||
|
||||
if (detail.style.display === 'none') {
|
||||
detail.style.display = 'block';
|
||||
icon.style.transform = 'rotate(180deg)';
|
||||
span.textContent = '隐藏详细说明';
|
||||
} else {
|
||||
detail.style.display = 'none';
|
||||
icon.style.transform = 'rotate(0deg)';
|
||||
span.textContent = '查看详细说明';
|
||||
}
|
||||
}
|
||||
@@ -1260,7 +1260,8 @@ function renderProcessDetails(messageId, processDetails) {
|
||||
addTimelineItem(timeline, eventType, {
|
||||
title: itemTitle,
|
||||
message: detail.message || '',
|
||||
data: data
|
||||
data: data,
|
||||
createdAt: detail.createdAt // 传递实际的事件创建时间
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1980,6 +1981,16 @@ async function deleteConversation(conversationId, skipConfirm = false) {
|
||||
addAttackChainButton(null);
|
||||
}
|
||||
|
||||
// 更新缓存 - 立即删除,确保后续加载时能正确识别
|
||||
delete conversationGroupMappingCache[conversationId];
|
||||
// 同时从待保留映射中移除
|
||||
delete pendingGroupMappings[conversationId];
|
||||
|
||||
// 如果当前在分组详情页面,重新加载分组对话
|
||||
if (currentGroupId) {
|
||||
await loadGroupConversations(currentGroupId);
|
||||
}
|
||||
|
||||
// 刷新对话列表
|
||||
loadConversations();
|
||||
} catch (error) {
|
||||
@@ -4983,9 +4994,25 @@ function closeBatchManageModal() {
|
||||
function showCreateGroupModal(andMoveConversation = false) {
|
||||
const modal = document.getElementById('create-group-modal');
|
||||
const input = document.getElementById('create-group-name-input');
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
const iconPicker = document.getElementById('group-icon-picker');
|
||||
const customInput = document.getElementById('custom-icon-input');
|
||||
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
// 重置图标为默认值
|
||||
if (iconBtn) {
|
||||
iconBtn.textContent = '📁';
|
||||
}
|
||||
// 清空自定义图标输入框
|
||||
if (customInput) {
|
||||
customInput.value = '';
|
||||
}
|
||||
// 关闭图标选择器
|
||||
if (iconPicker) {
|
||||
iconPicker.style.display = 'none';
|
||||
}
|
||||
if (modal) {
|
||||
modal.style.display = 'flex';
|
||||
modal.dataset.moveConversation = andMoveConversation ? 'true' : 'false';
|
||||
@@ -5005,6 +5032,21 @@ function closeCreateGroupModal() {
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
// 重置图标为默认值
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
if (iconBtn) {
|
||||
iconBtn.textContent = '📁';
|
||||
}
|
||||
// 清空自定义图标输入框
|
||||
const customInput = document.getElementById('custom-icon-input');
|
||||
if (customInput) {
|
||||
customInput.value = '';
|
||||
}
|
||||
// 关闭图标选择器
|
||||
const iconPicker = document.getElementById('group-icon-picker');
|
||||
if (iconPicker) {
|
||||
iconPicker.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// 选择建议标签
|
||||
@@ -5016,6 +5058,81 @@ function selectSuggestion(name) {
|
||||
}
|
||||
}
|
||||
|
||||
// 切换图标选择器显示状态
|
||||
function toggleGroupIconPicker() {
|
||||
const picker = document.getElementById('group-icon-picker');
|
||||
if (picker) {
|
||||
const isVisible = picker.style.display !== 'none';
|
||||
picker.style.display = isVisible ? 'none' : 'block';
|
||||
}
|
||||
}
|
||||
|
||||
// 选择分组图标
|
||||
function selectGroupIcon(icon) {
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
if (iconBtn) {
|
||||
iconBtn.textContent = icon;
|
||||
}
|
||||
// 清空自定义输入框
|
||||
const customInput = document.getElementById('custom-icon-input');
|
||||
if (customInput) {
|
||||
customInput.value = '';
|
||||
}
|
||||
// 关闭选择器
|
||||
const picker = document.getElementById('group-icon-picker');
|
||||
if (picker) {
|
||||
picker.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// 应用自定义图标
|
||||
function applyCustomIcon() {
|
||||
const customInput = document.getElementById('custom-icon-input');
|
||||
if (!customInput) return;
|
||||
|
||||
const customIcon = customInput.value.trim();
|
||||
if (!customIcon) {
|
||||
return;
|
||||
}
|
||||
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
if (iconBtn) {
|
||||
iconBtn.textContent = customIcon;
|
||||
}
|
||||
|
||||
// 清空输入框并关闭选择器
|
||||
customInput.value = '';
|
||||
const picker = document.getElementById('group-icon-picker');
|
||||
if (picker) {
|
||||
picker.style.display = 'none';
|
||||
}
|
||||
}
|
||||
|
||||
// 自定义图标输入框回车键处理
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const customInput = document.getElementById('custom-icon-input');
|
||||
if (customInput) {
|
||||
customInput.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
applyCustomIcon();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 点击外部关闭图标选择器
|
||||
document.addEventListener('click', function(event) {
|
||||
const picker = document.getElementById('group-icon-picker');
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
if (picker && iconBtn) {
|
||||
// 如果点击的不是图标按钮和选择器本身,则关闭选择器
|
||||
if (!picker.contains(event.target) && !iconBtn.contains(event.target)) {
|
||||
picker.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 创建分组
|
||||
async function createGroup(event) {
|
||||
// 阻止事件冒泡
|
||||
@@ -5060,6 +5177,10 @@ async function createGroup(event) {
|
||||
console.error('检查分组名称失败:', error);
|
||||
}
|
||||
|
||||
// 获取选中的图标
|
||||
const iconBtn = document.getElementById('create-group-icon-btn');
|
||||
const selectedIcon = iconBtn ? iconBtn.textContent.trim() : '📁';
|
||||
|
||||
try {
|
||||
const response = await apiFetch('/api/groups', {
|
||||
method: 'POST',
|
||||
@@ -5068,7 +5189,7 @@ async function createGroup(event) {
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
icon: '📁',
|
||||
icon: selectedIcon,
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -5750,4 +5871,34 @@ document.addEventListener('DOMContentLoaded', async () => {
|
||||
};
|
||||
}
|
||||
await loadConversationsWithGroups();
|
||||
|
||||
// 添加页面焦点时自动刷新对话列表的功能
|
||||
// 这样当通过OpenAPI创建对话后,切换回页面时能自动看到新对话
|
||||
let lastFocusTime = Date.now();
|
||||
const CONVERSATION_REFRESH_INTERVAL = 30000; // 30秒内最多刷新一次,避免过于频繁
|
||||
|
||||
window.addEventListener('focus', () => {
|
||||
const now = Date.now();
|
||||
// 如果距离上次刷新超过30秒,才刷新对话列表
|
||||
if (now - lastFocusTime > CONVERSATION_REFRESH_INTERVAL) {
|
||||
lastFocusTime = now;
|
||||
if (typeof loadConversationsWithGroups === 'function') {
|
||||
loadConversationsWithGroups();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 监听页面可见性变化(当用户切换标签页回来时)
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!document.hidden) {
|
||||
// 页面变为可见时,检查是否需要刷新
|
||||
const now = Date.now();
|
||||
if (now - lastFocusTime > CONVERSATION_REFRESH_INTERVAL) {
|
||||
lastFocusTime = now;
|
||||
if (typeof loadConversationsWithGroups === 'function') {
|
||||
loadConversationsWithGroups();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
// 仪表盘页面:拉取运行中任务、漏洞统计、批量任务、工具与 Skills 统计并渲染
|
||||
|
||||
async function refreshDashboard() {
|
||||
const runningEl = document.getElementById('dashboard-running-tasks');
|
||||
const vulnTotalEl = document.getElementById('dashboard-vuln-total');
|
||||
const severityIds = ['critical', 'high', 'medium', 'low', 'info'];
|
||||
|
||||
if (runningEl) runningEl.textContent = '…';
|
||||
if (vulnTotalEl) vulnTotalEl.textContent = '…';
|
||||
severityIds.forEach(s => {
|
||||
const el = document.getElementById('dashboard-severity-' + s);
|
||||
if (el) el.textContent = '0';
|
||||
const barEl = document.getElementById('dashboard-bar-' + s);
|
||||
if (barEl) barEl.style.width = '0%';
|
||||
});
|
||||
setDashboardOverviewPlaceholder('…');
|
||||
setEl('dashboard-kpi-tools-calls', '…');
|
||||
setEl('dashboard-kpi-success-rate', '…');
|
||||
var chartPlaceholder = document.getElementById('dashboard-tools-pie-placeholder');
|
||||
if (chartPlaceholder) { chartPlaceholder.style.removeProperty('display'); chartPlaceholder.textContent = '加载中…'; }
|
||||
var barChartEl = document.getElementById('dashboard-tools-bar-chart');
|
||||
if (barChartEl) { barChartEl.style.display = 'none'; barChartEl.innerHTML = ''; }
|
||||
|
||||
if (typeof apiFetch === 'undefined') {
|
||||
if (runningEl) runningEl.textContent = '-';
|
||||
if (vulnTotalEl) vulnTotalEl.textContent = '-';
|
||||
setDashboardOverviewPlaceholder('-');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const [tasksRes, vulnRes, batchRes, monitorRes, knowledgeRes, skillsRes] = await Promise.all([
|
||||
apiFetch('/api/agent-loop/tasks').then(r => r.ok ? r.json() : null).catch(() => null),
|
||||
apiFetch('/api/vulnerabilities/stats').then(r => r.ok ? r.json() : null).catch(() => null),
|
||||
apiFetch('/api/batch-tasks?limit=500&page=1').then(r => r.ok ? r.json() : null).catch(() => null),
|
||||
apiFetch('/api/monitor/stats').then(r => r.ok ? r.json() : null).catch(() => null),
|
||||
apiFetch('/api/knowledge/stats').then(r => r.ok ? r.json() : null).catch(() => null),
|
||||
apiFetch('/api/skills/stats').then(r => r.ok ? r.json() : null).catch(() => null)
|
||||
]);
|
||||
|
||||
if (tasksRes && Array.isArray(tasksRes.tasks)) {
|
||||
if (runningEl) runningEl.textContent = String(tasksRes.tasks.length);
|
||||
} else {
|
||||
if (runningEl) runningEl.textContent = '-';
|
||||
}
|
||||
|
||||
if (vulnRes && typeof vulnRes.total === 'number') {
|
||||
if (vulnTotalEl) vulnTotalEl.textContent = String(vulnRes.total);
|
||||
const bySeverity = vulnRes.by_severity || {};
|
||||
const total = vulnRes.total || 0;
|
||||
severityIds.forEach(sev => {
|
||||
const count = bySeverity[sev] || 0;
|
||||
const el = document.getElementById('dashboard-severity-' + sev);
|
||||
if (el) el.textContent = String(count);
|
||||
const barEl = document.getElementById('dashboard-bar-' + sev);
|
||||
if (barEl) barEl.style.width = total > 0 ? (count / total * 100) + '%' : '0%';
|
||||
});
|
||||
} else {
|
||||
if (vulnTotalEl) vulnTotalEl.textContent = '-';
|
||||
severityIds.forEach(sev => {
|
||||
const barEl = document.getElementById('dashboard-bar-' + sev);
|
||||
if (barEl) barEl.style.width = '0%';
|
||||
});
|
||||
}
|
||||
|
||||
// 批量任务队列:按状态统计(优化版)
|
||||
if (batchRes && Array.isArray(batchRes.queues)) {
|
||||
const queues = batchRes.queues;
|
||||
let pending = 0, running = 0, done = 0;
|
||||
queues.forEach(q => {
|
||||
const s = (q.status || '').toLowerCase();
|
||||
if (s === 'pending' || s === 'paused') pending++;
|
||||
else if (s === 'running') running++;
|
||||
else if (s === 'completed' || s === 'cancelled') done++;
|
||||
});
|
||||
const total = pending + running + done;
|
||||
setEl('dashboard-batch-pending', String(pending));
|
||||
setEl('dashboard-batch-running', String(running));
|
||||
setEl('dashboard-batch-done', String(done));
|
||||
setEl('dashboard-batch-total', total > 0 ? `共 ${total} 个` : '暂无任务');
|
||||
|
||||
// 更新进度条
|
||||
if (total > 0) {
|
||||
const pendingPct = (pending / total * 100).toFixed(1);
|
||||
const runningPct = (running / total * 100).toFixed(1);
|
||||
const donePct = (done / total * 100).toFixed(1);
|
||||
updateProgressBar('dashboard-batch-progress-pending', pendingPct);
|
||||
updateProgressBar('dashboard-batch-progress-running', runningPct);
|
||||
updateProgressBar('dashboard-batch-progress-done', donePct);
|
||||
} else {
|
||||
updateProgressBar('dashboard-batch-progress-pending', '0');
|
||||
updateProgressBar('dashboard-batch-progress-running', '0');
|
||||
updateProgressBar('dashboard-batch-progress-done', '0');
|
||||
}
|
||||
} else {
|
||||
setEl('dashboard-batch-pending', '-');
|
||||
setEl('dashboard-batch-running', '-');
|
||||
setEl('dashboard-batch-done', '-');
|
||||
setEl('dashboard-batch-total', '-');
|
||||
updateProgressBar('dashboard-batch-progress-pending', '0');
|
||||
updateProgressBar('dashboard-batch-progress-running', '0');
|
||||
updateProgressBar('dashboard-batch-progress-done', '0');
|
||||
}
|
||||
|
||||
// 工具调用:monitor/stats 为 { toolName: { totalCalls, successCalls, failedCalls, ... } }(优化版)
|
||||
if (monitorRes && typeof monitorRes === 'object') {
|
||||
const names = Object.keys(monitorRes);
|
||||
let totalCalls = 0, totalSuccess = 0, totalFailed = 0;
|
||||
names.forEach(k => {
|
||||
const v = monitorRes[k];
|
||||
const n = v && (v.totalCalls ?? v.TotalCalls);
|
||||
if (typeof n === 'number') totalCalls += n;
|
||||
const s = v && (v.successCalls ?? v.SuccessCalls);
|
||||
if (typeof s === 'number') totalSuccess += s;
|
||||
const f = v && (v.failedCalls ?? v.FailedCalls);
|
||||
if (typeof f === 'number') totalFailed += f;
|
||||
});
|
||||
setEl('dashboard-tools-count', String(names.length));
|
||||
setEl('dashboard-tools-calls', formatNumber(totalCalls));
|
||||
setEl('dashboard-kpi-tools-calls', String(totalCalls));
|
||||
var rateStr = totalCalls > 0 ? ((totalSuccess / totalCalls) * 100).toFixed(1) + '%' : '-';
|
||||
setEl('dashboard-kpi-success-rate', rateStr);
|
||||
setEl('dashboard-tools-success-rate', rateStr !== '-' ? `成功率 ${rateStr}` : '-');
|
||||
renderDashboardToolsBar(monitorRes);
|
||||
} else {
|
||||
setEl('dashboard-tools-count', '-');
|
||||
setEl('dashboard-tools-calls', '-');
|
||||
setEl('dashboard-kpi-tools-calls', '-');
|
||||
setEl('dashboard-kpi-success-rate', '-');
|
||||
setEl('dashboard-tools-success-rate', '-');
|
||||
renderDashboardToolsBar(null);
|
||||
}
|
||||
|
||||
// 知识:{ enabled, total_categories, total_items, ... }(优化版)
|
||||
const knowledgeItemsEl = document.getElementById('dashboard-knowledge-items');
|
||||
const knowledgeCategoriesEl = document.getElementById('dashboard-knowledge-categories');
|
||||
const knowledgeStatusEl = document.getElementById('dashboard-knowledge-status');
|
||||
if (knowledgeRes && typeof knowledgeRes === 'object') {
|
||||
if (knowledgeRes.enabled === false) {
|
||||
// 功能未启用:用状态标签展示,数值保持为 "-"
|
||||
if (knowledgeStatusEl) knowledgeStatusEl.textContent = '未启用';
|
||||
if (knowledgeItemsEl) knowledgeItemsEl.textContent = '-';
|
||||
if (knowledgeCategoriesEl) knowledgeCategoriesEl.textContent = '-';
|
||||
} else {
|
||||
const categories = knowledgeRes.total_categories ?? 0;
|
||||
const items = knowledgeRes.total_items ?? 0;
|
||||
if (knowledgeItemsEl) knowledgeItemsEl.textContent = formatNumber(items);
|
||||
if (knowledgeCategoriesEl) knowledgeCategoriesEl.textContent = formatNumber(categories);
|
||||
// 根据数据量给个轻量状态文案
|
||||
if (knowledgeStatusEl) {
|
||||
if (items > 0 || categories > 0) {
|
||||
knowledgeStatusEl.textContent = '已启用';
|
||||
} else {
|
||||
knowledgeStatusEl.textContent = '待配置';
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (knowledgeItemsEl) knowledgeItemsEl.textContent = '-';
|
||||
if (knowledgeCategoriesEl) knowledgeCategoriesEl.textContent = '-';
|
||||
if (knowledgeStatusEl) knowledgeStatusEl.textContent = '-';
|
||||
}
|
||||
|
||||
// Skills:{ total_skills, total_calls, ... }(优化版)
|
||||
if (skillsRes && typeof skillsRes === 'object') {
|
||||
const totalSkills = skillsRes.total_skills ?? 0;
|
||||
const totalCalls = skillsRes.total_calls ?? 0;
|
||||
setEl('dashboard-skills-count', formatNumber(totalSkills));
|
||||
setEl('dashboard-skills-calls', formatNumber(totalCalls));
|
||||
|
||||
// 设置状态标签
|
||||
const statusEl = document.getElementById('dashboard-skills-status');
|
||||
if (statusEl) {
|
||||
if (totalCalls === 0) {
|
||||
statusEl.textContent = '待使用';
|
||||
statusEl.style.background = 'rgba(0, 0, 0, 0.05)';
|
||||
statusEl.style.color = 'var(--text-secondary)';
|
||||
} else if (totalCalls < 10) {
|
||||
statusEl.textContent = '活跃';
|
||||
statusEl.style.background = 'rgba(16, 185, 129, 0.1)';
|
||||
statusEl.style.color = '#10b981';
|
||||
} else {
|
||||
statusEl.textContent = '高频';
|
||||
statusEl.style.background = 'rgba(59, 130, 246, 0.1)';
|
||||
statusEl.style.color = '#3b82f6';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setEl('dashboard-skills-count', '-');
|
||||
setEl('dashboard-skills-calls', '-');
|
||||
const statusEl = document.getElementById('dashboard-skills-status');
|
||||
if (statusEl) statusEl.textContent = '-';
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('仪表盘拉取统计失败', e);
|
||||
if (runningEl) runningEl.textContent = '-';
|
||||
if (vulnTotalEl) vulnTotalEl.textContent = '-';
|
||||
setDashboardOverviewPlaceholder('-');
|
||||
setEl('dashboard-kpi-success-rate', '-');
|
||||
setEl('dashboard-kpi-tools-calls', '-');
|
||||
renderDashboardToolsBar(null);
|
||||
var ph = document.getElementById('dashboard-tools-pie-placeholder');
|
||||
if (ph) { ph.style.removeProperty('display'); ph.textContent = '暂无调用数据'; }
|
||||
}
|
||||
}
|
||||
|
||||
function setEl(id, text) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = text;
|
||||
}
|
||||
|
||||
function setDashboardOverviewPlaceholder(t) {
|
||||
['dashboard-batch-pending', 'dashboard-batch-running', 'dashboard-batch-done', 'dashboard-batch-total',
|
||||
'dashboard-tools-count', 'dashboard-tools-calls', 'dashboard-tools-success-rate',
|
||||
'dashboard-skills-count', 'dashboard-skills-calls', 'dashboard-skills-status',
|
||||
'dashboard-knowledge-items', 'dashboard-knowledge-categories', 'dashboard-knowledge-status'].forEach(id => setEl(id, t));
|
||||
updateProgressBar('dashboard-batch-progress-pending', '0');
|
||||
updateProgressBar('dashboard-batch-progress-running', '0');
|
||||
updateProgressBar('dashboard-batch-progress-done', '0');
|
||||
}
|
||||
|
||||
// 格式化数字,添加千位分隔符
|
||||
function formatNumber(num) {
|
||||
if (typeof num !== 'number' || isNaN(num)) return '-';
|
||||
if (num === 0) return '0';
|
||||
return num.toLocaleString('zh-CN');
|
||||
}
|
||||
|
||||
// 更新进度条宽度
|
||||
function updateProgressBar(id, percentage) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) {
|
||||
const pct = parseFloat(percentage) || 0;
|
||||
el.style.width = Math.max(0, Math.min(100, pct)) + '%';
|
||||
}
|
||||
}
|
||||
|
||||
// Top 30 工具执行次数柱状图颜色(30 色不重复,柔和、易区分)
|
||||
var DASHBOARD_BAR_COLORS = [
|
||||
'#93c5fd', '#a78bfa', '#6ee7b7', '#fde047', '#fda4af',
|
||||
'#7dd3fc', '#a5b4fc', '#5eead4', '#fdba74', '#e9d5ff',
|
||||
'#67e8f9', '#c4b5fd', '#86efac', '#fcd34d', '#f9a8d4',
|
||||
'#bae6fd', '#c7d2fe', '#99f6e4', '#fed7aa', '#ddd6fe',
|
||||
'#22d3ee', '#8b5cf6', '#4ade80', '#fbbf24', '#fb7185',
|
||||
'#38bdf8', '#818cf8', '#2dd4bf', '#fb923c', '#e0e7ff'
|
||||
];
|
||||
|
||||
function esc(s) {
|
||||
if (typeof s !== 'string') return '';
|
||||
return s.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function renderDashboardToolsBar(monitorRes) {
|
||||
const placeholder = document.getElementById('dashboard-tools-pie-placeholder');
|
||||
const barChartEl = document.getElementById('dashboard-tools-bar-chart');
|
||||
if (!placeholder || !barChartEl) return;
|
||||
|
||||
if (!monitorRes || typeof monitorRes !== 'object') {
|
||||
placeholder.style.removeProperty('display');
|
||||
placeholder.textContent = '暂无调用数据';
|
||||
barChartEl.style.display = 'none';
|
||||
barChartEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const entries = Object.keys(monitorRes).map(function (k) {
|
||||
const v = monitorRes[k];
|
||||
const totalCalls = v && (v.totalCalls ?? v.TotalCalls);
|
||||
return { name: k, totalCalls: typeof totalCalls === 'number' ? totalCalls : 0 };
|
||||
}).filter(function (e) { return e.totalCalls > 0; })
|
||||
.sort(function (a, b) { return b.totalCalls - a.totalCalls; })
|
||||
.slice(0, 30);
|
||||
|
||||
if (entries.length === 0) {
|
||||
placeholder.style.removeProperty('display');
|
||||
placeholder.textContent = '暂无调用数据';
|
||||
barChartEl.style.display = 'none';
|
||||
barChartEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
placeholder.style.display = 'none';
|
||||
barChartEl.style.display = 'block';
|
||||
|
||||
const maxCalls = Math.max.apply(null, entries.map(function (e) { return e.totalCalls; }));
|
||||
var html = '';
|
||||
entries.forEach(function (e, i) {
|
||||
var pct = maxCalls > 0 ? (e.totalCalls / maxCalls) * 100 : 0;
|
||||
var label = e.name.length > 12 ? e.name.slice(0, 10) + '…' : e.name;
|
||||
var color = DASHBOARD_BAR_COLORS[i % DASHBOARD_BAR_COLORS.length];
|
||||
var fullName = esc(e.name);
|
||||
html += '<div class="dashboard-tools-bar-item" data-tooltip="' + fullName + '">';
|
||||
html += '<span class="dashboard-tools-bar-label">' + esc(label) + '</span>';
|
||||
html += '<div class="dashboard-tools-bar-track"><div class="dashboard-tools-bar-fill" style="width:' + pct + '%;background:' + color + '"></div></div>';
|
||||
html += '<span class="dashboard-tools-bar-value">' + e.totalCalls + '</span>';
|
||||
html += '</div>';
|
||||
});
|
||||
barChartEl.innerHTML = html;
|
||||
attachDashboardBarTooltips(barChartEl);
|
||||
}
|
||||
|
||||
var dashboardBarTooltipEl = null;
|
||||
var dashboardBarTooltipTimer = null;
|
||||
|
||||
function attachDashboardBarTooltips(barChartEl) {
|
||||
if (!barChartEl) return;
|
||||
if (!dashboardBarTooltipEl) {
|
||||
dashboardBarTooltipEl = document.createElement('div');
|
||||
dashboardBarTooltipEl.className = 'dashboard-tools-bar-tooltip';
|
||||
dashboardBarTooltipEl.setAttribute('role', 'tooltip');
|
||||
document.body.appendChild(dashboardBarTooltipEl);
|
||||
}
|
||||
barChartEl.removeEventListener('mouseover', dashboardBarTooltipOnOver);
|
||||
barChartEl.removeEventListener('mouseout', dashboardBarTooltipOnOut);
|
||||
barChartEl.addEventListener('mouseover', dashboardBarTooltipOnOver);
|
||||
barChartEl.addEventListener('mouseout', dashboardBarTooltipOnOut);
|
||||
}
|
||||
|
||||
function dashboardBarTooltipOnOver(ev) {
|
||||
var item = ev.target && ev.target.closest && ev.target.closest('.dashboard-tools-bar-item');
|
||||
if (!item || !dashboardBarTooltipEl) return;
|
||||
var text = item.getAttribute('data-tooltip');
|
||||
if (!text) return;
|
||||
clearTimeout(dashboardBarTooltipTimer);
|
||||
dashboardBarTooltipTimer = setTimeout(function () {
|
||||
dashboardBarTooltipEl.textContent = text;
|
||||
dashboardBarTooltipEl.style.display = 'block';
|
||||
requestAnimationFrame(function () {
|
||||
var rect = item.getBoundingClientRect();
|
||||
var ttRect = dashboardBarTooltipEl.getBoundingClientRect();
|
||||
var x = rect.left + (rect.width / 2) - (ttRect.width / 2);
|
||||
var y = rect.top - ttRect.height - 6;
|
||||
if (y < 8) y = rect.bottom + 6;
|
||||
var pad = 8;
|
||||
if (x < pad) x = pad;
|
||||
if (x + ttRect.width > window.innerWidth - pad) x = window.innerWidth - ttRect.width - pad;
|
||||
dashboardBarTooltipEl.style.left = x + 'px';
|
||||
dashboardBarTooltipEl.style.top = y + 'px';
|
||||
});
|
||||
}, 180);
|
||||
}
|
||||
|
||||
function dashboardBarTooltipOnOut(ev) {
|
||||
var item = ev.target && ev.target.closest && ev.target.closest('.dashboard-tools-bar-item');
|
||||
var related = ev.relatedTarget && ev.relatedTarget.closest && ev.relatedTarget.closest('.dashboard-tools-bar-item');
|
||||
if (item && item === related) return;
|
||||
clearTimeout(dashboardBarTooltipTimer);
|
||||
dashboardBarTooltipTimer = null;
|
||||
if (dashboardBarTooltipEl) dashboardBarTooltipEl.style.display = 'none';
|
||||
}
|
||||
@@ -835,7 +835,26 @@ function addTimelineItem(timeline, type, options) {
|
||||
item.id = itemId;
|
||||
item.className = `timeline-item timeline-item-${type}`;
|
||||
|
||||
const time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
// 使用传入的createdAt时间,如果没有则使用当前时间(向后兼容)
|
||||
let eventTime;
|
||||
if (options.createdAt) {
|
||||
// 处理字符串或Date对象
|
||||
if (typeof options.createdAt === 'string') {
|
||||
eventTime = new Date(options.createdAt);
|
||||
} else if (options.createdAt instanceof Date) {
|
||||
eventTime = options.createdAt;
|
||||
} else {
|
||||
eventTime = new Date(options.createdAt);
|
||||
}
|
||||
// 如果解析失败,使用当前时间
|
||||
if (isNaN(eventTime.getTime())) {
|
||||
eventTime = new Date();
|
||||
}
|
||||
} else {
|
||||
eventTime = new Date();
|
||||
}
|
||||
|
||||
const time = eventTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
|
||||
let content = `
|
||||
<div class="timeline-item-header">
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// 角色管理相关功能
|
||||
let currentRole = localStorage.getItem('currentRole') || '';
|
||||
let roles = [];
|
||||
let rolesSearchKeyword = ''; // 角色搜索关键词
|
||||
let rolesSearchTimeout = null; // 搜索防抖定时器
|
||||
let allRoleTools = []; // 存储所有工具列表(用于角色工具选择)
|
||||
let roleToolsPagination = {
|
||||
page: 1,
|
||||
@@ -258,6 +260,7 @@ async function refreshRoles() {
|
||||
}
|
||||
// 始终更新侧边栏角色选择列表
|
||||
renderRoleSelectionSidebar();
|
||||
showNotification('已刷新', 'success');
|
||||
}
|
||||
|
||||
// 渲染角色列表
|
||||
@@ -265,30 +268,25 @@ function renderRolesList() {
|
||||
const rolesList = document.getElementById('roles-list');
|
||||
if (!rolesList) return;
|
||||
|
||||
if (roles.length === 0) {
|
||||
rolesList.innerHTML = '<div class="empty-state">暂无角色</div>';
|
||||
// 过滤角色(根据搜索关键词)
|
||||
let filteredRoles = roles;
|
||||
if (rolesSearchKeyword) {
|
||||
const keyword = rolesSearchKeyword.toLowerCase();
|
||||
filteredRoles = roles.filter(role =>
|
||||
role.name.toLowerCase().includes(keyword) ||
|
||||
(role.description && role.description.toLowerCase().includes(keyword))
|
||||
);
|
||||
}
|
||||
|
||||
if (filteredRoles.length === 0) {
|
||||
rolesList.innerHTML = '<div class="empty-state">' +
|
||||
(rolesSearchKeyword ? '没有找到匹配的角色' : '暂无角色') +
|
||||
'</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新统计
|
||||
const stats = document.getElementById('roles-stats');
|
||||
if (stats) {
|
||||
const totalRoles = roles.length;
|
||||
const enabledRoles = roles.filter(r => r.enabled !== false).length;
|
||||
stats.innerHTML = `
|
||||
<div class="role-stat-item">
|
||||
<span class="role-stat-label">总角色数</span>
|
||||
<span class="role-stat-value">${totalRoles}</span>
|
||||
</div>
|
||||
<div class="role-stat-item">
|
||||
<span class="role-stat-label">已启用</span>
|
||||
<span class="role-stat-value">${enabledRoles}</span>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
// 对角色进行排序:默认角色第一个,其他按名称排序
|
||||
const sortedRoles = sortRoles(roles);
|
||||
const sortedRoles = sortRoles(filteredRoles);
|
||||
|
||||
rolesList.innerHTML = sortedRoles.map(role => {
|
||||
// 获取角色图标,如果是Unicode转义格式则转换为emoji
|
||||
@@ -307,47 +305,93 @@ function renderRolesList() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取工具列表显示
|
||||
let toolsDisplay = '';
|
||||
let toolsCount = 0;
|
||||
if (role.name === '默认') {
|
||||
toolsDisplay = '使用所有工具';
|
||||
} else if (role.tools && role.tools.length > 0) {
|
||||
toolsCount = role.tools.length;
|
||||
// 显示前5个工具名称
|
||||
const toolNames = role.tools.slice(0, 5).map(tool => {
|
||||
// 如果是外部工具,格式为 external_mcp::tool_name,只显示工具名
|
||||
const toolName = tool.includes('::') ? tool.split('::')[1] : tool;
|
||||
return escapeHtml(toolName);
|
||||
});
|
||||
if (toolsCount <= 5) {
|
||||
toolsDisplay = toolNames.join(', ');
|
||||
} else {
|
||||
toolsDisplay = toolNames.join(', ') + ` 等 ${toolsCount} 个`;
|
||||
}
|
||||
} else if (role.mcps && role.mcps.length > 0) {
|
||||
toolsCount = role.mcps.length;
|
||||
toolsDisplay = `等 ${toolsCount} 个`;
|
||||
} else {
|
||||
toolsDisplay = '使用所有工具';
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="role-item">
|
||||
<div class="role-item-content">
|
||||
<div class="role-item-header">
|
||||
<div class="role-item-name">
|
||||
<span class="role-item-icon" style="margin-right: 8px;">${roleIcon}</span>
|
||||
${escapeHtml(role.name)}
|
||||
</div>
|
||||
<div class="role-item-badge ${role.enabled !== false ? 'enabled' : 'disabled'}">
|
||||
${role.enabled !== false ? '已启用' : '已禁用'}
|
||||
</div>
|
||||
</div>
|
||||
<div class="role-item-description">${escapeHtml(role.description || '无描述')}</div>
|
||||
<div class="role-item-details">
|
||||
<div class="role-item-detail">
|
||||
<span class="role-item-detail-label">用户提示词:</span>
|
||||
<span class="role-item-detail-value">${role.user_prompt ? (role.user_prompt.length > 100 ? escapeHtml(role.user_prompt.substring(0, 100)) + '...' : escapeHtml(role.user_prompt)) : '无'}</span>
|
||||
</div>
|
||||
<div class="role-item-detail">
|
||||
<span class="role-item-detail-label">关联的工具:</span>
|
||||
<span class="role-item-detail-value">${
|
||||
role.name === '默认'
|
||||
? '使用所有工具'
|
||||
: (role.tools && role.tools.length > 0
|
||||
? `${role.tools.length} 个工具`
|
||||
: (role.mcps && role.mcps.length > 0
|
||||
? `${role.mcps.length} 个工具(兼容旧版)`
|
||||
: '使用所有工具'))
|
||||
}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="role-card">
|
||||
<div class="role-card-header">
|
||||
<h3 class="role-card-title">
|
||||
<span class="role-card-icon">${roleIcon}</span>
|
||||
${escapeHtml(role.name)}
|
||||
</h3>
|
||||
<span class="role-card-badge ${role.enabled !== false ? 'enabled' : 'disabled'}">
|
||||
${role.enabled !== false ? '已启用' : '已禁用'}
|
||||
</span>
|
||||
</div>
|
||||
<div class="role-item-actions">
|
||||
<button class="btn-secondary" onclick="editRole('${escapeHtml(role.name)}')">编辑</button>
|
||||
${role.name !== '默认' ? `<button class="btn-secondary btn-danger" onclick="deleteRole('${escapeHtml(role.name)}')">删除</button>` : ''}
|
||||
<div class="role-card-description">${escapeHtml(role.description || '无描述')}</div>
|
||||
<div class="role-card-tools">
|
||||
<span class="role-card-tools-label">工具:</span>
|
||||
<span class="role-card-tools-value">${toolsDisplay}</span>
|
||||
</div>
|
||||
<div class="role-card-actions">
|
||||
<button class="btn-secondary btn-small" onclick="editRole('${escapeHtml(role.name)}')">编辑</button>
|
||||
${role.name !== '默认' ? `<button class="btn-secondary btn-small btn-danger" onclick="deleteRole('${escapeHtml(role.name)}')">删除</button>` : ''}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
// 处理角色搜索输入
|
||||
function handleRolesSearchInput() {
|
||||
clearTimeout(rolesSearchTimeout);
|
||||
rolesSearchTimeout = setTimeout(() => {
|
||||
searchRoles();
|
||||
}, 300);
|
||||
}
|
||||
|
||||
// 搜索角色
|
||||
function searchRoles() {
|
||||
const searchInput = document.getElementById('roles-search');
|
||||
if (!searchInput) return;
|
||||
|
||||
rolesSearchKeyword = searchInput.value.trim();
|
||||
const clearBtn = document.getElementById('roles-search-clear');
|
||||
if (clearBtn) {
|
||||
clearBtn.style.display = rolesSearchKeyword ? 'block' : 'none';
|
||||
}
|
||||
|
||||
renderRolesList();
|
||||
}
|
||||
|
||||
// 清除角色搜索
|
||||
function clearRolesSearch() {
|
||||
const searchInput = document.getElementById('roles-search');
|
||||
if (searchInput) {
|
||||
searchInput.value = '';
|
||||
}
|
||||
rolesSearchKeyword = '';
|
||||
const clearBtn = document.getElementById('roles-search-clear');
|
||||
if (clearBtn) {
|
||||
clearBtn.style.display = 'none';
|
||||
}
|
||||
renderRolesList();
|
||||
}
|
||||
|
||||
// 生成工具唯一标识符(与settings.js中的getToolKey保持一致)
|
||||
function getToolKey(tool) {
|
||||
// 如果是外部工具,使用 external_mcp::tool.name 作为唯一标识符
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// 页面路由管理
|
||||
let currentPage = 'chat';
|
||||
let currentPage = 'dashboard';
|
||||
|
||||
// 初始化路由
|
||||
function initRouter() {
|
||||
@@ -8,7 +8,7 @@ function initRouter() {
|
||||
if (hash) {
|
||||
const hashParts = hash.split('?');
|
||||
const pageId = hashParts[0];
|
||||
if (pageId && ['chat', 'vulnerabilities', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'skills-monitor', 'skills-management', 'settings', 'tasks'].includes(pageId)) {
|
||||
if (pageId && ['dashboard', 'chat', 'info-collect', 'vulnerabilities', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'skills-monitor', 'skills-management', 'settings', 'tasks'].includes(pageId)) {
|
||||
switchPage(pageId);
|
||||
|
||||
// 如果是chat页面且带有conversation参数,加载对应对话
|
||||
@@ -32,8 +32,8 @@ function initRouter() {
|
||||
}
|
||||
}
|
||||
|
||||
// 默认显示对话页面
|
||||
switchPage('chat');
|
||||
// 默认显示仪表盘
|
||||
switchPage('dashboard');
|
||||
}
|
||||
|
||||
// 切换页面
|
||||
@@ -237,9 +237,20 @@ function showSubmenuPopup(navItem, menuId) {
|
||||
// 初始化页面
|
||||
function initPage(pageId) {
|
||||
switch(pageId) {
|
||||
case 'dashboard':
|
||||
if (typeof refreshDashboard === 'function') {
|
||||
refreshDashboard();
|
||||
}
|
||||
break;
|
||||
case 'chat':
|
||||
// 对话页面已由chat.js初始化
|
||||
break;
|
||||
case 'info-collect':
|
||||
// 信息收集页面
|
||||
if (typeof initInfoCollectPage === 'function') {
|
||||
initInfoCollectPage();
|
||||
}
|
||||
break;
|
||||
case 'tasks':
|
||||
// 初始化任务管理页面
|
||||
if (typeof initTasksPage === 'function') {
|
||||
@@ -254,16 +265,25 @@ function initPage(pageId) {
|
||||
break;
|
||||
case 'mcp-management':
|
||||
// 初始化MCP管理
|
||||
// 先加载外部MCP列表(快速),然后加载工具列表
|
||||
if (typeof loadExternalMCPs === 'function') {
|
||||
loadExternalMCPs();
|
||||
loadExternalMCPs().catch(err => {
|
||||
console.warn('加载外部MCP列表失败:', err);
|
||||
});
|
||||
}
|
||||
// 加载工具列表(MCP工具配置已移到MCP管理页面)
|
||||
// 使用异步加载,避免阻塞页面渲染
|
||||
if (typeof loadToolsList === 'function') {
|
||||
// 确保工具分页设置已初始化
|
||||
if (typeof getToolsPageSize === 'function' && typeof toolsPagination !== 'undefined') {
|
||||
toolsPagination.pageSize = getToolsPageSize();
|
||||
}
|
||||
loadToolsList(1, '');
|
||||
// 延迟加载,让页面先渲染
|
||||
setTimeout(() => {
|
||||
loadToolsList(1, '').catch(err => {
|
||||
console.error('加载工具列表失败:', err);
|
||||
});
|
||||
}, 100);
|
||||
}
|
||||
break;
|
||||
case 'vulnerabilities':
|
||||
@@ -280,6 +300,15 @@ function initPage(pageId) {
|
||||
break;
|
||||
case 'roles-management':
|
||||
// 初始化角色管理页面
|
||||
// 重置搜索UI(变量会在下次搜索时自动更新)
|
||||
const rolesSearchInput = document.getElementById('roles-search');
|
||||
if (rolesSearchInput) {
|
||||
rolesSearchInput.value = '';
|
||||
}
|
||||
const rolesSearchClear = document.getElementById('roles-search-clear');
|
||||
if (rolesSearchClear) {
|
||||
rolesSearchClear.style.display = 'none';
|
||||
}
|
||||
if (typeof loadRoles === 'function') {
|
||||
loadRoles().then(() => {
|
||||
if (typeof renderRolesList === 'function') {
|
||||
@@ -296,6 +325,15 @@ function initPage(pageId) {
|
||||
break;
|
||||
case 'skills-management':
|
||||
// 初始化Skills管理页面
|
||||
// 重置搜索UI(变量会在下次搜索时自动更新)
|
||||
const skillsSearchInput = document.getElementById('skills-search');
|
||||
if (skillsSearchInput) {
|
||||
skillsSearchInput.value = '';
|
||||
}
|
||||
const skillsSearchClear = document.getElementById('skills-search-clear');
|
||||
if (skillsSearchClear) {
|
||||
skillsSearchClear.style.display = 'none';
|
||||
}
|
||||
if (typeof initSkillsPagination === 'function') {
|
||||
initSkillsPagination();
|
||||
}
|
||||
@@ -323,7 +361,7 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
const hashParts = hash.split('?');
|
||||
const pageId = hashParts[0];
|
||||
|
||||
if (pageId && ['chat', 'tasks', 'vulnerabilities', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'skills-monitor', 'skills-management', 'settings'].includes(pageId)) {
|
||||
if (pageId && ['chat', 'info-collect', 'tasks', 'vulnerabilities', 'mcp-monitor', 'mcp-management', 'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'skills-monitor', 'skills-management', 'settings'].includes(pageId)) {
|
||||
switchPage(pageId);
|
||||
|
||||
// 如果是chat页面且带有conversation参数,加载对应对话
|
||||
|
||||
@@ -102,6 +102,15 @@ async function loadConfig(loadTools = true) {
|
||||
document.getElementById('openai-api-key').value = currentConfig.openai.api_key || '';
|
||||
document.getElementById('openai-base-url').value = currentConfig.openai.base_url || '';
|
||||
document.getElementById('openai-model').value = currentConfig.openai.model || '';
|
||||
|
||||
// 填充FOFA配置
|
||||
const fofa = currentConfig.fofa || {};
|
||||
const fofaEmailEl = document.getElementById('fofa-email');
|
||||
const fofaKeyEl = document.getElementById('fofa-api-key');
|
||||
const fofaBaseUrlEl = document.getElementById('fofa-base-url');
|
||||
if (fofaEmailEl) fofaEmailEl.value = fofa.email || '';
|
||||
if (fofaKeyEl) fofaKeyEl.value = fofa.api_key || '';
|
||||
if (fofaBaseUrlEl) fofaBaseUrlEl.value = fofa.base_url || '';
|
||||
|
||||
// 填充Agent配置
|
||||
document.getElementById('agent-max-iterations').value = currentConfig.agent.max_iterations || 30;
|
||||
@@ -183,6 +192,14 @@ let toolsSearchKeyword = '';
|
||||
|
||||
// 加载工具列表(分页)
|
||||
async function loadToolsList(page = 1, searchKeyword = '') {
|
||||
const toolsList = document.getElementById('tools-list');
|
||||
|
||||
// 显示加载状态
|
||||
if (toolsList) {
|
||||
// 清空整个容器,包括可能存在的分页控件
|
||||
toolsList.innerHTML = '<div class="tools-list-items"><div class="loading" style="padding: 20px; text-align: center; color: var(--text-muted);">⏳ 正在加载工具列表...</div></div>';
|
||||
}
|
||||
|
||||
try {
|
||||
// 在加载新页面之前,先保存当前页的状态到全局映射
|
||||
saveCurrentPageToolStates();
|
||||
@@ -193,7 +210,15 @@ async function loadToolsList(page = 1, searchKeyword = '') {
|
||||
url += `&search=${encodeURIComponent(searchKeyword)}`;
|
||||
}
|
||||
|
||||
const response = await apiFetch(url);
|
||||
// 使用较短的超时时间(10秒),避免长时间等待
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000);
|
||||
|
||||
const response = await apiFetch(url, {
|
||||
signal: controller.signal
|
||||
});
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('获取工具列表失败');
|
||||
}
|
||||
@@ -224,9 +249,12 @@ async function loadToolsList(page = 1, searchKeyword = '') {
|
||||
renderToolsPagination();
|
||||
} catch (error) {
|
||||
console.error('加载工具列表失败:', error);
|
||||
const toolsList = document.getElementById('tools-list');
|
||||
if (toolsList) {
|
||||
toolsList.innerHTML = `<div class="error">加载工具列表失败: ${escapeHtml(error.message)}</div>`;
|
||||
const isTimeout = error.name === 'AbortError' || error.message.includes('timeout');
|
||||
const errorMsg = isTimeout
|
||||
? '加载工具列表超时,可能是外部MCP连接较慢。请点击"刷新"按钮重试,或检查外部MCP连接状态。'
|
||||
: `加载工具列表失败: ${escapeHtml(error.message)}`;
|
||||
toolsList.innerHTML = `<div class="error" style="padding: 20px; text-align: center;">${errorMsg}</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -281,9 +309,21 @@ function renderToolsList() {
|
||||
const toolsList = document.getElementById('tools-list');
|
||||
if (!toolsList) return;
|
||||
|
||||
// 只渲染列表部分,分页控件单独渲染
|
||||
const listContainer = toolsList.querySelector('.tools-list-items') || document.createElement('div');
|
||||
listContainer.className = 'tools-list-items';
|
||||
// 移除可能存在的分页控件(会在 renderToolsPagination 中重新添加)
|
||||
const oldPagination = toolsList.querySelector('.tools-pagination');
|
||||
if (oldPagination) {
|
||||
oldPagination.remove();
|
||||
}
|
||||
|
||||
// 获取或创建列表容器
|
||||
let listContainer = toolsList.querySelector('.tools-list-items');
|
||||
if (!listContainer) {
|
||||
listContainer = document.createElement('div');
|
||||
listContainer.className = 'tools-list-items';
|
||||
toolsList.appendChild(listContainer);
|
||||
}
|
||||
|
||||
// 清空列表容器内容(移除加载提示)
|
||||
listContainer.innerHTML = '';
|
||||
|
||||
if (allTools.length === 0) {
|
||||
@@ -662,6 +702,11 @@ async function applySettings() {
|
||||
base_url: baseUrl,
|
||||
model: model
|
||||
},
|
||||
fofa: {
|
||||
email: document.getElementById('fofa-email')?.value.trim() || '',
|
||||
api_key: document.getElementById('fofa-api-key')?.value.trim() || '',
|
||||
base_url: document.getElementById('fofa-base-url')?.value.trim() || ''
|
||||
},
|
||||
agent: {
|
||||
max_iterations: parseInt(document.getElementById('agent-max-iterations').value) || 30
|
||||
},
|
||||
@@ -974,15 +1019,17 @@ async function changePassword() {
|
||||
|
||||
let currentEditingMCPName = null;
|
||||
|
||||
// 加载外部MCP列表
|
||||
// 拉取外部MCP列表数据(供轮询使用,返回 { servers, stats })
|
||||
async function fetchExternalMCPs() {
|
||||
const response = await apiFetch('/api/external-mcp');
|
||||
if (!response.ok) throw new Error('获取外部MCP列表失败');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// 加载外部MCP列表并渲染
|
||||
async function loadExternalMCPs() {
|
||||
try {
|
||||
const response = await apiFetch('/api/external-mcp');
|
||||
if (!response.ok) {
|
||||
throw new Error('获取外部MCP列表失败');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const data = await fetchExternalMCPs();
|
||||
renderExternalMCPList(data.servers || {});
|
||||
renderExternalMCPStats(data.stats || {});
|
||||
} catch (error) {
|
||||
@@ -994,6 +1041,29 @@ async function loadExternalMCPs() {
|
||||
}
|
||||
}
|
||||
|
||||
// 轮询列表直到指定 MCP 的工具数量已更新(每秒拉一次,拿到即停,无固定延迟)
|
||||
// name 为 null 时仅按 maxAttempts 次数轮询,不判断 tool_count
|
||||
async function pollExternalMCPToolCount(name, maxAttempts = 10) {
|
||||
const pollIntervalMs = 1000;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
await new Promise(r => setTimeout(r, pollIntervalMs));
|
||||
try {
|
||||
const data = await fetchExternalMCPs();
|
||||
renderExternalMCPList(data.servers || {});
|
||||
renderExternalMCPStats(data.stats || {});
|
||||
if (name != null) {
|
||||
const server = data.servers && data.servers[name];
|
||||
if (server && server.tool_count > 0) break;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('轮询工具数量失败:', e);
|
||||
}
|
||||
}
|
||||
if (typeof window !== 'undefined' && typeof window.refreshMentionTools === 'function') {
|
||||
window.refreshMentionTools();
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染外部MCP列表
|
||||
function renderExternalMCPList(servers) {
|
||||
const list = document.getElementById('external-mcp-list');
|
||||
@@ -1350,10 +1420,11 @@ async function saveExternalMCP() {
|
||||
|
||||
closeExternalMCPModal();
|
||||
await loadExternalMCPs();
|
||||
// 刷新对话界面的工具列表,使新添加的MCP工具立即可用
|
||||
if (typeof window !== 'undefined' && typeof window.refreshMentionTools === 'function') {
|
||||
window.refreshMentionTools();
|
||||
}
|
||||
// 轮询几次以拉取后端异步更新的工具数量(无固定延迟,拿到即停)
|
||||
pollExternalMCPToolCount(null, 5);
|
||||
alert('保存成功');
|
||||
} catch (error) {
|
||||
console.error('保存外部MCP失败:', error);
|
||||
@@ -1427,12 +1498,12 @@ async function toggleExternalMCP(name, currentStatus) {
|
||||
const status = statusData.status || 'disconnected';
|
||||
|
||||
if (status === 'connected') {
|
||||
// 已经连接,立即刷新
|
||||
await loadExternalMCPs();
|
||||
// 刷新对话界面的工具列表
|
||||
if (typeof window !== 'undefined' && typeof window.refreshMentionTools === 'function') {
|
||||
window.refreshMentionTools();
|
||||
}
|
||||
// 轮询直到该 MCP 工具数量已更新(每秒拉一次,无固定延迟)
|
||||
pollExternalMCPToolCount(name, 10);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -1490,12 +1561,12 @@ async function pollExternalMCPStatus(name, maxAttempts = 30) {
|
||||
const button = document.getElementById(buttonId);
|
||||
|
||||
if (status === 'connected') {
|
||||
// 连接成功,刷新列表
|
||||
await loadExternalMCPs();
|
||||
// 刷新对话界面的工具列表
|
||||
if (typeof window !== 'undefined' && typeof window.refreshMentionTools === 'function') {
|
||||
window.refreshMentionTools();
|
||||
}
|
||||
// 轮询直到该 MCP 工具数量已更新(每秒拉一次,无固定延迟)
|
||||
pollExternalMCPToolCount(name, 10);
|
||||
return;
|
||||
} else if (status === 'error' || status === 'disconnected') {
|
||||
// 连接失败,刷新列表并显示错误
|
||||
|
||||
@@ -94,7 +94,7 @@ function renderSkillsList() {
|
||||
|
||||
if (filteredSkills.length === 0) {
|
||||
skillsListEl.innerHTML = '<div class="empty-state">' +
|
||||
(skillsSearchKeyword ? '没有找到匹配的skills' : '暂无skills,点击"添加Skill"创建第一个skill') +
|
||||
(skillsSearchKeyword ? '没有找到匹配的skills' : '暂无skills,点击"创建Skill"创建第一个skill') +
|
||||
'</div>';
|
||||
// 搜索时隐藏分页
|
||||
const paginationContainer = document.getElementById('skills-pagination');
|
||||
@@ -105,47 +105,31 @@ function renderSkillsList() {
|
||||
}
|
||||
|
||||
skillsListEl.innerHTML = filteredSkills.map(skill => {
|
||||
const fileSize = skill.file_size || 0;
|
||||
const fileSizeStr = fileSize < 1024 ? fileSize + ' B' :
|
||||
fileSize < 1024 * 1024 ? (fileSize / 1024).toFixed(2) + ' KB' :
|
||||
(fileSize / (1024 * 1024)).toFixed(2) + ' MB';
|
||||
|
||||
return `
|
||||
<div class="skill-item">
|
||||
<div class="skill-item-header">
|
||||
<div class="skill-item-info">
|
||||
<h3 class="skill-item-name">${escapeHtml(skill.name || '')}</h3>
|
||||
${skill.description ? `<p class="skill-item-desc">${escapeHtml(skill.description)}</p>` : ''}
|
||||
</div>
|
||||
<div class="skill-item-actions">
|
||||
<button class="btn-icon" onclick="viewSkill('${escapeHtml(skill.name)}')" title="查看">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
|
||||
<circle cx="12" cy="12" r="3"></circle>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="btn-icon" onclick="editSkill('${escapeHtml(skill.name)}')" title="编辑">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
|
||||
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="btn-icon btn-danger" onclick="deleteSkill('${escapeHtml(skill.name)}')" title="删除">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<polyline points="3 6 5 6 21 6"></polyline>
|
||||
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="skill-card">
|
||||
<div class="skill-card-header">
|
||||
<h3 class="skill-card-title">${escapeHtml(skill.name || '')}</h3>
|
||||
<div class="skill-card-description">${escapeHtml(skill.description || '无描述')}</div>
|
||||
</div>
|
||||
<div class="skill-item-meta">
|
||||
<span class="skill-meta-item">路径: ${escapeHtml(skill.path || '')}</span>
|
||||
<span class="skill-meta-item">大小: ${fileSizeStr}</span>
|
||||
${skill.mod_time ? `<span class="skill-meta-item">修改时间: ${escapeHtml(skill.mod_time)}</span>` : ''}
|
||||
<div class="skill-card-actions">
|
||||
<button class="btn-secondary btn-small" onclick="viewSkill('${escapeHtml(skill.name)}')">查看</button>
|
||||
<button class="btn-secondary btn-small" onclick="editSkill('${escapeHtml(skill.name)}')">编辑</button>
|
||||
<button class="btn-secondary btn-small btn-danger" onclick="deleteSkill('${escapeHtml(skill.name)}')">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// 确保列表容器可以滚动,分页栏可见
|
||||
// 使用 setTimeout 确保 DOM 更新完成后再检查
|
||||
setTimeout(() => {
|
||||
const paginationContainer = document.getElementById('skills-pagination');
|
||||
if (paginationContainer && !skillsSearchKeyword) {
|
||||
// 确保分页栏可见
|
||||
paginationContainer.style.display = 'block';
|
||||
paginationContainer.style.visibility = 'visible';
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// 渲染分页组件(参考MCP管理页面样式)
|
||||
@@ -205,6 +189,11 @@ function renderSkillsPagination() {
|
||||
function alignPaginationWidth() {
|
||||
const skillsList = document.getElementById('skills-list');
|
||||
if (skillsList && paginationContainer) {
|
||||
// 确保分页容器始终可见
|
||||
paginationContainer.style.display = '';
|
||||
paginationContainer.style.visibility = 'visible';
|
||||
paginationContainer.style.opacity = '1';
|
||||
|
||||
// 获取列表的实际内容宽度(不包括滚动条)
|
||||
const listClientWidth = skillsList.clientWidth; // 可视区域宽度(不包括滚动条)
|
||||
const listScrollHeight = skillsList.scrollHeight; // 内容总高度
|
||||
@@ -213,7 +202,7 @@ function renderSkillsPagination() {
|
||||
|
||||
// 如果列表有垂直滚动条,分页组件应该与列表内容区域对齐(clientWidth)
|
||||
// 如果没有滚动条,使用100%宽度
|
||||
if (hasScrollbar) {
|
||||
if (hasScrollbar && listClientWidth > 0) {
|
||||
// 分页组件应该与列表内容区域对齐,不包括滚动条
|
||||
paginationContainer.style.width = `${listClientWidth}px`;
|
||||
} else {
|
||||
@@ -235,6 +224,10 @@ function renderSkillsPagination() {
|
||||
if (skillsList) {
|
||||
resizeObserver.observe(skillsList);
|
||||
}
|
||||
|
||||
// 确保分页容器始终可见(防止被隐藏)
|
||||
paginationContainer.style.display = 'block';
|
||||
paginationContainer.style.visibility = 'visible';
|
||||
}
|
||||
|
||||
// 改变每页显示数量
|
||||
@@ -288,6 +281,10 @@ async function searchSkills() {
|
||||
if (!searchInput) return;
|
||||
|
||||
skillsSearchKeyword = searchInput.value.trim();
|
||||
const clearBtn = document.getElementById('skills-search-clear');
|
||||
if (clearBtn) {
|
||||
clearBtn.style.display = skillsSearchKeyword ? 'block' : 'none';
|
||||
}
|
||||
|
||||
if (skillsSearchKeyword) {
|
||||
// 有搜索关键词时,使用后端搜索API(加载所有匹配结果,不分页)
|
||||
@@ -317,6 +314,21 @@ async function searchSkills() {
|
||||
}
|
||||
}
|
||||
|
||||
// 清除skills搜索
|
||||
function clearSkillsSearch() {
|
||||
const searchInput = document.getElementById('skills-search');
|
||||
if (searchInput) {
|
||||
searchInput.value = '';
|
||||
}
|
||||
skillsSearchKeyword = '';
|
||||
const clearBtn = document.getElementById('skills-search-clear');
|
||||
if (clearBtn) {
|
||||
clearBtn.style.display = 'none';
|
||||
}
|
||||
// 恢复分页加载
|
||||
loadSkills(1, skillsPagination.pageSize);
|
||||
}
|
||||
|
||||
// 刷新skills
|
||||
async function refreshSkills() {
|
||||
await loadSkills(skillsPagination.currentPage, skillsPagination.pageSize);
|
||||
@@ -611,10 +623,6 @@ function renderSkillsMonitor() {
|
||||
<div class="monitor-stat-label">成功率</div>
|
||||
<div class="monitor-stat-value">${successRate}%</div>
|
||||
</div>
|
||||
<div class="monitor-stat-card">
|
||||
<div class="monitor-stat-label">Skills目录</div>
|
||||
<div class="monitor-stat-value" style="font-size: 0.875rem;">${escapeHtml(skillsStats.skillsDir || '-')}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1051,106 +1051,90 @@ function renderBatchQueues() {
|
||||
renderBatchQueuesPagination();
|
||||
}
|
||||
|
||||
// 渲染批量任务队列分页控件
|
||||
// 渲染批量任务队列分页控件(参考Skills管理页面样式)
|
||||
function renderBatchQueuesPagination() {
|
||||
const paginationContainer = document.getElementById('batch-queues-pagination');
|
||||
if (!paginationContainer) return;
|
||||
|
||||
const { currentPage, pageSize, total, totalPages } = batchQueuesState;
|
||||
|
||||
// 如果没有数据,不显示分页控件
|
||||
// 即使只有一页也显示分页信息(参考Skills样式)
|
||||
if (total === 0) {
|
||||
paginationContainer.innerHTML = '';
|
||||
paginationContainer.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// 确保分页控件可见
|
||||
paginationContainer.style.display = '';
|
||||
|
||||
// 即使只有一页,也显示分页信息(总数和每页条数选择器)
|
||||
|
||||
// 计算显示的页码范围
|
||||
let startPage = Math.max(1, currentPage - 2);
|
||||
let endPage = Math.min(totalPages, currentPage + 2);
|
||||
|
||||
// 确保显示5个页码(如果可能)
|
||||
if (endPage - startPage < 4) {
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, startPage + 4);
|
||||
} else if (endPage === totalPages) {
|
||||
startPage = Math.max(1, endPage - 4);
|
||||
}
|
||||
}
|
||||
// 计算显示范围
|
||||
const start = total === 0 ? 0 : (currentPage - 1) * pageSize + 1;
|
||||
const end = total === 0 ? 0 : Math.min(currentPage * pageSize, total);
|
||||
|
||||
let paginationHTML = '<div class="pagination">';
|
||||
|
||||
const startItem = (currentPage - 1) * pageSize + 1;
|
||||
const endItem = Math.min(currentPage * pageSize, total);
|
||||
paginationHTML += `<div class="pagination-info">显示 ${startItem}-${endItem} / 共 ${total} 条</div>`;
|
||||
|
||||
// 每页条数选择器
|
||||
// 左侧:显示范围信息和每页数量选择器(参考Skills样式)
|
||||
paginationHTML += `
|
||||
<div class="pagination-page-size">
|
||||
<label for="batch-queues-page-size-pagination">每页:</label>
|
||||
<select id="batch-queues-page-size-pagination" onchange="changeBatchQueuesPageSize()">
|
||||
<option value="10" ${pageSize === 10 ? 'selected' : ''}>10</option>
|
||||
<option value="20" ${pageSize === 20 ? 'selected' : ''}>20</option>
|
||||
<option value="50" ${pageSize === 50 ? 'selected' : ''}>50</option>
|
||||
<option value="100" ${pageSize === 100 ? 'selected' : ''}>100</option>
|
||||
</select>
|
||||
<div class="pagination-info">
|
||||
<span>显示 ${start}-${end} / 共 ${total} 条</span>
|
||||
<label class="pagination-page-size">
|
||||
每页显示
|
||||
<select id="batch-queues-page-size-pagination" onchange="changeBatchQueuesPageSize()">
|
||||
<option value="10" ${pageSize === 10 ? 'selected' : ''}>10</option>
|
||||
<option value="20" ${pageSize === 20 ? 'selected' : ''}>20</option>
|
||||
<option value="50" ${pageSize === 50 ? 'selected' : ''}>50</option>
|
||||
<option value="100" ${pageSize === 100 ? 'selected' : ''}>100</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 只有当有多页时才显示页码导航
|
||||
if (totalPages > 1) {
|
||||
paginationHTML += '<div class="pagination-controls">';
|
||||
|
||||
// 上一页按钮
|
||||
if (currentPage > 1) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="goBatchQueuesPage(${currentPage - 1})" title="上一页">‹</button>`;
|
||||
} else {
|
||||
paginationHTML += '<button class="pagination-btn disabled" disabled>‹</button>';
|
||||
}
|
||||
|
||||
// 第一页
|
||||
if (startPage > 1) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="goBatchQueuesPage(1)">1</button>`;
|
||||
if (startPage > 2) {
|
||||
paginationHTML += '<span class="pagination-ellipsis">...</span>';
|
||||
}
|
||||
}
|
||||
|
||||
// 页码按钮
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
if (i === currentPage) {
|
||||
paginationHTML += `<button class="pagination-btn active">${i}</button>`;
|
||||
} else {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="goBatchQueuesPage(${i})">${i}</button>`;
|
||||
}
|
||||
}
|
||||
|
||||
// 最后一页
|
||||
if (endPage < totalPages) {
|
||||
if (endPage < totalPages - 1) {
|
||||
paginationHTML += '<span class="pagination-ellipsis">...</span>';
|
||||
}
|
||||
paginationHTML += `<button class="pagination-btn" onclick="goBatchQueuesPage(${totalPages})">${totalPages}</button>`;
|
||||
}
|
||||
|
||||
// 下一页按钮
|
||||
if (currentPage < totalPages) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="goBatchQueuesPage(${currentPage + 1})" title="下一页">›</button>`;
|
||||
} else {
|
||||
paginationHTML += '<button class="pagination-btn disabled" disabled>›</button>';
|
||||
}
|
||||
|
||||
paginationHTML += '</div>';
|
||||
}
|
||||
// 右侧:分页按钮(参考Skills样式:首页、上一页、第X/Y页、下一页、末页)
|
||||
paginationHTML += `
|
||||
<div class="pagination-controls">
|
||||
<button class="btn-secondary" onclick="goBatchQueuesPage(1)" ${currentPage === 1 || total === 0 ? 'disabled' : ''}>首页</button>
|
||||
<button class="btn-secondary" onclick="goBatchQueuesPage(${currentPage - 1})" ${currentPage === 1 || total === 0 ? 'disabled' : ''}>上一页</button>
|
||||
<span class="pagination-page">第 ${currentPage} / ${totalPages || 1} 页</span>
|
||||
<button class="btn-secondary" onclick="goBatchQueuesPage(${currentPage + 1})" ${currentPage >= totalPages || total === 0 ? 'disabled' : ''}>下一页</button>
|
||||
<button class="btn-secondary" onclick="goBatchQueuesPage(${totalPages || 1})" ${currentPage >= totalPages || total === 0 ? 'disabled' : ''}>末页</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
paginationHTML += '</div>';
|
||||
|
||||
paginationContainer.innerHTML = paginationHTML;
|
||||
|
||||
// 确保分页组件与列表内容区域对齐(不包括滚动条)
|
||||
function alignPaginationWidth() {
|
||||
const batchQueuesList = document.getElementById('batch-queues-list');
|
||||
if (batchQueuesList && paginationContainer) {
|
||||
// 获取列表的实际内容宽度(不包括滚动条)
|
||||
const listClientWidth = batchQueuesList.clientWidth; // 可视区域宽度(不包括滚动条)
|
||||
const listScrollHeight = batchQueuesList.scrollHeight; // 内容总高度
|
||||
const listClientHeight = batchQueuesList.clientHeight; // 可视区域高度
|
||||
const hasScrollbar = listScrollHeight > listClientHeight;
|
||||
|
||||
// 如果列表有垂直滚动条,分页组件应该与列表内容区域对齐(clientWidth)
|
||||
// 如果没有滚动条,使用100%宽度
|
||||
if (hasScrollbar) {
|
||||
// 分页组件应该与列表内容区域对齐,不包括滚动条
|
||||
paginationContainer.style.width = `${listClientWidth}px`;
|
||||
} else {
|
||||
// 如果没有滚动条,使用100%宽度
|
||||
paginationContainer.style.width = '100%';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 立即执行一次
|
||||
alignPaginationWidth();
|
||||
|
||||
// 监听窗口大小变化和列表内容变化
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
alignPaginationWidth();
|
||||
});
|
||||
|
||||
const batchQueuesList = document.getElementById('batch-queues-list');
|
||||
if (batchQueuesList) {
|
||||
resizeObserver.observe(batchQueuesList);
|
||||
}
|
||||
}
|
||||
|
||||
// 跳转到指定页面
|
||||
@@ -1213,7 +1197,8 @@ async function showBatchQueueDetail(queueId) {
|
||||
batchQueuesState.currentQueueId = queueId;
|
||||
|
||||
if (title) {
|
||||
title.textContent = queue.title ? `批量任务队列 - ${escapeHtml(queue.title)}` : '批量任务队列';
|
||||
// textContent 本身会做转义;这里不要再 escapeHtml,否则会把 && 显示成 &...(看起来像“变形/乱码”)
|
||||
title.textContent = queue.title ? `批量任务队列 - ${String(queue.title)}` : '批量任务队列';
|
||||
}
|
||||
|
||||
// 更新按钮显示
|
||||
|
||||
@@ -262,88 +262,41 @@ function renderVulnerabilityPagination() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 计算显示的页码范围
|
||||
let startPage = Math.max(1, currentPage - 2);
|
||||
let endPage = Math.min(totalPages, currentPage + 2);
|
||||
|
||||
// 确保显示5个页码(如果可能)
|
||||
if (endPage - startPage < 4) {
|
||||
if (startPage === 1) {
|
||||
endPage = Math.min(totalPages, startPage + 4);
|
||||
} else if (endPage === totalPages) {
|
||||
startPage = Math.max(1, endPage - 4);
|
||||
}
|
||||
}
|
||||
|
||||
// 计算显示范围
|
||||
const start = total === 0 ? 0 : (currentPage - 1) * pageSize + 1;
|
||||
const end = total === 0 ? 0 : Math.min(currentPage * pageSize, total);
|
||||
|
||||
let paginationHTML = '<div class="pagination">';
|
||||
|
||||
// 显示总数和当前范围
|
||||
const startItem = (currentPage - 1) * pageSize + 1;
|
||||
const endItem = Math.min(currentPage * pageSize, total);
|
||||
paginationHTML += `<div class="pagination-info">显示 ${startItem}-${endItem} / 共 ${total} 条</div>`;
|
||||
|
||||
// 每页条数选择器(始终显示)
|
||||
const savedPageSize = getVulnerabilityPageSize();
|
||||
// 左侧:显示范围信息和每页数量选择器(参考Skills样式)
|
||||
paginationHTML += `
|
||||
<div class="pagination-page-size">
|
||||
<label for="vulnerability-page-size-pagination">每页:</label>
|
||||
<select id="vulnerability-page-size-pagination" onchange="changeVulnerabilityPageSize()">
|
||||
<option value="10" ${savedPageSize === 10 ? 'selected' : ''}>10</option>
|
||||
<option value="20" ${savedPageSize === 20 ? 'selected' : ''}>20</option>
|
||||
<option value="50" ${savedPageSize === 50 ? 'selected' : ''}>50</option>
|
||||
<option value="100" ${savedPageSize === 100 ? 'selected' : ''}>100</option>
|
||||
</select>
|
||||
<div class="pagination-info">
|
||||
<span>显示 ${start}-${end} / 共 ${total} 条</span>
|
||||
<label class="pagination-page-size">
|
||||
每页显示
|
||||
<select id="vulnerability-page-size-pagination" onchange="changeVulnerabilityPageSize()">
|
||||
<option value="10" ${pageSize === 10 ? 'selected' : ''}>10</option>
|
||||
<option value="20" ${pageSize === 20 ? 'selected' : ''}>20</option>
|
||||
<option value="50" ${pageSize === 50 ? 'selected' : ''}>50</option>
|
||||
<option value="100" ${pageSize === 100 ? 'selected' : ''}>100</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 只有当有多页时才显示页码导航
|
||||
if (totalPages > 1) {
|
||||
paginationHTML += '<div class="pagination-controls">';
|
||||
|
||||
// 上一页按钮
|
||||
if (currentPage > 1) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="loadVulnerabilities(${currentPage - 1})" title="上一页">‹</button>`;
|
||||
} else {
|
||||
paginationHTML += '<button class="pagination-btn disabled" disabled>‹</button>';
|
||||
}
|
||||
|
||||
// 第一页
|
||||
if (startPage > 1) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="loadVulnerabilities(1)">1</button>`;
|
||||
if (startPage > 2) {
|
||||
paginationHTML += '<span class="pagination-ellipsis">...</span>';
|
||||
}
|
||||
}
|
||||
|
||||
// 页码按钮
|
||||
for (let i = startPage; i <= endPage; i++) {
|
||||
if (i === currentPage) {
|
||||
paginationHTML += `<button class="pagination-btn active">${i}</button>`;
|
||||
} else {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="loadVulnerabilities(${i})">${i}</button>`;
|
||||
}
|
||||
}
|
||||
|
||||
// 最后一页
|
||||
if (endPage < totalPages) {
|
||||
if (endPage < totalPages - 1) {
|
||||
paginationHTML += '<span class="pagination-ellipsis">...</span>';
|
||||
}
|
||||
paginationHTML += `<button class="pagination-btn" onclick="loadVulnerabilities(${totalPages})">${totalPages}</button>`;
|
||||
}
|
||||
|
||||
// 下一页按钮
|
||||
if (currentPage < totalPages) {
|
||||
paginationHTML += `<button class="pagination-btn" onclick="loadVulnerabilities(${currentPage + 1})" title="下一页">›</button>`;
|
||||
} else {
|
||||
paginationHTML += '<button class="pagination-btn disabled" disabled>›</button>';
|
||||
}
|
||||
|
||||
paginationHTML += '</div>';
|
||||
}
|
||||
// 右侧:分页按钮(参考Skills样式:首页、上一页、第X/Y页、下一页、末页)
|
||||
paginationHTML += `
|
||||
<div class="pagination-controls">
|
||||
<button class="btn-secondary" onclick="loadVulnerabilities(1)" ${currentPage === 1 || total === 0 ? 'disabled' : ''}>首页</button>
|
||||
<button class="btn-secondary" onclick="loadVulnerabilities(${currentPage - 1})" ${currentPage === 1 || total === 0 ? 'disabled' : ''}>上一页</button>
|
||||
<span class="pagination-page">第 ${currentPage} / ${totalPages || 1} 页</span>
|
||||
<button class="btn-secondary" onclick="loadVulnerabilities(${currentPage + 1})" ${currentPage >= totalPages || total === 0 ? 'disabled' : ''}>下一页</button>
|
||||
<button class="btn-secondary" onclick="loadVulnerabilities(${totalPages || 1})" ${currentPage >= totalPages || total === 0 ? 'disabled' : ''}>末页</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
paginationHTML += '</div>';
|
||||
|
||||
|
||||
paginationContainer.innerHTML = paginationHTML;
|
||||
}
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 614 KiB After Width: | Height: | Size: 442 KiB |
@@ -0,0 +1,926 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>API 文档 - CyberStrikeAI</title>
|
||||
<link rel="icon" type="image/png" href="/static/logo.png">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
<style>
|
||||
/* 覆盖主CSS的overflow限制,允许API文档页面滚动 */
|
||||
body {
|
||||
overflow: auto !important;
|
||||
height: auto !important;
|
||||
}
|
||||
|
||||
.api-docs-container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
padding: 24px;
|
||||
background: var(--bg-primary);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.api-docs-header {
|
||||
margin-bottom: 32px;
|
||||
padding-bottom: 24px;
|
||||
border-bottom: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-docs-header h1 {
|
||||
font-size: 2rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 8px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.api-docs-header p {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.9375rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.auth-info-section {
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
.auth-info-content {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.auth-info-section pre {
|
||||
margin: 0;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
|
||||
}
|
||||
|
||||
.auth-info-section code {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.auth-info-header {
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.auth-info-header:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.auth-info-arrow {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.auth-info-body {
|
||||
animation: slideDown 0.2s ease;
|
||||
}
|
||||
|
||||
@keyframes slideDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.api-docs-content {
|
||||
display: grid;
|
||||
grid-template-columns: 280px 1fr;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.api-docs-sidebar {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 8px;
|
||||
padding: 16px;
|
||||
height: fit-content;
|
||||
max-height: calc(100vh - 100px);
|
||||
position: sticky;
|
||||
top: 24px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.api-docs-sidebar h3 {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.api-group-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.api-group-item {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.api-group-link {
|
||||
display: block;
|
||||
padding: 8px 12px;
|
||||
color: var(--text-secondary);
|
||||
text-decoration: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.875rem;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.api-group-link:hover {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--accent-color);
|
||||
}
|
||||
|
||||
.api-group-link.active {
|
||||
background: rgba(0, 102, 255, 0.1);
|
||||
color: var(--accent-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.api-docs-main {
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.api-endpoint {
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 8px;
|
||||
margin-bottom: 24px;
|
||||
overflow: hidden;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.api-endpoint:hover {
|
||||
box-shadow: var(--shadow-md);
|
||||
}
|
||||
|
||||
.api-endpoint-header {
|
||||
padding: 20px 24px;
|
||||
background: var(--bg-secondary);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.api-endpoint-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.api-method {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.api-method.post {
|
||||
background: #49cc90;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.api-method.get {
|
||||
background: #61affe;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.api-method.put {
|
||||
background: #fca130;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.api-method.delete {
|
||||
background: #f93e3e;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.api-path {
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 0.9375rem;
|
||||
color: var(--text-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.api-summary {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.875rem;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.api-endpoint-body {
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.api-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.api-table-wrapper {
|
||||
overflow-x: auto;
|
||||
width: 100%;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* 确保表格在移动设备上也能正常显示 */
|
||||
@media (max-width: 768px) {
|
||||
.api-params-table {
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.api-params-table th,
|
||||
.api-params-table td {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
/* 移动设备上描述列可以更宽 */
|
||||
.api-params-table th:nth-child(3),
|
||||
.api-params-table td:nth-child(3) {
|
||||
min-width: 150px;
|
||||
}
|
||||
}
|
||||
|
||||
.api-section:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.api-section-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 12px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.api-description {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.6;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.api-description strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.api-description code {
|
||||
background: var(--bg-secondary);
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 0.875em;
|
||||
color: var(--accent-color);
|
||||
}
|
||||
|
||||
.api-description pre {
|
||||
background: var(--bg-secondary);
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 8px 0;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.api-description pre code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.api-description ul {
|
||||
margin: 8px 0;
|
||||
padding-left: 24px;
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.api-description li {
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
/* Markdown样式 */
|
||||
.api-description-detail .md-h1 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 16px 0 12px 0;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 2px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-description-detail .md-h2 {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 14px 0 10px 0;
|
||||
padding-bottom: 6px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-description-detail .md-h3 {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin: 12px 0 8px 0;
|
||||
}
|
||||
|
||||
.api-description-detail .md-paragraph {
|
||||
margin: 8px 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.api-description-detail .md-list {
|
||||
margin: 8px 0;
|
||||
padding-left: 24px;
|
||||
list-style-type: disc;
|
||||
}
|
||||
|
||||
.api-description-detail .md-list ol {
|
||||
list-style-type: decimal;
|
||||
margin: 4px 0;
|
||||
padding-left: 24px;
|
||||
}
|
||||
|
||||
.api-description-detail .md-list-item {
|
||||
margin: 4px 0;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.api-description-detail .md-link {
|
||||
color: var(--accent-color);
|
||||
text-decoration: none;
|
||||
border-bottom: 1px solid transparent;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.api-description-detail .md-link:hover {
|
||||
color: var(--accent-hover);
|
||||
border-bottom-color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.api-description-detail .inline-code {
|
||||
background: var(--bg-secondary);
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 0.875em;
|
||||
color: var(--accent-color);
|
||||
}
|
||||
|
||||
.api-description-detail .code-block {
|
||||
background: var(--bg-secondary);
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
overflow-x: auto;
|
||||
margin: 12px 0;
|
||||
font-size: 0.875rem;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-description-detail .code-block code {
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
color: var(--text-secondary);
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
display: block;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.api-description-detail .code-lang {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
color: var(--text-muted);
|
||||
margin-bottom: 8px;
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.api-description-detail strong {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.api-description-detail em {
|
||||
font-style: italic;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.api-description-toggle {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.description-toggle-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--accent-color);
|
||||
cursor: pointer;
|
||||
padding: 6px 0;
|
||||
font-size: 0.875rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
transition: all 0.2s ease;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.description-toggle-btn:hover {
|
||||
color: var(--accent-hover);
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.description-toggle-icon {
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.api-description-detail {
|
||||
margin-top: 12px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
animation: slideDown 0.2s ease;
|
||||
}
|
||||
|
||||
@keyframes slideDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.api-params-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.875rem;
|
||||
table-layout: fixed;
|
||||
}
|
||||
|
||||
.api-params-table th,
|
||||
.api-params-table td {
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
/* 设置列宽 */
|
||||
.api-params-table th:nth-child(1),
|
||||
.api-params-table td:nth-child(1) {
|
||||
width: 15%;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.api-params-table th:nth-child(2),
|
||||
.api-params-table td:nth-child(2) {
|
||||
width: 12%;
|
||||
min-width: 100px;
|
||||
}
|
||||
|
||||
.api-params-table th:nth-child(3),
|
||||
.api-params-table td:nth-child(3) {
|
||||
width: 45%;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
.api-params-table th:nth-child(4),
|
||||
.api-params-table td:nth-child(4) {
|
||||
width: 10%;
|
||||
min-width: 80px;
|
||||
}
|
||||
|
||||
.api-params-table th:nth-child(5),
|
||||
.api-params-table td:nth-child(5) {
|
||||
width: 18%;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
/* 参数名、类型、必需列不换行 */
|
||||
.api-params-table th:nth-child(1),
|
||||
.api-params-table td:nth-child(1),
|
||||
.api-params-table th:nth-child(2),
|
||||
.api-params-table td:nth-child(2),
|
||||
.api-params-table th:nth-child(4),
|
||||
.api-params-table td:nth-child(4) {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* 示例列允许换行,完整显示 */
|
||||
.api-params-table th:nth-child(5),
|
||||
.api-params-table td:nth-child(5) {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* 确保示例列中的code标签也能完整显示 */
|
||||
.api-params-table td:nth-child(5) code {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
display: inline-block;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* 描述列允许换行,但保持水平方向 */
|
||||
.api-params-table th:nth-child(3),
|
||||
.api-params-table td:nth-child(3) {
|
||||
white-space: normal;
|
||||
word-wrap: break-word;
|
||||
word-break: normal;
|
||||
overflow-wrap: break-word;
|
||||
writing-mode: horizontal-tb !important;
|
||||
direction: ltr !important;
|
||||
text-align: left;
|
||||
line-height: 1.6;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* 确保描述单元格内的内容正常显示 */
|
||||
.api-params-table td:nth-child(3) * {
|
||||
display: inline;
|
||||
writing-mode: horizontal-tb !important;
|
||||
}
|
||||
|
||||
.api-params-table th {
|
||||
background: var(--bg-secondary);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
writing-mode: horizontal-tb !important;
|
||||
direction: ltr !important;
|
||||
}
|
||||
|
||||
.api-params-table td {
|
||||
color: var(--text-secondary);
|
||||
writing-mode: horizontal-tb !important;
|
||||
direction: ltr !important;
|
||||
}
|
||||
|
||||
.api-param-name {
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
color: var(--accent-color);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.api-param-type {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.api-param-required {
|
||||
color: var(--error-color);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.api-param-optional {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.api-test-section {
|
||||
margin-top: 24px;
|
||||
padding-top: 24px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-test-form {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.api-test-input-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.api-test-input-group label {
|
||||
display: block;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.api-test-input-group input,
|
||||
.api-test-input-group textarea {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
font-size: 0.875rem;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.api-test-input-group input:focus,
|
||||
.api-test-input-group textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 3px rgba(0, 102, 255, 0.1);
|
||||
}
|
||||
|
||||
.api-test-input-group textarea {
|
||||
min-height: 120px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.api-test-buttons {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.api-test-btn {
|
||||
padding: 10px 20px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.api-test-btn.primary {
|
||||
background: var(--accent-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.api-test-btn.primary:hover {
|
||||
background: var(--accent-hover);
|
||||
}
|
||||
|
||||
.api-test-btn.secondary {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-test-btn.secondary:hover {
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
/* 复制curl按钮 - 黄色主题 */
|
||||
.api-test-btn.copy-curl {
|
||||
background: #ffc107;
|
||||
color: white;
|
||||
border: 1px solid #ffb300;
|
||||
}
|
||||
|
||||
.api-test-btn.copy-curl:hover {
|
||||
background: #ffb300;
|
||||
border-color: #ffa000;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(255, 193, 7, 0.3);
|
||||
}
|
||||
|
||||
.api-test-btn.copy-curl:active {
|
||||
transform: translateY(0);
|
||||
box-shadow: 0 1px 4px rgba(255, 193, 7, 0.2);
|
||||
}
|
||||
|
||||
/* 清除结果按钮 - 红色/橙色主题 */
|
||||
.api-test-btn.clear-result {
|
||||
background: #ff6b6b;
|
||||
color: white;
|
||||
border: 1px solid #ff5252;
|
||||
}
|
||||
|
||||
.api-test-btn.clear-result:hover {
|
||||
background: #ff5252;
|
||||
border-color: #ff4444;
|
||||
transform: translateY(-1px);
|
||||
box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
|
||||
}
|
||||
|
||||
.api-test-btn.clear-result:active {
|
||||
transform: translateY(0);
|
||||
box-shadow: 0 1px 4px rgba(255, 107, 107, 0.2);
|
||||
}
|
||||
|
||||
.api-test-result {
|
||||
margin-top: 20px;
|
||||
padding: 16px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.875rem;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.api-test-result.success {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.api-test-result.error {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
.api-test-result.loading {
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.api-response-example {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 6px;
|
||||
padding: 16px;
|
||||
margin-top: 12px;
|
||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
||||
font-size: 0.8125rem;
|
||||
color: var(--text-secondary);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.api-response-example pre {
|
||||
margin: 0;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.api-tag {
|
||||
display: inline-block;
|
||||
padding: 4px 8px;
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-secondary);
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.loading-spinner {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid rgba(255, 255, 255, 0.3);
|
||||
border-top-color: white;
|
||||
border-radius: 50%;
|
||||
animation: spin 0.6s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.empty-state svg {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
margin-bottom: 16px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.empty-state h3 {
|
||||
font-size: 1.125rem;
|
||||
margin-bottom: 8px;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="api-docs-container">
|
||||
<div class="api-docs-header">
|
||||
<h1>
|
||||
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<polyline points="14 2 14 8 20 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<line x1="16" y1="13" x2="8" y2="13" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<line x1="16" y1="17" x2="8" y2="17" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
API 文档
|
||||
</h1>
|
||||
<p>CyberStrikeAI 平台 API 接口文档,支持在线测试</p>
|
||||
</div>
|
||||
|
||||
<div id="auth-info-section" class="auth-info-section" style="display: none;">
|
||||
<div class="auth-info-content">
|
||||
<div class="auth-info-header" onclick="toggleAuthInfo()" style="display: flex; align-items: center; justify-content: space-between; cursor: pointer; user-select: none;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
|
||||
<path d="M7 11V7a5 5 0 0 1 10 0v4"/>
|
||||
</svg>
|
||||
<h3 style="margin: 0; font-size: 1rem; font-weight: 600; color: var(--text-primary);">API 认证说明</h3>
|
||||
</div>
|
||||
<svg id="auth-info-arrow" class="auth-info-arrow" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="transition: transform 0.2s ease;">
|
||||
<polyline points="6 9 12 15 18 9"/>
|
||||
</svg>
|
||||
</div>
|
||||
<div id="auth-info-body" class="auth-info-body" style="display: none; color: var(--text-secondary); font-size: 0.875rem; line-height: 1.6; margin-top: 16px;">
|
||||
<p style="margin: 0 0 12px 0;"><strong>所有 API 接口都需要 Token 认证。</strong></p>
|
||||
<div style="background: var(--bg-secondary); padding: 12px; border-radius: 6px; margin-bottom: 12px;">
|
||||
<p style="margin: 0 0 8px 0; font-weight: 500;">1. 获取 Token:</p>
|
||||
<p style="margin: 0 0 8px 0;">在前端页面登录后,Token 会自动保存。您也可以通过以下方式获取:</p>
|
||||
<pre style="background: var(--bg-primary); padding: 8px; border-radius: 4px; margin: 8px 0; overflow-x: auto; font-size: 0.8125rem;"><code>POST /api/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"password": "your_password"
|
||||
}
|
||||
|
||||
响应: {
|
||||
"token": "eyJhbGc...",
|
||||
"expires_at": "2026-01-27T...",
|
||||
"session_duration_hr": 24
|
||||
}</code></pre>
|
||||
</div>
|
||||
<div style="background: var(--bg-secondary); padding: 12px; border-radius: 6px; margin-bottom: 12px;">
|
||||
<p style="margin: 0 0 8px 0; font-weight: 500;">2. 使用 Token:</p>
|
||||
<p style="margin: 0 0 8px 0;">在请求头中添加 Authorization 字段:</p>
|
||||
<pre style="background: var(--bg-primary); padding: 8px; border-radius: 4px; margin: 8px 0; overflow-x: auto; font-size: 0.8125rem;"><code>Authorization: Bearer your_token_here</code></pre>
|
||||
<p style="margin: 8px 0 0 0; font-size: 0.8125rem; color: var(--text-muted);">💡 提示:本页面会自动使用您已登录的 Token,无需手动填写。</p>
|
||||
</div>
|
||||
<div id="token-status" style="display: none; background: rgba(0, 102, 255, 0.1); padding: 8px 12px; border-radius: 6px; border-left: 3px solid var(--accent-color);">
|
||||
<p style="margin: 0; font-size: 0.8125rem; color: var(--accent-color);">
|
||||
<strong>✓ 已检测到 Token</strong> - 您可以直接测试 API 接口
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function toggleAuthInfo() {
|
||||
const body = document.getElementById('auth-info-body');
|
||||
const arrow = document.getElementById('auth-info-arrow');
|
||||
if (body && arrow) {
|
||||
const isExpanded = body.style.display !== 'none';
|
||||
body.style.display = isExpanded ? 'none' : 'block';
|
||||
arrow.style.transform = isExpanded ? 'rotate(0deg)' : 'rotate(180deg)';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="api-docs-content">
|
||||
<div class="api-docs-sidebar">
|
||||
<h3>API 分组</h3>
|
||||
<ul class="api-group-list" id="api-group-list">
|
||||
<li class="api-group-item">
|
||||
<a href="#" class="api-group-link active" data-group="all">全部接口</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="api-docs-main" id="api-docs-main">
|
||||
<div class="empty-state">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<circle cx="12" cy="12" r="10"/>
|
||||
<line x1="12" y1="8" x2="12" y2="12"/>
|
||||
<line x1="12" y1="16" x2="12.01" y2="16"/>
|
||||
</svg>
|
||||
<h3>加载中...</h3>
|
||||
<p>正在加载 API 文档</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/api-docs.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>CyberStrikeAI - 自主渗透测试平台</title>
|
||||
<title>CyberStrikeAI</title>
|
||||
<link rel="icon" type="image/png" href="/static/logo.png">
|
||||
<link rel="shortcut icon" type="image/png" href="/static/favicon.ico">
|
||||
<link rel="stylesheet" href="/static/css/style.css">
|
||||
@@ -11,7 +11,7 @@
|
||||
<body>
|
||||
<div id="login-overlay" class="login-overlay" style="display: none;">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="login-brand">
|
||||
<h2>登录 CyberStrikeAI</h2>
|
||||
<p class="login-subtitle">请输入配置中的访问密码</p>
|
||||
</div>
|
||||
@@ -21,7 +21,9 @@
|
||||
<input type="password" id="login-password" placeholder="输入登录密码" required autocomplete="current-password" />
|
||||
</div>
|
||||
<div id="login-error" class="login-error" role="alert" style="display: none;"></div>
|
||||
<button type="submit" class="btn-primary login-submit">登录</button>
|
||||
<button type="submit" class="btn-primary login-submit">
|
||||
<span>登录</span>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
@@ -29,13 +31,16 @@
|
||||
<div class="container">
|
||||
<header>
|
||||
<div class="header-content">
|
||||
<div class="logo">
|
||||
<div class="logo header-logo-link" onclick="switchPage('dashboard')" role="button" title="返回仪表盘">
|
||||
<img src="/static/logo.png" alt="CyberStrikeAI Logo" style="width: 32px; height: 32px; margin-right: 8px;">
|
||||
<h1>CyberStrikeAI</h1>
|
||||
<span class="version-badge" title="当前版本">{{.Version}}</span>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<p class="header-subtitle">AI 驱动的自动化安全测试平台</p>
|
||||
<div class="header-actions">
|
||||
<button class="openapi-doc-btn" onclick="window.open('/api-docs', '_blank')" title="OpenAPI 文档">
|
||||
<span>API 文档</span>
|
||||
</button>
|
||||
<div class="user-menu-container">
|
||||
<button class="user-avatar-btn" onclick="toggleUserMenu()" title="用户菜单">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
@@ -68,6 +73,17 @@
|
||||
</svg>
|
||||
</div>
|
||||
<nav class="main-sidebar-nav">
|
||||
<div class="nav-item" data-page="dashboard">
|
||||
<div class="nav-item-content" data-title="仪表盘" onclick="switchPage('dashboard')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="3" y="3" width="7" height="9"></rect>
|
||||
<rect x="14" y="3" width="7" height="5"></rect>
|
||||
<rect x="14" y="12" width="7" height="9"></rect>
|
||||
<rect x="3" y="16" width="7" height="5"></rect>
|
||||
</svg>
|
||||
<span>仪表盘</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nav-item" data-page="chat">
|
||||
<div class="nav-item-content" data-title="对话" onclick="switchPage('chat')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -76,6 +92,15 @@
|
||||
<span>对话</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nav-item" data-page="info-collect">
|
||||
<div class="nav-item-content" data-title="信息收集" onclick="switchPage('info-collect')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="11" cy="11" r="8"></circle>
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
||||
</svg>
|
||||
<span>信息收集</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="nav-item" data-page="tasks">
|
||||
<div class="nav-item-content" data-title="任务管理" onclick="switchPage('tasks')">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
@@ -189,8 +214,175 @@
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="content-area">
|
||||
<!-- 仪表盘页面 -->
|
||||
<div id="page-dashboard" class="page active">
|
||||
<div class="dashboard-page">
|
||||
<div class="page-header">
|
||||
<h2>仪表盘</h2>
|
||||
<div class="page-header-actions">
|
||||
<button class="btn-secondary" onclick="refreshDashboard()" title="刷新数据">刷新</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashboard-content">
|
||||
<!-- 第一行:核心 KPI(仪表盘最佳实践:关键指标置顶) -->
|
||||
<div class="dashboard-kpi-row" id="dashboard-cards">
|
||||
<div class="dashboard-kpi-card" role="button" tabindex="0" onclick="switchPage('tasks')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('tasks'); }" title="点击查看任务管理"> <div class="dashboard-kpi-value" id="dashboard-running-tasks">-</div><div class="dashboard-kpi-label">运行中任务</div></div>
|
||||
<div class="dashboard-kpi-card" role="button" tabindex="0" onclick="switchPage('vulnerabilities')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('vulnerabilities'); }" title="点击查看漏洞管理"><div class="dashboard-kpi-value" id="dashboard-vuln-total">-</div><div class="dashboard-kpi-label">漏洞总数</div></div>
|
||||
<div class="dashboard-kpi-card" role="button" tabindex="0" onclick="switchPage('mcp-monitor')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('mcp-monitor'); }" title="点击查看 MCP 监控"><div class="dashboard-kpi-value" id="dashboard-kpi-tools-calls">-</div><div class="dashboard-kpi-label">工具调用次数</div></div>
|
||||
<div class="dashboard-kpi-card" role="button" tabindex="0" onclick="switchPage('mcp-monitor')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('mcp-monitor'); }" title="点击查看 MCP 监控"><div class="dashboard-kpi-value" id="dashboard-kpi-success-rate">-</div><div class="dashboard-kpi-label">工具执行成功率</div></div>
|
||||
</div>
|
||||
<!-- 两列主内容区 -->
|
||||
<div class="dashboard-grid">
|
||||
<div class="dashboard-main">
|
||||
<section class="dashboard-section dashboard-section-chart">
|
||||
<h3 class="dashboard-section-title">漏洞严重程度分布</h3>
|
||||
<div class="dashboard-chart-wrap">
|
||||
<div class="dashboard-stacked-bar" id="dashboard-stacked-bar">
|
||||
<span class="dashboard-bar-seg seg-critical" id="dashboard-bar-critical" style="width: 0%"></span>
|
||||
<span class="dashboard-bar-seg seg-high" id="dashboard-bar-high" style="width: 0%"></span>
|
||||
<span class="dashboard-bar-seg seg-medium" id="dashboard-bar-medium" style="width: 0%"></span>
|
||||
<span class="dashboard-bar-seg seg-low" id="dashboard-bar-low" style="width: 0%"></span>
|
||||
<span class="dashboard-bar-seg seg-info" id="dashboard-bar-info" style="width: 0%"></span>
|
||||
</div>
|
||||
<div class="dashboard-legend" id="dashboard-vuln-bars">
|
||||
<div class="dashboard-legend-item"><span class="dashboard-legend-dot critical"></span><span class="dashboard-legend-label">严重</span><span class="dashboard-legend-value" id="dashboard-severity-critical">0</span></div>
|
||||
<div class="dashboard-legend-item"><span class="dashboard-legend-dot high"></span><span class="dashboard-legend-label">高危</span><span class="dashboard-legend-value" id="dashboard-severity-high">0</span></div>
|
||||
<div class="dashboard-legend-item"><span class="dashboard-legend-dot medium"></span><span class="dashboard-legend-label">中危</span><span class="dashboard-legend-value" id="dashboard-severity-medium">0</span></div>
|
||||
<div class="dashboard-legend-item"><span class="dashboard-legend-dot low"></span><span class="dashboard-legend-label">低危</span><span class="dashboard-legend-value" id="dashboard-severity-low">0</span></div>
|
||||
<div class="dashboard-legend-item"><span class="dashboard-legend-dot info"></span><span class="dashboard-legend-label">信息</span><span class="dashboard-legend-value" id="dashboard-severity-info">0</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="dashboard-section dashboard-section-overview">
|
||||
<h3 class="dashboard-section-title">运行概览</h3>
|
||||
<div class="dashboard-overview-list">
|
||||
<div class="dashboard-overview-item dashboard-overview-item-batch" role="button" tabindex="0" onclick="switchPage('tasks')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('tasks'); }">
|
||||
<span class="dashboard-overview-icon dashboard-overview-icon-batch" aria-hidden="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg></span>
|
||||
<div class="dashboard-overview-content">
|
||||
<div class="dashboard-overview-header">
|
||||
<span class="dashboard-overview-label">批量任务队列</span>
|
||||
<span class="dashboard-overview-total" id="dashboard-batch-total">-</span>
|
||||
</div>
|
||||
<div class="dashboard-overview-stats">
|
||||
<span class="dashboard-overview-stat dashboard-overview-stat-pending">
|
||||
<span class="dashboard-overview-stat-badge badge-pending"></span>
|
||||
<span class="dashboard-overview-stat-value" id="dashboard-batch-pending">-</span>
|
||||
<span class="dashboard-overview-stat-label">待执行</span>
|
||||
</span>
|
||||
<span class="dashboard-overview-stat dashboard-overview-stat-running">
|
||||
<span class="dashboard-overview-stat-badge badge-running"></span>
|
||||
<span class="dashboard-overview-stat-value" id="dashboard-batch-running">-</span>
|
||||
<span class="dashboard-overview-stat-label">执行中</span>
|
||||
</span>
|
||||
<span class="dashboard-overview-stat dashboard-overview-stat-done">
|
||||
<span class="dashboard-overview-stat-badge badge-done"></span>
|
||||
<span class="dashboard-overview-stat-value" id="dashboard-batch-done">-</span>
|
||||
<span class="dashboard-overview-stat-label">已完成</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="dashboard-overview-progress">
|
||||
<div class="dashboard-overview-progress-bar">
|
||||
<div class="dashboard-overview-progress-segment dashboard-overview-progress-pending" id="dashboard-batch-progress-pending" style="width: 0%"></div>
|
||||
<div class="dashboard-overview-progress-segment dashboard-overview-progress-running" id="dashboard-batch-progress-running" style="width: 0%"></div>
|
||||
<div class="dashboard-overview-progress-segment dashboard-overview-progress-done" id="dashboard-batch-progress-done" style="width: 0%"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashboard-overview-item dashboard-overview-item-tools" role="button" tabindex="0" onclick="switchPage('mcp-monitor')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('mcp-monitor'); }">
|
||||
<span class="dashboard-overview-icon dashboard-overview-icon-tools" aria-hidden="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg></span>
|
||||
<div class="dashboard-overview-content">
|
||||
<div class="dashboard-overview-header">
|
||||
<span class="dashboard-overview-label">工具调用</span>
|
||||
<span class="dashboard-overview-success-rate" id="dashboard-tools-success-rate">-</span>
|
||||
</div>
|
||||
<div class="dashboard-overview-value-group">
|
||||
<span class="dashboard-overview-value-large" id="dashboard-tools-calls">-</span>
|
||||
<span class="dashboard-overview-value-unit">次调用</span>
|
||||
<span class="dashboard-overview-value-separator">·</span>
|
||||
<span class="dashboard-overview-value-normal" id="dashboard-tools-count">-</span>
|
||||
<span class="dashboard-overview-value-unit">个工具</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashboard-overview-item dashboard-overview-item-knowledge" role="button" tabindex="0" onclick="switchPage('knowledge-management')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('knowledge-management'); }">
|
||||
<span class="dashboard-overview-icon dashboard-overview-icon-knowledge" aria-hidden="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"></path><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"></path></svg></span>
|
||||
<div class="dashboard-overview-content">
|
||||
<div class="dashboard-overview-header">
|
||||
<span class="dashboard-overview-label">知识</span>
|
||||
<span class="dashboard-overview-status" id="dashboard-knowledge-status">-</span>
|
||||
</div>
|
||||
<div class="dashboard-overview-value-group">
|
||||
<span class="dashboard-overview-value-large" id="dashboard-knowledge-items">-</span>
|
||||
<span class="dashboard-overview-value-unit">项知识</span>
|
||||
<span class="dashboard-overview-value-separator">·</span>
|
||||
<span class="dashboard-overview-value-normal" id="dashboard-knowledge-categories">-</span>
|
||||
<span class="dashboard-overview-value-unit">个分类</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashboard-overview-item dashboard-overview-item-skills" role="button" tabindex="0" onclick="switchPage('skills-monitor')" onkeydown="if(event.key==='Enter'||event.key===' ') { event.preventDefault(); switchPage('skills-monitor'); }">
|
||||
<span class="dashboard-overview-icon dashboard-overview-icon-skills" aria-hidden="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg></span>
|
||||
<div class="dashboard-overview-content">
|
||||
<div class="dashboard-overview-header">
|
||||
<span class="dashboard-overview-label">Skills</span>
|
||||
<span class="dashboard-overview-status" id="dashboard-skills-status">-</span>
|
||||
</div>
|
||||
<div class="dashboard-overview-value-group">
|
||||
<span class="dashboard-overview-value-large" id="dashboard-skills-calls">-</span>
|
||||
<span class="dashboard-overview-value-unit">次调用</span>
|
||||
<span class="dashboard-overview-value-separator">·</span>
|
||||
<span class="dashboard-overview-value-normal" id="dashboard-skills-count">-</span>
|
||||
<span class="dashboard-overview-value-unit">个 Skill</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="dashboard-section dashboard-section-quick dashboard-quick-inline">
|
||||
<h3 class="dashboard-section-title">快捷入口</h3>
|
||||
<div class="dashboard-quick-links dashboard-quick-links-row">
|
||||
<a class="dashboard-quick-link" onclick="switchPage('chat')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg></span><span>对话</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('tasks')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"></path><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path></svg></span><span>任务管理</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('vulnerabilities')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"></path></svg></span><span>漏洞管理</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('mcp-management')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"></path></svg></span><span>MCP 管理</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('knowledge-management')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"></path><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"></path></svg></span><span>知识管理</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('skills-management')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"></path><polyline points="14 2 14 8 20 8"></polyline></svg></span><span>Skills 管理</span></a>
|
||||
<a class="dashboard-quick-link" onclick="switchPage('roles-management')"><span class="dashboard-quick-icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg></span><span>角色管理</span></a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
<div class="dashboard-side">
|
||||
<section class="dashboard-section dashboard-section-tools">
|
||||
<h3 class="dashboard-section-title">工具执行次数</h3>
|
||||
<div class="dashboard-tools-chart-wrap">
|
||||
<div class="dashboard-tools-chart-placeholder" id="dashboard-tools-pie-placeholder">暂无数据</div>
|
||||
<div class="dashboard-tools-bar-chart" id="dashboard-tools-bar-chart"></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dashboard-cta-block">
|
||||
<div class="dashboard-cta-content">
|
||||
<div class="dashboard-cta-icon" aria-hidden="true">
|
||||
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
|
||||
</div>
|
||||
<div class="dashboard-cta-copy">
|
||||
<p class="dashboard-cta-text">开始你的安全之旅</p>
|
||||
<p class="dashboard-cta-sub">在对话中描述目标,AI 将协助执行扫描与漏洞分析</p>
|
||||
</div>
|
||||
</div>
|
||||
<button class="dashboard-cta-btn" onclick="switchPage('chat')">
|
||||
<span>前往对话</span>
|
||||
<span class="dashboard-cta-btn-arrow" aria-hidden="true"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M5 12h14M12 5l7 7-7 7"/></svg></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 对话页面 -->
|
||||
<div id="page-chat" class="page active">
|
||||
<div id="page-chat" class="page">
|
||||
<div class="chat-page-layout">
|
||||
<!-- 历史对话侧边栏 -->
|
||||
<aside class="conversation-sidebar">
|
||||
@@ -541,6 +733,105 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 信息收集页面 -->
|
||||
<div id="page-info-collect" class="page">
|
||||
<div class="page-header">
|
||||
<h2>信息收集</h2>
|
||||
<div class="page-header-actions">
|
||||
<button class="btn-secondary" onclick="resetFofaForm()">重置</button>
|
||||
<button class="btn-primary" onclick="submitFofaSearch()">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="page-content">
|
||||
<div class="info-collect-panel">
|
||||
<div class="info-collect-form">
|
||||
<div class="form-group">
|
||||
<label for="fofa-query">FOFA 查询语法</label>
|
||||
<textarea id="fofa-query" class="info-collect-query-input" rows="1" placeholder='例如:app="Apache" && country="CN"'></textarea>
|
||||
<small class="form-hint">查询语法参考 FOFA 文档,支持 && / || / () 等。</small>
|
||||
<div class="info-collect-presets" aria-label="FOFA 查询示例">
|
||||
<button class="preset-chip" type="button" onclick="applyFofaQueryPreset('app="Apache" && country="CN"')" title="填入示例">Apache + 中国</button>
|
||||
<button class="preset-chip" type="button" onclick="applyFofaQueryPreset('title="登录" && country="CN"')" title="填入示例">登录页 + 中国</button>
|
||||
<button class="preset-chip" type="button" onclick="applyFofaQueryPreset('domain="example.com"')" title="填入示例">指定域名</button>
|
||||
<button class="preset-chip" type="button" onclick="applyFofaQueryPreset('ip="1.1.1.1"')" title="填入示例">指定 IP</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="fofa-nl">自然语言(AI 解析为 FOFA 语法)</label>
|
||||
<div class="info-collect-nl-row">
|
||||
<textarea id="fofa-nl" class="info-collect-query-input" rows="1" placeholder="例如:找美国 Missouri 的 Apache 站点,标题包含 Home"></textarea>
|
||||
<button id="fofa-nl-parse-btn" class="btn-secondary" type="button" onclick="parseFofaNaturalLanguage()" title="将自然语言解析为 FOFA 查询语法">AI 解析</button>
|
||||
</div>
|
||||
<div id="fofa-nl-status" class="fofa-nl-status muted" style="display: none;" aria-live="polite"></div>
|
||||
<small class="form-hint">解析后会弹窗展示 FOFA 语法(可编辑),确认无误后再填入查询框并执行查询。</small>
|
||||
</div>
|
||||
<div class="info-collect-form-row">
|
||||
<div class="form-group">
|
||||
<label for="fofa-size">返回数量</label>
|
||||
<input type="number" id="fofa-size" min="1" max="10000" value="100" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="fofa-page">页码</label>
|
||||
<input type="number" id="fofa-page" min="1" value="1" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label class="checkbox-label" style="margin-top: 24px;">
|
||||
<input type="checkbox" id="fofa-full" class="modern-checkbox" />
|
||||
<span class="checkbox-custom"></span>
|
||||
<span class="checkbox-text">full</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="fofa-fields">返回字段名(逗号分隔)</label>
|
||||
<input type="text" id="fofa-fields" value="host,ip,port,domain,title,protocol,country,province,city,server" />
|
||||
<div class="info-collect-presets" aria-label="FOFA 字段模板">
|
||||
<button class="preset-chip" type="button" onclick="applyFofaFieldsPreset('host,ip,port,domain')" title="适合快速导出目标">最小字段</button>
|
||||
<button class="preset-chip" type="button" onclick="applyFofaFieldsPreset('host,title,ip,port,domain,protocol,server,icp,country,province,city')" title="适合浏览和筛选">Web 常用</button>
|
||||
<button class="preset-chip" type="button" onclick="applyFofaFieldsPreset('host,ip,port,domain,title,protocol,country,province,city,server,as_number,as_organization,icp,header,banner')" title="更偏指纹/情报">情报增强</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="info-collect-results">
|
||||
<div class="info-collect-results-header">
|
||||
<div class="info-collect-results-header-left">
|
||||
<div class="info-collect-results-title">查询结果</div>
|
||||
<div class="info-collect-results-meta" id="fofa-results-meta">-</div>
|
||||
</div>
|
||||
<div class="info-collect-results-toolbar" aria-label="结果工具条">
|
||||
<div class="info-collect-selected" id="fofa-selected-meta">已选择 0 条</div>
|
||||
<button class="btn-secondary btn-small" type="button" onclick="toggleFofaColumnsPanel()" title="显示/隐藏字段">列</button>
|
||||
<button class="btn-secondary btn-small" type="button" onclick="exportFofaResults('csv')" title="导出当前结果为 CSV">导出 CSV</button>
|
||||
<button class="btn-secondary btn-small" type="button" onclick="exportFofaResults('json')" title="导出当前结果为 JSON">导出 JSON</button>
|
||||
<button class="btn-primary btn-small" type="button" onclick="batchScanSelectedFofaRows()" title="将所选行创建为批量任务队列">批量扫描</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-collect-results-table-wrap">
|
||||
<!-- 字段显示/隐藏面板 -->
|
||||
<div id="fofa-columns-panel" class="info-collect-columns-panel" style="display: none;">
|
||||
<div class="info-collect-columns-panel-header">
|
||||
<div class="info-collect-columns-title">显示字段</div>
|
||||
<div class="info-collect-columns-actions">
|
||||
<button class="btn-secondary btn-small" type="button" onclick="showAllFofaColumns()">全选</button>
|
||||
<button class="btn-secondary btn-small" type="button" onclick="hideAllFofaColumns()">全不选</button>
|
||||
<button class="btn-secondary btn-small" type="button" onclick="closeFofaColumnsPanel()">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="fofa-columns-list" class="info-collect-columns-list"></div>
|
||||
</div>
|
||||
<table class="info-collect-table">
|
||||
<thead id="fofa-results-thead"></thead>
|
||||
<tbody id="fofa-results-tbody">
|
||||
<tr><td class="muted" style="padding: 16px;">暂无数据</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 漏洞管理页面 -->
|
||||
<div id="page-vulnerabilities" class="page">
|
||||
<div class="page-header">
|
||||
@@ -624,7 +915,7 @@
|
||||
</div>
|
||||
|
||||
<!-- 分页控件 -->
|
||||
<div id="vulnerability-pagination"></div>
|
||||
<div id="vulnerability-pagination" class="pagination-container pagination-fixed"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -665,7 +956,7 @@
|
||||
</div>
|
||||
<div id="batch-queues-list" class="batch-queues-list"></div>
|
||||
<!-- 分页控件 -->
|
||||
<div id="batch-queues-pagination"></div>
|
||||
<div id="batch-queues-pagination" class="pagination-container pagination-fixed"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -676,23 +967,22 @@
|
||||
<h2>角色管理</h2>
|
||||
<div class="page-header-actions">
|
||||
<button class="btn-secondary" onclick="refreshRoles()">刷新</button>
|
||||
<button class="btn-primary" onclick="showAddRoleModal()">添加角色</button>
|
||||
<button class="btn-primary" onclick="showAddRoleModal()">创建角色</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="page-content">
|
||||
<div class="roles-controls">
|
||||
<div class="roles-stats-bar" id="roles-stats">
|
||||
<div class="role-stat-item">
|
||||
<span class="role-stat-label">总角色数</span>
|
||||
<span class="role-stat-value">-</span>
|
||||
</div>
|
||||
<div class="role-stat-item">
|
||||
<span class="role-stat-label">已启用</span>
|
||||
<span class="role-stat-value">-</span>
|
||||
</div>
|
||||
<div class="roles-search-box">
|
||||
<input type="text" id="roles-search" placeholder="搜索角色..." oninput="handleRolesSearchInput()" onkeydown="if(event.key==='Enter') searchRoles()" />
|
||||
<button class="roles-search-clear" id="roles-search-clear" onclick="clearRolesSearch()" style="display: none;" title="清除搜索">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M15 9l-6 6M9 9l6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="roles-list" class="roles-list">
|
||||
<div id="roles-list" class="roles-grid">
|
||||
<div class="loading-spinner">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -737,23 +1027,22 @@
|
||||
<h2>Skills管理</h2>
|
||||
<div class="page-header-actions">
|
||||
<button class="btn-secondary" onclick="refreshSkills()">刷新</button>
|
||||
<button class="btn-primary" onclick="showAddSkillModal()">添加Skill</button>
|
||||
<button class="btn-primary" onclick="showAddSkillModal()">创建Skill</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="page-content page-content-with-pagination">
|
||||
<div class="skills-controls">
|
||||
<div class="skills-stats-bar" id="skills-management-stats">
|
||||
<div class="skill-stat-item">
|
||||
<span class="skill-stat-label">总Skills数</span>
|
||||
<span class="skill-stat-value">-</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="skills-filters">
|
||||
<input type="text" id="skills-search" placeholder="搜索skill..." oninput="handleSkillsSearchInput()" onkeydown="if(event.key==='Enter') searchSkills()" />
|
||||
<button class="btn-search" onclick="searchSkills()" title="搜索">🔍</button>
|
||||
<div class="skills-search-box">
|
||||
<input type="text" id="skills-search" placeholder="搜索Skills..." oninput="handleSkillsSearchInput()" onkeydown="if(event.key==='Enter') searchSkills()" />
|
||||
<button class="skills-search-clear" id="skills-search-clear" onclick="clearSkillsSearch()" style="display: none;" title="清除搜索">
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2"/>
|
||||
<path d="M15 9l-6 6M9 9l6 6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="skills-list" class="skills-list skills-list-with-pagination">
|
||||
<div id="skills-list" class="skills-grid">
|
||||
<div class="loading-spinner">加载中...</div>
|
||||
</div>
|
||||
<div id="skills-pagination" class="pagination-container pagination-fixed"></div>
|
||||
@@ -805,6 +1094,27 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- FOFA配置 -->
|
||||
<div class="settings-subsection">
|
||||
<h4>FOFA 配置</h4>
|
||||
<div class="settings-form">
|
||||
<div class="form-group">
|
||||
<label for="fofa-base-url">Base URL</label>
|
||||
<input type="text" id="fofa-base-url" placeholder="https://fofa.info/api/v1/search/all(可选)" />
|
||||
<small class="form-hint">留空则使用默认地址。</small>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="fofa-email">Email</label>
|
||||
<input type="text" id="fofa-email" placeholder="输入 FOFA 账号邮箱" autocomplete="off" />
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="fofa-api-key">API Key</label>
|
||||
<input type="password" id="fofa-api-key" placeholder="输入 FOFA API Key" autocomplete="off" />
|
||||
<small class="form-hint">仅保存在服务器配置中(`config.yaml`)。</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Agent配置 -->
|
||||
<div class="settings-subsection">
|
||||
<h4>Agent 配置</h4>
|
||||
@@ -1283,8 +1593,44 @@ version: 1.0.0<br>
|
||||
<div class="modal-body create-group-body">
|
||||
<p class="create-group-description">分组功能可将对话集中归类管理,让对话更加井然有序。</p>
|
||||
<div class="create-group-input-wrapper">
|
||||
<span class="group-icon-input">😊</span>
|
||||
<button type="button" class="group-icon-input" id="create-group-icon-btn" onclick="toggleGroupIconPicker()" title="点击选择图标">📁</button>
|
||||
<input type="text" id="create-group-name-input" placeholder="请输入分组名称" />
|
||||
<!-- Emoji选择器面板 -->
|
||||
<div id="group-icon-picker" class="group-icon-picker" style="display: none;">
|
||||
<div class="icon-picker-header">
|
||||
<span>选择图标</span>
|
||||
<div class="icon-picker-custom">
|
||||
<input type="text" id="custom-icon-input" class="custom-icon-input" placeholder="自定义" maxlength="2" />
|
||||
<button type="button" class="custom-icon-btn" onclick="applyCustomIcon()">确定</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="icon-picker-grid">
|
||||
<span class="icon-option" onclick="selectGroupIcon('📁')">📁</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🔒')">🔒</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🛡️')">🛡️</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('⚔️')">⚔️</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🎯')">🎯</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🔍')">🔍</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('💻')">💻</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🐛')">🐛</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🚀')">🚀</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('⚡')">⚡</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🔥')">🔥</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('💡')">💡</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🎮')">🎮</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🏴☠️')">🏴☠️</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🕵️')">🕵️</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🔑')">🔑</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('📡')">📡</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🌐')">🌐</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('📊')">📊</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('📝')">📝</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('🗂️')">🗂️</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('📌')">📌</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('⭐')">⭐</span>
|
||||
<span class="icon-option" onclick="selectGroupIcon('💎')">💎</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="create-group-suggestions">
|
||||
<div class="suggestion-tag" onclick="selectSuggestion('渗透测试')">渗透测试</div>
|
||||
@@ -1424,10 +1770,10 @@ version: 1.0.0<br>
|
||||
<h2 id="batch-queue-detail-title">批量任务队列详情</h2>
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<div class="modal-header-actions">
|
||||
<button class="btn-secondary" id="batch-queue-add-task-btn" onclick="showAddBatchTaskModal()" style="display: none;">添加任务</button>
|
||||
<button class="btn-primary" id="batch-queue-start-btn" onclick="startBatchQueue()" style="display: none;">开始执行</button>
|
||||
<button class="btn-secondary" id="batch-queue-pause-btn" onclick="pauseBatchQueue()" style="display: none;">暂停队列</button>
|
||||
<button class="btn-secondary btn-danger" id="batch-queue-delete-btn" onclick="deleteBatchQueue()" style="display: none;">删除队列</button>
|
||||
<button class="btn-secondary btn-small" id="batch-queue-add-task-btn" onclick="showAddBatchTaskModal()" style="display: none;">添加任务</button>
|
||||
<button class="btn-primary btn-small" id="batch-queue-start-btn" onclick="startBatchQueue()" style="display: none;">开始执行</button>
|
||||
<button class="btn-secondary btn-small" id="batch-queue-pause-btn" onclick="pauseBatchQueue()" style="display: none;">暂停队列</button>
|
||||
<button class="btn-secondary btn-small btn-danger" id="batch-queue-delete-btn" onclick="deleteBatchQueue()" style="display: none;">删除队列</button>
|
||||
</div>
|
||||
<span class="modal-close" onclick="closeBatchQueueDetailModal()">×</span>
|
||||
</div>
|
||||
@@ -1663,7 +2009,9 @@ version: 1.0.0<br>
|
||||
|
||||
<script src="/static/js/builtin-tools.js"></script>
|
||||
<script src="/static/js/auth.js"></script>
|
||||
<script src="/static/js/info-collect.js"></script>
|
||||
<script src="/static/js/router.js"></script>
|
||||
<script src="/static/js/dashboard.js"></script>
|
||||
<script src="/static/js/monitor.js"></script>
|
||||
<script src="/static/js/chat.js"></script>
|
||||
<script src="/static/js/settings.js"></script>
|
||||
|
||||