feat(frontend): migrate to Semi Design and refresh workspace

统一 React + Semi Design 页面与视觉体系,保留既有业务接口、权限和深链接;补齐构建产物、SPA 入口校验及浏览器回归,减少旧模板与全局脚本的维护成本。
This commit is contained in:
Sycun 2026-11-19 09:09:11 +08:00
parent e8ad42ac2c
commit 04a70859b7
423 changed files with 41559 additions and 164972 deletions

View File

@ -1,9 +1,9 @@
name: Deep assessments
on:
push:
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/assessment-workbench.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/frontend/**', '.github/workflows/deep-assessments.yml']
pull_request:
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/static/js/deep-assessments.js', 'web/static/js/deep-assessment-graph.js', 'web/static/js/assessment-finding-links.js', 'web/static/js/assessment-exploration-views.js', 'web/static/js/assessment-node-panel.js', 'web/static/js/assessment-workbench.js', 'web/static/js/vulnerability*.js', 'web/static/css/deep-assessments.css', 'web/templates/index.html', 'scripts/deep-assessments-browser.test.cjs', 'scripts/assessment-findings-browser.test.cjs', '.github/workflows/deep-assessments.yml']
paths: ['internal/deepassessment/**', 'internal/database/vulnerability*', 'internal/database/assessment*', 'internal/database/asset*', 'internal/database/schemas/application.sql', 'internal/app/vulnerability_tools.go', 'internal/app/assessment_finding_test.go', 'internal/handler/vulnerability*', 'internal/handler/deep_assessment*', 'internal/multiagent/**', 'internal/agentruntime/**', 'runtime/pi/**', 'web/frontend/**', '.github/workflows/deep-assessments.yml']
permissions:
contents: read
jobs:
@ -24,9 +24,3 @@ jobs:
- run: go test ./internal/app -run TestRecordVulnerabilityAssessmentEvidence
- run: go test -race ./internal/deepassessment
- run: go test -race ./internal/handler -run TestDeepAssessment
- name: Browser fixture dependencies
run: |
npm install --prefix "$RUNNER_TEMP/assessment-ui-deps" --no-save --ignore-scripts --package-lock=false playwright@1.65.0
"$RUNNER_TEMP/assessment-ui-deps/node_modules/.bin/playwright" install --with-deps chromium
- name: Independent assessment and unchanged batch UI
run: NODE_PATH="$RUNNER_TEMP/assessment-ui-deps/node_modules" node --test scripts/deep-assessments-browser.test.cjs scripts/assessment-findings-browser.test.cjs scripts/batch-tasks-browser.test.cjs

41
.github/workflows/frontend-build.yml vendored Normal file
View File

@ -0,0 +1,41 @@
name: Frontend build
on:
push:
paths: ['web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'internal/app/app.go', 'internal/app/spa_test.go', '.github/workflows/frontend-build.yml']
pull_request:
paths: ['web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'internal/app/app.go', 'internal/app/spa_test.go', '.github/workflows/frontend-build.yml']
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Build React + Semi Design bundle
run: |
npm ci --prefix web/frontend
npm run --prefix web/frontend build
- name: Committed bundle matches sources
run: |
if [ -n "$(git status --porcelain web/static/app)" ]; then
echo "web/static/app is out of date; run: npm run --prefix web/frontend build" >&2
git status --porcelain web/static/app >&2
exit 1
fi
- name: SPA entry and build artifacts
run: go test ./internal/app -run TestSPA -count=1
- run: node --test web/frontend/tests/*.test.mjs
- name: Install Chromium for isolated UI tests
working-directory: web/frontend
run: npx playwright install --with-deps chromium
- name: Browser regression tests
run: npm run --prefix web/frontend test:ui -- --reporter=line

View File

@ -1,9 +1,9 @@
name: Self-update
on:
push:
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
pull_request:
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/static/js/**', 'web/static/i18n/**', 'web/static/css/style.css', 'web/templates/index.html', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
paths: ['internal/update/**', 'internal/app/update_restart*', 'internal/security/auth*', 'internal/workflow/**', 'internal/config/**', 'internal/handler/**', 'internal/mcp/**', 'cmd/server/**', 'web/frontend/**', 'web/static/app/**', 'web/static/i18n/**', 'upgrade.sh', 'run.sh', 'go.mod', 'go.sum', '.gitignore', '.github/workflows/self-update.yml']
permissions:
contents: read
jobs:
@ -27,9 +27,12 @@ jobs:
- name: Authentication and update session handoff
run: go test -race ./internal/security -run '^(TestAuthManager|TestAttachRBACStore|TestRevokeRoleSessions|TestPublishSession|TestRestartHandoff)'
- run: go build ./...
- name: Frontend regression tests
- name: Frontend build and SPA artifacts
shell: bash
run: node --test web/static/js/*.test.cjs
run: |
npm ci --prefix web/frontend
npm run --prefix web/frontend build
go test ./internal/app -run TestSPA -count=1
- name: Shell syntax
shell: bash
run: bash -n run.sh upgrade.sh

View File

@ -1,24 +0,0 @@
name: Task management UI
on:
push:
paths: ['web/templates/index.html', 'web/static/js/tasks.js', 'web/static/js/router.js', 'web/static/js/auth.js', 'web/static/js/modal.js', 'web/static/js/rbac-guards.js', 'web/static/css/**', 'web/static/i18n/**', 'scripts/batch-tasks-browser.test.cjs', 'scripts/helpers/batch-task-ui-fixture.cjs', '.github/workflows/task-ui.yml']
pull_request:
paths: ['web/templates/index.html', 'web/static/js/tasks.js', 'web/static/js/router.js', 'web/static/js/auth.js', 'web/static/js/modal.js', 'web/static/js/rbac-guards.js', 'web/static/css/**', 'web/static/i18n/**', 'scripts/batch-tasks-browser.test.cjs', 'scripts/helpers/batch-task-ui-fixture.cjs', '.github/workflows/task-ui.yml']
permissions:
contents: read
jobs:
browser:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
- name: Install isolated browser test dependencies
run: |
npm install --prefix "$RUNNER_TEMP/task-ui-deps" --no-save --ignore-scripts --package-lock=false playwright@1.65.0
"$RUNNER_TEMP/task-ui-deps/node_modules/.bin/playwright" install --with-deps chromium
- name: Test real task page entrypoints and controls
run: |
NODE_PATH="$RUNNER_TEMP/task-ui-deps/node_modules" node --test scripts/batch-tasks-browser.test.cjs

2
.gitignore vendored
View File

@ -72,6 +72,8 @@ __pycache__/
# Node / browser extension
node_modules/
/web/frontend/test-results/
/web/frontend/playwright-report/
# macOS / Windows / editors
.DS_Store

View File

@ -1,5 +1,19 @@
# Changelog
## 2026-11-19 · 前端整体迁移到 React + Semi Design
- Web 界面重写为 Vite 构建的 React 19 单页应用,组件统一使用 Semi Design;页面按 `#/<页面 id>` 路由,
深链接(会话、漏洞、项目、测评、设置分区、MCP 执行、HITL 审批)保持可分享。
- 服务端不再渲染业务模板:`GET /` 直接返回 `web/static/app/index.html`,`/api-docs` 302 到 `/#/api-docs`,
API 文档改为应用内 OpenAPI 浏览器(含在线调试)。
- 复用既有 REST 接口、`cyberstrike-auth` 会话令牌、`cyberstrike-theme` 主题偏好与 `web/static/i18n` 词条;
新增 `src/lib/http.js` 统一注入令牌、错误与 SSE 解析,`components/ui.jsx` 统一页面骨架、表格、指标卡、
Markdown/JSON 视图与抽屉。
- 30 个业务页面 + API 文档全部由 React 组件实现,覆盖对话流式回复与内联审批、深度测评图谱与验收、
资产/漏洞/项目/任务/工作流、WebShell 与 C2、MCP 与 HITL、知识与技能、角色与平台权限、系统设置。
- 新增 `internal/app/spa_test.go` 校验构建产物与入口路由;CI 增加 `frontend-build.yml`,
`self-update.yml` 的前端回归改为构建校验,移除依赖旧模板的 `task-ui.yml` 与浏览器夹具测试。
## 2026-11-15 · 深度测评工作台与完整链路
- 探索图增加主链路/执行记录两种视图,跨页引用和原始上下游分页导航;归档按真实分支分组,重新引用后重新计冷却轮次,漏洞与人工线索保持可见,旧归档链接继续可读。

View File

@ -2,53 +2,38 @@
[中文](../zh-CN/frontend-i18n.md)
CyberStrikeAI frontend i18n is static and lightweight. Text is organized in JSON files and applied through `data-i18n` attributes plus JavaScript helper functions.
The web UI is a React + Semi Design single-page app. Translations come from
`web/frontend/src/lib/i18n.jsx`, backed by the same JSON files the backend ships.
## Files
```text
web/static/i18n/zh-CN.json
web/static/i18n/en-US.json
web/static/js/i18n.js
web/static/i18n/ru-RU.json
web/static/i18n/ar-SA.json
web/frontend/src/lib/i18n.jsx
```
## Key Principles
## Runtime behavior
- Keep keys stable and semantic.
- Update Chinese and English together.
- Do not hardcode new visible text in JS when it should be localized.
- Preserve default HTML text as fallback before JS initialization.
- Preference is stored in `localStorage['csai_lang']`; otherwise it follows `navigator.language`, defaulting to `zh-CN`.
- The provider loads the active language plus `zh-CN` and `en-US` fallbacks; lookups fall back `active → zh-CN → en-US → caller default`.
- Switching language updates `<html lang>`, sets `dir="rtl"` for Arabic, and swaps Semi's `ConfigProvider` locale.
- No page reload is required; `useT()` re-renders consumers.
## HTML Usage
## Usage
```html
<button data-i18n="common.save">保存</button>
```jsx
const t = useT();
t('vulnerability.title');
t('common.minutesAgo', { n: 5 }); // {{n}} interpolation
t('chat.unknownKey', null, '中文兜底'); // explicit Chinese fallback
```
For attributes, follow the existing `i18n.js` conventions.
Rules:
## JavaScript Usage
Use the global translation helper where available:
```javascript
const label = t('common.save');
```
When adding dynamic UI, make sure language switching refreshes the text or re-renders the component.
## Migration Workflow
1. Add or update UI text.
2. Add keys to `zh-CN.json`.
3. Add matching keys to `en-US.json`.
4. Replace hardcoded text with `data-i18n` or `t()`.
5. Test both languages and browser console.
## Common Pitfalls
- Missing keys only in one language.
- Dynamic text built from hardcoded fragments.
- Button labels too long in English.
- HTML fallback text diverges from JSON text.
- Adding new page text without updating language switch behavior.
1. Every visible string goes through `t(...)` with a Chinese fallback as the third argument.
2. Add new keys to `zh-CN.json` and `en-US.json` together; `ru-RU`/`ar-SA` may lag and rely on the fallback chain.
3. Format dates with `formatDateTime`/`relativeTime` from `src/lib/format.js`.
4. Keep keys two levels deep (`<domain>.<key>`) and stable across releases.

View File

@ -117,4 +117,4 @@ Plugins should not bypass platform controls:
- Capture: `devtools.js`, `background/service-worker.js`
- OpenAPI: `internal/handler/openapi.go`
- External MCP: `internal/handler/external_mcp.go`
- Web auth reference: `web/static/js/auth.js`
- Web auth reference: `web/frontend/src/lib/auth.jsx`

View File

@ -40,7 +40,7 @@ Expand testing when changing:
- `internal/multiagent/`: streaming, tool calls, summarization, retry, HITL;
- `internal/security/`: auth, shell, timeout, no-output;
- `internal/database/`: old data compatibility;
- `web/static/js/chat.js`: chat, process details, attack chain, groups.
- `web/frontend/src/pages/chat/`: chat, process details, attack chain, groups.
## Test Data

View File

@ -580,6 +580,6 @@ On save, the system checks:
| Graph validation | `internal/workflow/validation.go` |
| Expressions / JSONPath / joins | `internal/workflow/expression.go`, `jsonpath.go`, `join.go` |
| Dry-run / replay data | `internal/workflow/dry_run.go`, `internal/handler/workflow_run.go` |
| Canvas UI | `web/static/js/workflows.js` |
| Canvas UI | `web/frontend/src/pages/workflows/` |
| Workflow API | `internal/handler/workflow.go` |
| Role binding | `internal/config/config.go` (`workflow_id` field) |

View File

@ -1,68 +1,34 @@
# 界面样式约定
# 前端设计系统
主应用的公共样式位于 `web/static/css/design-system.css`,在模块与移动端 CSS 后加载。
颜色沿用现有主题变量;抽屉外框统一为直角,卡片圆角 16px,控件圆角 10px,桌面正文内边距 24px,移动端 16px。
状态色、选中态、图表、终端和工作流画布保留各自的业务语义。
主应用前端已统一迁移到 [Semi Design](https://semi.design/zh-CN/)(React 19 + Vite),
不再维护手写 HTML/CSS/JS 的组件体系。
## 容器选择
## 结构
- 详情、日志、长表单:右侧抽屉,默认 720px;代码、长文本等宽编辑面板 960px;标题栏可展开至 1440px。
- 手机(小于 768px):抽屉全屏,适配安全区,正文单独滚动,底部操作保持可见。
- 确认、重命名、简短绑定:居中短弹窗,手机上同样保持紧凑。
- 数据比较和批量操作继续使用表格;终端、工作流、会话工作区不强制改成卡片列表。
- 页面:`web/frontend/src/pages/<页面 id>/index.jsx`,路由 `#/<页面 id>`。
- 共享组件:`web/frontend/src/components/ui.jsx`(PageHeader、SectionCard、DataTable、StatGrid、ErrorBanner、MarkdownView、JsonViewer、Drawer 等)。
- 外壳样式:`web/frontend/src/styles/app.css`,只放布局与共享排版;颜色一律用 Semi 变量。
- 构建产物:`web/static/app/`,由 Go 直接提供。
`web/static/js/modal.js` 的 `DRAWER_IDS` 和 `WIDE_IDS` 管理既有模块迁移清单。
新模块应通过 `openAppModal` / `closeAppModal` 开关容器,关闭时保留原有清理和未保存提示逻辑。
共用生命周期负责嵌套层级、背景滚动锁定、焦点返回、Tab 焦点约束和 Escape 触发原关闭按钮。
异步更新的标题栏会自动补齐展开按钮。短 C2 休眠设置仍为弹窗。
## 颜色与主题
不要再为单个抽屉添加独立的定位、遮罩、圆角或主题色覆盖。
现阶段公共布局中少量 `!important` 用于覆盖历史内联宽高和移动端旧规则;后续修改这些模块时可逐步去除对应历史声明。
品牌主色 `#3266e3`(暗色 `#81a7ff`),通过覆盖 `--semi-color-primary` 等变量接入 Semi 主题,
暗色由 `body[theme-mode="dark"]` 驱动,偏好保存在 `localStorage['cyberstrike-theme']`(system/light/dark)。
## 验证
## 组件约定
前端回归:
- 列表页用 `DataTable` + `useResource`,统一 loading / 空态 / 错误态(`ErrorBanner`)。
- 指标卡用 `StatGrid`/`StatCard`;详情抽屉用 `Drawer`(封装 Semi `SideSheet`)。
- 危险操作用 `confirmAction`;反馈用 `toastSuccess`/`toastError`。
- Markdown 统一走 `MarkdownView`(marked + DOMPurify),不要自行插入 HTML。
## 校验
```sh
node --test web/static/js/*.test.cjs
npm ci --prefix web/frontend
npm run --prefix web/frontend build
go test ./internal/app -run TestSPA -count=1
```
浏览器验证需要外部安装的 Playwright 和 Chromium,例如:
```sh
npm install --prefix /tmp/csai-ui-tools playwright
/tmp/csai-ui-tools/node_modules/.bin/playwright install chromium
NODE_PATH=/tmp/csai-ui-tools/node_modules node scripts/check-ui-design-system.cjs
```
脚本使用真实模板、样式和选定模块的真实渲染函数,配以合成数据;不启动后端或访问测试目标。
检查 1440、1024、390、360px 四档屏宽和深浅主题,验证抽屉边界、内部横向溢出、底栏、嵌套层级、展开、键盘关闭、焦点返回,以及主页面横向溢出。
截图与结果默认写入系统临时目录,也可通过 `CSAI_UI_ARTIFACTS` 指定目录。
这覆盖界面布局和公共交互,不等同于真实后端数据、保存操作、所有下拉菜单状态或物理手机软键盘的完整验收。
### 真实数据形态回归(Kali 界面验收后补充)
`check-ui-design-system.cjs` 现在调用 `ui-realistic-scenarios.cjs`,并加载真实 i18next/翻译实现。
回归数据依据实际页面的数量、文本长度和按钮状态匿名构造,不复制目标地址、凭据或业务证据。
- 365 条队列任务,分别渲染暂停、运行、完成状态;验证真实操作按钮不会挤压标题或越界。
- 626 个工具、614 个已启用工具及长描述;使用真实角色编辑入口检查统计换行和正文滚动。
- 角色与多文件 Skill 的新增/编辑切换,以及打开编辑后跨越桌面/手机断点;验证翻译刷新不改变编辑标题。
- 深度测评的原生 dialog 创建和详情入口:公共样式、宽度展开、Escape 关闭、展开状态重置和稳定的可访问名称。
- 50 条长漏洞记录和三页分页:验证手机整页滚动,标题与分页不会固定占用记录区。
所有场景都在四档屏宽与两种主题下运行;夹具请求拒绝非 GET 操作。
需要定位单个断点时可设置 `CSAI_UI_WIDTHS=390`;提交前省略该变量运行完整矩阵。
### 队列动态文案与按钮对比度
队列标题将可翻译的前缀与原样保留的队列名称分开渲染;执行按钮的 `data-i18n` 随暂停、待执行及 Cron 状态更新。
主要操作的小号按钮明确使用强调色背景和配套文字色,避免旧尺寸样式把背景改灰后仍保留深色文字。
回归增加了:暂停/待执行/运行/完成/取消、Cron 开关、中英文切换、桌面与手机断点切换、空标题和含特殊字符的标题。
针对可见的开始/继续/重跑按钮,检查正常、悬停和键盘焦点状态下的计算颜色,要求文字与不透明背景的对比度不低于 4.5:1;每档尺寸和主题的计算结果保存为 `queue-contrast-*.json`。
浏览器回归使用真实 i18next 翻译函数,不再用固定中文替代函数覆盖它。
Skill 的“查看”入口动态创建 `skill-view-modal`,与编辑入口共用宽抽屉。回归同时验证摘要展示、按需加载全文、展开、Escape 清理以及“查看 → 编辑”切换,防止只验证编辑表单而遗漏只读详情入口。
信息收集的字段全文、AI 查询解析结果,以及 WebShell 数据库连接配置也使用公共抽屉。信息收集动态节点采用标准 header/body/footer 类和公共关闭逻辑;回归使用长文本、警告说明与离线数据库配置夹具,检查滚动、重复打开、复制、仅应用查询语法和关闭清理,不执行外部查询或数据库连接。
`internal/app/spa_test.go` 会检查 `web/static/app/index.html` 引用的哈希资源是否存在,
防止构建产物缺失或未提交。页面开发契约见 `web/frontend/CONTRACT.md`。

View File

@ -24,10 +24,10 @@ flowchart LR
入口在 `cmd/server/`,应用组装在 `internal/app/`。Web 使用 Gin:
- `web/templates/index.html`:主页面。
- `web/templates/api-docs.html`:API 文档页面。
- `web/static/js/`:各业务模块前端逻辑。
- `web/static/css/`:样式。
- `web/frontend/`:前端源码(React 19 + Semi Design,Vite 构建),页面位于 `src/pages/<页面 id>/`。
- `web/static/app/`:前端构建产物,`GET /` 直接返回其中的 `index.html`,`/api-docs` 跳转到 `/#/api-docs`。
- `web/static/i18n/`:多语言词条,前端与后端共用。
- `web/static/`:Logo、favicon 与多语言等公共静态资源。
路由注册集中在 `internal/app/app.go`。

View File

@ -41,7 +41,7 @@ go run ./cmd/server --config config.yaml
2. 在 `internal/database/` 增加必要的数据访问。
3. 在 `internal/app/app.go` 构造并注册路由。
4. 如需对外文档,更新 `internal/handler/openapi.go`。
5. 如需前端调用,更新 `web/static/js/`。
5. 如需前端调用,更新 `web/frontend/src/pages/`。
## 一键更新:让安装目录更新它自己的源码
@ -203,7 +203,7 @@ Skill 放在 `skills/<name>/SKILL.md`。用于提供专题能力、流程说明
## 前端开发
前端代码按功能拆分在 `web/static/js/`。新增页面或模块时:
前端代码按功能拆分在 `web/frontend/src/pages/`。新增页面或模块时:
- 复用现有 `apiFetch`、modal、通知、i18n 工具。
- 同步更新 `web/static/i18n/zh-CN.json` 和 `en-US.json`。

View File

@ -1,335 +1,33 @@
## CyberStrikeAI 前端国际化方案
# 前端国际化
本文档说明 CyberStrikeAI Web 前端(`web/templates/index.html` + `web/static/js/*.js`)的国际化设计与开发规范,确保在不引入打包工具和不改动后端路由的前提下,实现可扩展、低返工的多语言支持。
前端已迁移为 React + Semi Design 单页应用,国际化由 `web/frontend/src/lib/i18n.jsx` 提供,
词条继续复用后端同目录 `web/static/i18n/*.json`(zh-CN / en-US / ru-RU / ar-SA)。
当前目标:
## 运行时行为
- **支持中英文切换(zh-CN / en-US)**
- 后续可方便扩展更多语言(如 ja-JP、ko-KR 等)
- 语言偏好保存在 `localStorage['csai_lang']`,未设置时按 `navigator.language` 推断,默认 `zh-CN`。
- 启动时并行加载当前语言、`zh-CN` 兜底与 `en-US`(第三兜底)三份词条;缺失的键按「当前语言 → zh-CN → en-US → 调用方兜底中文」回退。
- 切换语言会更新 `<html lang>`,阿拉伯语自动把 `<html dir>` 设为 `rtl`,并通过 Semi `ConfigProvider` 切换组件语言包。
- 语言切换不会刷新页面;`useT()` 返回的 `t` 会随 Provider 重新渲染。
---
## 在页面里使用
## 一、总体设计原则
- **前端主导的客户端国际化**:所有 UI 文案在浏览器端根据当前语言动态渲染,后端 Go 仅负责结构和数据,不参与语言分发。
- **单一 HTML 模板**:继续使用一份 `index.html` 模板,不为不同语言复制模板文件。
- **文案与逻辑分离**:所有可见文本通过「键值表」管理(多语言 JSON),HTML / JS 只写 key,不直接写中文/英文常量。
- **渐进式改造**:先覆盖 header / 登录 / 侧边栏 / 系统设置等关键区域,其他页面按模块逐步迁移,避免一次性大改动。
- **可回退默认语言**:即使目标语言未完全翻译,也能回退到默认中文,不出现原始 key。
---
## 二、技术选型与目录结构
### 2.1 技术选型
- **i18n 引擎**:使用 [i18next](https://www.i18next.com/) 的浏览器 UMD 版本(通过 CDN 引入),无需打包器。
- **资源格式**:每种语言一份 JSON 文件,采用「域 + 语义」的层级 key 方案,例如:
- `common.ok`
- `nav.dashboard`
- `header.apiDocs`
- `settings.robot.wecom.token`
### 2.2 目录结构
- `web/templates/index.html`
- 页面骨架 + 所有静态文案位置,将逐步改为 `data-i18n` 标记。
- `web/static/js/i18n.js`
- 前端 i18n 初始化与 DOM 应用逻辑(本方案新增)。
- `web/static/i18n/`(新增目录)
- `zh-CN.json`:中文文案(默认语言)
- `en-US.json`:英文文案
- 未来可新增:`ja-JP.json`、`ko-KR.json` 等。
---
## 三、文案组织规范
### 3.1 Key 命名约定
- 采用「**模块.语义**」形式,最多 2–3 级,确保可读性:
- 导航:`nav.dashboard`、`nav.chat`、`nav.settings`
- 头部:`header.title`、`header.apiDocs`、`header.logout`
- 登录:`login.title`、`login.subtitle`、`login.passwordLabel`、`login.submit`
- 仪表盘:`dashboard.title`、`dashboard.refresh`、`dashboard.runningTasks`
- 系统设置:`settings.title`、`settings.nav.basic`、`settings.nav.robot`、`settings.apply`
- 机器人配置:`settings.robot.wecom.enabled`、`settings.robot.wecom.token` 等。
- 尽量按「界面区域」而不是「文件名」划分域,便于非开发人员理解。
### 3.2 JSON 示例
`web/static/i18n/zh-CN.json` 示例:
```json
{
"common": {
"ok": "确定",
"cancel": "取消"
},
"nav": {
"dashboard": "仪表盘",
"chat": "对话",
"infoCollect": "信息收集",
"tasks": "任务管理",
"vulnerabilities": "漏洞管理",
"settings": "系统设置"
},
"header": {
"title": "CyberStrikeAI",
"apiDocs": "API 文档",
"logout": "退出登录",
"language": "界面语言"
},
"login": {
"title": "登录 CyberStrikeAI",
"subtitle": "请输入配置中的访问密码",
"passwordLabel": "密码",
"passwordPlaceholder": "输入登录密码",
"submit": "登录"
}
}
```jsx
const t = useT();
t('vulnerability.title'); // 词条里存在键
t('common.minutesAgo', { n: 5 }); // 支持 {{n}} 插值
t('chat.unknownKey', null, '中文兜底'); // 键缺失时用第三参数
```
英文文件 `en-US.json` 保持相同 key,不同 value:
要求:
```json
{
"common": {
"ok": "OK",
"cancel": "Cancel"
},
"nav": {
"dashboard": "Dashboard",
"chat": "Chat",
"infoCollect": "Recon",
"tasks": "Tasks",
"vulnerabilities": "Vulnerabilities",
"settings": "Settings"
},
"header": {
"title": "CyberStrikeAI",
"apiDocs": "API Docs",
"logout": "Sign out",
"language": "Interface language"
},
"login": {
"title": "Sign in to CyberStrikeAI",
"subtitle": "Enter the access password from config",
"passwordLabel": "Password",
"passwordPlaceholder": "Enter password",
"submit": "Sign in"
}
}
```
1. 可见文案统一走 `t(...)`,第三个参数写中文兜底,避免出现原始 key。
2. 新增词条时同时更新 `web/static/i18n/zh-CN.json` 与 `en-US.json`;`ru-RU`/`ar-SA` 可暂时缺失,靠回退链。
3. 表单校验、Toast、空态文案同样走 `t(...)`。
4. 时间格式化使用 `src/lib/format.js` 的 `formatDateTime/relativeTime`,不要手拼日期。
> 约定:**新增界面时,必须先定义 i18n key,再在 HTML/JS 中使用 key**,禁止直接写死中文/英文。
---
## 四、HTML 标记规范(data-i18n)
### 4.1 基本规则
- 使用 `data-i18n` 将元素文本与某个 key 绑定:
```html
<span data-i18n="nav.dashboard">仪表盘</span>
```
- 默认行为:脚本会替换元素的 `textContent`。
- 同时翻译属性时,额外使用 `data-i18n-attr`,逗号分隔多个属性名:
```html
<button
class="openapi-doc-btn"
onclick="window.open('/api-docs', '_blank')"
data-i18n="header.apiDocs"
data-i18n-attr="title"
title="API 文档">
<span data-i18n="header.apiDocs">API 文档</span>
</button>
```
### 4.2 默认文本的作用
- HTML 内的中文默认值作为「**无 JS / 初始化前**」的占位内容:
- 页面在 JS 尚未加载完成时不会出现空白或 key。
- JS 初始化后会用当前语言覆盖这些文本。
---
## 五、JavaScript 中的文案规范
### 5.1 全局翻译函数 `t()`
由 `i18n.js` 暴露以下全局函数:
- `window.t(key: string): string`
- 返回当前语言下的翻译文本,若缺失则回退到默认语言,再不行则返回 key 本身。
- `window.changeLanguage(lang: string): Promise<void>`
- 切换语言并刷新页面文案(不会刷新整页)。
示例(以 `web/static/js/settings.js` 为例):
```js
// 之前
alert('加载配置失败: ' + error.message);
// 之后
alert(t('settings.loadConfigFailed') + ': ' + error.message);
```
> 规范:**JS 内所有面向用户的提示、按钮文字、对话框标题都应通过 `t()` 获取**,不直接写死中文/英文。
### 5.2 渐进迁移建议
- 优先改造:
- 频繁弹出的错误提示 / 成功提示;
- 登录相关、系统设置相关文案。
- 低优先级:
- 仅面向运维人员的调试提示,可以暂时保留英文/中文常量。
---
## 六、i18n 初始化与语言切换实现
### 6.1 语言选择策略
- 默认语言:`zh-CN`。
- 优先级(从高到低):
1. `localStorage` 中的用户选择(key:`csai_lang`)。
2. 浏览器 `navigator.language`(`zh` 开头 → `zh-CN`,否则 `en-US`)。
3. 默认 `zh-CN`。
### 6.2 初始化流程(`i18n.js`)
1. 读取初始语言。
2. 初始化 i18next:
- `lng` 为当前语言;
- `fallbackLng` 为 `zh-CN`;
- 资源先留空,采用按需加载。
3. 通过 `fetch` 拉取 `/static/i18n/{lng}.json` 并 `i18next.addResources`。
4. 更新:
- `<html lang="...">` 属性;
- 所有带 `data-i18n` / `data-i18n-attr` 的元素。
5. 暴露 `window.t` 与 `window.changeLanguage`。
### 6.3 DOM 应用逻辑
伪代码:
```js
function applyTranslations(root = document) {
const elements = root.querySelectorAll('[data-i18n]');
elements.forEach(el => {
const key = el.getAttribute('data-i18n');
if (!key) return;
const text = i18next.t(key);
if (text) {
el.textContent = text;
}
const attrList = el.getAttribute('data-i18n-attr');
if (attrList) {
attrList.split(',').map(s => s.trim()).forEach(attr => {
if (!attr) return;
const val = i18next.t(key);
if (val) el.setAttribute(attr, val);
});
}
});
}
```
> 对于由 JS 动态插入的元素,需要在插入后再次调用 `applyTranslations(新容器)`。
---
## 七、语言切换 UI 规范
### 7.1 位置与形态
- 位置:`index.html` header 右侧 `API 文档` 按钮附近(靠近用户头像)。
- 交互形式:
- 一个紧凑的语言切换组件,例如:
- `🌐` 图标 + 当前语言文本(`中文` / `English`)的下拉按钮;
- 下拉内容列出所有可用语言。
### 7.2 示例结构
```html
<div class="lang-switcher">
<button class="btn-secondary lang-switcher-btn" onclick="toggleLangDropdown()" data-i18n="header.language">
<span class="lang-switcher-icon">🌐</span>
<span id="current-lang-label">中文</span>
</button>
<div id="lang-dropdown" class="lang-dropdown" style="display: none;">
<div class="lang-option" data-lang="zh-CN" onclick="onLanguageSelect('zh-CN')">中文</div>
<div class="lang-option" data-lang="en-US" onclick="onLanguageSelect('en-US')">English</div>
</div>
</div>
```
对应 JS(在 `i18n.js` 中):
```js
function onLanguageSelect(lang) {
changeLanguage(lang).then(updateLangLabel).catch(console.error);
closeLangDropdown();
}
function updateLangLabel() {
const labelEl = document.getElementById('current-lang-label');
if (!labelEl) return;
const lang = i18next.language || 'zh-CN';
labelEl.textContent = lang.startsWith('zh') ? '中文' : 'English';
}
```
> 规范:**语言切换只更新文案,不刷新整页,也不修改 URL hash**。
---
## 八、开发流程建议
### 8.1 新增 / 修改界面的流程
1. 设计界面时,先列出所有文案。
2. 在对应语言 JSON 中补充/修改 key 与翻译。
3. 在 HTML 中使用 `data-i18n`,在 JS 中使用 `t('...')`。
4. 在浏览器中切换中英文,确认两种语言显示都正确。
### 8.2 渐进式改造顺序(推荐)
1. **阶段 1(已规划)**
- 引入 i18next 与 `i18n.js`。
- 新建 `zh-CN.json` / `en-US.json`(先覆盖 header / 登录 / 左侧导航)。
- 实现 header 区域语言切换组件。
2. **阶段 2**(已完成)
- 系统设置页面(包括机器人配置页面)全部文案 i18n 化。
- `settings.js` 中的提示与错误信息改用 `t()`。
3. **阶段 3**(进行中)
- 仪表盘、任务管理、漏洞管理、MCP、Skills、Roles 等页面按模块逐步迁移。
4. **阶段 4**
- 清理 JS / HTML 中残留的硬编码中文,统一通过 i18n。
---
## 九、后续扩展新语言
当需要新增语言时:
1. 在 `web/static/i18n/` 中新增 `{lang}.json`,复制现有英文/中文文件结构,补充对应翻译。
2. 在语言切换下拉中添加对应选项,例如:
- `data-lang="ja-JP"` / 文本 `日本語`
3. 无需修改 `i18n.js` 或现有 HTML/JS 逻辑,即可支持新语言。
---
## 十、注意事项与坑点
- **不要复制多份 HTML 模板** 来做多语言,那样维护成本极高,本方案统一由前端 i18n 控制。
- **避免 key 直接用中文/英文句子**,统一采用「模块.语义」短 key,便于 diff 与搜索。
- 避免在 CSS 中写死文本(如 `content: "xxx"`),如确有需要,应通过 JS 设置并走 i18n。
- 对于后端返回的可本地化错误文本(未来可能支持),优先由后端根据 `Accept-Language` 返回对应语言,前端只负责展示。
## 词条组织
`web/static/i18n/zh-CN.json` 按业务域分组:`common`、`nav`、`dashboard`、`vulnerability`、`chat`、
`settings`、`knowledge`、`skills`、`roles`、`auth`、`apiDocs` 等。新增分组时保持两级键名
(`<domain>.<key>`),避免深层嵌套影响可读性。

View File

@ -66,7 +66,7 @@ npm test
cd ../..
go test -race ./internal/agentruntime ./internal/multiagent ./internal/workflow ./internal/knowledge
go test ./...
node --test web/static/js/*.test.cjs
npm run --prefix web/frontend build
```
SDK 集成测试使用本地模拟模型和无副作用的工具夹具,覆盖 OpenAI/Claude 动作建议、审批编辑、子代理工具边界、流式输出、取消、进程中断及备用模型切换。

View File

@ -213,4 +213,4 @@ schema 越具体,HITL 越容易判断风险,Agent 也越不容易发散。
- 捕获:`devtools.js`、`background/service-worker.js`
- OpenAPI:`internal/handler/openapi.go`
- 外部 MCP:`internal/handler/external_mcp.go`
- Web 端认证参考:`web/static/js/auth.js`
- Web 端认证参考:`web/frontend/src/lib/auth.jsx`

View File

@ -108,6 +108,15 @@ go build -o cyberstrike-ai ./cmd/server
## 前端冒烟
前端是 React 19 + Semi Design 单页应用(`web/frontend`)。构建与产物校验:
```sh
npm ci --prefix web/frontend
npm run --prefix web/frontend build
git status --porcelain web/static/app # 应为空,产物需随源码提交
go test ./internal/app -run TestSPA -count=1
```
修改前端后至少验证:
- 登录和退出。
@ -115,8 +124,9 @@ go build -o cyberstrike-ai ./cmd/server
- 新建对话和流式回复。
- 设置页面保存。
- 相关业务页面增删改查。
- 中英文切换。
- 浏览器控制台无明显错误。
- 中英文切换与暗色主题。
- 逐个访问 `#/<页面 id>`(清单见 `web/frontend/src/lib/nav.js`),浏览器控制台无 error、无页面异常。
- 深链接可直接打开:`#/chat?conversation=…`、`#/vulnerabilities?id=…`、`#/projects?id=…`、`#/settings?section=…`。
## 高风险模块测试
@ -149,7 +159,7 @@ C2、WebShell、终端、批量任务只能在授权测试环境验证。测试
- `internal/multiagent/`:测流式、工具调用、摘要、重试、HITL。
- `internal/security/`:测认证、Shell、超时、无输出。
- `internal/database/`:测旧数据兼容。
- `web/static/js/chat.js`:测对话、过程详情、攻击链、分组。
- `web/frontend/src/pages/chat/`:测对话、过程详情、攻击链、分组。
## 测试数据管理

View File

@ -580,6 +580,6 @@ token 与成本是否存在取决于底层模型/Agent 事件是否上报 usage
| 图校验 | `internal/workflow/validation.go` |
| 表达式 / JSONPath / 汇聚 | `internal/workflow/expression.go`、`jsonpath.go`、`join.go` |
| dry-run / replay 数据 | `internal/workflow/dry_run.go`、`internal/handler/workflow_run.go` |
| 画布前端 | `web/static/js/workflows.js` |
| 画布前端 | `web/frontend/src/pages/workflows/` |
| 流程 API | `internal/handler/workflow.go` |
| 角色绑定 | `internal/config/config.go`(`workflow_id` 字段) |

View File

@ -1542,22 +1542,18 @@ func setupRoutes(
// 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)
})
// 静态文件
// 静态文件(前端为 React + Semi Design 单页应用,构建产物在 web/static/app)
router.Static("/static", "./web/static")
router.LoadHTMLGlob("web/templates/*")
// API 文档已并入单页应用路由(#/api-docs),保留旧地址跳转
router.GET("/api-docs", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/#/api-docs")
})
// 前端页面
router.GET("/", func(c *gin.Context) {
version := app.config.Version
if version == "" {
version = "v1.0.0"
}
c.HTML(http.StatusOK, "index.html", gin.H{"Version": version})
c.Header("Cache-Control", "no-cache")
c.File("./web/static/app/index.html")
})
}

57
internal/app/spa_test.go Normal file
View File

@ -0,0 +1,57 @@
package app
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
// TestSPABuildArtifacts 校验前端构建产物已随仓库提交:
// 首页必须引用 /static/app/assets/ 下的哈希资源,且这些文件真实存在。
// 前端源码在 web/frontend,构建命令:npm run --prefix web/frontend build。
func TestSPABuildArtifacts(t *testing.T) {
root := filepath.Join("..", "..", "web", "static", "app")
indexPath := filepath.Join(root, "index.html")
index, err := os.ReadFile(indexPath)
if err != nil {
t.Fatalf("前端构建产物缺失 %s: %v", indexPath, err)
}
html := string(index)
if !strings.Contains(html, `<div id="root">`) {
t.Fatalf("index.html 缺少 React 挂载点: %s", indexPath)
}
assetPattern := regexp.MustCompile(`(?:src|href)="(/static/app/[^"]+)"`)
matches := assetPattern.FindAllStringSubmatch(html, -1)
if len(matches) == 0 {
t.Fatalf("index.html 未引用任何构建资源: %s", indexPath)
}
staticRoot := filepath.Join("..", "..", "web", "static")
for _, match := range matches {
relative := strings.TrimPrefix(match[1], "/static/")
if strings.HasPrefix(relative, "favicon") || strings.HasPrefix(relative, "site.webmanifest") {
continue
}
assetPath := filepath.Join(staticRoot, filepath.FromSlash(relative))
if _, err := os.Stat(assetPath); err != nil {
t.Fatalf("index.html 引用的资源不存在: %s", assetPath)
}
}
}
// TestSPAEntryDoesNotDependOnLegacyTemplates 防止页面回退到 Go 模板渲染。
func TestSPAEntryDoesNotDependOnLegacyTemplates(t *testing.T) {
source, err := os.ReadFile("app.go")
if err != nil {
t.Fatal(err)
}
code := string(source)
if strings.Contains(code, "LoadHTMLGlob") {
t.Fatal("app.go 仍在加载 Go 模板,前端应统一由 web/static/app 提供")
}
if !strings.Contains(code, `c.File("./web/static/app/index.html")`) {
t.Fatal("app.go 未通过 c.File 提供前端入口")
}
}

View File

@ -1,19 +0,0 @@
package app
import (
"bytes"
"html/template"
"path/filepath"
"testing"
)
func TestFrontendTemplatesRender(t *testing.T) {
templates, err := template.ParseGlob(filepath.Join("..", "..", "web", "templates", "*"))
if err != nil {
t.Fatalf("server template initialization fails: %v", err)
}
var output bytes.Buffer
if err = templates.ExecuteTemplate(&output, "index.html", map[string]interface{}{"Version": "test"}); err != nil {
t.Fatal(err)
}
}

View File

@ -1,153 +0,0 @@
const {test}=require('node:test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const path=require('node:path');
const http=require('node:http');
const {chromium}=require('playwright');
const root=path.join(__dirname,'..');
const read=file=>fs.readFileSync(path.join(root,file),'utf8');
const template=read('web/templates/index.html');
function div(id){
const start=template.indexOf(`<div id="${id}"`);assert.ok(start>=0,id);
const tags=/<\/?div\b[^>]*>/g;tags.lastIndex=start;let depth=0,m;
while((m=tags.exec(template))){depth+=m[0].startsWith('</')?-1:1;if(!depth)return template.slice(start,tags.lastIndex);}
throw new Error('unclosed '+id);
}
async function fixture(t){
const now=new Date().toISOString();
const sourceStep={id:'early-step',title:'Origin step outside current page',status:'completed',instruction:'Read local fixture',summary:'source observation',evidence:['receipt-1'],depends_on:[],attempts:1,conversation_id:'source-conversation'};
const task={id:'same-id',name:'域名深度测评',status:'completed',revision:1,objective:'Inspect fixture',scope:'local',criteria:'real evidence',steps:[],metrics:{},rounds:3,tokens_used:100,updated_at:now};
const finding={id:'finding-1',title:'权限校验问题',description:'Fixture finding',severity:'high',status:'open',type:'authorization',target:'https://example.test/account',conversation_id:'source-conversation',project_id:'',assessment_id:'same-id',assessment_name:task.name,assessment_step_id:sourceStep.id,assessment_step_title:sourceStep.title,assessment_can_open:true,reproduction_steps:'1. Read the supplied fixture\n2. Verify the recorded result',evidence:'original-proof <img src=x onerror="window.injected=1">',impact:'fixture impact',recommendation:'fixture fix',created_at:now,updated_at:now,targets:[{host:'example.test',raw:'https://example.test/account',domain:'example.test'}]};
const batch={id:'batch-finding',title:'批量任务原有漏洞',severity:'medium',status:'open',description:'batch fixture',target:'https://batch.example.test',task_id:'same-id',task_queue_id:'batch-queue',task_queue_title:'原批量队列',created_at:now,updated_at:now};
const state={task,sourceStep,finding,batch,requests:[],errors:[],canOpen:true};
const locale=JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<','\\u003c');
const scripts=['router','auth','modal','vulnerability','assessment-finding-links','vulnerability-workspace','assessment-workbench','assessment-node-panel','assessment-exploration-views','deep-assessment-graph','deep-assessments'].map(x=>`<script src="/static/js/${x}.js"></script>`).join('');
const styles=['style','mobile','vulnerability-workspace','vulnerability-list','deep-assessments','design-system'].map(x=>`<link rel="stylesheet" href="/static/css/${x}.css">`).join('');
const html=`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${styles}</head><body><div class="container"><main class="main-layout"><section class="content-area">${div('page-deep-assessments')}${div('page-vulnerabilities')}<div class="page" id="page-chat"></div></section></main></div>${div('vulnerability-inspector')}<script>window.t=(key,opts={})=>{const v=key.split('.').reduce((o,k)=>o&&o[k],${locale});return String(v||key).replace(/{{(\\w+)}}/g,(_,k)=>String(opts[k]??''))};window.loadConversation=async id=>{window.visitedConversation=id};window.initializeChatUI=()=>{};window.refreshAppData=async()=>{};</script><script src="/static/vendor/cytoscape.min.js"></script>${scripts}<script>document.removeEventListener('DOMContentLoaded',initializeApp);saveAuth('fixture-token',new Date(Date.now()+3600000),{user:{id:'fixture',username:'fixture'},permissions:['assessments:read','assessments:write','vulnerability:read','vulnerability:write','chat:read','chat:write','project:read'],scope:'own'});</script></body></html>`;
const server=http.createServer(async(req,res)=>{
const url=new URL(req.url,'http://fixture');
const send=(code,data)=>{res.statusCode=code;res.setHeader('Content-Type','application/json; charset=utf-8');res.end(JSON.stringify(data));};
try{
if(url.pathname.startsWith('/static/')){res.setHeader('Content-Type',url.pathname.endsWith('.css')?'text/css':'text/javascript');return res.end(read('web'+url.pathname));}
if(url.pathname==='/'){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end(html);}
if(url.pathname==='/favicon.ico'){res.statusCode=204;return res.end();}
state.requests.push({path:url.pathname,query:Object.fromEntries(url.searchParams),method:req.method});
if(req.headers.authorization!=='Bearer fixture-token')return send(401,{error:'authentication missing'});
if(url.pathname==='/api/projects')return send(200,{projects:[]});
if(url.pathname==='/api/deep-assessments')return send(200,{tasks:[task],has_more:false});
if(url.pathname==='/api/deep-assessments/same-id')return send(200,{task,step_total:101,step_next_offset:50,step_has_more:true});
if(url.pathname==='/api/deep-assessments/same-id/graph')return send(200,{nodes:[{id:'goal',kind:'goal',state:'completed',title:task.name,body:'',source:{}}],edges:[],total:0,folded:0,has_more:false});
if(url.pathname==='/api/deep-assessments/same-id/steps/review-step')return send(200,{step:{...sourceStep,id:'review-step',title:'Independent review step'}});
if(url.pathname==='/api/deep-assessments/same-id/receipts'&&url.searchParams.get('step_id')==='review-step')return send(200,{receipts:[{id:'review-receipt',execution_id:'review-execution',step_id:'review-step',tool:'fixture_recheck',arguments:'{}',result:'independent-review-evidence',status:'completed'}],next_offset:1,has_more:false});
if(url.pathname==='/api/deep-assessments/same-id/steps/early-step')return send(200,{step:sourceStep});
if(url.pathname==='/api/deep-assessments/same-id/vulnerabilities')return send(200,{vulnerabilities:[finding],total:1,next_offset:1,has_more:false});
if(url.pathname==='/api/deep-assessments/same-id/vulnerabilities/finding-1')return send(200,{vulnerability:finding,step:sourceStep});
if(url.pathname==='/api/deep-assessments/same-id/receipts')return send(200,{receipts:[{id:'receipt-1',execution_id:'execution-1',step_id:'early-step',tool:'fixture_read',arguments:'{}',result:'original-execution-evidence',status:'completed'}],next_offset:1,has_more:false});
if(url.pathname==='/api/deep-assessments/same-id/events')return send(200,{events:[]});
if(url.pathname==='/api/vulnerabilities/filter-options')return send(200,{vulnerability_ids:['finding-1','batch-finding'],task_ids:['same-id'],queue_ids:['batch-queue'],assessment_ids:['same-id'],conversation_ids:[],conversation_tags:[],task_tags:[]});
let items=[finding,batch];if(url.searchParams.get('assessment_id'))items=items.filter(v=>v.assessment_id===url.searchParams.get('assessment_id'));if(url.searchParams.get('id'))items=items.filter(v=>v.id===url.searchParams.get('id'));
if(url.pathname==='/api/vulnerabilities/stats')return send(200,{total:items.length,by_severity:{high:items.filter(v=>v.severity==='high').length,medium:items.filter(v=>v.severity==='medium').length},by_status:{open:items.length}});
if(url.pathname==='/api/vulnerabilities'){
// Full navigation is separate from the selected page of finding records.
const navigation=items.map(v=>v.assessment_id
? {key:'assessment:'+v.assessment_id,label:v.assessment_name,count:1,severities:{[v.severity]:1}}
: {key:'queue:'+v.task_queue_id,label:v.task_queue_title,count:1,severities:{[v.severity]:1},children:[{key:'task:'+v.task_id,label:v.task_id,count:1,severities:{[v.severity]:1}}]});
const selection=url.searchParams.get('selection')||'';
if(selection)items=items.filter(v=>selection==='assessment:'+v.assessment_id||selection==='queue:'+v.task_queue_id||selection==='task:'+v.task_id);
return send(200,{vulnerabilities:items,total:items.length,page:1,page_size:20,total_pages:1,navigation,selection});
}
if(url.pathname==='/api/vulnerabilities/finding-1/context')return send(200,{vulnerability:{...finding,assessment_can_open:state.canOpen},history:[],members:[],assets:[]});
if(url.pathname==='/api/vulnerabilities/finding-1')return send(200,{...finding,assessment_can_open:state.canOpen});
return send(404,{error:'unhandled fixture route '+url.pathname});
}catch(error){send(500,{error:error.message});}
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const executablePath=process.env.CHROME_PATH||(process.platform==='darwin'?'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome':undefined);
const browser=await chromium.launch(executablePath?{executablePath}:{});
t.after(async()=>{await browser.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));});
const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(6000);page.on('pageerror',e=>state.errors.push(e.message));page.on('dialog',d=>d.accept());
await page.goto(`http://127.0.0.1:${server.address().port}/#deep-assessments`);await page.locator('[data-da-action="select"]').waitFor();
return {page,state};
}
test('assessment findings round-trip through vulnerability management to exact evidence',async t=>{
const {page,state}=await fixture(t);
await page.locator('[data-da-action="select"]').click();await page.locator('[data-da-action="tab"][data-tab="findings"]').click();
await page.locator('.da-finding').waitFor();assert.match(await page.locator('.da-finding').innerText(),/权限校验问题/);
await page.locator('.da-finding [data-da-action="open-finding"]').click();
await page.locator('#vulnerability-inspector a[data-assessment-jump]').first().waitFor();
assert.match(await page.locator('.vulnerability-assessment-source').innerText(),/域名深度测评/);
await page.locator('#vulnerability-inspector a[data-assessment-jump]').first().click();
await page.locator('#da-workspace .da-step[data-step="early-step"][open]').waitFor();
assert.match(page.url(),/assessment_id=same-id/);assert.match(page.url(),/step_id=early-step/);
assert.match(await page.locator('.da-source-banner').innerText(),/权限校验问题/);
await page.reload();await page.locator('#da-workspace .da-step[data-step="early-step"][open]').waitFor();
await page.locator('.da-source-banner [data-da-action="open-finding"]').click();
await page.locator('#vulnerability-inspector a[data-assessment-jump]').last().waitFor();await page.locator('#vulnerability-inspector a[data-assessment-jump]').last().click();
await page.waitForFunction(()=>document.querySelector('.da-source-banner')?.textContent.includes('original-proof'));
assert.match(page.url(),/tab=evidence/);assert.equal(await page.locator('.da-source-banner img').count(),0);assert.equal(await page.evaluate(()=>window.injected),undefined);
assert.ok(state.requests.some(r=>r.path.endsWith('/receipts')&&r.query.step_id==='early-step'));
await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
await page.waitForFunction(()=>document.getElementById('da-workspace').getAnimations().every(a=>a.playState==='finished'));
assert.equal(await page.locator('#vulnerability-inspector').isVisible(),false);assert.equal(await page.locator('dialog[open]').count(),0);
const box=await page.locator('#da-workspace').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=391);
assert.ok(state.requests.every(r=>r.method==='GET'));
assert.deepEqual(state.errors,[]);
const dir=process.env.CSAI_SCREENSHOT_DIR;if(dir){fs.mkdirSync(dir,{recursive:true});await page.screenshot({path:path.join(dir,'assessment-finding-evidence.png'),fullPage:true});}
});
test('task grouping separates assessment IDs from batch IDs and disabled source links',async t=>{
const {page,state}=await fixture(t);
await page.evaluate(()=>{location.hash='vulnerabilities?view=task';});
await page.locator('#vulnerabilities-list [data-host-key="assessment:same-id"]').waitFor();
assert.match(await page.locator('[data-host-key="assessment:same-id"]').innerText(),/域名深度测评/);
assert.match(await page.locator('[data-host-key="queue:batch-queue"]').innerText(),/原批量队列/);
await page.locator('[data-host-key="assessment:same-id"]').click();
await page.waitForFunction(()=>document.querySelector('[data-host-key="assessment:same-id"]').getAttribute('aria-pressed')==='true' && document.getElementById('vulnerability-card-finding-1') && !document.getElementById('vulnerability-card-batch-finding'));
assert.equal(await page.locator('#vulnerability-host-table #vulnerability-card-batch-finding').count(),0);
state.canOpen=false;
await page.locator('#vulnerability-host-table #vulnerability-card-finding-1 .vulnerability-record-main').click();
await page.locator('.vulnerability-assessment-source').waitFor();assert.equal(await page.locator('.vulnerability-assessment-source a').count(),0);
assert.deepEqual(state.errors,[]);
});
test('independent review links remain usable after assessment polling refreshes',async t=>{
const {page,state}=await fixture(t);
state.finding.assessment_reviews=[{id:'review-1',step_id:'review-step',verdict:'confirmed',reason:'Independent fixture review',evidence:['review-receipt']}];
await page.locator('[data-da-action="select"]').click();
await page.locator('[data-da-action="tab"][data-tab="findings"]').click();
await page.locator('.da-finding [data-da-action="open-finding"]').click();
await page.getByRole('link',{name:'查看步骤与复现证据',exact:true}).click();
const review=page.locator('#da-workspace .da-review-records details');
await review.locator('summary').click();
await page.evaluate(()=>window.DeepAssessments.refresh());
await page.evaluate(()=>window.DeepAssessments.refresh());
assert.equal(await review.getAttribute('open'),'');
await review.getByRole('link',{name:'查看复核意图与回执',exact:true}).click();
await page.locator('#da-workspace .da-step[data-step="review-receipt"]').waitFor();
assert.match(page.url(),/step_id=review-step/);
assert.match(await page.locator('.da-source-banner').innerText(),/Independent review step/);
await page.locator('#da-workspace .da-step[data-step="review-receipt"] summary').click();
assert.match(await page.locator('#da-body').innerText(),/independent-review-evidence/);
assert.doesNotMatch(await page.locator('#da-body').innerText(),/original-execution-evidence/);
assert.ok(state.requests.every(r=>r.method==='GET'));
assert.deepEqual(state.errors,[]);
});
test('authenticated refresh restores the requested assessment and write controls',async t=>{
const {page,state}=await fixture(t);
await page.evaluate(async()=>{
document.querySelector('[data-da-action="create"]').remove();
history.replaceState(null,'','#deep-assessments?assessment_id=same-id&step_id=review-step&tab=evidence');
window.loadConversations=async()=>{};
window.loadActiveTasks=async()=>{};
await refreshAppData();
});
await page.locator('#da-workspace .da-step[data-step="review-receipt"]').waitFor();
assert.match(await page.locator('.da-source-banner').innerText(),/Independent review step/);
assert.equal(await page.locator('[data-da-action="create"]').count(),1);
assert.ok(state.requests.every(r=>r.method==='GET'));
assert.deepEqual(state.errors,[]);
});

View File

@ -1,71 +0,0 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { fixture, queue } = require('./helpers/batch-task-ui-fixture.cjs');
test('original batch task page loads, filters and paginates existing queues', async t => {
const { page, state, refresh } = await fixture(t);
for (let i = 0; i < 22; i++) state.queues.set('q-' + i, { ...queue('q-' + i), title: 'Fixture ' + i, status: 'paused' });
await refresh();
assert.equal(await page.locator('#batch-queues-list .batch-queue-item').count(), 10);
await page.locator('#batch-queues-pagination button[onclick="goBatchQueuesPage(2)"]').first().click();
await page.waitForFunction(() => document.querySelector('#batch-queues-pagination .pagination-page').textContent.includes('2'));
await page.locator('#batch-queues-page-size-pagination').selectOption('20');
await page.waitForFunction(() => document.querySelectorAll('#batch-queues-list .batch-queue-item').length === 20);
await page.locator('.tasks-filter-select-trigger').click();
await page.locator('.tasks-filter-select-option[data-value="pending"]').click();
await page.waitForFunction(() => document.querySelectorAll('#batch-queues-list .batch-queue-item').length === 1);
await page.locator('.tasks-filter-select-trigger').click();
await page.locator('.tasks-filter-select-option[data-value="all"]').click();
await page.locator('#batch-queues-search').fill('Fixture 21');
await page.waitForFunction(() => document.querySelectorAll('#batch-queues-list .batch-queue-item').length === 1 && document.querySelector('#batch-queues-list').textContent.includes('Fixture 21'));
assert.ok(state.requests.every(r => !r.path.startsWith('/api/long-tasks') && r.path !== '/api/tasks'));
assert.equal(await page.locator('#long-task-workspace, #page-assessments').count(), 0);
assert.deepEqual(state.pageErrors, []);
});
test('original creation and detail dialogs retain batch controls without automatically starting work', async t => {
const { page, state } = await fixture(t);
await page.locator('#page-tasks button[onclick="showBatchImportModal()"]').click();
// The existing modal focuses its initial field on the next animation frame.
// Wait for that frame before filling another field, especially in parallel CI.
await page.waitForFunction(() => document.activeElement === document.getElementById('batch-tasks-input'));
await page.locator('#batch-tasks-input').fill('Read local fixture A\nRead local fixture B');
await page.locator('#batch-queue-title').fill('Restored batch workflow');
assert.equal(await page.locator('#batch-queue-execute-now').isChecked(), false);
await page.locator('#batch-import-modal button[onclick="createBatchQueue()"]').click();
await page.locator('#batch-queue-detail-content [data-bq-detail-for="new-queue"]').waitFor();
const created = state.requests.find(r => r.method === 'POST' && r.path === '/api/batch-tasks');
assert.deepEqual(created.body.tasks, ['Read local fixture A', 'Read local fixture B']);
assert.equal(created.body.executeNow, false);
assert.equal(created.body.scheduleMode, 'manual');
assert.equal(await page.locator('#batch-queue-detail-content .batch-task-item').count(), 2);
await page.locator('#batch-queue-add-task-btn').click();
await page.locator('#add-task-message').fill('Read local fixture C');
await page.locator('#add-batch-task-modal button[onclick="saveAddBatchTask()"]').click();
await page.waitForFunction(() => document.querySelectorAll('#batch-queue-detail-content .batch-task-item').length === 3);
await page.locator('#batch-queue-start-btn').click();
await page.locator('#batch-queue-pause-btn').waitFor({ state: 'visible' });
await page.locator('#batch-queue-pause-btn').click();
await page.locator('#batch-queue-start-btn').waitFor({ state: 'visible' });
assert.equal(state.queues.get('new-queue').status, 'paused');
await page.locator('#batch-queue-delete-btn').click();
await page.waitForFunction(() => !document.querySelector('#batch-queues-list [data-queue-id="new-queue"]'));
assert.equal(state.queues.has('new-queue'), false);
assert.deepEqual(state.pageErrors, []);
});
test('restored task list and creation modal fit desktop, dark mode and mobile', async t => {
const { page, state } = await fixture(t);
for (const width of [1440, 390]) {
await page.setViewportSize({ width, height: 900 });
await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
await page.locator('#page-tasks button[onclick="showBatchImportModal()"]').click();
const modal = page.locator('#batch-import-modal .modal-content');
await page.locator('#batch-tasks-input').waitFor({ state: 'visible' });
const rect = await modal.boundingBox();
assert.ok(rect && rect.width <= width && rect.x >= 0);
await page.locator('#batch-import-modal button[onclick="closeBatchImportModal()"]').last().click();
}
assert.deepEqual(state.pageErrors, []);
});

View File

@ -1,147 +0,0 @@
/* Offline regression. Requires Playwright and Chrome (or CHROME_PATH).
* Run: node --test scripts/chat-scroll-browser.test.cjs
*/
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { test } = require('node:test');
const { chromium } = require('playwright');
const read = file => fs.readFileSync(path.join(__dirname, '..', 'web/static', file), 'utf8');
async function scrollState(page) {
return page.evaluate(() => {
const chat = document.getElementById('chat-messages');
const timeline = document.querySelector('.progress-timeline');
return {
outerGap: chat.scrollHeight - chat.clientHeight - chat.scrollTop,
innerGap: timeline.scrollHeight - timeline.clientHeight - timeline.scrollTop,
innerTop: timeline.scrollTop,
outerFollowing: window.captureScrollPinState(),
pruned: !!timeline.querySelector('.timeline-live-pruned-marker')
};
});
}
test('long live and restored conversations stay at the latest iteration without stealing manual scroll', async () => {
const browser = await chromium.launch({
...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}),
});
try {
for (const width of [1440, 390]) {
for (const restored of [false, true]) {
const label = `${width}px ${restored ? 'restored' : 'live'}`;
const page = await browser.newPage({ viewport: { width, height: 820 } });
try {
await page.route('**/*', route => route.request().url() === 'http://chat.test/'
? route.fulfill({
contentType: 'text/html',
body: `<!doctype html><html data-theme="dark"><body>
<div class="chat-container" style="height: 700px">
<div id="chat-messages" class="chat-messages"></div>
<button id="chat-return-latest" hidden></button>
</div></body></html>`
})
: route.abort());
await page.goto('http://chat.test/');
for (const file of ['style.css', 'mobile.css']) {
await page.addStyleTag({ content: read('css/' + file) });
}
// Supply only the chat globals required by the real progress renderer.
await page.addScriptTag({ content: `
let messageCounter = 0, currentConversationId = '';
const escapeHtml = text => escapeHtmlLocal(text);
` });
for (const file of ['chat-scroll.js', 'monitor.js']) {
await page.addScriptTag({ content: read('js/' + file) });
}
await page.evaluate(async restored => {
const chat = document.getElementById('chat-messages');
for (let i = 0; i < 30; i++) {
const row = document.createElement('div');
row.className = 'message user';
row.innerHTML = '<div class="message-bubble">Synthetic history</div>';
chat.append(row);
}
if (restored) {
chat.insertAdjacentHTML('beforeend', `
<div class="message assistant assistant-turn-with-process">
<div class="message-content">
<div id="process-details-restored" class="process-details-container is-streaming">
<div class="process-details-content"><div class="progress-timeline expanded"></div></div>
</div>
</div>
</div>`);
startProcessDetailsLatestFollow('restored');
} else {
addProgressMessage();
}
const timeline = document.querySelector('.progress-timeline');
for (let i = 0; i < (restored ? 50 : 156); i++) {
addTimelineItem(timeline, 'reasoning_chain', {
title: 'Synthetic reasoning ' + i,
message: 'Example reasoning text.\n'.repeat(i % 11 === 0 ? 65 : i % 9 + 1)
});
if (i % 10 === 0) await new Promise(requestAnimationFrame);
}
}, restored);
await page.waitForFunction(() => {
const tl = document.querySelector('.progress-timeline');
const chat = document.getElementById('chat-messages');
return tl.scrollHeight - tl.clientHeight - tl.scrollTop <= 2 &&
chat.scrollHeight - chat.clientHeight - chat.scrollTop <= 2;
}, null, { timeout: 2000 });
const latest = await scrollState(page);
assert.equal(latest.pruned, !restored, label);
const box = await page.locator('.progress-timeline').boundingBox();
await page.mouse.move(box.x + 40, box.y + box.height / 2);
await page.mouse.wheel(0, -420);
await page.waitForFunction(() => processDetailsDistanceFromLatest(
document.querySelector('.progress-timeline')) > 100);
const reading = await scrollState(page);
assert.equal(reading.outerFollowing, true, label);
assert.ok(reading.outerGap <= 2, label);
if (restored) {
// Upgrading the restore follower to the live subscription preserves reading position.
await page.evaluate(() => startProcessDetailsLatestFollow('restored', { persistent: true }));
}
await page.evaluate(async () => {
const row = document.querySelector('.progress-timeline .timeline-item:last-child .timeline-item-content');
scheduleStreamPlainTextUpdate(row, row.textContent + 'A new line.\n'.repeat(20));
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
});
const afterUpdate = await scrollState(page);
assert.equal(afterUpdate.innerTop, reading.innerTop, label);
assert.ok(afterUpdate.innerGap > reading.innerGap, label);
if (restored) {
await page.locator('.process-details-return-latest').click();
} else {
await page.mouse.wheel(0, 100000);
}
await page.waitForFunction(() => processDetailsDistanceFromLatest(
document.querySelector('.progress-timeline')) <= 2);
await page.evaluate(async () => {
const timeline = document.querySelector('.progress-timeline');
addTimelineItem(timeline, 'reasoning_chain', {
title: 'Latest iteration', message: 'More output.\n'.repeat(50)
});
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
await new Promise(requestAnimationFrame);
});
const atBottom = await scrollState(page);
assert.ok(atBottom.innerGap <= 2 && atBottom.outerGap <= 2, label);
} finally {
await page.close();
}
}
}
} finally {
await browser.close();
}
});

View File

@ -1,378 +0,0 @@
/** Offline Chromium layout/keyboard regression checks using production HTML/CSS/renderers.
* Install Playwright outside the source tree; run with NODE_PATH pointing to that node_modules.
* Uses synthetic records; never starts the backend or sends requests to assessment targets.
*/
const { chromium } = require("playwright");
const fs = require("fs"),
http = require("http"),
path = require("path");
const root = path.resolve(__dirname, "..");
const out =
process.env.CSAI_UI_ARTIFACTS ||
fs.mkdtempSync(path.join(require("os").tmpdir(), "csai-ui-"));
fs.mkdirSync(out, { recursive: true });
const html = fs
.readFileSync(root + "/web/templates/index.html", "utf8")
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/g, "")
.replace(/\{\{\.Version\}\}/g, "UI preview")
.replace(
"</body>",
'<script>window.switchPage=function(){};</script><script src="/static/vendor/i18next.min.js"></script><script src="/static/js/i18n.js"></script><script src="/static/js/modal.js"></script><script src="/static/js/mobile-ui.js"></script></body>',
);
const server = http.createServer((req, res) => {
const p = req.url.split("?")[0];
if (p.startsWith("/api/")) {
res.setHeader("Content-Type", "application/json");
return res.end("{}");
}
if (p === "/") {
res.setHeader("Content-Type", "text/html");
return res.end(html);
}
const f = path.join(root, "web", p);
if (!f.startsWith(root + "/web/") || !fs.existsSync(f)) {
res.statusCode = 404;
return res.end();
}
res.setHeader(
"Content-Type",
p.endsWith(".css")
? "text/css"
: p.endsWith(".js")
? "application/javascript"
: "application/octet-stream",
);
res.end(fs.readFileSync(f));
});
(async () => {
await new Promise((r) => server.listen(0, "127.0.0.1", r));
const browser = await chromium.launch({ headless: true });
const findings = [];
let count = 0;
for (const width of process.env.CSAI_UI_WIDTHS
? process.env.CSAI_UI_WIDTHS.split(",").map(Number)
: [1440, 1024, 390, 360])
for (const theme of ["light", "dark"]) {
const height =
width === 360 ? 640 : width === 390 ? 844 : width === 1024 ? 768 : 900;
const page = await browser.newPage({
viewport: { width, height },
colorScheme: theme,
locale: "zh-CN",
});
page.on("pageerror", (e) =>
findings.push({ width, theme, issue: e.message }),
);
await page.goto("http://127.0.0.1:" + server.address().port);
await page.evaluate(() => window.i18nReady);
await page.evaluate((t) => {
document.documentElement.dataset.theme = t;
document
.querySelectorAll(".page")
.forEach((e) => e.classList.remove("active"));
document
.getElementById("page-roles-management")
.classList.add("active");
}, theme);
const ids = await page
.locator('[data-ui-surface="drawer"]')
.evaluateAll((els) => els.map((e) => e.id));
for (const id of ids) {
// A drawer nested in a page is visible only while that page is active.
await page.evaluate((id) => {
const e = document.getElementById(id);
e.closest(".settings-section-content")?.classList.add("active");
const parent = e.closest(".page");
if (parent) {
document
.querySelectorAll(".page")
.forEach((p) => p.classList.remove("active"));
parent.classList.add("active");
}
openAppModal(id);
}, id);
await page.locator('#' + id).evaluate(async (element) => {
element.getBoundingClientRect();
const animations = element.getAnimations({ subtree: true }).filter(
animation => animation.effect?.getComputedTiming().iterations !== Infinity,
);
await Promise.all(animations.map(animation => animation.finished.catch(() => {})));
});
const info = await page.evaluate((id) => {
const e = document.getElementById(id),
p = e.firstElementChild,
r = p.getBoundingClientRect(),
s = getComputedStyle(p),
b = p.querySelector(
".modal-body,.projects-modal-body,.c2-modal-body,#vulnerability-inspector-body",
);
return {
id,
x: r.x,
y: r.y,
w: r.width,
h: r.height,
bg: s.backgroundColor,
corners: [
s.borderTopLeftRadius,
s.borderTopRightRadius,
s.borderBottomRightRadius,
s.borderBottomLeftRadius,
],
overflow: b ? b.scrollWidth > b.clientWidth + 2 : false,
footer: p
.querySelector(
".modal-footer,.projects-modal-footer,.c2-modal-footer",
)
?.getBoundingClientRect().bottom,
};
}, id);
count++;
const channel = Number(info.bg.match(/\d+/)?.[0]);
if (
(theme === "dark" && channel > 100) ||
(theme === "light" && channel < 200)
)
findings.push({
width,
theme,
id,
issue: "surface theme mismatch",
bg: info.bg,
});
if (
info.x < -0.5 ||
info.y < -0.5 ||
Math.abs(info.x + info.w - width) > 2 ||
Math.abs(info.h - height) > 2 ||
info.footer > height + 1 ||
info.overflow ||
info.corners.some((radius) => radius !== "0px")
)
findings.push({ width, theme, ...info });
if (
[
"role-modal",
"asset-editor-modal",
"vulnerability-modal",
"skill-modal",
].includes(id)
)
await page.screenshot({
animations: "disabled",
path: out + "/" + id + "-" + width + "-" + theme + ".png",
});
await page.evaluate((id) => closeAppModal(id), id);
}
// Compact actions should remain short on mobile; test nested layer and restoration.
await page.evaluate(() => {
openAppModal("fact-detail-modal");
openAppModal("fact-modal");
});
const nested = await page.evaluate(
() =>
Number(
getComputedStyle(document.getElementById("fact-modal")).zIndex,
) >
Number(
getComputedStyle(document.getElementById("fact-detail-modal"))
.zIndex,
),
);
if (!nested) throw new Error("nested stacking");
await page.evaluate(() => {
closeAppModal("fact-modal");
closeAppModal("fact-detail-modal");
openAppModal("project-modal");
});
const small = await page.locator("#project-modal > div").boundingBox();
if (small.height >= height - 10)
throw new Error("short dialog is full screen");
await page.evaluate(() => closeAppModal("project-modal"));
if (width === 1440) {
await page.evaluate(() => openAppModal("role-modal"));
await page.locator("#role-modal .app-drawer-expand").click();
const expanded = await page.locator("#role-modal > div").boundingBox();
if (expanded.width < 1200) throw new Error("expand failed");
await page.evaluate(() => closeAppModal("role-modal"));
}
// Load production renderers with synthetic data; no backend or target execution.
await page.evaluate(() => {
window.apiFetch = async () => ({
ok: true,
json: async () => ({
log: {
createdAt: "2026-11-15T08:00:00Z",
category: "config",
action: "apply",
result: "success",
message: "配置已保存",
detail: { source: "UI fixture" },
},
}),
});
window.showToast = (m) => console.log("TOAST", m);
});
for (const script of ["knowledge", "audit", "roles", "c2"])
await page.addScriptTag({ url: "/static/js/" + script + ".js" });
await page.evaluate(() => showAuditLogDetail("fixture"));
await page.waitForTimeout(100);
if (
(await page
.locator("#audit-detail-modal .app-drawer-expand")
.count()) !== 1
) {
console.log(
await page
.locator("#audit-detail-modal")
.evaluateAll((es) => es.map((e) => e.outerHTML)),
);
throw new Error("deferred audit header missing");
}
await page.screenshot({
animations: "disabled",
path: out + "/audit-" + width + "-" + theme + ".png",
});
await page.keyboard.press("Escape");
if (await page.locator("#audit-detail-modal").count())
throw new Error("Escape did not run audit cleanup");
await page.evaluate(() =>
showRetrievalLogDetailsModal(
{
createdAt: "2026-11-15T08:00:00Z",
query: "查找接口鉴权检查方法",
riskType: "鉴权",
},
[
{
title: "接口鉴权检查",
category: "Web",
content: "验证不同角色之间的数据访问边界。",
},
],
),
);
await page.waitForTimeout(100);
await page.screenshot({
animations: "disabled",
path: out + "/retrieval-" + width + "-" + theme + ".png",
});
await page.evaluate(() => closeRetrievalLogDetailsModal());
await page.route("**/api/**", (route) =>
route.fulfill({ json: { profiles: [], projects: [], listeners: [] } }),
);
await page.evaluate(() => C2.showCreateListenerModal());
await page.waitForTimeout(200);
if ((await page.locator("#c2-modal .app-drawer-expand").count()) !== 1)
throw new Error("C2 header missing");
await page.screenshot({
animations: "disabled",
path: out + "/c2-" + width + "-" + theme + ".png",
});
await page.evaluate(() => C2.closeModal());
// Test focus wrap, native close cleanup and restoration through real role handlers.
await page.evaluate(() => {
const b = document.createElement("button");
b.textContent = "Open editor";
document.body.appendChild(b);
b.focus();
window.fixtureFocus = b;
openAppModal("role-modal");
});
await page.waitForTimeout(30);
await page.locator("#role-modal .modal-footer .btn-primary").focus();
await page.keyboard.press("Tab");
if (
!(await page.evaluate(() =>
document
.getElementById("role-modal")
.contains(document.activeElement),
))
)
throw new Error("focus escaped");
await page.keyboard.press("Escape");
if (
!(await page.evaluate(
() =>
!isAppModalOpen("role-modal") &&
document.activeElement === window.fixtureFocus,
))
)
throw new Error("close/focus restore failed");
await page.evaluate(() => {
window.fixtureFocus.remove();
roles = [
{
name: "安全审计",
description: "检查授权范围内的代码与配置,整理可复核的证据。",
tools: ["read_file", "search_code"],
enabled: true,
},
{
name: "报告整理",
description: "汇总已验证发现,生成清晰的报告。",
tools: [],
enabled: true,
},
];
renderRolesList();
});
const pageIds = await page
.locator(".page[id]")
.evaluateAll((es) => es.map((e) => e.id));
for (const id of pageIds) {
await page.evaluate((id) => {
document
.querySelectorAll(".page")
.forEach((e) => e.classList.toggle("active", e.id === id));
if (window.CSAMobile)
CSAMobile.wrapTables(document.getElementById(id));
}, id);
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > innerWidth + 2,
);
if (overflow)
findings.push({ width, theme, id, issue: "page overflow" });
if (
[
"page-dashboard",
"page-roles-management",
"page-asset-library",
"page-workflows",
"page-settings",
].includes(id)
)
await page.screenshot({
animations: "disabled",
path: out + "/" + id + "-" + width + "-" + theme + ".png",
});
}
await require("./ui-realistic-scenarios.cjs")({
page,
width,
height,
theme,
out,
});
await require("./ui-extra-drawers.cjs")({
page,
width,
height,
theme,
out,
});
await page.close();
}
fs.writeFileSync(
out + "/results.json",
JSON.stringify({ count, findings }, null, 2),
);
console.log(JSON.stringify({ count, findings, artifacts: out }, null, 2));
if (findings.length) process.exitCode = 1;
await browser.close();
server.close();
})().catch((e) => {
console.error(e);
server.close();
process.exit(1);
});

View File

@ -1,743 +0,0 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { chromium } = require('playwright');
const root = path.join(__dirname, '..');
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
const template = read('web/templates/index.html');
const region = template.match(/<div id="page-deep-assessments"[^>]*><div id="deep-assessments-root"><\/div><\/div>/)?.[0];
assert.ok(region, 'independent page missing');
const navOrder = [...template.slice(template.indexOf('<nav class="main-sidebar-nav">'), template.indexOf('</nav>', template.indexOf('<nav class="main-sidebar-nav">'))).matchAll(/class="nav-item(?: [^"]*)?" data-page="([^"]+)"/g)].map(m => m[1]);
assert.equal(navOrder[navOrder.indexOf('chat') + 1], 'deep-assessments');
const sample = id => ({ id, name: '隔离样例 ' + id, status: 'draft', revision: 0, objective: '检查本地夹具', scope: '仅本地', criteria: '引用真实证据', strategy: '', summary: '', question: '', concurrency: 2, remaining_seconds: 172800, token_budget: 2000000, tokens_used: 0, max_rounds: 512, rounds: 0, updated_at: new Date().toISOString(), steps: [], metrics: {}, auto_resume: true });
async function fixture(t) {
const state = { tasks: new Map(Array.from({ length: 24 }, (_, i) => ['t' + i, sample('t' + i)])), requests: [], errors: [], sharedAssets: [], linkedAssets: new Map() };
const locale = JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<', '\\u003c');
const scripts = ['router', 'auth', 'assessment-workbench','assessment-node-panel','assessment-exploration-views','deep-assessment-graph', 'deep-assessments'].map(x => `<script src="/static/js/${x}.js"></script>`).join('');
const html = `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">${['style', 'mobile', 'deep-assessments', 'design-system'].map(x=>`<link rel="stylesheet" href="/static/css/${x}.css">`).join('')}</head><body><div class="container"><main class="main-layout"><section class="content-area">${region}<div class="page" id="page-chat"></div><div class="page" id="page-tasks"></div></section></main></div><script>window.t=k=>k.split('.').reduce((o,p)=>o&&o[p],${locale})||k;window.loadConversation=async id=>{window.visitedConversation=id};window.initializeChatUI=()=>{};window.refreshAppData=async()=>{};</script><script src="/static/vendor/cytoscape.min.js"></script><script>const originalGraph=window.cytoscape;window.cytoscape=(...args)=>{const chart=originalGraph(...args);window.fixtureGraph=chart;return chart};</script>${scripts}<script>document.removeEventListener('DOMContentLoaded',initializeApp);saveAuth('fixture-token',new Date(Date.now()+3600000),{user:{id:'fixture',username:'fixture'},permissions:['assessments:read','assessments:write','assessments:delete','agent:execute','chat:read','chat:write','tasks:read','asset:read'],scope:'own'});</script></body></html>`;
const server = http.createServer(async (req,res)=>{
const url = new URL(req.url,'http://fixture');
const send=(code,body)=>{res.statusCode=code;res.setHeader('Content-Type','application/json; charset=utf-8');res.end(JSON.stringify(body));};
if(url.pathname.startsWith('/static/')){res.setHeader('Content-Type',url.pathname.endsWith('.css')?'text/css':'text/javascript');return res.end(read('web'+url.pathname));}
if(url.pathname==='/'){res.setHeader('Content-Type','text/html; charset=utf-8');return res.end(html);}
if(url.pathname==='/favicon.ico'){res.statusCode=204;return res.end();}
let raw='';for await(const chunk of req)raw+=chunk;const body=raw?JSON.parse(raw):null;
state.requests.push({path:url.pathname,method:req.method,body,query:Object.fromEntries(url.searchParams),authorization:req.headers.authorization});
if(req.headers.authorization!=='Bearer fixture-token')return send(401,{error:'authentication missing'});
if(url.pathname==='/api/deep-assessments/options')return send(200,{models:[{id:'fixture',name:'Fixture'}],roles:['review'],projects:[]});
if(url.pathname==='/api/deep-assessments'){
if(req.method==='POST'){const task={...sample('new'),...body};state.tasks.set(task.id,task);return send(201,{task});}
const filtered=[...state.tasks.values()].filter(t=>!!t.archived===(url.searchParams.get('archived')==='true')).filter(t=>(!url.searchParams.get('q')||t.name.includes(url.searchParams.get('q')))&&(!url.searchParams.get('status')||t.status===url.searchParams.get('status')));
const offset=Number(url.searchParams.get('offset')||0),limit=Number(url.searchParams.get('limit')||20);return send(200,{tasks:filtered.slice(offset,offset+limit).map(t=>({...t,steps:undefined,review_count:(t.steps||[]).filter(s=>['uncertain','cleanup_unconfirmed'].includes(s.status)).length})),has_more:filtered.length>offset+limit});
}
const match=url.pathname.match(/^\/api\/deep-assessments\/([^/]+)(?:\/(.*))?$/);
if(!match)return send(404,{error:'unhandled route'});
const task=state.tasks.get(match[1]);if(!task)return send(404,{error:'missing task'});
const graph=task.graph||{nodes:[{id:'goal',kind:'goal',state:task.status,title:task.name,body:task.objective,source:{}}],edges:[],total:0,folded:0,next_offset:0,has_more:false};
if(match[2]==='assets'){
if(req.method==='POST'){state.linkedAssets.set(task.id,body.asset_ids);return send(200,{saved:true});}
if(url.searchParams.get('asset_id')){const offset=Number(url.searchParams.get('offset')||0),rows=Array.from({length:51},(_,i)=>({id:'ep-'+i,method:'GET',path:'/endpoint/'+i,title:'fixture'}));return send(200,{endpoints:rows.slice(offset,offset+50),has_more:offset+50<rows.length,next_offset:offset+50});}
const assets=state.sharedAssets.filter(a=>url.searchParams.get('scope')==='all'||(state.linkedAssets.get(task.id)||[]).includes(a.id));
return send(200,{assets,nodes:assets.flatMap(a=>[{id:'domain:example.test',kind:'domain',title:'example.test',body:'',asset_ids:[a.id]},{id:'asset:'+a.id,kind:'service',title:a.host,body:JSON.stringify(a),asset_ids:[a.id]},{id:'endpoint:'+a.id,kind:'endpoint',title:'GET /fixture',body:'original endpoint',asset_ids:[a.id]}]),edges:assets.flatMap(a=>[{source:'domain:example.test',target:'asset:'+a.id,relation:'exposes'},{source:'asset:'+a.id,target:'endpoint:'+a.id,relation:'contains'}]),total:assets.length,next_offset:assets.length,has_more:false});
}
if(match[2]==='facts'){const facts=(task.facts||[]).filter(f=>!url.searchParams.get('confidence')||f.confidence===url.searchParams.get('confidence')),offset=Number(url.searchParams.get('offset')||0);return send(200,{facts:facts.slice(offset,offset+20),next_offset:offset+20,has_more:offset+20<facts.length});}
if(match[2]==='vulnerabilities'){const rows=task.findings||[],offset=Number(url.searchParams.get('offset')||0);return send(200,{vulnerabilities:rows.slice(offset,offset+20),total:rows.length,has_more:offset+20<rows.length});}
if(match[2]?.startsWith('vulnerabilities/')){const vulnerability=task.findings.find(f=>f.id===match[2].slice(16));return send(200,{vulnerability,step:task.steps.find(st=>st.id===vulnerability.assessment_step_id)});}
if(match[2]?.startsWith('steps/'))return send(200,{step:task.steps.find(s=>s.id===match[2].slice(6)),revision:task.revision,task_status:task.status});
if(match[2]==='graph'){const summary=url.searchParams.get('view')==='summary';const nodes=summary?graph.nodes.filter(n=>!['receipt','observation'].includes(n.kind)):graph.nodes;const ids=new Set(nodes.map(n=>n.id));return send(200,{...graph,nodes,edges:graph.edges.filter(e=>ids.has(e.source)&&ids.has(e.target)),primary_count:nodes.filter(n=>!n.boundary).length-1,details_hidden:graph.nodes.length-nodes.length,boundary_total:graph.boundary_total||0});}
if(match[2]==='graph/node'){const node=graph.nodes.find(n=>n.id===url.searchParams.get('node_id'));if(!node)return send(404,{error:'missing node'});const refs=graph.edges.flatMap(e=>e.target===node.id?[{direction:'upstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.source)}]:e.source===node.id?[{direction:'downstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.target)}]:[]).filter(r=>r.node);return send(200,{node,next_offset:node.body.length,has_more:false,relations:refs,relations_next_offset:refs.length,relations_has_more:false});}
if(match[2]==='events')return send(200,{events:task.events||[]});
if(match[2]==='receipts')return send(200,{receipts:(task.receipts||[]).filter(r=>!url.searchParams.get('step_id')||r.step_id===url.searchParams.get('step_id')),next_offset:0,has_more:false});
if(match[2]==='report'){res.setHeader('Content-Type','text/markdown');return res.end('# fixture report');}
if(match[2]?.startsWith('control/')){
if(body.revision!==task.revision)return send(409,{error:'stale revision'});
if(match[2]==='control/start'&&task.steps.some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status))){
if(!task.known_cancellation)return send(400,{error:'仍有结果不明的工具调用,请先查看待核对步骤和回执'});
task.steps.forEach(s=>{if(s.status==='uncertain')s.status='pending';});
}
const action=match[2].split('/')[1];if(action==='start'||action==='continue-stopped'){task.status='running';task.steps.forEach(s=>{if(s.status==='reconciled')s.status='pending';});}if(action==='pause')task.status='paused';if(action==='archive'){task.archived=true;if(!['draft','completed','cancelled'].includes(task.status))task.status='paused';}if(action==='restore')task.archived=false;if(action==='guidance')task.summary=body.message;if(action==='budget')Object.assign(task,body);task.revision++;
if(action==='intent-pause'){const st=task.steps.find(s=>s.id===body.step_id);st.status='paused';st.user_paused=true;}
if(action==='intent-resume'){const st=task.steps.find(s=>s.id===body.step_id);st.status='pending';st.user_paused=false;}
if(action==='intent-priority')task.steps.find(s=>s.id===body.step_id).priority=body.priority;
if(action==='intent-guidance'){const st=task.steps.find(s=>s.id===body.step_id);(st.guidance||=[]).push(body.message);}
if(action==='retry'||action==='reconcile'){
const step=task.steps.find(s=>s.id===body.step_id);if(!step||!body.reconciled)return send(400,{error:'review required'});
const closed=['cancelled','completed'].includes(task.status);step.status=closed?'reconciled':'pending';if(!closed)task.status=task.steps.some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status))?'needs_review':'paused';
}
} else if(req.method==='DELETE') state.tasks.delete(task.id);
const counts={};for(const step of task.steps||[])counts[step.status]=(counts[step.status]||0)+1;counts.needs_review=(counts.uncertain||0)+(counts.cleanup_unconfirmed||0);
const queue=url.searchParams.get('step_order')==='queue',filter=url.searchParams.get('step_status');
const steps=(task.steps||[]).filter(s=>!queue||!filter||s.status===filter||filter==='needs_review'&&['uncertain','cleanup_unconfirmed'].includes(s.status));
const stepLimit=Number(url.searchParams.get('step_limit')||steps.length)||50;
const requestedOffset=Number(url.searchParams.get('step_offset')||0),stepOffset=requestedOffset>=steps.length?(steps.length?Math.floor((steps.length-1)/stepLimit)*stepLimit:0):requestedOffset;
return send(200,{runtime:{live:{active:task.status==='running',planning:false,workers:counts.running||0},counts,intents:(task.steps||[]).filter(s=>s.status==='running'),tools:[],recent:[],facts:0,findings:0,findings_visible:true,asset_names:{},...task.runtime},guidance_delivered:match[2]==='control/intent-guidance'&&task.status==='running'&&task.steps.find(s=>s.id===body?.step_id)?.status==='running',step:body?.step_id?task.steps.find(s=>s.id===body.step_id):undefined,task:{...task,review_count:counts.needs_review,steps:steps.slice(stepOffset,stepOffset+stepLimit)},intent_counts:counts,step_total:steps.length,step_offset:stepOffset,step_has_more:stepOffset+stepLimit<steps.length});
});
await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));
const executablePath=process.env.CHROME_PATH||(process.platform==='darwin'?'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome':undefined);
const browser=await chromium.launch(executablePath?{executablePath}:{});
t.after(async()=>{await browser.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));});
const page=await browser.newPage({viewport:{width:1440,height:1000},acceptDownloads:true});page.setDefaultTimeout(5000);
page.on('pageerror',error=>state.errors.push(error.message));page.on('dialog',d=>d.accept());
await page.goto(`http://127.0.0.1:${server.address().port}/#deep-assessments`);
await page.locator('[data-da-action="select"]').first().waitFor();
return {page,state};
}
test('deep assessment is independent, paginates and only creates drafts',async t=>{
const {page,state}=await fixture(t);
assert.equal(await page.locator('.da-list-item').count(),20);
await page.locator('[data-da-action="next"]').click();await page.waitForFunction(()=>document.querySelectorAll('.da-list-item').length===4);
await page.locator('[data-da-action="create"]').click();
await page.locator('[name="name"]').fill('Two day fixture');await page.locator('[name="objective"]').fill('Read fixture evidence');
const scope=page.getByRole('textbox',{name:'补充限制与排除项(选填)',exact:true});
const criteria=page.getByRole('textbox',{name:'验收条件(选填)',exact:true});
assert.equal(await scope.getAttribute('required'),null);assert.equal(await criteria.getAttribute('required'),null);
assert.match(await scope.getAttribute('placeholder'),/例如:排除支付接口/);
assert.match(await criteria.getAttribute('placeholder'),/例如:报告列明已测范围/);
assert.match(await page.locator('#da-scope-hint').innerText(),/留空沿用目标/);
assert.match(await page.locator('#da-criteria-hint').innerText(),/留空沿用目标/);
assert.equal(await scope.inputValue(),'');assert.equal(await criteria.inputValue(),'');
assert.equal(await page.locator('#da-create-form').evaluate(form=>form.checkValidity()),true);
assert.equal(await page.locator('[name="hours"],[name="token_budget"],[name="max_rounds"]').count(),0);
await page.locator('#da-create-form button[type="submit"]').click();await page.waitForFunction(()=>document.querySelector('#da-title').textContent.includes('Two day fixture'));
const create=state.requests.find(r=>r.method==='POST'&&r.path==='/api/deep-assessments');assert.equal(create.body.remaining_seconds,undefined);assert.equal(create.body.token_budget,undefined);assert.equal(create.body.max_rounds,undefined);assert.equal(create.body.auto_resume,true);assert.equal(create.body.scope,'');assert.equal(create.body.criteria,'');
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,0);
await page.locator('[data-da-action="start"]').click();await page.locator('[data-da-action="pause"]').waitFor();
await page.locator('#da-guidance-panel > summary').click(); await page.locator('#da-guidance').fill('Keep this unsent text');await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.locator('#da-guidance').inputValue(),'Keep this unsent text');
await page.locator('[data-da-action="pause"]').click();await page.locator('[data-da-action="start"]').waitFor();
const download=page.waitForEvent('download');await page.locator('[data-da-action="report"]').click();assert.match((await download).suggestedFilename(),/^assessment-/);
assert.ok(state.requests.every(r=>!r.path.startsWith('/api/batch-tasks')&&r.path!=='/api/tasks'));
assert.deepEqual(state.errors,[]);
});
test('assessment escapes evidence and fits mobile and dark layouts',async t=>{
const {page,state}=await fixture(t);const task=state.tasks.get('t0');task.name='<img src=x onerror="window.injected=1">';task.steps=[{id:'s1',title:'Evidence review',instruction:'Read fixture',summary:'<script>window.injected=1</script>',status:'completed',depends_on:[],attempts:3,conversation_id:'fixture-conversation',evidence:['receipt']}];
await page.evaluate(()=>DeepAssessments.refresh());await page.locator('[data-da-action="select"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="plan"]').click();await page.locator('.da-step summary').click();
assert.equal(await page.evaluate(()=>window.injected),undefined);assert.equal(await page.locator('#da-title img').count(),0);
await page.locator('#da-guidance-panel > summary').click(); await page.locator('#da-guidance').fill('Unsent direction');await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.locator('.da-step[open]').count(),1);
const screenshotRoot=process.env.CSAI_SCREENSHOT_DIR;
if(screenshotRoot){fs.mkdirSync(screenshotRoot,{recursive:true});await page.screenshot({path:path.join(screenshotRoot,'deep-assessments-desktop.png'),fullPage:true});}
await page.setViewportSize({width:390,height:844});await page.evaluate(()=>document.documentElement.setAttribute('data-theme','dark'));
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
await page.locator('[data-da-action="back-list"]').click();
await page.locator('[data-da-action="create"]').click();
await page.locator('#da-form-drawer').waitFor({state:'visible'});
await page.waitForFunction(()=>Math.abs(document.getElementById('da-form-drawer').getBoundingClientRect().right-innerWidth)<1);
const box=await page.locator('#da-form-drawer').boundingBox();assert.ok(box.x>=0&&box.x+box.width<=391);assert.ok(Math.abs(box.y)<1&&Math.abs(box.height-844)<1);
if(screenshotRoot)await page.screenshot({path:path.join(screenshotRoot,'deep-assessments-mobile.png'),fullPage:true});
assert.deepEqual(state.errors,[]);
});
test('assessment creation uses a right drawer with backdrop, Escape and button dismissal',async t=>{
const {page,state}=await fixture(t);
await page.locator('[data-da-action="create"]').click();
const drawer=page.locator('#da-form-drawer');await drawer.waitFor({state:'visible'});
// Wait for the short slide transition before checking final viewport geometry.
await page.waitForFunction(()=>Math.abs(document.getElementById('da-form-drawer').getBoundingClientRect().right-innerWidth)<1);
const box=await drawer.boundingBox();assert.ok(box.x>0);assert.equal(box.y,0);assert.equal(box.height,1000);assert.ok(Math.abs(box.x+box.width-1440)<1);
assert.equal(await page.locator('[name="name"]').evaluate(el=>el===document.activeElement),true);
await page.locator('[name="name"]').fill('Unsubmitted draft');
await page.locator('[name="objective"]').click();assert.equal(await drawer.isVisible(),true);
// A blank area inside the panel must not count as its backdrop.
await page.mouse.click(box.x+8,110);assert.equal(await drawer.isVisible(),true);
// Dragging out of a field must not accidentally dismiss the drawer.
const input=await page.locator('[name="name"]').boundingBox();
await page.mouse.move(input.x+10,input.y+10);await page.mouse.down();await page.mouse.move(20,110);await page.mouse.up();assert.equal(await drawer.isVisible(),true);
await page.mouse.click(20,110);await drawer.waitFor({state:'hidden'});
assert.equal(await page.locator('body').evaluate(el=>el.classList.contains('da-drawer-open')),false);
await page.locator('[data-da-action="create"]').click();await drawer.waitFor({state:'visible'});await page.keyboard.press('Escape');await drawer.waitFor({state:'hidden'});
await page.locator('[data-da-action="create"]').click();await drawer.waitFor({state:'visible'});await drawer.locator('.da-drawer-close').click();await drawer.waitFor({state:'hidden'});
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
assert.deepEqual(state.errors,[]);
});
test('continuous assessment workspace shows graph memories and returns to the list',async t=>{
const {page,state}=await fixture(t);
const task=state.tasks.get('t0');task.graph={nodes:[
{id:'goal',kind:'goal',state:'running',title:'目标',body:'fixture goal',source:{}},
{id:'step:s1',kind:'step',step_id:'s1',state:'completed',title:'历史探索',body:'observed evidence',source:{evidence:['receipt-one']}},
{id:'memory:pi1',kind:'memory',step_id:'s1',state:'summary',title:'Pi 摘要',body:'Persisted original summary <script>window.injected=1</script>',source:{session_entry_id:'pi-entry',provenance:'pi_compaction'}},
{id:'digest:old',kind:'digest',state:'folded',title:'历史归档',body:'eight earlier directions',source:{members:['step:s1']}}
],edges:[{source:'goal',target:'digest:old',relation:'archives'},{source:'goal',target:'step:s1',relation:'plans'},{source:'step:s1',target:'memory:pi1',relation:'summarizes'}],total:3,folded:8,next_offset:3,has_more:false};
assert.equal(await page.locator('#da-workspace').isVisible(),false);
const list=await page.locator('.da-list-panel').boundingBox();assert.ok(list.width>1300);
const pager=await page.locator('.da-pagination').boundingBox();assert.ok(pager.y+pager.height<=1000);
await page.locator('[data-da-action="select"][data-id="t0"]').click();
const inspector=page.locator('#da-workspace');await inspector.waitFor({state:'visible'});
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
await page.locator('#da-graph-select option[value="memory:pi1"]').waitFor({state:'attached'});
assert.ok(await page.locator('#da-graph-canvas canvas').count()>0);
await page.locator('#da-graph-select').selectOption('memory:pi1');
await page.waitForFunction(()=>document.getElementById('da-graph-node').textContent.includes('Persisted original summary'));
await page.locator('#da-graph-node details summary').click();
await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await page.locator('#da-graph-node details').getAttribute('open'),'');
assert.equal(await page.evaluate(()=>window.injected),undefined);
await page.waitForFunction(()=>document.getElementById('da-workspace').getAnimations().every(a=>a.playState==='finished'));
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'deep-assessment-graph.png'),fullPage:true});
await page.locator('#da-graph-select').selectOption('digest:old');await page.locator('[data-da-action="graph-expand"]').click();
assert.ok(state.requests.some(r=>r.path.endsWith('/graph/node')));
assert.equal(await page.locator('[data-da-action="budget"]').count(),0);
if(!await page.locator('#da-guidance').isVisible())await page.locator('#da-guidance-panel > summary').click(); await page.locator('#da-guidance').fill('Keep this draft direction');
await page.locator('[data-da-action="back-list"]').click();await inspector.waitFor({state:'hidden'});
await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await inspector.isVisible(),false);
await page.locator('[data-da-action="select"][data-id="t0"]').click();await inspector.waitFor({state:'visible'});assert.equal(await page.locator('#da-guidance').inputValue(),'Keep this draft direction');
await page.keyboard.press('Escape');assert.equal(await inspector.isVisible(),true);
await page.locator('[data-da-action="back-list"]').click();await inspector.waitFor({state:'hidden'});
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
assert.deepEqual(state.errors,[]);
});
test('shared assets, intent priorities and observed facts stay linked across navigation',async t=>{
const {page,state}=await fixture(t);
state.sharedAssets=[{id:'shared-asset',host:'https://app.example.test',title:'<img src=x onerror="window.injected=1">'}];
const task=state.tasks.get('t0');task.steps=[{id:'inspect',title:'Inspect fixture intent',instruction:'Read fixture',priority:1,asset_ids:['shared-asset'],source_ids:['fact:inferred'],status:'completed',evidence:['receipt-own']}];
task.facts=[{id:'fact:observed',step_id:'inspect',confidence:'observed',summary:'Observed fixture',body:'Original <script>window.injected=1</script>',evidence:['receipt-own']},{id:'fact:inferred',step_id:'inspect',confidence:'inferred',summary:'Hypothesis',body:'Needs independent evidence',evidence:[]}];
await page.locator('[data-da-action="select"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="assets"]').click();
await page.locator('[data-da-action="asset-all"]').click();
await page.locator('[data-da-action="asset-attach"]').click();
await page.waitForFunction(()=>document.querySelector('[data-da-action="asset-linked"]').getAttribute('aria-pressed')==='true');
assert.deepEqual(state.linkedAssets.get('t0'),['shared-asset']);
assert.ok(await page.locator('#da-asset-canvas canvas').count()>0);
await page.locator('#da-asset-select').selectOption('endpoint:shared-asset');
assert.match(await page.locator('#da-asset-detail').innerText(),/GET \/fixture/);
await page.reload();await page.locator('#da-asset-canvas canvas').first().waitFor();
await page.locator('#da-asset-select').selectOption('asset:shared-asset');
await page.locator('[data-da-action="asset-endpoints"]').click();
await page.waitForFunction(()=>document.querySelectorAll('.da-endpoint-list p').length===50);
await page.locator('[data-da-action="asset-endpoints-next"]').click();
await page.waitForFunction(()=>document.querySelectorAll('.da-endpoint-list p').length===1);
assert.match(await page.locator('.da-endpoint-list').innerText(),/endpoint\/50/);
await page.locator('[data-da-action="tab"][data-tab="plan"]').click();
await page.locator('.da-step summary').click();
assert.match(await page.locator('.da-step').innerText(),/优先级: 1/);
await page.locator('[data-da-action="intent-asset"]').click();
await page.waitForFunction(()=>location.hash.includes('tab=assets')&&location.hash.includes('asset_id=shared-asset'));
await page.locator('[data-da-action="asset-intents"]').click();
await page.waitForFunction(()=>location.hash.includes('tab=plan'));
await page.locator('#da-intent-status').waitFor();
assert.ok(state.requests.some(r=>r.query.step_asset==='shared-asset'));
await page.locator('#da-intent-status').selectOption('pending');
await page.waitForFunction(()=>location.hash.includes('tab=plan'));
assert.ok(state.requests.some(r=>r.query.step_order==='queue'&&r.query.step_status==='pending'));
await page.locator('[data-da-action="tab"][data-tab="facts"]').click();
await page.waitForFunction(()=>document.querySelectorAll('.da-finding').length===2);
assert.equal(await page.locator('.da-finding').count(),2);
await page.locator('[data-da-action="fact-filter"][data-confidence="inferred"]').click();
await page.waitForFunction(()=>document.querySelectorAll('.da-finding').length===1);
assert.match(await page.locator('.da-finding').innerText(),/推断待证/);
await page.locator('[data-da-action="fact-proof"]').click();
await page.waitForFunction(()=>location.hash.includes('tab=evidence')&&location.hash.includes('step_id=inspect'));
assert.match(await page.locator('.da-source-banner').innerText(),/Inspect fixture intent/);
await page.locator('[data-da-action="tab"][data-tab="assets"]').click();
await page.setViewportSize({width:390,height:844});
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
const box=await page.locator('#da-asset-canvas').boundingBox();assert.ok(box.height>=300);
const output='/tmp/csai-intents-ui';fs.mkdirSync(output,{recursive:true});await page.screenshot({path:output+'/shared-assets-mobile.png'});
assert.equal(await page.evaluate(()=>window.injected),undefined);
assert.deepEqual(state.errors,[]);
assert.equal(state.requests.filter(r=>r.method==='POST'&&!r.path.endsWith('/assets')).length,0);
});
test('assessment rows control and archive work without opening detail or touching batch tasks',async t=>{
const {page,state}=await fixture(t);const row=page.locator('.da-list-item[data-id="t0"]');
assert.equal(await row.locator('[data-da-action="row-start"]').isEnabled(),true);
assert.equal(await row.locator('[data-da-action="row-pause"]').isEnabled(),false);
await page.locator('section.content-area').evaluate(el=>el.style.maxWidth='780px');
const area=await page.locator('section.content-area').boundingBox(),actions=await row.locator('.da-row-actions').boundingBox();assert.ok(actions.x+actions.width<=area.x+area.width+1);
await page.locator('section.content-area').evaluate(el=>el.style.maxWidth='');
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'assessment-row-actions.png'),fullPage:true});
await row.locator('[data-da-action="row-start"]').click();
await page.waitForFunction(()=>document.querySelector('.da-list-item[data-id="t0"] [data-da-action="row-pause"]').disabled===false);
assert.equal(await page.locator('#da-workspace').isVisible(),false);
assert.equal(await row.locator('[data-da-action="row-archive"]').isEnabled(),false);
await row.locator('[data-da-action="row-pause"]').click();
await page.waitForFunction(()=>document.querySelector('.da-list-item[data-id="t0"] [data-da-action="row-archive"]').disabled===false);
await row.locator('[data-da-action="row-archive"]').click();await row.waitFor({state:'detached'});
await page.locator('#da-archive-filter').selectOption('archived');await row.waitFor();
assert.equal(await row.locator('[data-da-action="row-start"]').isEnabled(),false);
await row.locator('[data-da-action="details"]').click();await page.locator('#da-workspace').waitFor();
assert.equal(await page.locator('dialog[open]').count(),0);
await page.locator('#da-title .da-archived').waitFor();
assert.match(await page.locator('#da-title').innerText(),/已归档/);
await page.locator('[data-da-action="back-list"]').click();await row.waitFor();
await row.locator('[data-da-action="row-restore"]').click();await row.waitFor({state:'detached'});
await page.locator('#da-archive-filter').selectOption('current');await row.waitFor();
assert.equal(state.tasks.get('t0').status,'paused');
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,1);
assert.ok(state.requests.every(r=>!r.path.startsWith('/api/batch-tasks')));
assert.deepEqual(state.errors,[]);
});
test('detail is a full page and browser back restores the filtered task list',async t=>{
const {page,state}=await fixture(t);
await page.locator('#da-search').fill('隔离样例 t0');
await page.waitForFunction(()=>document.querySelectorAll('.da-list-item').length===1);
await page.locator('[data-da-action="details"]').click();await page.locator('#da-workspace').waitFor();
const root=await page.locator('#deep-assessments-root').boundingBox(),detail=await page.locator('#da-workspace').boundingBox();
assert.ok(Math.abs(detail.width-root.width)<2);assert.equal(await page.locator('dialog[open]').count(),0);
assert.equal(await page.locator('#da-list-view').isVisible(),false);
assert.equal(await page.locator('#da-guidance').isVisible(),false);
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
const canvas=await page.locator('#da-graph-canvas').boundingBox();assert.ok(canvas.width>1000&&canvas.height>=400);
await page.goBack();await page.locator('#da-list-view').waitFor();
assert.equal(await page.locator('#da-search').inputValue(),'隔离样例 t0');
await page.goForward();await page.locator('#da-workspace').waitFor();
await page.reload();await page.locator('#da-workspace').waitFor();
assert.match(page.url(),/assessment_id=t0/);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
assert.deepEqual(state.errors,[]);
});
test('graph preserves the viewport through polling, side panel resize and tab changes',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.graph={nodes:[{id:'goal',kind:'goal',title:task.name,state:'running',body:'',source:{}},...Array.from({length:12},(_,i)=>({id:'step:s'+i,step_id:'s'+i,kind:'step',title:'持续探索方向与很长的中文节点说明,完整内容在选中后展示 '+i,state:'pending',body:'Fixture detail',source:{}}))],edges:Array.from({length:12},(_,i)=>({source:i>=3?'step:s'+(i-3):'goal',target:'step:s'+i,relation:'depends_on'})),total:12,folded:0,has_more:false};
// A review/proof cycle must not flatten the entire graph into one column.
task.graph.edges.push({source:'step:s6',target:'step:s3',relation:'supports'});
await page.locator('[data-da-action="details"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
await page.locator('#da-graph-select option[value="step:s3"]').waitFor({state:'attached'});
const before=await page.locator('#da-graph-canvas').boundingBox();
const navigator=page.locator('.da-graph-minimap');await navigator.waitFor({state:'visible'});
const panBefore=await page.evaluate(()=>fixtureGraph.pan());await navigator.press('ArrowRight');
assert.equal((await page.evaluate(()=>fixtureGraph.pan())).x,panBefore.x-80);
await page.evaluate(()=>{fixtureGraph.zoom(.8);fixtureGraph.pan({x:70,y:40});});
const positions=await page.evaluate(()=>Object.fromEntries(fixtureGraph.nodes().map(n=>[n.id(),n.position()])));
assert.ok(new Set(Object.values(positions).map(p=>p.x)).size>2);
await page.locator('#da-graph-select').selectOption('step:s3');
await page.locator('#da-graph-node .da-node-heading h3').waitFor();
await page.waitForFunction(width=>document.getElementById('da-graph-canvas').clientWidth<width-200,before.width);
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.8);
await page.locator('[data-da-action="graph-details"]').click();
await page.waitForFunction(()=>document.getElementById('da-graph-node').getClientRects().length===0);
const expanded=await page.locator('#da-graph-canvas').boundingBox();assert.ok(expanded.width>=before.width-2);
task.graph.nodes.push({id:'fact:new',step_id:'s3',kind:'fact',state:'observed',title:'New evidence',body:'fixture',source:{}});task.graph.edges.push({source:'step:s3',target:'fact:new',relation:'produces'});task.graph.total++;
await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.8);
assert.deepEqual(await page.evaluate(()=>Object.fromEntries(fixtureGraph.nodes().filter(n=>n.id()!=='fact:new').map(n=>[n.id(),n.position()]))),positions);
const newPosition=await page.evaluate(()=>fixtureGraph.getElementById('fact:new').position());assert.ok(!Object.values(positions).some(p=>p.x===newPosition.x&&p.y===newPosition.y));
await page.locator('[data-da-action="tab"][data-tab="overview"]').click();await page.locator('.da-stats').waitFor();
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();await page.locator('#da-graph-select').waitFor();
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.8);
assert.equal(await page.locator('#da-graph-node').isVisible(),false);
await page.locator('[data-da-action="graph-fit"]').click();
assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'assessment-workspace-full.png'),fullPage:true});
await page.setViewportSize({width:390,height:844});
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'assessment-workspace-mobile.png'),fullPage:true});
});
test('long node details have an adjustable reader and keep their position through refreshes',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
await page.setViewportSize({width:1572,height:870});
const instruction=Array.from({length:45},(_,i)=>`${i+1}. 检查本地样例记录,保存观察结果并注明来源。这里是用于验证长文本阅读布局的内容,不会执行网络操作。`).join('\n\n');
task.name='长文本阅读示例';task.graph={nodes:[
{id:'goal',kind:'goal',title:'整理样例证据',state:'running',body:'整理本地样例证据并形成可核对记录。',source:{}},
{id:'step:read',kind:'step',step_id:'read',title:'核对样例记录与证据来源',state:'running',body:'已整理记录,正在核对原始回执。\n\nInstruction: '+instruction,source:{evidence:['receipt:sample'],asset_ids:Array.from({length:13},(_,i)=>'fixture-asset-00000000-0000-0000-'+i)}},
{id:'receipt:sample',kind:'receipt',step_id:'read',title:'本地样例回执',state:'completed',body:Array.from({length:120},(_,i)=>`record ${i}: example.test /fixture — verified fixture`).join('\n'),source:{tool:'fixture'}}
],edges:[{source:'goal',target:'step:read',relation:'plans'},{source:'step:read',target:'receipt:sample',relation:'executes'}],total:2,folded:0,has_more:false};
await page.locator('[data-da-action="details"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();await page.locator('[data-da-action="graph-view"][data-view="full"]').click();
await page.locator('#da-graph-select').selectOption('step:read');
await page.locator('.da-node-heading h3').waitFor();
const panel=page.locator('#da-graph-node'),content=panel.locator('.da-node-content'),bar=page.getByRole('separator');
assert.match(await panel.locator('.da-node-heading').innerText(),/核对样例记录/);
assert.deepEqual(await panel.locator('.da-node-section h4').allTextContents(),['结果摘要','执行说明']);
assert.equal(await panel.locator('.da-node-prose').nth(1).textContent(),instruction);
const bounds=await panel.boundingBox();assert.ok(bounds.width>=400,JSON.stringify(bounds));
const geometry=await content.evaluate(el=>({height:el.clientHeight,total:el.scrollHeight,font:parseFloat(getComputedStyle(el.querySelector('.da-node-prose')).fontSize),family:getComputedStyle(el.querySelector('.da-node-prose')).fontFamily}));
assert.ok(geometry.height>=200&&geometry.total>geometry.height,JSON.stringify(geometry));
assert.ok(geometry.font>=14);assert.doesNotMatch(geometry.family,/monospace/i);
assert.ok((await panel.locator('.da-node-actions').boundingBox()).height<100);
assert.equal(await panel.locator('.da-node-actions [data-da-action="intent-asset"]').count(),0);
assert.equal(await panel.locator('.da-node-links [data-da-action="intent-asset"]').count(),13);
await panel.locator('.da-node-links summary').click();
await content.evaluate(el=>el.scrollTop=480);
const scroll=await content.evaluate(el=>el.scrollTop);
await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await content.evaluate(el=>el.scrollTop),scroll);
assert.equal(await panel.locator('.da-node-links').getAttribute('open'),'');
await page.evaluate(()=>fixtureGraph.zoom(.75));
const separator=await bar.boundingBox();
await page.mouse.move(separator.x+separator.width/2,separator.y+40);await page.mouse.down();await page.mouse.move(separator.x-100,separator.y+40);await page.mouse.up();
assert.ok((await panel.boundingBox()).width>bounds.width+90);
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.75);
const dragged=(await panel.boundingBox()).width;
await bar.press('ArrowRight');assert.ok(Math.abs((await panel.boundingBox()).width-dragged+32)<2);
await bar.press('Home');assert.ok(Math.abs((await panel.boundingBox()).width-bounds.width)<2);
await content.evaluate(el=>el.scrollTop=0);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'node-reader-split.png'),fullPage:true});
await panel.getByRole('button',{name:'展开阅读',exact:true}).click();
assert.equal(await page.locator('#da-graph-canvas').isVisible(),false);
assert.ok((await panel.boundingBox()).width>1200);
await content.evaluate(el=>el.scrollTop=300);
await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await page.locator('#da-graph-canvas').isVisible(),false);
assert.equal(await content.evaluate(el=>el.scrollTop),300);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'node-reader-expanded.png'),fullPage:true});
await page.locator('#da-graph-select').selectOption('receipt:sample');
await panel.locator('.da-node-code').first().waitFor();
assert.equal(await content.evaluate(el=>el.scrollTop),0);
assert.match(await panel.locator('.da-node-code').first().textContent(),/record 119/);
await panel.getByRole('button',{name:'返回图',exact:true}).click();
assert.equal(await page.locator('#da-graph-canvas').isVisible(),true);
assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),.75);
await page.setViewportSize({width:390,height:844});
await panel.getByRole('button',{name:'展开阅读',exact:true}).click();
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
assert.equal(await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop),0);
assert.ok((await content.boundingBox()).height>200);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'node-reader-mobile.png'),fullPage:true});
await panel.getByRole('button',{name:'关闭节点详情',exact:true}).click();
assert.equal(await panel.isVisible(),false);assert.equal(await page.locator('#da-graph-canvas').isVisible(),true);
assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
});
test('asset search controls have room for focus and empty graphs explain the next step',async t=>{
const {page,state}=await fixture(t);
await page.locator('[data-da-action="details"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="assets"]').click();
await page.locator('#da-asset-query').waitFor();
assert.match(await page.locator('#da-asset-canvas').innerText(),/本次测评尚未关联资产/);
assert.equal(await page.locator('#da-asset-select').isDisabled(),true);
for(const width of [1440,1024,390]){
await page.setViewportSize({width,height:width===390?844:1000});await page.locator('#da-asset-query').focus();
const geometry=await page.evaluate(()=>{
const rect=id=>document.querySelector(id).getBoundingClientRect();
const search=rect('#da-asset-query'),toolbar=rect('.da-asset-toolbar'),navigation=rect('.da-graph-navigation'),scroll=rect('.da-detail-scroll');
return {gap:navigation.top-toolbar.bottom,inset:search.left-scroll.left,right:scroll.right-search.right,height:search.height,overflow:document.documentElement.scrollWidth-innerWidth};
});
assert.ok(geometry.gap>=10,JSON.stringify(geometry));assert.ok(geometry.inset>=4&&geometry.right>=4,JSON.stringify(geometry));
assert.ok(geometry.height>=32);assert.ok(geometry.overflow<=1);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,`asset-search-${width}.png`),fullPage:true});
}
await page.setViewportSize({width:1440,height:1000});
state.sharedAssets=[{id:'fixture-service',host:'https://app.example.test',port:443,protocol:'https',title:'样例应用',server:'Fixture server',status:'active'}];
await page.locator('[data-da-action="asset-browse"]').click();
await page.locator('#da-asset-select').selectOption('asset:fixture-service');
await page.locator('.da-node-properties').waitFor();
assert.match(await page.locator('.da-node-properties').innerText(),/地址\nhttps:\/\/app.example.test/);
assert.match(await page.locator('.da-node-properties').innerText(),/端口\n443/);
assert.equal(await page.locator('#da-asset-detail .da-node-source').getAttribute('open'),null);
assert.ok((await page.locator('#da-asset-detail').boundingBox()).width>=400);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'asset-reader.png'),fullPage:true});
assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
});
test('large cyclic evidence graphs keep lineage and focus a selected node at readable scale',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
await page.setViewportSize({width:1572,height:870});
task.name='探索链路布局回归';
const nodes=[{id:'goal',kind:'goal',title:'核对样例记录',body:'本地界面夹具',state:'running',source:{}}],edges=[];
for(let i=0;i<12;i++){
nodes.push({id:'step:'+i,kind:'step',step_id:String(i),title:'核对方向 '+i,state:i===5?'running':'completed',body:'样例记录核对结果。\n\nInstruction: 核对已有记录与证据来源,不发起网络操作。',source:{asset_ids:Array.from({length:13},(_,j)=>'fixture-asset-'+j)}});
nodes.push({id:'fact:'+i,kind:'fact',step_id:String(i),title:'样例观察 '+i,state:'observed',body:'记录中的直接观察。',source:{}});
nodes.push({id:'observation:'+i,kind:'observation',step_id:String(i),title:'阶段记录 '+i,state:'note',body:'阶段记录',source:{}});
edges.push({source:i?'step:'+(i-1):'goal',target:'step:'+i,relation:i?'depends_on':'plans'},{source:'step:'+i,target:'fact:'+i,relation:'produces'},{source:'fact:'+i,target:'step:0',relation:'informs'},{source:'step:'+i,target:'observation:'+i,relation:'records'});
for(let j=0;j<3;j++){
const id='receipt:'+i+':'+j;nodes.push({id,kind:'receipt',step_id:String(i),title:'样例回执 '+j,state:'completed',body:'fixture output',source:{}});
edges.push({source:'step:'+i,target:id,relation:'executes'},{source:id,target:'fact:'+i,relation:'supports'});
}
}
task.graph={nodes,edges,total:nodes.length-1,folded:0,has_more:false};
await page.locator('[data-da-action="details"][data-id="t0"]').click();
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
await page.locator('#da-graph-select option[value="step:5"]').waitFor({state:'attached'});
await page.locator('[data-da-action="graph-view"][data-view="full"]').click();await page.waitForFunction(()=>fixtureGraph.nodes().length===73);
const graphState=await page.evaluate(()=>({nodes:fixtureGraph.nodes().length,edges:fixtureGraph.edges().length,columns:new Set(fixtureGraph.nodes().map(n=>n.position().x)).size}));
assert.equal(graphState.nodes,nodes.length);assert.equal(graphState.edges,edges.length);assert.ok(graphState.columns>5);
await page.locator('#da-graph-select').selectOption('step:5');
await page.locator('.da-node-content').waitFor();
await page.waitForFunction(()=>fixtureGraph.zoom()>=.65);
assert.ok((await page.locator('.da-node-content').boundingBox()).height>=200);
const pos=await page.evaluate(()=>({node:fixtureGraph.getElementById('step:5').renderedPosition(),width:fixtureGraph.width(),height:fixtureGraph.height()}));
assert.ok(pos.node.x>=0&&pos.node.x<=pos.width&&pos.node.y>=0&&pos.node.y<=pos.height);
const zoom=await page.evaluate(()=>fixtureGraph.zoom());
await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.evaluate(()=>fixtureGraph.zoom()),zoom);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'large-evidence-graph.png'),fullPage:true});
await page.locator('[data-da-action="tab"][data-tab="assets"]').click();await page.locator('#da-asset-select').waitFor();
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();await page.locator('#da-graph-select').waitFor();
assert.equal(await page.locator('#da-graph-node').isVisible(),false,'switching graphs must not expose an empty inherited panel');
assert.deepEqual(state.errors,[]);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
});
test('unknown results remain reviewable without automatically starting the assessment',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.status='needs_review';task.auto_resume=true;
task.steps=[{id:'old-unknown',title:'较早的待核对步骤',status:'uncertain',instruction:'核对本地样例回执',conversation_id:'fixture-one'},...Array.from({length:65},(_,i)=>({id:'done-'+i,title:'已完成样例 '+i,status:'completed'})),{id:'cleanup',title:'等待资源核对的步骤',status:'cleanup_unconfirmed',instruction:'核对执行是否结束',conversation_id:'fixture-two'}];
await page.evaluate(()=>DeepAssessments.refresh());
const row=page.locator('.da-list-item[data-id="t0"]');
assert.equal(await row.locator('[data-da-action="row-start"]').isEnabled(),true);
assert.equal(await row.locator('[data-da-action="row-pause"]').isEnabled(),false);
assert.match(await row.locator('[data-da-action="row-pause"]').getAttribute('title'),/当前未在执行/);
await row.getByRole('button',{name:'处理待核对',exact:true}).click();
await page.waitForFunction(()=>document.querySelectorAll('#da-body .da-step').length===2);
assert.match(page.url(),/step_status=needs_review/);
assert.equal(await page.locator('#da-intent-status').inputValue(),'needs_review');
assert.match(await page.locator('#da-recovery-notice').innerText(),/未派发新步骤/);
assert.equal(await page.locator('.da-step[open]').count(),2);
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
await page.reload();await page.locator('.da-step[data-step="old-unknown"]').waitFor();
assert.equal(await page.locator('.da-step').count(),2);
await page.locator('[data-da-action="tab"][data-tab="overview"]').click();
await page.locator('.da-stats').waitFor();
assert.match(await page.locator('.da-stats').innerText(),/待核对/);
assert.doesNotMatch(await page.locator('.da-stats').innerText(),/持续执行/);
assert.match(await page.locator('#da-body').innerText(),/打开页面不会启动任务/);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'review-overview.png'),fullPage:true});
await page.locator('#da-recovery-notice [data-da-action="review"]').click();await page.locator('.da-step[data-step="old-unknown"]').waitFor();
await page.locator('.da-step[data-step="old-unknown"]').getByRole('button',{name:'查看回执',exact:true}).click();
await page.waitForFunction(()=>location.hash.includes('tab=evidence'));
await page.locator('.da-source-banner').waitFor();
assert.ok(state.requests.some(r=>r.path.endsWith('/receipts')&&r.query.step_id==='old-unknown'));
await page.locator('#da-recovery-notice [data-da-action="review"]').click();await page.locator('.da-step[data-step="old-unknown"]').waitFor();
page.removeAllListeners('dialog');page.once('dialog',d=>d.dismiss());
await page.locator('.da-step[data-step="old-unknown"] [data-da-action="reconcile"]').click();
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
page.on('dialog',d=>d.accept());
await page.locator('.da-step[data-step="old-unknown"] [data-da-action="reconcile"]').click();
await page.waitForFunction(()=>document.querySelectorAll('.da-step').length===1);
assert.equal(task.status,'needs_review');assert.equal(await page.locator('#da-controls [data-da-action="start"]').isEnabled(),true);
await page.setViewportSize({width:390,height:844});
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'review-mobile.png'),fullPage:true});
await page.locator('.da-step[data-step="cleanup"] [data-da-action="reconcile"]').click();
await page.waitForFunction(()=>document.querySelector('#da-controls [data-da-action="start"]')?.disabled===false);
assert.equal(task.status,'paused');assert.equal(await page.locator('#da-recovery-notice').isVisible(),false);
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,0);
assert.equal(state.requests.filter(r=>r.method==='POST').length,2);
assert.deepEqual(state.errors,[]);
});
test('start resumes confirmed cancellations and pause also stops scheduled retries',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.status='needs_review';task.known_cancellation=true;task.steps=[{id:'one',status:'uncertain',title:'已确认取消的样例'}];
await page.evaluate(()=>DeepAssessments.refresh());
const row=page.locator('.da-list-item[data-id="t0"]');
await row.locator('[data-da-action="row-start"]').click();
await page.waitForFunction(()=>document.querySelector('.da-list-item[data-id="t0"] [data-da-action="row-pause"]').disabled===false);
assert.equal(task.status,'running');assert.equal(task.steps[0].status,'pending');
await row.locator('[data-da-action="row-pause"]').click();
await page.waitForFunction(()=>document.querySelector('.da-list-item[data-id="t0"] [data-da-action="row-start"]').disabled===false);
assert.equal(task.status,'paused');
for(const status of ['recovering','waiting_retry','waiting_progress']){
task.status=status;await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await row.locator('[data-da-action="row-pause"]').isEnabled(),true);
await row.locator('[data-da-action="row-pause"]').click();await page.waitForFunction(()=>document.querySelector('.da-list-item[data-id="t0"] .da-paused'));
assert.equal(task.status,'paused');
}
await row.locator('[data-da-action="details"]').click();await page.locator('#da-controls [data-da-action="start"]').waitFor();
assert.equal(await page.locator('#da-controls [data-da-action="start"]').isEnabled(),true);
assert.equal(await page.locator('#da-controls [data-da-action="pause"]').isEnabled(),false);
await page.reload();await page.locator('#da-controls [data-da-action="start"]').waitFor();
assert.equal(task.status,'paused');assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,1);
assert.deepEqual(state.errors,[]);
});
test('live overview and intent controls keep sibling work and scoped guidance independent',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.name='持续测评工作台样例';task.status='running';task.steps=[{id:'one',title:'核对应用入口',status:'running',instruction:'本地样例步骤',priority:100,asset_ids:['asset-one'],conversation_id:'conv-one'},{id:'two',title:'整理服务证据',status:'running',instruction:'另一条本地样例步骤',priority:100,asset_ids:['asset-two'],conversation_id:'conv-two'}];
task.runtime={sessions:{two:{stage:'compacting',updated_at:new Date().toISOString()}},tools:[{id:'exec-one',step_id:'one',tool:'fixture_read',status:'running',started_at:new Date(Date.now()-90000).toISOString(),output_bytes:2048}],recent:[{id:1,step_id:'one',kind:'checkpoint',message:'已保存样例观察,等待原始回执。',created_at:new Date().toISOString()}],facts:3,findings:1,findings_visible:true,asset_names:{'asset-one':'app.example.test','asset-two':'service.example.test'}};
await page.locator('[data-da-action="details"][data-id="t0"]').click();
await page.locator('.da-live-board').waitFor();
assert.match(await page.locator('.da-live-board').innerText(),/fixture_read/);assert.match(await page.locator('.da-live-board').innerText(),/app.example.test/);
assert.equal(await page.locator('.da-live-intent').count(),2);assert.match(await page.locator('.da-live-intent').nth(1).innerText(),/Pi 正在压缩上下文/);assert.equal(state.requests.filter(r=>r.method==='POST').length,0);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'workbench-live-overview.png'),fullPage:true});
task.runtime.recent=Array.from({length:8},(_,i)=>({id:i+1,step_id:'one',kind:'checkpoint',message:'较早的进展记录。'.repeat(20),created_at:new Date().toISOString()}));await page.evaluate(()=>DeepAssessments.refresh());
await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop=240);
const reading=await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop);
task.runtime.recent.unshift({id:9,step_id:'one',kind:'checkpoint',message:'NEW_PROGRESS_FOR_READER',created_at:new Date().toISOString()});await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await page.locator('#da-overview-updates').isVisible(),true);assert.doesNotMatch(await page.locator('.da-live-events').innerText(),/NEW_PROGRESS_FOR_READER/);assert.equal(await page.locator('.da-detail-scroll').evaluate(el=>el.scrollTop),reading);
await page.locator('#da-overview-updates').click();assert.match(await page.locator('.da-live-events').innerText(),/NEW_PROGRESS_FOR_READER/);
await page.locator('.da-live-intent').first().getByRole('button',{name:'查看此意图',exact:true}).click();
const step=page.locator('.da-step[data-step="one"]');await step.waitFor();
await step.getByRole('button',{name:'暂停此意图',exact:true}).click();await step.getByRole('button',{name:'继续此意图',exact:true}).waitFor();
assert.equal(task.status,'running');assert.equal(task.steps[0].status,'paused');assert.equal(task.steps[1].status,'running');
await step.getByRole('combobox',{name:'意图优先级',exact:true}).selectOption('10');await page.waitForFunction(()=>document.querySelector('[data-da-intent-priority="one"]').value==='10');
await step.locator('details[data-da-detail="intent-guidance:one"] > summary').click();
let input=step.getByRole('textbox',{name:'给此意图补充方向',exact:true});await input.fill('只调整这一条意图的方向');
await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await input.inputValue(),'只调整这一条意图的方向');
await input.evaluate(el=>{el.dataset.fixture='same';el.focus();el.setSelectionRange(3,3);});await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await input.getAttribute('data-fixture'),'same');
task.steps[1].summary='Sibling progress changed';await page.evaluate(()=>DeepAssessments.refresh());
assert.equal(await input.inputValue(),'只调整这一条意图的方向');assert.equal(await input.evaluate(el=>el===document.activeElement&&el.selectionStart===3),true);
await step.getByRole('button',{name:'提交给此意图',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-da-intent-guidance="one"] textarea').value==='');
assert.deepEqual(task.steps[0].guidance,['只调整这一条意图的方向']);assert.equal(task.steps[1].guidance,undefined);assert.deepEqual(task.guidance||[],[]);
const sent=state.requests.find(r=>r.path.endsWith('/control/intent-guidance'));assert.equal(sent.body.step_id,'one');
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')||r.path.endsWith('/control/pause')).length,0);
await step.getByRole('button',{name:'继续此意图',exact:true}).click();await step.getByRole('button',{name:'暂停此意图',exact:true}).waitFor();
assert.equal(task.steps[0].status,'pending');assert.equal(task.steps[1].status,'running');
await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
await page.locator('#page-deep-assessments').evaluate(async el=>{await Promise.all(el.getAnimations({subtree:true}).filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})));});
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'workbench-intent-mobile.png'),fullPage:true});
assert.deepEqual(state.errors,[]);
});
test('main graph exposes cross-page references and drills into original execution records',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.graph={nodes:[{id:'goal',kind:'goal',title:'样例目标',body:'goal',source:{}},{id:'step:one',kind:'step',step_id:'one',title:'当前意图',body:'current intent',source:{}},{id:'step:outside',kind:'step',step_id:'outside',title:'其他页面的上游意图',body:'upstream original',boundary:true,source:{}},{id:'receipt:one',kind:'receipt',step_id:'one',title:'原始执行回执',body:'original fixture output',source:{}}],edges:[{source:'goal',target:'step:outside',relation:'plans'},{source:'step:outside',target:'step:one',relation:'depends_on'},{source:'step:one',target:'receipt:one',relation:'executes'}],total:2,boundary_total:1,folded:0,has_more:false};
await page.locator('[data-da-action="details"][data-id="t0"]').click();await page.getByRole('tab',{name:'探索图',exact:true}).click();
await page.locator('#da-graph-select').selectOption('step:one');await page.locator('.da-node-relations').first().waitFor();
assert.equal(await page.evaluate(()=>fixtureGraph.getElementById('receipt:one').length),0);
assert.match(await page.locator('#da-graph-meta').innerText(),/跨页引用/);
await page.locator('#da-graph-node [data-da-action="graph-open"][data-node="step:outside"]').click();
await page.waitForFunction(()=>location.hash.includes('graph_scope=step%3Aoutside'));
await page.waitForFunction(()=>document.querySelector('#da-graph-node').textContent.includes('upstream original'));
await page.locator('#da-graph-select').selectOption('step:one');
await page.locator('#da-graph-node [data-da-action="graph-open"][data-node="receipt:one"]').click();
await page.waitForFunction(()=>document.querySelector('#da-graph-node').textContent.includes('original fixture output'));
assert.match(page.url(),/graph_view=full/);assert.equal(await page.evaluate(()=>fixtureGraph.getElementById('receipt:one').length),1);
await page.reload();await page.locator('#da-graph-select').waitFor();
assert.ok(state.requests.some(r=>r.path.endsWith('/graph')&&r.query.scope==='receipt:one'&&r.query.view==='full'));
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.deepEqual(state.errors,[]);
});
test('stopped assessments can acknowledge reviews without restarting and explicitly continue later',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='cancelled';task.steps=[{id:'one',title:'待核对样例一',status:'uncertain',conversation_id:'original-one',attempts:2},{id:'two',title:'待核对样例二',status:'cleanup_unconfirmed',conversation_id:'original-two',attempts:1}];
await page.evaluate(()=>DeepAssessments.refresh());const row=page.locator('.da-list-item[data-id="t0"]');
assert.equal(await row.getByRole('button',{name:'继续测评',exact:true}).isEnabled(),true);assert.equal(await row.locator('[data-da-action="row-pause"]').isEnabled(),false);assert.equal(await row.locator('[data-da-action="row-archive"]').isEnabled(),false);
await row.getByRole('button',{name:'处理待核对',exact:true}).click();await page.locator('.da-step[data-step="one"]').waitFor();
page.removeAllListeners('dialog');page.on('dialog',async dialog=>{task.revision++;await dialog.accept();});
await page.locator('.da-step[data-step="one"] [data-da-action="reconcile"]').click();await page.locator('.da-step[data-step="one"]').waitFor({state:'detached'});
assert.equal(task.status,'cancelled');assert.equal(task.steps[0].status,'reconciled');assert.equal(await page.locator('.da-step').count(),1);
await page.locator('.da-step[data-step="two"] [data-da-action="reconcile"]').click();await page.waitForFunction(()=>document.querySelectorAll('.da-step').length===0);
assert.equal(task.status,'cancelled');assert.equal(await page.locator('#da-recovery-notice').isVisible(),false);assert.match(await page.locator('#da-body').innerText(),/没有待核对步骤/);
assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')||r.path.endsWith('/control/continue-stopped')).length,0);
await page.reload();await page.locator('#da-controls [data-da-action="continue-stopped"]').waitFor();assert.equal(await page.locator('.da-step').count(),0);
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'stopped-review-cleared.png'),fullPage:true});
await page.locator('#da-controls [data-da-action="continue-stopped"]').click();await page.waitForFunction(()=>document.querySelector('#da-controls [data-da-action="pause"]')?.disabled===false);
assert.equal(task.status,'running');assert.equal(state.requests.filter(r=>r.path.endsWith('/control/continue-stopped')).length,1);assert.deepEqual(state.errors,[]);
});
test('review preflight refuses to acknowledge a newer execution attempt',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='needs_review';task.steps=[{id:'one',title:'原始待核对步骤',status:'uncertain',attempts:1,conversation_id:'original-session'}];
await page.evaluate(()=>DeepAssessments.refresh());await page.locator('.da-list-item[data-id="t0"] [data-da-action="review"]').click();await page.locator('.da-step[data-step="one"]').waitFor();
page.removeAllListeners('dialog');page.on('dialog',async dialog=>{task.steps[0].attempts=2;task.revision++;await dialog.accept();});
await page.locator('[data-da-action="reconcile"]').click();await page.waitForFunction(()=>document.querySelector('#da-detail-notice').textContent.includes('新的执行'));
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.equal(task.steps[0].status,'uncertain');assert.deepEqual(state.errors,[]);
});
test('navigation during a control preflight cannot redirect it to another assessment',async t=>{
const {page,state}=await fixture(t);state.tasks.get('t0').status='cancelled';
await page.evaluate(()=>DeepAssessments.refresh());await page.locator('.da-list-item[data-id="t0"] [data-da-action="details"]').click();
await page.locator('#da-controls [data-da-action="continue-stopped"]').waitFor();
let release,started;const gate=new Promise(r=>release=r),reached=new Promise(r=>started=r);
await page.route('**/api/deep-assessments/t0?step_limit=1',async route=>{started();await gate;await route.continue();});
await page.locator('#da-controls [data-da-action="continue-stopped"]').click();await reached;
await page.evaluate(()=>{location.hash='#deep-assessments?assessment_id=t1&tab=overview';DeepAssessments.fromLocation();});
release();await page.waitForFunction(()=>document.querySelector('#da-title').textContent.includes('t1'));
assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.equal(state.tasks.get('t0').status,'cancelled');assert.equal(state.tasks.get('t1').status,'draft');assert.deepEqual(state.errors,[]);
});
test('a control response cannot overwrite a different assessment opened while waiting',async t=>{
const {page,state}=await fixture(t);await page.locator('.da-list-item[data-id="t0"] [data-da-action="details"]').click();
let release,started;const gate=new Promise(r=>release=r),reached=new Promise(r=>started=r);
await page.route('**/api/deep-assessments/t0/control/start?*',async route=>{const response=await route.fetch();started();await gate;await route.fulfill({response});});
await page.locator('#da-controls [data-da-action="start"]').click();await reached;
await page.evaluate(()=>{location.hash='#deep-assessments?assessment_id=t1&tab=overview';DeepAssessments.fromLocation();});
release();await page.waitForFunction(()=>document.querySelector('#da-title').textContent.includes('t1'));
assert.equal(state.tasks.get('t0').status,'running');assert.equal(state.tasks.get('t1').status,'draft');assert.equal(state.requests.filter(r=>r.method==='POST').length,1);assert.deepEqual(state.errors,[]);
});
test('reviewing the last item on a later page returns to the remaining review items',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='cancelled';task.steps=Array.from({length:51},(_,i)=>({id:'review-'+i,title:'待核对 '+i,status:'uncertain'}));
await page.evaluate(()=>DeepAssessments.refresh());await page.locator('.da-list-item[data-id="t0"] [data-da-action="review"]').click();
await page.locator('[data-da-action="step-next"]').click();await page.locator('.da-step[data-step="review-50"]').waitFor();
await page.locator('.da-step[data-step="review-50"] [data-da-action="reconcile"]').click();
await page.locator('.da-step[data-step="review-0"]').waitFor();assert.equal(await page.locator('.da-step').count(),50);assert.equal(task.status,'cancelled');assert.equal(await page.locator('[data-da-action="step-previous"]').count(),0);assert.deepEqual(state.errors,[]);
});
test('overview statistics open complete matching queues and readable activity without writes',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='paused';task.rounds=4;task.tokens_used=1234;task.metrics={session:{step_id:'running',tokens:1234}};
const statuses=['running','pending','pausing','paused','completed','blocked','failed','uncertain','cleanup_unconfirmed','interrupted','retired','reconciled'];
task.steps=statuses.map(status=>({id:status,title:'样例 '+status,status,conversation_id:'session-'+status}));task.events=[{id:1,kind:'planning',message:'规划记录样例',created_at:new Date().toISOString()}];
await page.locator('[data-da-action="details"][data-id="t0"]').click();
const overview=async()=>{await page.locator('#da-tabs [data-tab="overview"]').click();await page.locator('.da-live-board').waitFor();};
for(const [filter,expected] of [['',statuses],...statuses.filter(s=>!['uncertain','cleanup_unconfirmed'].includes(s)).map(s=>[s,[s]]),['needs_review',['uncertain','cleanup_unconfirmed']]]){
await overview();const count=page.locator('.da-live-counts [data-status="'+filter+'"]');assert.match(await count.innerText(),new RegExp(' '+expected.length+'$'));await count.click();
await page.waitForFunction(f=>document.querySelector('#da-intent-status')?.value===f,filter);
assert.deepEqual((await page.locator('.da-step').evaluateAll(rows=>rows.map(r=>r.dataset.step))).sort(),[...expected].sort());
await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.locator('#da-intent-status').inputValue(),filter);
}
await page.reload();await page.locator('#da-intent-status').waitFor();assert.equal(await page.locator('#da-intent-status').inputValue(),'needs_review');assert.equal(await page.locator('.da-step').count(),2);
await overview();await page.locator('.da-stats [data-tab="quality"]').focus();await page.keyboard.press('Enter');await page.locator('.da-table-wrap').waitFor();assert.match(await page.locator('#da-body').innerText(),/1,234/);
for(const index of [0,2]){await overview();await page.locator('.da-stats > button').nth(index).click();await page.locator('.da-event').waitFor();assert.match(await page.locator('.da-event').innerText(),/规划记录样例/);}
await overview();await page.locator('.da-live-section-title button').click();await page.locator('.da-event').waitFor();
assert.ok(state.requests.every(r=>r.method==='GET'));assert.deepEqual(state.errors,[]);
});
test('overview totals reset facts and findings filters, paging and previous source context',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='running';task.steps=[{id:'one',title:'当前意图样例',status:'running',conversation_id:'conv-one'}];
task.facts=Array.from({length:41},(_,i)=>({id:'f'+i,confidence:i<21?'observed':'inferred',summary:'事实样例 '+i,body:'原始观察',step_id:'one',evidence:[]}));
task.findings=Array.from({length:21},(_,i)=>({id:'finding-'+i,title:'关联样例 '+i,severity:'info',status:'open',assessment_step_id:'one'}));
task.receipts=[{id:'receipt-one',step_id:'one',tool:'fixture-read',status:'completed',result:'原始回执样例'}];task.runtime={facts:41,findings:21,findings_visible:true,asset_names:{'asset-one':'fixture.example.test'},recent:[{id:1,step_id:'one',kind:'checkpoint',message:'记录样例',created_at:new Date().toISOString()}]};
task.steps[0].asset_ids=['asset-one'];state.sharedAssets=[{id:'asset-one',host:'fixture.example.test'}];state.linkedAssets.set('t0',['asset-one']);
await page.evaluate(()=>{const original=window.hasPermission;window.hasPermission=p=>p==='vulnerability:read'||original(p);});
await page.locator('[data-da-action="details"][data-id="t0"]').click();
const overview=async()=>{await page.locator('#da-tabs [data-tab="overview"]').click();await page.locator('.da-live-board').waitFor();};
const facts=()=>page.locator('.da-live-counts [data-tab="facts"]');
await facts().click();await page.locator('[data-da-action="fact-next"]').click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='事实样例 20');
await overview();await facts().click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='事实样例 0');
await page.locator('[data-da-action="fact-filter"][data-confidence="inferred"]').click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='事实样例 21');
await overview();await facts().click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='事实样例 0');assert.equal(await page.locator('[data-da-action="fact-filter"][aria-pressed="true"]').getAttribute('data-confidence'),'');
await overview();await page.locator('.da-live-counts [data-tab="findings"]').click();await page.locator('[data-da-action="next-findings"]').click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='关联样例 20');
await overview();await page.locator('.da-live-counts [data-tab="findings"]').click();await page.waitForFunction(()=>document.querySelector('.da-finding h4')?.textContent==='关联样例 0');
await page.locator('[data-da-action="finding-evidence"]').first().click();await page.locator('.da-source-banner').waitFor();await overview();
await page.locator('.da-live-counts [data-status="running"]').click();await page.locator('.da-step').waitFor();assert.equal(await page.locator('.da-source-banner').count(),0);assert.doesNotMatch(page.url(),/vulnerability_id|step_id=/);
await overview();await page.locator('.da-live-intent [data-da-action="fact-proof"]').click();await page.locator('.da-step[data-step="receipt-one"]').waitFor();assert.match(page.url(),/step_id=one/);
await overview();await page.evaluate(()=>DeepAssessments.refresh());await page.locator('.da-live-intent [data-da-action="show-step"]').click();await page.locator('.da-step[data-step="one"][open]').waitFor();
await overview();await page.locator('.da-live-events [data-da-action="show-step"]').click();await page.locator('.da-step[data-step="one"][open]').waitFor();
await overview();await page.locator('.da-live-intent [data-da-action="intent-asset"]').click();await page.locator('#da-asset-select').waitFor();assert.equal(await page.locator('#da-asset-select').inputValue(),'asset:asset-one');assert.match(await page.locator('#da-asset-detail').innerText(),/fixture.example.test/);
task.findings=[];task.runtime.findings=0;await overview();await page.locator('.da-live-counts [data-tab="findings"]').click();await page.waitForFunction(()=>document.querySelector('#da-body').textContent.includes('暂未登记漏洞'));assert.equal(await page.locator('.da-finding').count(),0);
await overview();await page.locator('.da-live-intent [data-da-action="conversation"]').click();assert.equal(await page.evaluate(()=>window.visitedConversation),'conv-one');
assert.ok(state.requests.every(r=>r.method==='GET'));assert.deepEqual(state.errors,[]);
});
test('overview links remain usable for readers and empty lists explain the selected filter',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='paused';task.steps=[{id:'one',title:'只读样例',status:'uncertain',conversation_id:'private-session',asset_ids:['private-asset']}];task.runtime={intents:task.steps,findings_visible:true,asset_names:{'private-asset':'private.example.test'}};
await page.evaluate(()=>{window.hasPermission=p=>p==='assessments:read';});
await page.locator('[data-da-action="details"][data-id="t0"]').click();await page.locator('.da-live-board').waitFor();
assert.equal(await page.locator('.da-live-counts [data-tab="findings"]').count(),0);assert.equal(await page.locator('.da-live-intent [data-da-action="conversation"],.da-live-intent [data-da-action="intent-asset"]').count(),0);
await page.locator('.da-live-counts [data-status="failed"]').click();await page.waitForFunction(()=>document.querySelector('#da-intent-status')?.value==='failed');assert.match(await page.locator('#da-body').innerText(),/没有符合当前筛选条件/);
await page.locator('#da-tabs [data-tab="overview"]').click();await page.locator('.da-live-counts [data-tab="facts"]').click();await page.locator('[data-da-action="fact-filter"]').first().waitFor();assert.match(await page.locator('#da-body').innerText(),/暂无记录/);
await page.locator('#da-tabs [data-tab="overview"]').click();await page.locator('.da-live-board').waitFor();await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
await page.locator('#page-deep-assessments').evaluate(async el=>{await Promise.all(el.getAnimations({subtree:true}).filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})));});
for(const card of await page.locator('.da-stats > button').all()){const label=await card.locator('small').first().boundingBox(),value=await card.locator('strong').boundingBox(),link=await card.locator('.da-stat-link').boundingBox();assert.ok(label.y+label.height<=value.y+1&&value.y+value.height<=link.y+1);}
if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'overview-stat-links-mobile.png'),fullPage:true});
assert.ok(state.requests.every(r=>r.method==='GET'));assert.deepEqual(state.errors,[]);
});
test('assessment-level blocking stays visible when there are no blocked intents',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');
task.status='blocked';task.summary='收到补充方向';task.steps=[{id:'done',title:'已完成样例',status:'completed'},{id:'pending',title:'待执行样例',status:'pending'}];
const cause='规划失败: Pi worker exited without a result: invalid Pi protocol JSON: unexpected end of JSON input <script>window.injected=1</script>';
task.runtime={blocker:{id:1,kind:'blocked',message:cause,created_at:new Date().toISOString()},recent:[{id:2,kind:'step_result',message:'context canceled',created_at:new Date().toISOString()}]};
task.events=[task.runtime.blocker,...task.runtime.recent];
await page.locator('[data-da-action="details"][data-id="t0"]').click();await page.locator('#da-task-blocker').waitFor();
assert.match(await page.locator('#da-task-blocker').innerText(),/规划失败: Pi worker/);assert.equal(await page.locator('#da-task-blocker script').count(),0);assert.equal(await page.evaluate(()=>window.injected),undefined);
const blocked=page.locator('.da-live-counts [data-status="blocked"]');assert.equal(await blocked.innerText(),'受阻意图 0');await blocked.click();await page.locator('#da-intent-status').waitFor();
assert.equal(await page.locator('.da-step').count(),0);assert.match(await page.locator('#da-body').innerText(),/整条测评的原因见上方/);assert.match(await page.locator('#da-task-blocker').innerText(),/unexpected end of JSON input/);
await page.evaluate(()=>{document.querySelector('#da-task-blocker pre').dataset.fixture='retained';});await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.locator('#da-task-blocker pre').getAttribute('data-fixture'),'retained');
await page.locator('#da-title [data-da-action="blocked-reason"]').click();assert.equal(await page.locator('#da-task-blocker').evaluate(el=>document.activeElement===el),true);
await page.locator('#da-task-blocker [data-tab="activity"]').click();await page.locator('.da-event').first().waitFor();assert.match(page.url(),/tab=activity/);assert.match(await page.locator('#da-task-blocker').innerText(),/规划失败/);
await page.reload();await page.locator('#da-task-blocker').waitFor();assert.match(await page.locator('#da-task-blocker').innerText(),/规划失败/);
await page.setViewportSize({width:390,height:844});assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1));
if(process.env.CSAI_SCREENSHOT_DIR){await page.locator('#page-deep-assessments').evaluate(async el=>{await Promise.all(el.getAnimations({subtree:true}).filter(a=>a.effect?.getComputedTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})));});await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'task-blocker-mobile.png'),fullPage:true});}
task.status='running';task.revision++;await page.evaluate(()=>DeepAssessments.refresh());assert.equal(await page.locator('#da-task-blocker').isVisible(),false);
assert.ok(state.requests.every(r=>r.method==='GET'));assert.deepEqual(state.errors,[]);
});
test('older blocked assessments explain the saved summary without runtime diagnostics',async t=>{
const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='blocked';task.summary='模型渠道不可用';
await page.locator('[data-da-action="details"][data-id="t0"]').click();await page.locator('#da-task-blocker').waitFor();assert.match(await page.locator('#da-task-blocker').innerText(),/模型渠道不可用/);
assert.ok(state.requests.every(r=>r.method==='GET'));assert.deepEqual(state.errors,[]);
});

View File

@ -1,71 +0,0 @@
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { chromium } = require('playwright');
const root = path.join(__dirname, '../..');
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
const template = read('web/templates/index.html');
function div(id) {
const start = template.indexOf(`<div id="${id}"`);
if (start < 0) throw new Error(`missing template region ${id}`);
const tags = /<\/?div\b[^>]*>/g; tags.lastIndex = start;
let depth = 0, match;
while ((match = tags.exec(template))) { depth += match[0].startsWith('</') ? -1 : 1; if (!depth) return template.slice(start, tags.lastIndex); }
throw new Error(`unclosed region ${id}`);
}
function queue(id = 'q1') {
return { id, title: '批量样例', status: 'pending', role: '', agentMode: 'single', hitlPolicy: '', scheduleMode: 'manual', scheduleEnabled: true, concurrency: 1, createdAt: new Date().toISOString(), currentIndex: 0, tasks: [{ id: 'b1', message: 'first local task', status: 'pending', conversationId: 'batch-conversation' }, { id: 'b2', message: 'second local task', status: 'pending' }] };
}
async function fixture(t) {
const state = { queues: new Map([['q1', queue()]]), requests: [], hook: null, confirm: true, pageErrors: [] };
const scripts = [...template.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["'][^>]*><\/script>/g)].filter(m => /^\/static\/js\/(router|auth|modal|tasks|rbac-guards)\.js(?:\?|$)/.test(m[1])).map(m => m[0]).join('');
const styles = [...template.matchAll(/<link\b[^>]*\bhref=["']([^"']+)["'][^>]*>/g)].filter(m => /^\/static\/css\/(style|mobile)\.css(?:\?|$)/.test(m[1])).map(m => m[0]).join('');
const locale = JSON.stringify(JSON.parse(read('web/static/i18n/zh-CN.json'))).replaceAll('<', '\\u003c');
const html = `<!doctype html><html><head><meta charset="UTF-8">${styles}</head><body><div class="container"><main class="main-layout"><section class="content-area">${div('page-tasks')}<div class="page" id="page-dashboard"><button onclick="switchPage('tasks')">Back to tasks</button></div><div class="page" id="page-chat"></div></section></main></div>${div('batch-import-modal')}${div('batch-queue-detail-modal')}${div('add-batch-task-modal')}<script>window.t=(key,opts={})=>{let v=key.split('.').reduce((o,k)=>o&&o[k],${locale});return String(v||key).replace(/{{(\\w+)}}/g,(_,k)=>String(opts[k]??''))};window.loadRoles=async()=>[];window.loadConversation=async id=>{window.visitedConversation=id};window.initializeChatUI=()=>{};window.refreshAppData=async()=>{};</script>${scripts}<script>document.removeEventListener('DOMContentLoaded',initializeApp);saveAuth('fixture-token',new Date(Date.now()+3600000),{user:{id:'fixture',username:'fixture'},permissions:['tasks:read','tasks:write','tasks:delete','agent:execute','chat:read','chat:write'],scope:'own'});</script></body></html>`;
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://fixture');
const send = (status, value) => { res.statusCode = status; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(value)); };
try {
if (url.pathname.startsWith('/static/')) { const file = path.join(root, 'web', url.pathname); res.setHeader('Content-Type', file.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8'); return res.end(fs.readFileSync(file)); }
if (url.pathname === '/') { res.setHeader('Content-Type', 'text/html; charset=utf-8'); return res.end(html); }
if (url.pathname === '/favicon.ico') { res.statusCode = 204; return res.end(); }
let raw = ''; for await (const c of req) raw += c;
const body = raw ? JSON.parse(raw) : null;
const request = { method: req.method, path: url.pathname, query: Object.fromEntries(url.searchParams), body, authorization: req.headers.authorization }; state.requests.push(request);
if (req.headers.authorization !== 'Bearer fixture-token') return send(401, { error: 'fixture requires authentication' });
if (state.hook) { const intercepted = await state.hook(request); if (intercepted) return send(intercepted.status || 200, intercepted.body); }
if (url.pathname === '/api/projects') return send(200, { projects: [] });
if (url.pathname === '/api/batch-tasks') {
if (req.method === 'POST') { const q = { ...queue('new-queue'), ...body, tasks: body.tasks.map((message, i) => ({ id: 'new-' + i, message, status: 'pending' })) }; state.queues.set(q.id, q); return send(200, { queueId: q.id }); }
const filtered = [...state.queues.values()].filter(q => (!url.searchParams.get('status') || q.status === url.searchParams.get('status')) && (!url.searchParams.get('keyword') || q.title.includes(url.searchParams.get('keyword'))));
const limit = Number(url.searchParams.get('limit') || 10), page = Number(url.searchParams.get('page') || 1);
return send(200, { queues: filtered.slice((page - 1) * limit, page * limit), total: filtered.length, total_pages: Math.max(1, Math.ceil(filtered.length / limit)) });
}
const batch = url.pathname.match(/^\/api\/batch-tasks\/([^/]+)(?:\/(.*))?$/);
if (batch) {
const q = state.queues.get(batch[1]); if (!q) return send(404, { error: 'queue missing' }); const suffix = batch[2] || '';
if (suffix === 'start' || suffix === 'rerun') q.status = 'running';
else if (suffix === 'pause') q.status = 'paused';
else if (suffix === 'metadata' || suffix === 'schedule' || suffix === 'schedule-enabled') Object.assign(q, body);
else if (suffix === 'tasks' && req.method === 'POST') q.tasks.push({ id: 'added', message: body.message, status: 'pending' });
else if (suffix.startsWith('tasks/')) { const parts = suffix.split('/'), item = q.tasks.find(t => t.id === parts[1]); if (!item) return send(404, { error: 'step missing' }); if (parts[2] === 'run') { item.status = 'completed'; q.status = 'paused'; } else if (req.method === 'DELETE') q.tasks = q.tasks.filter(t => t !== item); else Object.assign(item, body); }
else if (req.method === 'DELETE') state.queues.delete(q.id);
return send(200, { queue: q });
}
return send(404, { error: 'unhandled fixture route' });
} catch (error) { send(500, { error: error.message }); }
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const executablePath = process.env.CHROME_PATH || (process.platform === 'darwin' ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : undefined);
const browser = await chromium.launch(executablePath ? { executablePath } : {});
t.after(async () => { await browser.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, acceptDownloads: true }); page.setDefaultTimeout(5000);
page.on('pageerror', error => state.pageErrors.push(error.message));
page.on('dialog', dialog => (dialog.type() === 'confirm' && !state.confirm) ? dialog.dismiss() : dialog.accept());
await page.goto(`http://127.0.0.1:${server.address().port}/#tasks`);
await page.locator('[data-queue-id="q1"]').waitFor();
await page.locator('#tasks-auto-refresh').uncheck();
const refresh = () => page.evaluate(() => refreshBatchQueues());
return { page, state, refresh };
}
module.exports = { fixture, queue };

View File

@ -1,184 +0,0 @@
/*
* CyberStrikeAI — mobile shell screenshots.
*
* Captures the injected mobile chrome (appbar / tab bar / drawer / bottom sheet)
* at a phone viewport without needing a login: the chrome is injected by
* mobile-ui.js boot() purely from the viewport width, so hiding the login
* overlay is enough to make syncAuthChrome re-show the tab bar. Data-driven page
* bodies stay empty — this is for judging the *shell*, not the content.
*
* node scripts/mobile-shot.mjs --state=plain --out=/tmp/shot.png
* node scripts/mobile-shot.mjs --state=drawer --base=http://127.0.0.1:8088
* states: login | plain | drawer | sheet | chat
*/
import fs from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
const argv = Object.fromEntries(process.argv.slice(2).map(a => {
const i = a.indexOf('=');
return i === -1 ? [a.replace(/^--/, ''), '1'] : [a.slice(2, i), a.slice(i + 1)];
}));
const W = Number(argv.width || 390), H = Number(argv.height || 844);
const PORT = argv.port || '9713';
const BASE = (argv.base || 'http://127.0.0.1:8088').replace(/\/$/, '');
const STATE = argv.state || 'plain';
const OUT = argv.out || `/tmp/cs-shot/${STATE}-${W}x${H}.png`;
fs.mkdirSync(dirnameOf(OUT), { recursive: true });
function dirnameOf(p) { const i = p.lastIndexOf('/'); return p.slice(0, i) || '.'; }
const CH = process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const chrome = await import('node:child_process').then(m =>
m.spawn(CH, ['--headless=new', `--remote-debugging-port=${PORT}`,
`--user-data-dir=/tmp/cs-shot-${PORT}`, '--no-sandbox', 'about:blank'], { stdio: 'ignore' }));
process.on('exit', () => { try { chrome.kill('SIGKILL'); } catch { /* gone */ } });
let ws;
for (let i = 0; i < 80; i++) {
try {
const r = await fetch(`http://127.0.0.1:${PORT}/json/version`);
ws = new WebSocket((await r.json()).webSocketDebuggerUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; setTimeout(rej, 4000); });
break;
} catch { await sleep(300); }
}
if (!ws) { console.error('chrome devtools unreachable'); process.exit(1); }
let idc = 0; const pending = new Map();
ws.onmessage = e => {
const m = JSON.parse(e.data);
if (m.id && pending.has(m.id)) {
const { res, rej } = pending.get(m.id); pending.delete(m.id);
m.error ? rej(new Error(JSON.stringify(m.error))) : res(m.result);
}
};
const send = (method, params = {}, sessionId) => new Promise((res, rej) => {
const id = ++idc; pending.set(id, { res, rej });
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
for (const m of ['Page.enable', 'Runtime.enable']) await send(m, {}, sessionId);
await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 3, mobile: true }, sessionId);
await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }, sessionId);
await send('Network.setUserAgentOverride', {
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1'
}, sessionId);
const ev = async expr => {
const r = await send('Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true }, sessionId);
if (r.exceptionDetails) return { __err: (r.exceptionDetails.exception?.description || r.exceptionDetails.text).slice(0, 200) };
return r.result?.value;
};
/* 主题要先落进本站点的 localStorage,about:blank 上写是写给另一个 origin。
换主题用 Page.navigate 重新进,不要在 eval 里 location.reload()——awaitPromise
会等一个永远不回来的执行上下文。 */
await send('Page.navigate', { url: BASE + '/' }, sessionId);
await sleep(1500);
const theme = argv.theme || (argv.dark === '1' ? 'dark' : '');
if (theme) {
await ev(`localStorage.setItem('cyberstrike-theme', ${JSON.stringify(theme)})`);
await send('Page.navigate', { url: BASE + '/' }, sessionId);
}
await sleep(3000);
if (STATE !== 'login') {
/* 藏掉登录遮罩会触发 mobile-ui.js 的 MutationObserver,把底部栏显示回来 */
await ev(`document.getElementById('login-overlay').style.display='none'`);
await sleep(600);
if (STATE === 'drawer') await ev(`window.CSAMobile && CSAMobile.openDrawer()`);
if (STATE === 'sheet') await ev(`window.CSAMobile && CSAMobile.openSheet()`);
if (STATE === 'chat') { await ev(`window.switchPage && switchPage('chat')`); await sleep(1500); }
await sleep(1200);
}
const state = await ev(`(()=>({
booted: !!window.CSAMobile,
tabbar: !!document.querySelector('#m-tabbar') && getComputedStyle(document.querySelector('#m-tabbar')).display,
sheet: !!document.querySelector('#m-sheet'),
drawerOpen: !!document.querySelector('#main-sidebar.m-open'),
sheetOpen: !!document.querySelector('#m-sheet.m-show'),
lang: document.documentElement.getAttribute('lang')
}))()`);
console.log(JSON.stringify(state));
/* 带凭据时真的登进去:未登录时对话/列表页的容器根本不渲染,看不到真东西。
凭据同样只从参数或环境变量来,绝不写进文件。 */
const USER = argv.user || process.env.CSAI_AUDIT_USER || '';
const PASS = argv.pass || process.env.CSAI_AUDIT_PASS || '';
const COOKIE = argv.cookie || process.env.CSAI_AUDIT_COOKIE || '';
if (COOKIE) await send('Network.setCookie', { name: 'auth_token', value: COOKIE, domain: new URL(BASE).hostname, path: '/' }, sessionId);
if (USER && PASS) {
await ev(`(()=>{const u=document.getElementById('login-username'),p=document.getElementById('login-password');if(u&&p){u.value=${JSON.stringify(USER)};p.value=${JSON.stringify(PASS)};document.getElementById('login-form').requestSubmit();}})()`);
await sleep(7000);
console.log('logged in:', JSON.stringify(await ev(`(()=>{const o=document.getElementById('login-overlay');return o?getComputedStyle(o).display:'none'})()`)));
}
if (argv.route) { await ev(`location.hash=${JSON.stringify(argv.route)}`); await sleep(3000); }
/* --eval='...' 用来在同一个已登录/已注入的页面上量一把真实计算样式 */
if (argv.eval) {
const probe = await ev(`(function(){${argv.eval}})()`);
console.log(JSON.stringify(probe, null, 2));
}
/* --why='.notification-btn' --prop=border-radius
规则写了却不生效时,用 CDP 的匹配样式表分清:没命中,还是被更高优先级压住。 */
if (argv.why) {
await send('DOM.enable', {}, sessionId);
await send('CSS.enable', {}, sessionId);
const { root } = await send('DOM.getDocument', { depth: -1 }, sessionId);
const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector: argv.why }, sessionId);
if (!nodeId) { console.log('selector 未命中任何节点:', argv.why); }
else {
const matched = await send('CSS.getMatchedStylesForNode', { nodeId }, sessionId);
const want = (argv.prop || 'border-radius,border,background').split(',');
const rows = [];
for (const e of matched.matchedCSSRules || []) {
const m = e.rule;
const decl = (m.style.cssProperties || []).filter(p => want.includes(p.name) && !p.disabled && p.value);
if (!decl.length) continue;
const sel = (m.selectorList && m.selectorList.text) || '?';
rows.push({
origin: m.origin,
sheet: (m.style.styleSheetId || '').split('@').pop(),
selector: sel.length > 78 ? sel.slice(0, 78) + '…' : sel,
decls: decl.map(d => `${d.name}:${d.value}${d.important ? ' !important' : ''}`),
});
}
console.log(`== ${argv.why} 上命中且声明了 [${want.join(', ')}] 的规则,按级联顺序(后=更优先)==`);
rows.forEach((r, i) => console.log(`${String(i).padStart(2)} ${r.origin.padEnd(10)} ${r.decls.join(' | ')}\n ${r.selector}`));
const cs = await ev(`(()=>{const e=document.querySelector(${JSON.stringify(argv.why)});const c=getComputedStyle(e);return JSON.stringify(${JSON.stringify(want)}.reduce((o,k)=>(o[k]=c[k],o),{}),null,1)})()`);
console.log('最终计算值:', cs);
}
}
/* --tap='SEL' 用真手指(只发 touch)点一个选择器,配合 --shots=3 连拍,
用来看"点下去之后屏幕上闪出来的那块是什么"。 */
async function fingerTap(x, y) {
const t = { x: Math.round(x), y: Math.round(y) };
await send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [t] }, sessionId);
await sleep(40);
await send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }, sessionId);
}
if (argv.tap) {
const box = await ev(`(()=>{const e=document.querySelector(${JSON.stringify(argv.tap)});if(!e)return null;const r=e.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2}})()`);
if (!box) console.log('tap 目标不存在:', argv.tap);
else {
await fingerTap(box.x, box.y);
const shots = Number(argv.shots || 3);
for (let i = 0; i < shots; i++) {
const png = await send('Page.captureScreenshot', { format: 'png' }, sessionId);
fs.writeFileSync(OUT.replace(/\.png$/, '') + `-t${i}.png`, Buffer.from(png.data, 'base64'));
const who = await ev(`(()=>{const e=document.elementFromPoint(innerWidth/2,innerHeight/2);if(!e)return null;var s=e.tagName.toLowerCase()+(e.id?"#"+e.id:"")+(typeof e.className==="string"&&e.className?"."+e.className.trim().split(/\s+/)[0]:"");var r=e.getBoundingClientRect();var c=getComputedStyle(e);return JSON.stringify({el:s,z:c.zIndex,pos:c.position,box:[Math.round(r.width),Math.round(r.height)],bg:c.backgroundColor})})()`);
console.log(`t${i} 视口中央:`, who);
await sleep(Number(argv.shotDelay || 300));
}
process.exit(0);
}
}
const shot = await send('Page.captureScreenshot', { format: 'png' }, sessionId);
fs.writeFileSync(OUT, Buffer.from(shot.data, 'base64'));
console.log('shot -> ' + OUT);
process.exit(0);

View File

@ -1,460 +0,0 @@
/*
* CyberStrikeAI — mobile tap audit.
*
* Proves the claim "every button on a phone can actually be tapped and shows up
* correctly". It is deliberately narrower than scripts/mobile-audit.mjs (layout
* defects): here every interactive element in the *active* page must pass four
* geometric/reachability checks, and the injected mobile chrome must pass a
* scripted finger tap.
*
* node scripts/mobile-tap-audit.mjs --user=admin --pass=... --width=390 --height=844
* CSAI_AUDIT_USER=admin CSAI_AUDIT_PASS=... node scripts/mobile-tap-audit.mjs --all
* node scripts/mobile-tap-audit.mjs --cookie=<auth_token 的值> --all
*
* Flags: --base=https://127.0.0.1:8088 --pages=a,b,c --allow-writes=0|1 --ua=iphone|android
* --chrome=0 (skip the finger-tap suite) --json=<path>
*
* Nothing destructive is tapped: elements whose label matches a write verb are
* measured but never clicked, and 新对话-style writes need --allow-writes=1.
* Credentials are never defaulted — a baked-in password leaks the moment this
* file is committed or served.
*/
import fs from 'node:fs';
import { setTimeout as sleep } from 'node:timers/promises';
const argv = Object.fromEntries(process.argv.slice(2).map(a => {
const i = a.indexOf('=');
return i === -1 ? [a.replace(/^--/, ''), '1'] : [a.slice(2, i), a.slice(i + 1)];
}));
const W = Number(argv.width || 390), H = Number(argv.height || 844);
const PORT = argv.port || '9712';
const BASE = (argv.base || 'https://127.0.0.1:8088').replace(/\/$/, '');
const USER = argv.user || process.env.CSAI_AUDIT_USER || '';
const PASS = argv.pass || process.env.CSAI_AUDIT_PASS || '';
/* 不想交出口令时的替代路径:在浏览器里登录 127.0.0.1:8088,从 DevTools 复制
auth_token 的值,用 --cookie=... 或 CSAI_AUDIT_COOKIE=... 传进来。会话本身 12 小时
过期,比长期有效的主机口令暴露面小。两者都没有则拒绝运行。 */
const COOKIE = argv.cookie || process.env.CSAI_AUDIT_COOKIE || '';
const ALLOW_WRITES = argv['allow-writes'] === '1';
const MIN_TAP = Number(argv['min-tap'] || 44);
const CHROME = argv.chrome !== '0';
const OUT = argv.out || `/tmp/cs-tap/${W}x${H}`;
const JSON_OUT = argv.json || `${OUT}/tap-audit.json`;
const BASELINE = argv.baseline || 'scripts/mobile-tap-baseline.json';
if (!COOKIE && (!USER || !PASS)) {
console.error('Refusing to run without credentials: pass --user=... --pass=... (or CSAI_AUDIT_USER/CSAI_AUDIT_PASS), or an existing session via --cookie=... (or CSAI_AUDIT_COOKIE).');
process.exit(2);
}
const SPA_PAGES = (argv.pages || (argv.all ? '' : 'dashboard,chat,hitl,tasks'))
.split(',').filter(Boolean);
const PAGES = argv.all
? ['dashboard', 'chat', 'projects', 'vulnerabilities', 'tasks', 'workflows', 'asset-overview',
'asset-library', 'info-collect', 'hitl', 'tool-guard', 'webshell', 'c2-listeners', 'c2-sessions',
'c2-tasks', 'c2-payloads', 'c2-events', 'c2-profiles', 'chat-files', 'mcp-monitor', 'mcp-management',
'knowledge-management', 'knowledge-retrieval-logs', 'roles-management', 'platform-rbac',
'skills-monitor', 'skills-management', 'agents-management', 'settings', 'audit-log', 'monitor']
: SPA_PAGES;
fs.mkdirSync(OUT, { recursive: true });
/* Write verbs: an element carrying one of these in its label is measured, never
tapped. Without this the audit would delete real rows in whatever instance it
points at. */
const WRITE_RE = /(删除|清空|清理|退出|注销|重启|停止|终止|中止|执行|运行|发送|提交|保存|新建|新增|创建|导入|上传|应用|重置|启用|禁用|安装|卸载|开始|立即|一键|批量|覆盖|恢复|回滚|delete|remove|clear|logout|submit|save|create|import|upload|apply|reset|install|uninstall|run|execute|send|restart|stop|kill|rollback|restore)/i;
const CH = process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const chrome = await import('node:child_process').then(m =>
m.spawn(CH, ['--headless=new', `--remote-debugging-port=${PORT}`,
`--user-data-dir=/tmp/cs-tap-${PORT}`, '--ignore-certificate-errors',
'--no-sandbox', '--allow-running-insecure-content', 'about:blank'], { stdio: 'ignore' }));
/* 任何提前退出(连不上、登录失败)都不许把 headless Chrome 留在机器上 */
process.on('exit', () => { try { chrome.kill('SIGKILL'); } catch { /* 已退出 */ } });
let ws;
for (let i = 0; i < 80; i++) {
try {
const r = await fetch(`http://127.0.0.1:${PORT}/json/version`);
ws = new WebSocket((await r.json()).webSocketDebuggerUrl);
await new Promise((res, rej) => { ws.onopen = res; ws.onerror = rej; setTimeout(rej, 4000); });
break;
} catch { await sleep(300); }
}
if (!ws) { console.error('chrome devtools unreachable'); process.exit(1); }
let idc = 0; const pending = new Map(); const events = [];
ws.onmessage = e => {
const m = JSON.parse(e.data);
if (m.id && pending.has(m.id)) {
const { res, rej } = pending.get(m.id); pending.delete(m.id);
m.error ? rej(new Error(JSON.stringify(m.error))) : res(m.result);
} else if (m.method) { events.push(m.method); }
};
const send = (method, params = {}, sessionId) => new Promise((res, rej) => {
const id = ++idc; pending.set(id, { res, rej });
ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const { targetId } = await send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await send('Target.attachToTarget', { targetId, flatten: true });
for (const m of ['Page.enable', 'Runtime.enable', 'Security.enable', 'Log.enable']) await send(m, {}, sessionId);
await send('Security.setIgnoreCertificateErrors', { ignore: true }, sessionId);
await send('Emulation.setDeviceMetricsOverride', { width: W, height: H, deviceScaleFactor: 3, mobile: true }, sessionId);
await send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }, sessionId);
/* --ua=android 用安卓 Chrome 的 UA 复跑同一套门禁(壳层按视口宽度判定,与 UA 无关;
这里换 UA 是为了让"同一份 UI 在安卓浏览器下同样合格"有可复现的证据)。 */
const UA_STRINGS = {
iphone: 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1',
android: 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36'
};
const UA = UA_STRINGS[(argv.ua || 'iphone').toLowerCase()];
if (!UA) { console.error(`unknown --ua=${argv.ua} (iphone | android)`); process.exit(2); }
await send('Network.setUserAgentOverride', { userAgent: UA }, sessionId);
const ev = async expr => {
const r = await send('Runtime.evaluate', { expression: expr, awaitPromise: true, returnByValue: true }, sessionId);
if (r.exceptionDetails) return { __err: (r.exceptionDetails.exception?.description || r.exceptionDetails.text).slice(0, 300) };
return r.result?.value;
};
/* 真手指只有 touch:Chromium 在移动模拟下会自己从 touchEnd 合成一次 click。
再补一对 mouse 事件就是第二次 click —— 抽屉/面板会被「开了又关」,
于是 menu-open 这类断言假失败(实测踩过)。 */
async function fingerTap(x, y) {
const t = { x: Math.round(x), y: Math.round(y) };
await send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [t] }, sessionId);
await sleep(40);
await send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }, sessionId);
await sleep(260);
}
const DETECT = `(function(){
var vw=innerWidth, vh=innerHeight, MIN=${MIN_TAP};
var SEL='button,a[href],input:not([type=hidden]),select,textarea,[onclick],[role=button],[role=tab],[role=menuitem],[role=switch],[role=checkbox],[role=link],.nav-item-content,.nav-submenu-item,.settings-custom-select-trigger,.tab,.switch';
function nm(el){
var s=el.tagName.toLowerCase();
if(el.id) s+='#'+el.id;
else if(typeof el.className==='string'&&el.className.trim()){
var c=el.className.trim().split(/\\s+/).filter(function(x){return !/^is-|^active$|^has-/.test(x)});
s+='.'+(c[0]||''); if(c[1]&&/layout|sidebar|content|panel|main|nav|list|detail|grid|row|header|body|wrap|table|bar|tab/i.test(c[1])) s+='.'+c[1];
}
return s;
}
function path(el){ var p=[],n=el; for(var i=0;i<4&&n&&n.tagName;i++){p.unshift(nm(n));n=n.parentElement} return p.join('>') }
function label(el){
var t=(el.innerText||'').trim();
if(!t) t=(el.value||'').trim();
if(!t) t=el.getAttribute('aria-label')||el.getAttribute('title')||el.getAttribute('placeholder')||'';
if(!t&&el.getAttribute('data-i18n')) t=el.getAttribute('data-i18n');
if(!t){ var i=el.querySelector('i,svg,img'); t=(el.className||'')+'[icon]'; }
return String(t).replace(/\\s+/g,' ').trim().slice(0,42);
}
function shown(el){
var n=el;
while(n&&n!==document.documentElement){
var c=getComputedStyle(n);
if(c.display==='none'||c.visibility==='hidden'||parseFloat(c.opacity)===0) return false;
n=n.parentElement;
}
return true;
}
function inActivePage(el){
var p=el.closest('.page');
return !p||p.classList.contains('active');
}
function scrollAncestor(el,axis){
var a=el.parentElement;
while(a){ var c=getComputedStyle(a);
if(axis==='x'&&/auto|scroll/.test(c.overflowX)) return a;
if(axis==='y'&&/auto|scroll/.test(c.overflowY)) return a;
if(a===document.body) break; a=a.parentElement; }
return null;
}
function clipAncestor(el){
var a=el.parentElement;
while(a){ var c=getComputedStyle(a);
if(c.overflowX==='hidden'||c.overflowY==='hidden'||c.overflow==='hidden') return a;
if(a===document.body) break; a=a.parentElement; }
return null;
}
var fixedTally=function(){
var out=[];
[...document.querySelectorAll('*')].forEach(function(el){
var c=getComputedStyle(el);
if(c.position!=='fixed'&&c.position!=='sticky') return;
if(!shown(el)) return;
var r=el.getBoundingClientRect();
if(r.width<1||r.height<1) return;
if(c.pointerEvents==='none') return;
if(parseFloat(c.zIndex||0)<0&&c.zIndex!=='auto') {}
out.push({el:el,r:r,n:nm(el),z:c.zIndex});
});
return out;
}();
function overFixed(r){
for(var i=0;i<fixedTally.length;i++){
var f=fixedTally[i];
if(r.top>=f.r.top&&r.bottom<=f.r.bottom&&r.left>=f.r.left&&r.right<=f.r.right) return f.n;
}
return null;
}
var bad=[], scanned=0, chromeSeen={};
var list=[...document.querySelectorAll(SEL)];
list.forEach(function(el){
if(!shown(el)||!inActivePage(el)) return;
/* 折叠 <details> 里的控件本来就要展开才存在,不算"点不到" */
var det=el.closest('details');
if(det&&!det.open&&!det.querySelector('summary').contains(el)) return;
/*SCOPE*/
if(el.ownerSVGElement) return;
if(el.closest('.markdown-body')&&getComputedStyle(el).display==='inline') return;
scanned++;
var c=getComputedStyle(el);
var r=el.getBoundingClientRect();
/* try to bring it into view first: unreachable means a real dead button */
if(r.top<0||r.bottom>vh||r.left<0||r.right>vw){
/* 判"够不够得到"必须按手指能做的事来:逐层把可滚祖先滚到把元素居中。
scrollIntoView 不算——实测它在这种「外层 overflow:hidden + 内层 auto」的嵌套里
根本不滚(元素原地不动),会把 59 个划得到的控件误报成 offscreen。
overflow:hidden 的祖先手指也划不动,所以只滚 auto/scroll 的层。 */
(function reveal(node){
var a=node.parentElement;
while(a&&a!==document.documentElement){
var cc=getComputedStyle(a);
if(/auto|scroll/.test(cc.overflowY)&&a.scrollHeight>a.clientHeight+2){
var ab=a.getBoundingClientRect(), rb2=node.getBoundingClientRect();
a.scrollTop+= (rb2.top+rb2.height/2)-(ab.top+ab.height/2);
}
if(/auto|scroll/.test(cc.overflowX)&&a.scrollWidth>a.clientWidth+2){
var ab2=a.getBoundingClientRect(), rb3=node.getBoundingClientRect();
a.scrollLeft+= (rb3.left+rb3.width/2)-(ab2.left+ab2.width/2);
}
a=a.parentElement;
}
})(el);
r=el.getBoundingClientRect();
}
var w=r.width,h=r.height;
var out={el:nm(el),p:path(el),t:label(el),w:Math.round(w),h:Math.round(h)};
if(w<2||h<2){ out.why='zero'; bad.push(out); return; }
if(c.pointerEvents==='none'||c.pointerEvents==='hidden'){ out.why='pointer-none'; bad.push(out); return; }
if(w<MIN||h<MIN){
/* 复选/单选框的命中区常常由外层 label 提供(iOS 设置里也是整行可点):
自身 >=32 且 label 两个方向都到下限才算合格,否则照报 tiny */
var pass=false;
/* 本层对复选/单选框的口径是 30px(见 mobile.css 24.11),整行/label 才是命中区 */
if((el.type==='checkbox'||el.type==='radio')&&w>=30&&h>=30){
/* 命中区常常由 label 或整行提供(本层 24.11 就是按"整行可点"写的):
向上找第一个真正可点的祖先,它到下限就算合格 */
var n=el, d=0;
while(n&&n!==document.body&&d++<5){
var clickable=n.tagName==='LABEL'||n.hasAttribute('onclick')||getComputedStyle(n).cursor==='pointer';
if(clickable){var nb=n.getBoundingClientRect(); if(nb.width>=MIN&&nb.height>=MIN){pass=true;break;}}
n=n.parentElement;
}
}
if(!pass){ out.why='tiny'; bad.push(out); return; }
}
var cx=r.left+w/2, cy=r.top+h/2;
if(cx<0||cy<0||cx>vw||cy>vh){
var cl=clipAncestor(el), sx=scrollAncestor(el,'x'), sy=scrollAncestor(el,'y');
out.why='offscreen'; out.clip=cl?nm(cl):null; out.swipes=[sx?'x':null,sy?'y':null].filter(Boolean).join('');
bad.push(out); return;
}
var hitTop=document.elementFromPoint(cx,cy);
var ok=false, cur=hitTop;
while(cur){ if(cur===el){ok=true;break} cur=cur.parentElement; }
if(!ok){
cur=el;
while(cur&&!ok){ if(cur.contains&&hitTop&&cur.contains(hitTop)) ok=true; cur=cur.parentElement; }
}
if(!ok&&hitTop){
/* delegation: a handler on an ancestor is a legitimate target */
var a=el.parentElement, d=0;
while(a&&d++<4){ if(a.contains(hitTop)){ok=true;break} a=a.parentElement; }
}
if(!ok){
out.why='covered';
out.blocker=hitTop?nm(hitTop):'none';
out.blockerPath=hitTop?path(hitTop):'';
var of=overFixed(r); if(of) out.blockerFixed=of;
bad.push(out); return;
}
if(el.id) chromeSeen[el.id]=1;
});
var scr=document.scrollingElement||document.documentElement;
return {
vw:vw,vh:vh,scanned:scanned,bad:bad,
doc:{h:Math.round(scr.scrollHeight),clientH:scr.clientHeight,canScrollY:scr.scrollHeight>scr.clientHeight+2,
bodyOverflowY:getComputedStyle(document.body).overflowY,htmlTouch:getComputedStyle(document.documentElement).touchAction},
chrome:{tabbar:!!document.querySelector('#m-tabbar'),sheet:!!document.querySelector('#m-sheet'),
menu:!!document.querySelector('.m-menu-btn'),more:!!document.querySelector('.m-more-btn'),
chatbar:!!document.querySelector('#m-chat-bar'),scrim:!!document.querySelector('#m-scrim')},
locale:(document.documentElement.getAttribute('lang')||'')
};
})()`;
/* DETECT 默认扫"当前页 + 全局固定件"。遮罩展开时页面元素会被 scrim 判成 covered,
所以扫抽屉/面板要限定作用域,否则全是假红。 */
const detectFor = scope => DETECT.replace('/*SCOPE*/',
scope ? `if(!el.closest(${JSON.stringify(scope)})) return;` : '');
async function openPage(hash) {
await ev(`location.hash=${JSON.stringify(hash)}`);
await sleep(2600);
}
const host = new URL(BASE).hostname;
if (COOKIE) await send('Network.setCookie', { name: 'auth_token', value: COOKIE, domain: host, path: '/' }, sessionId);
await send('Page.navigate', { url: BASE + '/' }, sessionId);
await sleep(3500);
/* The login card is a phone surface too — check it before authenticating. */
const login = await ev(DETECT);
if (!COOKIE) {
await ev(`(()=>{const u=document.getElementById('login-username'),p=document.getElementById('login-password');if(u&&p){u.value=${JSON.stringify(USER)};p.value=${JSON.stringify(PASS)};document.getElementById('login-form').requestSubmit();}})()`);
await sleep(8000);
} else {
console.log('using the session cookie supplied via --cookie; no password was sent');
}
const who = await ev(`(()=>{const o=document.getElementById('login-overlay');return o?getComputedStyle(o).display:'none'})()`);
if (who !== 'none') { console.error('login did not take (overlay still displayed):', who); process.exit(3); }
const report = { login, pages: {}, chromeTaps: [] };
let grand = {};
const bump = k => { grand[k] = (grand[k] || 0) + 1; };
const log = (o, k) => { (o.bad || []).forEach(b => bump(b.why)); };
for (const pg of PAGES) {
await openPage(pg);
const r = await ev(DETECT);
if (!r || r.__err) { console.log(pg, 'DETECT ERROR', r && r.__err); continue; }
report.pages[pg] = r;
log(r);
const n = r.bad.length;
console.log(`${pg.padEnd(26)} scanned=${String(r.scanned).padStart(3)} defects=${String(n).padStart(3)} ${n ? '' : ' OK'}`);
r.bad.slice(0, 6).forEach(b => console.log(` ${b.why.padEnd(12)} ${String(b.w)}x${String(b.h)} ${b.t} ${b.el}${b.blocker ? ' <= ' + b.blocker : ''}`));
const shot = await send('Page.captureScreenshot', { format: 'png' }, sessionId);
fs.writeFileSync(`${OUT}/${pg}.png`, Buffer.from(shot.data, 'base64'));
}
/* ---------------- overlays: 抽屉与面板展开后的按钮 ---------------- */
const OVERLAYS = [
{ name: 'sheet', route: 'dashboard', open: `CSAMobile.openSheet()`, scope: '#m-sheet' },
{ name: 'drawer', route: 'dashboard', open: `CSAMobile.openDrawer()`, scope: '#main-sidebar' },
{ name: 'chat-drawer', route: 'chat', open: `CSAMobile.openChatDrawer()`, scope: '#conversation-sidebar' },
];
for (const o of OVERLAYS) {
await openPage(o.route);
await ev(`(()=>{try{${o.open}}catch(e){}})()`);
await sleep(900); /* 等开合动画结束,动画中量到的是位移中的盒子 */
const r = await ev(detectFor(o.scope));
if (!r || r.__err) { console.log(o.name, 'DETECT ERROR', r && r.__err); continue; }
report.pages[o.name] = r;
log(r);
console.log(`${('[' + o.name + ']').padEnd(26)} scanned=${String(r.scanned).padStart(3)} defects=${String(r.bad.length).padStart(3)} ${r.bad.length ? '' : ' OK'}`);
r.bad.slice(0, 6).forEach(b => console.log(` ${b.why.padEnd(12)} ${String(b.w)}x${String(b.h)} ${b.t} ${b.el}${b.blocker ? ' <= ' + b.blocker : ''}`));
await ev(`CSAMobile.closeSheet();CSAMobile.closeDrawer();CSAMobile.closeChatDrawer();`);
}
/* ---------------- chrome finger taps ---------------- */
/* 关闭要走用户真能点到的控件:抽屉展开后汉堡键被抽屉自己盖住,
再点它点的是侧栏(真实用户用抽屉内的 × 或遮罩)。每步前先复位,
否则一条失败会连锁把后面的断言全带偏。 */
const RESET = `CSAMobile.closeDrawer();CSAMobile.closeSheet();CSAMobile.closeChatDrawer();`;
const TAPS = [
{ name: 'menu-open', sel: '.m-menu-btn', pre: RESET, expect: `document.querySelector('#main-sidebar').classList.contains('m-open')` },
{ name: 'menu-close', sel: '#main-sidebar .m-close-btn', pre: `${RESET}CSAMobile.openDrawer();`, expect: `!document.querySelector('#main-sidebar').classList.contains('m-open')` },
{ name: 'menu-scrim-close', sel: '#m-scrim', pre: `${RESET}CSAMobile.openDrawer();`, expect: `!document.querySelector('#main-sidebar').classList.contains('m-open')` },
{ name: 'more-open', sel: '.m-more-btn', pre: RESET, expect: `document.querySelector('#m-sheet').classList.contains('m-show')` },
{ name: 'more-close', sel: '#m-sheet .m-close-btn', pre: `${RESET}CSAMobile.openSheet();`, expect: `!document.querySelector('#m-sheet').classList.contains('m-show')` },
{ name: 'tab-hitl', sel: '#m-tabbar [data-tab=hitl]', expect: `document.querySelector('#page-hitl').classList.contains('active')` },
{ name: 'tab-tasks', sel: '#m-tabbar [data-tab=tasks]', expect: `document.querySelector('#page-tasks').classList.contains('active')` },
{ name: 'tab-dashboard', sel: '#m-tabbar [data-tab=dashboard]', expect: `document.querySelector('#page-dashboard').classList.contains('active')` },
{ name: 'tab-chat', sel: '#m-tabbar [data-tab=chat]', expect: `document.querySelector('#page-chat').classList.contains('active')` },
{ name: 'chat-drawer-open', sel: '#m-chat-bar button:first-child', expect: `document.querySelector('#conversation-sidebar').classList.contains('m-open')` },
{ name: 'chat-drawer-close', sel: '#conversation-sidebar .m-close-btn', expect: `!document.querySelector('#conversation-sidebar').classList.contains('m-open')` },
];
if (CHROME) {
await openPage('chat');
for (const t of TAPS) {
if (t.pre) await ev(`(()=>{try{${t.pre}}catch(e){}})()`);
await sleep(320);
const box = await ev(`(()=>{const e=document.querySelector(${JSON.stringify(t.sel)});if(!e)return null;const r=e.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2,w:r.width,h:r.height,shown:getComputedStyle(e).display!=='none'}})()`);
if (!box || !box.shown) { report.chromeTaps.push({ name: t.name, ok: false, why: 'absent' }); console.log(`tap ${t.name.padEnd(20)} ABSENT`); continue; }
events.length = 0;
await fingerTap(box.x, box.y);
const passed = await ev(`(()=>{try{return !!(${t.expect})}catch(e){return false}})()`);
const err = events.includes('Runtime.exceptionThrown');
report.chromeTaps.push({ name: t.name, ok: !!passed && !err, state: passed, err });
console.log(`tap ${t.name.padEnd(20)} ${passed && !err ? 'ok' : 'FAIL'} (state=${passed} jsErr=${err})`);
}
/* language round-trip: the injected chrome must re-label itself */
await ev(`window.changeLanguage && window.changeLanguage('en-US')`);
await sleep(2500);
const en = await ev(`(()=>{const o=[];document.querySelectorAll('#m-tabbar .m-tab>span:not(.m-tab-badge),#m-sheet .m-sheet-item>span').forEach(function(s){o.push(s.textContent.trim())});return {lang:document.documentElement.getAttribute('lang'),labels:o}})()`);
report.langEn = en;
console.log('en-US chrome labels:', JSON.stringify(en));
await ev(`window.changeLanguage && window.changeLanguage('ru-RU')`);
await sleep(2500);
const ru = await ev(`(()=>{const o=[];document.querySelectorAll('#m-tabbar .m-tab>span:not(.m-tab-badge),#m-sheet .m-sheet-item>span').forEach(function(s){o.push(s.textContent.trim())});return {lang:document.documentElement.getAttribute('lang'),labels:o}})()`);
report.langRu = ru;
console.log('ru-RU chrome labels:', JSON.stringify(ru));
await ev(`window.changeLanguage && window.changeLanguage('zh-CN')`);
await sleep(2000);
}
fs.writeFileSync(JSON_OUT, JSON.stringify(report, null, 2));
const chromeFail = report.chromeTaps.filter(t => !t.ok).length;
const total = Object.values(grand).reduce((a, b) => a + b, 0);
console.log(`\n=========== MOBILE TAP AUDIT @${W}x${H} ===========`);
console.log(`pages ${Object.keys(report.pages).length}`);
console.log(`covered (occluded) ${grand.covered || 0}`);
console.log(`offscreen ${grand.offscreen || 0}`);
console.log(`zero-size ${grand.zero || 0}`);
console.log(`pointer-events:none ${grand['pointer-none'] || 0}`);
console.log(`tap target < ${MIN_TAP}px ${grand.tiny || 0}`);
console.log(`chrome taps failed ${chromeFail}`);
console.log(`report ${JSON_OUT}`);
/* Ratchet: the钉死的 baseline may only go down. */
let bl = null;
try { bl = JSON.parse(fs.readFileSync(BASELINE, 'utf8')); } catch { }
let ratchetFail = false;
if (bl) {
for (const [k, v] of Object.entries(grand)) {
if ((bl[k] ?? 0) < v) { console.log(`RATCHET FAIL ${k}: baseline ${bl[k]} -> now ${v}`); ratchetFail = true; }
}
for (const k of Object.keys(bl)) {
if (k.startsWith('page:')) {
const name = k.slice(5), now = (report.pages[name] || {}).bad?.length ?? 0;
if (bl[k] < now) { console.log(`RATCHET FAIL ${name}: baseline ${bl[k]} -> now ${now}`); ratchetFail = true; }
}
}
if (chromeFail > (bl.chromeFail ?? 0)) { console.log(`RATCHET FAIL chrome: ${bl.chromeFail} -> ${chromeFail}`); ratchetFail = true; }
} else {
const fresh = { ...grand };
for (const [p, r] of Object.entries(report.pages)) fresh['page:' + p] = r.bad.length;
fresh.chromeFail = chromeFail;
fresh.note = 'generated by scripts/mobile-tap-audit.mjs; numbers may only decrease';
fs.writeFileSync(BASELINE, JSON.stringify(fresh, null, 2));
console.log(`baseline written -> ${BASELINE}`);
}
/* 退出码口径(写死,别每次靠人判断):
- 够不到 / 被遮挡 / 零尺寸 / pointer-events:none —— 任何一处都是硬失败,控件点不到没有"存量债"可言;
- 自家注入的抽屉、面板、会话抽屉里的按钮 —— 必须 0,不许留债;
- 桌面遗留控件的小命中区 —— 走基线只降不升,超基线即红。 */
const hard = (grand.covered || 0) + (grand.offscreen || 0) + (grand.zero || 0) + (grand['pointer-none'] || 0);
const ownChrome = ['sheet', 'drawer', 'chat-drawer'].reduce((n, k) => n + ((report.pages[k] || {}).bad || []).length, 0);
const fail = hard || ownChrome || chromeFail || ratchetFail;
console.log(`\n判定: 硬缺陷 ${hard} | 自家外壳 ${ownChrome} | 点击失败 ${chromeFail} | 基线回潮 ${ratchetFail ? '是' : '否'} -> ${fail ? 'FAIL' : 'PASS'}`);
process.exit(fail ? 1 : 0);

View File

@ -1 +0,0 @@
{"tiny": 3, "page:dashboard": 0, "page:chat": 0, "page:projects": 0, "page:vulnerabilities": 0, "page:tasks": 0, "page:workflows": 0, "page:asset-overview": 0, "page:asset-library": 1, "page:info-collect": 0, "page:hitl": 0, "page:tool-guard": 2, "page:webshell": 0, "page:c2-listeners": 0, "page:c2-sessions": 0, "page:c2-tasks": 0, "page:c2-payloads": 0, "page:c2-events": 0, "page:c2-profiles": 0, "page:chat-files": 0, "page:mcp-monitor": 0, "page:mcp-management": 0, "page:knowledge-management": 0, "page:knowledge-retrieval-logs": 0, "page:roles-management": 0, "page:platform-rbac": 0, "page:skills-monitor": 0, "page:skills-management": 0, "page:agents-management": 0, "page:settings": 0, "page:audit-log": 0, "page:monitor": 0, "page:sheet": 0, "page:drawer": 0, "page:chat-drawer": 0, "chromeFail": 0, "note": "generated by scripts/mobile-tap-audit.mjs; numbers may only decrease"}

View File

@ -1,265 +0,0 @@
/* Offline browser regression for the project header overlap and tab hit targets.
* Requires Playwright and Chrome (or CHROME_PATH); no server/login/data is used.
* Run: node --test scripts/project-mobile-layout.test.cjs
*/
const fs = require('node:fs');
const path = require('node:path');
const assert = require('node:assert/strict');
const { test } = require('node:test');
const { chromium } = require('playwright');
const root = path.resolve(__dirname, '..');
const read = file => fs.readFileSync(path.join(root, file), 'utf8');
const template = read('web/templates/index.html');
const start = template.indexOf('<main class="projects-detail"');
assert.ok(start >= 0, 'project detail fixture must exist');
const markup = template.slice(start, template.indexOf('</main>', start) + 7);
const source = read('web/static/js/projects.js');
const switchTab = source.slice(source.indexOf('function switchProjectTab('), source.indexOf('async function loadProjectAssets('));
const tabs = ['facts', 'graph', 'assets', 'conversations', 'vulns', 'settings'];
test('project headers contain their content and all tabs receive mobile taps', async () => {
const browser = await chromium.launch({
headless: true,
...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}),
});
try {
for (const width of [320, 390, 430, 767, 768, 900, 1440]) {
const context = await browser.newContext({ viewport: { width, height: 900 }, isMobile: width < 768, hasTouch: true });
try {
const page = await context.newPage();
// Keep the real markup and both complete stylesheets, including theme overrides.
await page.setContent(`<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div class="container"><header><div class="header-content">CyberStrikeAI</div></header><div id="page-projects" class="page active"><div class="page-content projects-page-layout">${markup}</div></div></div></body></html>`);
for (const file of ['style.css', 'mobile.css']) await page.addStyleTag({ content: read(`web/static/css/${file}`) });
// Use the real tab handler; replace only data loaders to keep the test offline.
await page.addScriptTag({ content: `let currentProjectTab = 'facts'; window.loads = [];
${['Facts', 'FactGraph', 'Assets', 'Conversations', 'Vulnerabilities'].map(name => `function loadProject${name}() { window.loads.push('${name}'); }`).join('\n')}
${switchTab}` });
for (const locale of ['zh-CN', 'en-US', 'ru-RU']) {
const translations = JSON.parse(read(`web/static/i18n/${locale}.json`));
await page.evaluate(dict => {
document.querySelectorAll('[data-i18n]').forEach(el => {
if (el.children.length || el.hasAttribute('data-i18n-attr')) return;
const value = el.dataset.i18n.split('.').reduce((obj, key) => obj?.[key], dict);
if (typeof value === 'string') el.textContent = value;
});
document.querySelector('.projects-detail').classList.add('has-project');
document.querySelector('#projects-detail-inner').hidden = false;
document.querySelector('#projects-detail-title').textContent = '玉米 — Long project name / '.repeat(8);
const desc = document.querySelector('#projects-detail-desc');
desc.hidden = false;
desc.textContent = 'Long project description / 项目描述 '.repeat(20);
document.querySelector('#project-stat-sparse').hidden = false;
document.querySelector('#projects-detail-meta-time').textContent = '2 days ago';
}, translations);
for (const theme of ['light', 'dark']) {
const label = `${width}px ${locale} ${theme}`;
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
await page.locator('.projects-detail-header').scrollIntoViewIfNeeded();
const layout = await page.evaluate(() => {
const header = document.querySelector('.projects-detail-header');
const bounds = header.getBoundingClientRect();
const children = ['.projects-detail-headline', '.projects-detail-desc', '.projects-detail-header-actions'];
return {
contained: children.every(selector => {
const r = document.querySelector(selector).getBoundingClientRect();
return r.top >= bounds.top && r.bottom <= bounds.bottom;
}),
separate: document.querySelector('.projects-tabs').getBoundingClientRect().top >= bounds.bottom,
appHeight: document.querySelector('.container > header').getBoundingClientRect().height,
overflow: document.documentElement.scrollWidth > innerWidth,
};
});
assert.ok(layout.contained, `${label}: header content escapes its bounds`);
assert.ok(layout.separate, `${label}: header overlaps tabs`);
assert.equal(layout.overflow, false, `${label}: page overflows horizontally`);
if (width < 768) {
assert.equal(layout.appHeight, 52, `${label}: app bar height changed`);
assert.ok(await page.locator('#project-facts-search').evaluate(input => {
const bounds = input.getBoundingClientRect();
const icon = document.querySelector('.projects-fact-search-icon').getBoundingClientRect();
const textStart = bounds.left + parseFloat(getComputedStyle(input).paddingLeft);
return textStart > icon.right && Math.abs((icon.top + icon.bottom - bounds.top - bounds.bottom) / 2) < 1;
}), `${label}: search icon overlaps text or is off center`);
}
for (const tab of [...tabs, 'facts']) {
const button = page.locator(`#project-tab-${tab}`);
await button.scrollIntoViewIfNeeded();
await button.tap({ timeout: 3000 });
assert.ok(await button.evaluate(el => {
const r = el.getBoundingClientRect();
const nav = el.parentElement.getBoundingClientRect();
const x = (Math.max(r.left, nav.left, 0) + Math.min(r.right, nav.right, innerWidth)) / 2;
return el.contains(document.elementFromPoint(x, r.y + r.height / 2));
}), `${label}: ${tab} hit target is covered`);
await assert.doesNotReject(() => page.waitForFunction(tab => {
return document.querySelector(`#project-tab-${tab}`).classList.contains('is-active') &&
[...document.querySelectorAll('.projects-panel')].every(panel => panel.hidden === (panel.id !== `project-panel-${tab}`));
}, tab, { timeout: 1000 }), `${label}: ${tab} failed to switch`);
}
}
}
} finally {
await context.close();
}
}
} finally {
await browser.close();
}
});
// Unlike the header-only fixture above, this uses the entire project page inside
// the actual flex shell, including its fixed heading, project list and bottom bar.
test('mobile project page scrolls its final row above the bottom navigation', async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
try {
for (const [width, height, visibleHeight] of [[320, 568, 568], [393, 852, 700], [430, 932, 780], [767, 600, 500]]) {
const context = await browser.newContext({ viewport: { width, height }, isMobile: true, hasTouch: true });
try {
const page = await context.newPage();
const projectPage = await page.evaluate(template => new DOMParser().parseFromString(template, 'text/html').querySelector('#page-projects').outerHTML, template);
await page.setContent(`<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div class="container"><header><div class="header-content">CyberStrikeAI</div></header><div class="main-layout"><div class="content-area">${projectPage}</div></div></div><nav id="m-tabbar">底部导航</nav></body></html>`);
for (const file of ['style.css', 'mobile.css']) await page.addStyleTag({ content: read(`web/static/css/${file}`) });
await page.evaluate(visibleHeight => {
document.documentElement.style.setProperty('--m-app-height', `${visibleHeight}px`);
document.documentElement.style.setProperty('--m-safe-bottom', '20px');
document.querySelector('#page-projects').classList.add('active');
document.querySelector('.projects-detail').classList.add('has-project');
document.querySelector('#projects-detail-inner').hidden = false;
document.querySelector('#projects-detail-title').textContent = 'Long project name / 项目名称 '.repeat(6);
document.querySelector('#projects-list').innerHTML = '<div class="projects-list-item">项目一</div>'.repeat(3);
document.querySelector('#projects-pagination').textContent = '1–3/3 1/1 每页 50';
}, visibleHeight);
await page.addScriptTag({ content: `let currentProjectTab = 'facts';
${['Facts', 'FactGraph', 'Assets', 'Conversations', 'Vulnerabilities'].map(name => `function loadProject${name}() {}`).join('\n')}
${switchTab}` });
for (const theme of ['light', 'dark']) {
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
for (const rowCount of [1, 35]) {
for (const tab of ['facts', 'assets', 'conversations', 'vulns']) {
const label = `${width}x${height}/${visibleHeight} ${theme} ${tab} ${rowCount} rows`;
await page.evaluate(({tab, rowCount}) => {
window.switchProjectTab(tab);
const panel = document.querySelector(`#project-panel-${tab}`);
const cells = panel.querySelectorAll('thead th').length;
panel.querySelector('tbody').innerHTML = Array.from({length: rowCount}, (_, i) => `<tr><td><button type="button" ${i === rowCount - 1 ? 'data-last-row' : ''} onclick="window.lastRowClicked=true">${i + 1}</button></td>${'<td>test</td>'.repeat(cells - 1)}</tr>`).join('');
const scroller = document.querySelector('.projects-page-layout');
scroller.scrollTop = scroller.scrollHeight;
}, {tab, rowCount});
if (rowCount === 35 && tab === 'conversations' && theme === 'light') {
await page.evaluate(() => { document.querySelector('.projects-page-layout').scrollTop = 0; });
const bounds = await page.locator('.projects-page-layout').boundingBox();
await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height - 20);
await page.mouse.wheel(0, 500);
await page.waitForFunction(() => document.querySelector('.projects-page-layout').scrollTop > 0);
await page.evaluate(() => {
const scroller = document.querySelector('.projects-page-layout');
scroller.scrollTop = scroller.scrollHeight;
});
}
const result = await page.evaluate(tab => {
const scroller = document.querySelector('.projects-page-layout');
const row = document.querySelector(`#project-panel-${tab} [data-last-row]`);
const r = row.getBoundingClientRect();
const area = scroller.getBoundingClientRect();
const bar = document.querySelector('#m-tabbar').getBoundingClientRect();
return {areaBottom: area.bottom, barTop: bar.top, rowTop: r.top, rowBottom: r.bottom, areaTop: area.top,
hit: row.contains(document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2))};
}, tab);
assert.ok(result.areaBottom <= result.barTop + 1, `${label}: page scroller extends under bottom bar ${JSON.stringify(result)}`);
assert.ok(result.rowTop >= result.areaTop && result.rowBottom <= result.areaBottom, `${label}: final row is clipped ${JSON.stringify(result)}`);
assert.ok(result.hit, `${label}: final row cannot receive a tap`);
await page.evaluate(() => { window.lastRowClicked = false; });
await page.locator(`#project-panel-${tab} [data-last-row]`).tap();
assert.equal(await page.evaluate(() => window.lastRowClicked), true, `${label}: final row tap failed`);
}
}
for (const tab of ['graph', 'settings']) {
const result = await page.evaluate(tab => {
window.switchProjectTab(tab);
const scroller = document.querySelector('.projects-page-layout');
scroller.scrollTop = scroller.scrollHeight;
const footer = document.querySelector(tab === 'graph' ? '.project-fact-graph-footer' : '.projects-settings-footer');
const r = footer.getBoundingClientRect();
const area = scroller.getBoundingClientRect();
return {visible: r.top >= area.top && r.bottom <= area.bottom,
graphHeight: document.querySelector('.project-fact-graph-layout').getBoundingClientRect().height};
}, tab);
assert.ok(result.visible, `${width}px ${theme} ${tab}: footer is clipped`);
if (tab === 'graph') assert.ok(result.graphHeight >= 240, `${width}px ${theme}: graph canvas collapsed`);
}
}
} finally { await context.close(); }
}
} finally { await browser.close(); }
});
test('mobile facts keep badges and actions inside their columns while scrolling horizontally', async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
try {
for (const width of [320, 393, 767]) {
const context = await browser.newContext({viewport: {width, height: 900}, isMobile: true, hasTouch: true});
try {
const page = await context.newPage();
await page.setContent(`<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div class="container"><header>CyberStrikeAI</header><div id="page-projects" class="page active"><div class="page-content projects-page-layout">${markup}</div></div></div></body></html>`);
for (const file of ['style.css', 'mobile.css']) await page.addStyleTag({content: read(`web/static/css/${file}`)});
await page.addScriptTag({content: source});
const mobileSource = read('web/static/js/mobile-ui.js');
const wrapTables = mobileSource.slice(mobileSource.indexOf(' function wrapTables('), mobileSource.indexOf(' /* ---------------------------------------------------------------------\n 11.'));
await page.addScriptTag({content: `const isMobile = () => true;
const $$ = (selector, root) => Array.from(root.querySelectorAll(selector));
const el = (tag, cls) => Object.assign(document.createElement(tag), {className: cls});
${wrapTables}
wrapTables(document);`});
await page.evaluate(() => {
currentProjectId = 'fixture-project';
document.querySelector('.projects-detail').classList.add('has-project');
document.querySelector('#projects-detail-inner').hidden = false;
window.apiFetch = async () => ({ok: true, json: async () => [
{id:'note', fact_key:'note/automatic-continuation', category:'note', summary:'自动续接的项目记录 '.repeat(10), body:'详细记录', confidence:'tentative', updated_at:'2026-10-12T10:00:00Z'},
{id:'finding', fact_key:'finding/8080/exposure', category:'finding', summary:'8080 / exposed service', body:'## Steps\n1. curl http://target:8080\n## Request\nGET /', confidence:'confirmed', updated_at:'2026-10-12T10:00:00Z', link_counts:{incoming:2,outgoing:10}},
]});
refreshProjectHeaderStats = () => {};
window.showEditFactModal = () => { window.actionClicked = 'edit'; };
window.viewProjectFactBody = () => { window.actionClicked = 'details'; };
});
for (const locale of ['zh-CN', 'en-US', 'ru-RU']) {
await page.evaluate(dict => {
window.t = key => key.split('.').reduce((v, k) => v?.[k], dict) || key;
document.querySelectorAll('thead [data-i18n]').forEach(el => { el.textContent = window.t(el.dataset.i18n); });
}, JSON.parse(read(`web/static/i18n/${locale}.json`)));
await page.evaluate(() => loadProjectFacts());
for (const theme of ['light', 'dark']) {
const label = `${width}px ${locale} ${theme}`;
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
const layout = await page.evaluate(() => {
const table = document.querySelector('#project-panel-facts table');
return {
width:table.getBoundingClientRect().width,
badCells: [...table.querySelectorAll('thead th, tbody td')].filter(cell => {
const r = cell.getBoundingClientRect();
return [...cell.children].some(child => {
const c = child.getBoundingClientRect();
return c.left < r.left - 1 || c.right > r.right + 1;
});
}).map(cell => cell.className || cell.textContent),
sticky: getComputedStyle(table.querySelector('td.col-actions')).position,
};
});
assert.ok(layout.width >= 1200, `${label}: eight columns are squeezed to the phone width`);
assert.deepEqual(layout.badCells, [], `${label}: badges or actions escape their cells`);
assert.notEqual(layout.sticky, 'sticky', `${label}: action column overlays fact data`);
const scroller = page.locator('#project-panel-facts .projects-table-wrap');
await scroller.evaluate(el => { el.scrollLeft = el.scrollWidth; });
for (const [selector, action] of [['.projects-action-btn--edit', 'edit'], ['.projects-action-btn--view', 'details']]) {
await page.locator(`#project-facts-tbody ${selector}`).first().tap({timeout: 3000});
assert.equal(await page.evaluate(() => window.actionClicked), action, `${label}: ${action} is unreachable`);
}
await scroller.evaluate(el => { el.scrollLeft = 0; });
}
}
} finally { await context.close(); }
}
} finally { await browser.close(); }
});

View File

@ -1,209 +0,0 @@
// Exercise the production dynamic renderers with offline data only.
const assert = require("node:assert/strict");
module.exports = async ({ page, width, height, theme, out }) => {
for (const name of ["info-collect", "webshell"])
await page.addScriptTag({ url: "/static/js/" + name + ".js" });
const activate = (id) =>
page.evaluate(
(id) =>
document
.querySelectorAll(".page")
.forEach((e) => e.classList.toggle("active", e.id === id)),
id,
);
const verify = async (id, name) => {
await page.locator("#" + id + " .modal-body").waitFor();
await page.waitForTimeout(220);
const box = await page.locator("#" + id).evaluate((e) => {
const p = e.querySelector(".modal-content"),
b = e.querySelector(".modal-body"),
h = e.querySelector(".modal-header h2"),
r = p.getBoundingClientRect(),
s = getComputedStyle(p);
return {
surface: e.dataset.uiSurface,
x: r.x,
right: r.right,
width: r.width,
height: r.height,
radius: s.borderRadius,
bg: s.backgroundColor,
titleColor: getComputedStyle(h).color,
bodyWidth: b.clientWidth,
bodyScroll: b.scrollWidth,
footer: e.querySelector(".modal-footer").getBoundingClientRect().bottom,
expandedButton: !!e.querySelector(".app-drawer-expand"),
};
});
assert.equal(box.surface, "drawer");
assert.equal(box.radius, "0px");
assert(box.expandedButton);
assert(
Math.abs(box.right - width) < 2 && Math.abs(box.height - height) < 2,
JSON.stringify(box),
);
assert(
box.width <= (width < 768 ? width : width - 48) + 1 && box.width > 0,
JSON.stringify(box),
);
assert(
box.footer <= height + 1 && box.bodyScroll <= box.bodyWidth + 2,
JSON.stringify(box),
);
assert.equal(
box.bg,
theme === "dark" ? "rgb(17, 24, 39)" : "rgb(255, 255, 255)",
);
if (theme === "dark")
assert(Number(box.titleColor.match(/\d+/)[0]) > 150, JSON.stringify(box));
await page.screenshot({
animations: "disabled",
path: `${out}/extra-${name}-${width}-${theme}.png`,
});
if (width >= 768) {
await page.locator("#" + id + " .app-drawer-expand").click();
assert(
(await page.locator("#" + id + " .modal-content").boundingBox()).width >
box.width,
);
await page.locator("#" + id + " .app-drawer-expand").click();
}
};
await activate("page-info-collect");
await page.evaluate(() => {
window.extraDrawerRequests = [];
window.apiFetch = async (url, options = {}) => {
extraDrawerRequests.push({ url, method: options.method || "GET" });
return { ok: true, json: async () => ({ conversations: [] }) };
};
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: {
writeText: async (text) => {
window.extraDrawerCopied = text;
},
},
});
window.extraDrawerText =
"Content-Security-Policy: " +
"example.test ".repeat(120) +
"\n" +
"详细字段内容 <script>不应执行</script>\n".repeat(60);
showCellDetailModal("响应头完整内容", extraDrawerText);
});
await verify("info-collect-cell-modal", "cell-fulltext");
assert.equal(
await page.locator(".info-collect-cell-modal-pre").textContent(),
await page.evaluate(() => extraDrawerText),
);
await page.locator("#info-collect-cell-modal-copy").click();
assert.equal(
await page.evaluate(() => extraDrawerCopied),
await page.evaluate(() => extraDrawerText),
);
await page.keyboard.press("Escape");
assert.equal(await page.locator("#info-collect-cell-modal").count(), 0);
await page.evaluate(() => {
showCellDetailModal("旧字段", "旧值");
showCellDetailModal("新字段", "新值");
});
assert.equal(await page.locator("#info-collect-cell-modal").count(), 1);
await page.locator("#info-collect-cell-modal-ok").click();
assert.equal(
await page.evaluate(() =>
document.body.classList.contains("app-modal-open"),
),
false,
);
await page.evaluate(() =>
showFofaParseModal("查找演示资产", {
query: 'domain="example.test"',
warnings: ["仅展示语法,未发起查询。".repeat(20)],
explanation: "查询条件解释。\n".repeat(80),
}),
);
await verify("fofa-parse-modal", "parse-result");
await page.locator("#fofa-parse-query").fill('domain="demo.example.test"');
await page.locator("#fofa-parse-apply").click();
assert.equal(
await page.locator("#fofa-query").inputValue(),
'domain="demo.example.test"',
);
assert.equal(await page.locator("#fofa-parse-modal").count(), 0);
assert.equal(
await page.evaluate(() => extraDrawerRequests.length),
0,
"Applying syntax must not query a provider",
);
await page.evaluate(() => {
showFofaParseModal("旧请求", { query: "old" });
showFofaParseModal("新请求", { query: "new" });
});
await page.locator("#fofa-parse-query").waitFor();
assert.equal(await page.locator("#fofa-parse-query").inputValue(), "new");
await page.keyboard.press("Escape");
assert.equal(await page.locator("#fofa-parse-modal").count(), 0);
assert.equal(
await page.evaluate(() =>
document.body.classList.contains("app-modal-open"),
),
false,
);
await activate("page-webshell");
await page.evaluate(() => {
// Keep terminal and persistence transports out of this UI fixture. The actual
// workspace renderer and DB add/edit/close handlers still execute unchanged.
initWebshellTerminal = () => {};
queueWebshellPersistStateSave = () => {};
webshellConnections = [
{
id: "offline-ui",
name: "离线界面回归",
url: "https://example.test",
type: "php",
project_id: "",
},
];
selectWebshell("offline-ui", true);
});
await page.locator('.webshell-tab[data-tab="db"]').click();
await page.locator("#webshell-db-add-profile-btn").click();
await verify("webshell-db-profile-modal", "db-add");
await page.locator("#webshell-db-profile-cancel-btn").click();
await page
.locator('#webshell-db-profiles [data-action="edit"]')
.first()
.click();
await verify("webshell-db-profile-modal", "db-edit");
const toolbarBackground = await page
.locator("#webshell-db-profile-modal .webshell-db-toolbar")
.evaluate((e) => getComputedStyle(e).backgroundColor);
if (theme === "dark")
assert(Number(toolbarBackground.match(/\d+/)[0]) < 100, toolbarBackground);
await page.locator("#webshell-db-type").selectOption("sqlite");
assert(await page.locator("#webshell-db-sqlite-path").isVisible());
assert(!(await page.locator("#webshell-db-host").isVisible()));
await page.keyboard.press("Escape");
assert(!(await page.locator("#webshell-db-profile-modal").isVisible()));
assert.equal(
await page.evaluate(() =>
document.body.classList.contains("app-modal-open"),
),
false,
);
const requests = await page.evaluate(() => extraDrawerRequests);
assert(
requests.every(
(r) =>
r.method === "GET" &&
[
"/api/roles",
"/api/config",
"/api/webshell/connections/offline-ui/ai-conversations",
"/api/webshell/connections/offline-ui/ai-history",
].includes(r.url),
),
JSON.stringify(requests),
);
};

View File

@ -1,601 +0,0 @@
// Anonymized reproductions of the real Kali UI states: 365 tasks, 626 tools,
// 614 enabled tools, multi-file skill, 50 long findings. All writes are rejected.
const assert = require("node:assert/strict");
module.exports = async function ({ page, width, height, theme, out }) {
await page.addScriptTag({ url: "/static/vendor/cytoscape.min.js" });
for (const script of [
"tasks",
"skills",
"assessment-workbench",
"assessment-node-panel",
"assessment-exploration-views",
"deep-assessment-graph",
"deep-assessments",
"vulnerability",
"vulnerability-workspace",
])
await page.addScriptTag({ url: "/static/js/" + script + ".js" });
await page.evaluate(() => {
const tools = Array.from({ length: 626 }, (_, i) => ({
name: "review_tool_" + i,
description: "检查授权范围内的接口、权限和配置,保留可复核证据。".repeat(
4,
),
enabled: i < 614,
}));
const role = {
name: "界面回归角色",
description: "真实规模的长描述与工具清单",
enabled: true,
tools: [],
user_prompt: "根据已有证据整理报告。".repeat(12),
};
const assessment = {
id: "assessment-fixture",
name: "授权评估回归任务",
status: "draft",
revision: 1,
steps: [],
objective: "检查已有数据的布局",
scope: "离线界面回归",
updated_at: "2026-11-15T08:00:00Z",
};
const graph = {
nodes: [
{ id: "goal", kind: "goal", title: "核对已有证据", body: "整理本地样例记录。", source: {} },
{ id: "step:fixture", kind: "step", step_id: "fixture", title: "核对记录和原始回执", state: "completed", body: "已整理样例记录,保留原始回执。\n\nInstruction: " + "核对已有证据,记录来源及尚未确认的内容。此段用于验证长文本布局。\n\n".repeat(30), source: { evidence: ["receipt:fixture"] } },
{ id: "receipt:fixture", kind: "receipt", title: "样例执行回执", body: "example.test /fixture — local sample", source: {} },
],
edges: [{ source: "goal", target: "step:fixture", relation: "plans" }, { source: "step:fixture", target: "receipt:fixture", relation: "executes" }],
total: 2, folded: 0, has_more: false,
};
const queue = {
id: "ui-fixture",
title: "多目标授权评估回归队列",
status: "paused",
role: role.name,
agentMode: "single",
scheduleMode: "manual",
concurrency: 2,
totalTasks: 365,
completedTasks: 34,
createdAt: "2026-11-10T13:01:13Z",
tasks: Array.from({ length: 365 }, (_, i) => ({
id: "task-" + i,
status: i < 34 ? "completed" : "pending",
message:
"https://long-service-name-" + i + ".example.test/verification",
})),
};
window.fixtureQueue = queue;
window.apiFetch = async (input, opts = {}) => {
if (opts.method && opts.method !== "GET")
throw new Error("UI regression must not write: " + input);
const url = new URL(input, location.origin);
let data = {};
if (url.pathname === "/api/roles") data = { roles: [role] };
else if (url.pathname === "/api/config/tools") {
const size = Number(url.searchParams.get("page_size") || 20),
index = Number(url.searchParams.get("page") || 1);
data = {
tools: tools.slice((index - 1) * size, index * size),
total: 626,
total_enabled: 614,
total_pages: Math.ceil(626 / size),
page: index,
page_size: size,
};
} else if (url.pathname === "/api/batch-tasks/ui-fixture")
data = { queue };
else if (url.pathname.endsWith("/files"))
data = {
files: [
{ path: "SKILL.md" },
{ path: "references/long-reference-name.md" },
{ path: "assets/README.txt" },
],
};
else if (url.pathname.startsWith("/api/skills/"))
data = {
skill: {
id: "review-skill",
description: "多文件技能包编辑测试",
name: "review-skill",
path: "skills/review-skill",
scripts: [
{ rel_path: "scripts/check.py", description: "离线证据校核" },
],
content:
url.searchParams.get("depth") === "summary"
? "# 技能摘要\n按需加载正文。"
: "# 审核步骤\n" + "核对已有证据。\n".repeat(40),
},
};
else if (url.pathname === "/api/deep-assessments/options")
data = {
roles: [role.name],
models: ["默认模型"],
projects: [{ id: "ui-project", name: "回归项目" }],
};
else if (url.pathname === "/api/deep-assessments")
data = { tasks: [assessment], has_more: false };
else if (url.pathname === "/api/deep-assessments/assessment-fixture")
data = { task: assessment };
else if (url.pathname.endsWith("/graph"))
data = graph;
else if (url.pathname.endsWith("/graph/node"))
data = { node: graph.nodes.find(n => n.id === url.searchParams.get("node_id")), has_more: false };
else if (url.pathname.endsWith("/assets"))
data = { nodes: [], edges: [], assets: [], total: 0, has_more: false };
return { ok: true, json: async () => data };
};
window.showNotification = (message, type) => {
if (type === "error") throw new Error(message);
};
roles = [role];
});
const activate = async (id) =>
page.evaluate(
(id) =>
document
.querySelectorAll(".page")
.forEach((e) => e.classList.toggle("active", e.id === id)),
id,
);
const shot = async (name) =>
page.screenshot({
animations: "disabled",
path: `${out}/real-${name}-${width}-${theme}.png`,
});
const contrastResults = [];
await activate("page-tasks");
const states = [
{ status: "paused", scheduleMode: "manual", label: "继续执行" },
{ status: "pending", scheduleMode: "manual", label: "开始执行" },
{
status: "pending",
scheduleMode: "cron",
scheduleEnabled: true,
label: "立即执行一轮",
},
{
status: "pending",
scheduleMode: "cron",
scheduleEnabled: false,
label: "开始执行",
},
{ status: "running", scheduleMode: "manual" },
{ status: "completed", scheduleMode: "manual" },
{ status: "cancelled", scheduleMode: "manual" },
];
for (const state of states) {
await page.evaluate(async (state) => {
Object.assign(fixtureQueue, state);
await showBatchQueueDetail("ui-fixture");
}, state);
await page
.locator("#batch-queue-detail-content .batch-task-item")
.first()
.waitFor();
const layout = await page
.locator("#batch-queue-detail-modal .modal-header")
.evaluate((e) => {
const title = e.querySelector("h2").getBoundingClientRect(),
header = e.getBoundingClientRect();
const controls = Array.from(e.querySelectorAll("button"))
.filter((b) => b.getClientRects().length)
.map((b) => b.getBoundingClientRect());
return {
titleWidth: title.width,
headerHeight: header.height,
allInside: controls.every(
(r) => r.left >= header.left && r.right <= header.right + 1,
),
titleOverlaps: controls.some(
(r) =>
r.left < title.right &&
r.right > title.left &&
r.top < title.bottom &&
r.bottom > title.top,
),
};
});
assert(layout.titleWidth > 200, JSON.stringify(layout));
assert(layout.headerHeight < 190, JSON.stringify(layout));
assert(layout.allInside && !layout.titleOverlaps, JSON.stringify(layout));
await page.evaluate(() => applyTranslations(document.body));
const assertLabels = async () => {
const text = await page.locator("#batch-queue-detail-title").innerText();
assert.equal(text, "批量任务队列 - 多目标授权评估回归队列");
if (state.label)
assert.equal(
await page.locator("#batch-queue-start-btn").innerText(),
state.label,
);
else
assert.equal(
await page.locator("#batch-queue-start-btn").isVisible(),
false,
);
};
await assertLabels();
// Real breakpoint transitions call mobile boot, which reapplies all translations.
if (width === 1440 && state.label) {
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForTimeout(150);
await assertLabels();
await page.setViewportSize({ width, height });
await page.waitForTimeout(150);
await assertLabels();
}
for (const button of await page
.locator(
"#batch-queue-detail-modal .modal-header-actions .btn-primary:visible",
)
.all()) {
for (const appearance of ["normal", "hover", "focus"]) {
if (appearance === "normal")
await page.mouse.move(width - 4, height - 4);
if (appearance === "hover") await button.hover();
if (appearance === "focus") {
await page.mouse.move(width - 4, height - 4);
await button.focus();
await page.keyboard.press("Tab");
await page.keyboard.press("Shift+Tab");
assert(
await button.evaluate((e) => e.matches(":focus-visible")),
"Keyboard focus indicator missing",
);
}
await page.waitForTimeout(220);
const colors = await button.evaluate((e) => ({
foreground: getComputedStyle(e).color,
background: getComputedStyle(e).backgroundColor,
disabled: e.disabled,
text: e.textContent,
}));
assert(!colors.disabled);
const rgb = (value) => {
assert(/^rgb/.test(value), JSON.stringify(colors));
const values = value.match(/[\d.]+/g).map(Number);
assert(
values.length === 3 || values[3] === 1,
"Primary background must be opaque",
);
return values.slice(0, 3).map((v) => {
const c = v / 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
});
};
const lum = (value) => {
const [r, g, b] = rgb(value);
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
};
const a = lum(colors.foreground),
b = lum(colors.background);
const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
contrastResults.push({
state: state.status,
label: state.label,
appearance,
ratio,
...colors,
});
assert(
ratio >= 4.5,
JSON.stringify({ width, theme, appearance, ratio, ...colors }),
);
}
}
if (state.status === "paused") await shot("queue");
await page.evaluate(() => closeBatchQueueDetailModal());
}
// Queue names are literal content, including characters that look like markup.
await page.evaluate(async () => {
fixtureQueue.title = "复核 & <说明>";
fixtureQueue.status = "paused";
await showBatchQueueDetail("ui-fixture");
applyTranslations(document.body);
});
assert.equal(
await page.locator("#batch-queue-detail-title").innerText(),
"批量任务队列 - 复核 & <说明>",
);
assert.equal(await page.locator("#batch-queue-detail-title > *").count(), 1);
await page.evaluate(async () => {
fixtureQueue.title = "";
await showBatchQueueDetail("ui-fixture");
applyTranslations(document.body);
});
assert.equal(
await page.locator("#batch-queue-detail-title").innerText(),
"批量任务队列",
);
await page.evaluate(() => {
fixtureQueue.title = "多目标授权评估回归队列";
});
require("node:fs").writeFileSync(
`${out}/queue-contrast-${width}-${theme}.json`,
JSON.stringify(contrastResults, null, 2),
);
// A real language change translates the prefix and action, but never the queue name.
await page.evaluate(async () => {
fixtureQueue.status = "paused";
await showBatchQueueDetail("ui-fixture");
onLanguageSelect("en-US");
});
await page.waitForFunction(
() =>
document.documentElement.lang === "en-US" &&
document.getElementById("batch-queue-start-btn").textContent === "Resume",
);
assert(
(await page.locator("#batch-queue-detail-title").innerText()).endsWith(
" - 多目标授权评估回归队列",
),
);
await page.evaluate(() => onLanguageSelect("zh-CN"));
await page.waitForFunction(
() =>
document.documentElement.lang === "zh-CN" &&
document.getElementById("batch-queue-start-btn").textContent ===
"继续执行",
);
assert.equal(
await page.locator("#batch-queue-detail-title").innerText(),
"批量任务队列 - 多目标授权评估回归队列",
);
await page.evaluate(() => closeBatchQueueDetailModal());
await activate("page-roles-management");
await page.evaluate(() => editRole("界面回归角色"));
await page.locator("#role-tools-list input").first().waitFor();
await page.evaluate(() => applyTranslations(document));
assert.equal(await page.locator("#role-modal-title").innerText(), "编辑角色");
const stats = await page.locator("#role-tools-stats").evaluate((e) => ({
width: e.clientWidth,
scroll: e.scrollWidth,
text: e.textContent,
}));
assert(stats.text.includes("614") && stats.text.includes("626"), stats.text);
assert(stats.scroll <= stats.width + 2, JSON.stringify(stats));
await page.locator("#role-tools-stats").scrollIntoViewIfNeeded();
await shot("role-tools");
await page.evaluate(() => closeRoleModal());
await page.evaluate(() => showAddRoleModal());
await page.evaluate(() => applyTranslations(document));
assert.equal(await page.locator("#role-modal-title").innerText(), "添加角色");
await page.evaluate(() => closeRoleModal());
await activate("page-skills-management");
// View is dynamically created and must use the same square drawer as Edit.
await page.evaluate(() => viewSkill("review-skill"));
await page.locator("#skill-view-modal").waitFor();
await page.waitForTimeout(220);
const skillView = await page.locator("#skill-view-modal").evaluate((e) => {
const p = e.querySelector(".modal-content"),
r = p.getBoundingClientRect(),
s = getComputedStyle(p);
return {
surface: e.dataset.uiSurface,
width: r.width,
right: r.right,
height: r.height,
radius: s.borderRadius,
bg: s.backgroundColor,
footer: e.querySelector(".modal-footer").getBoundingClientRect().bottom,
};
});
assert.equal(skillView.surface, "drawer");
assert.equal(skillView.radius, "0px");
assert(
Math.abs(skillView.right - width) < 2 &&
Math.abs(skillView.height - height) < 2,
JSON.stringify(skillView),
);
assert(
Math.abs(
skillView.width - (width < 768 ? width : Math.min(960, width - 48)),
) < 2,
JSON.stringify(skillView),
);
assert(skillView.footer <= height + 1, JSON.stringify(skillView));
assert.equal(
skillView.bg,
theme === "dark" ? "rgb(17, 24, 39)" : "rgb(255, 255, 255)",
);
assert.equal(
await page.locator("#skill-view-body").innerText(),
"# 技能摘要\n按需加载正文。",
);
await shot("skill-view-summary");
await page.locator("#skill-view-modal [data-skill-load-full]").click();
await page.waitForFunction(() =>
document
.getElementById("skill-view-body")
.textContent.startsWith("# 审核步骤"),
);
if (width >= 768) {
await page.locator("#skill-view-modal .app-drawer-expand").click();
assert(
(await page.locator("#skill-view-modal .modal-content").boundingBox())
.width >= skillView.width,
);
}
await page.keyboard.press("Escape");
assert.equal(await page.locator("#skill-view-modal").count(), 0);
assert.equal(
await page.evaluate(() =>
document.body.classList.contains("app-modal-open"),
),
false,
);
await page.evaluate(() => viewSkill("review-skill"));
await page.locator("#skill-view-modal [data-skill-view-edit]").click();
assert.equal(await page.locator("#skill-view-modal").count(), 0);
await page.locator("#skill-modal").waitFor();
assert.equal(
await page.locator("#skill-modal").getAttribute("data-ui-surface"),
"drawer",
);
await page.locator("#skill-content").waitFor();
await page.evaluate(() => applyTranslations(document));
assert.equal(
await page.locator("#skill-modal-title").innerText(),
"编辑Skill",
);
await shot("skill");
await page.evaluate(() => closeSkillModal());
await page.evaluate(() => showAddSkillModal());
await page.evaluate(() => applyTranslations(document));
assert.equal(
await page.locator("#skill-modal-title").innerText(),
"添加Skill",
);
await page.evaluate(() => closeSkillModal());
// Real breakpoint transition: mobile boot reapplies the translations.
if (width === 1440) {
await activate("page-roles-management");
await page.evaluate(() => editRole("界面回归角色"));
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForTimeout(100);
assert.equal(
await page.locator("#role-modal-title").innerText(),
"编辑角色",
);
await page.evaluate(() => closeRoleModal());
await page.setViewportSize({ width, height });
await activate("page-skills-management");
await page.evaluate(() => editSkill("review-skill"));
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForTimeout(100);
assert.equal(
await page.locator("#skill-modal-title").innerText(),
"编辑Skill",
);
await page.evaluate(() => closeSkillModal());
await page.setViewportSize({ width, height });
}
await activate("page-deep-assessments");
await page.evaluate(() => DeepAssessments.init());
await page.locator('[data-da-action="create"]').click();
await page.locator("#da-form-drawer[open]").waitFor();
await page.waitForTimeout(220);
const native = await page.locator("#da-form-drawer").evaluate((e) => ({
rect: e.getBoundingClientRect().toJSON(),
bg: getComputedStyle(e).backgroundColor,
radius: getComputedStyle(e).borderRadius,
expand: !!e.querySelector(".app-drawer-expand"),
}));
assert(native.expand);
assert.equal(native.radius, "0px");
assert(Math.abs(native.rect.right - width) < 2, JSON.stringify(native));
assert(Math.abs(native.rect.height - height) < 2);
assert.equal(
native.bg,
theme === "dark" ? "rgb(17, 24, 39)" : "rgb(255, 255, 255)",
);
if (width >= 768) {
const before = native.rect.width;
await page.locator("#da-form-drawer .app-drawer-expand").click();
assert(
(await page.locator("#da-form-drawer").boundingBox()).width > before,
);
await page.locator("#da-form-drawer .app-drawer-expand").click();
}
await shot("assessment");
await page.keyboard.press("Escape");
assert.equal(
await page.locator("#da-form-drawer").getAttribute("open"),
null,
);
assert.equal(
await page
.locator("#da-form-drawer .app-drawer-expand")
.getAttribute("aria-pressed"),
"false",
);
await page.locator('[data-da-action="select"]').click();
await page.locator("#da-title h2").waitFor();
await page.locator('[data-da-action="tab"][data-tab="overview"]').click();
assert.equal(
await page.locator("#da-workspace").getAttribute("aria-labelledby"),
"da-title",
);
assert.equal(
await page.locator("#da-workspace .app-drawer-expand").count(),
0,
);
assert.equal(
await page
.locator("#da-workspace")
.evaluate((e) => getComputedStyle(e).borderRadius),
"0px",
);
await shot("assessment-detail");
await page.locator('[data-da-action="tab"][data-tab="graph"]').click();
await page.locator('#da-graph-select').selectOption('step:fixture');
await page.locator('.da-node-prose').first().waitFor();
const reader = page.locator('#da-graph-node');
if (width >= 1440) assert((await reader.boundingBox()).width >= 400);
await shot("assessment-node-split");
await reader.getByRole('button', { name: '展开阅读', exact: true }).click();
assert.equal(await page.locator('#da-graph-canvas').isVisible(), false);
assert((await reader.locator('.da-node-content').boundingBox()).height >= 160);
await shot("assessment-node-reader");
await page.locator('[data-da-action="tab"][data-tab="assets"]').click();
await page.locator('#da-asset-query').focus();
assert.equal(await page.locator('.da-empty-state').count(), 1);
await shot("assessment-assets");
await page.locator('[data-da-action="back-list"]').click();
await activate("page-vulnerabilities");
await page.evaluate(() => {
const rows = Array.from({ length: 50 }, (_, i) => ({
id: "finding-" + i,
title: "接口响应与权限检查发现:包含较长的组件版本和复现说明 " + i,
description: "已验证的证据摘要。".repeat(10),
severity: i % 3 ? "low" : "high",
status: "open",
target: "https://service-" + i + ".example.test",
target_host: "service-" + i + ".example.test",
target_domain: "example.test",
createdAt: "2026-11-10T12:00:00Z",
}));
vulnerabilityPagination = {
currentPage: 1,
totalPages: 3,
total: 110,
pageSize: 50,
};
renderVulnerabilities(rows, { view: "host" });
renderVulnerabilityPagination();
});
await page.locator(".vulnerability-record-row").first().waitFor();
if (width < 768) {
await page
.locator(".vulnerability-record-row")
.first()
.scrollIntoViewIfNeeded();
await page.locator("#page-vulnerabilities").evaluate((e) => {
e.scrollTop +=
e.querySelector(".vulnerability-record-row").getBoundingClientRect()
.top - e.getBoundingClientRect().top;
});
const scroll = await page
.locator("#page-vulnerabilities")
.evaluate((e) => ({
height: e.clientHeight,
scrollTop: e.scrollTop,
contentOverflow: getComputedStyle(e.querySelector(".page-content"))
.overflowY,
headerBottom: e.querySelector(".page-header").getBoundingClientRect()
.bottom,
top: e.getBoundingClientRect().top,
}));
assert(
scroll.scrollTop > 0 && scroll.headerBottom <= scroll.top + 1,
JSON.stringify(scroll),
);
assert(scroll.contentOverflow === "visible", JSON.stringify(scroll));
assert(scroll.height >= height - 150, JSON.stringify(scroll));
}
await shot("findings");
};

80
web/frontend/CONTRACT.md Normal file
View File

@ -0,0 +1,80 @@
# 前端契约(React 19 + Semi Design)
所有页面都在 `web/frontend/src/pages/<页面 id>/` 下实现,入口固定为 `index.jsx`,默认导出页面组件。
页面 id 与路由 `#/<页面 id>` 一一对应,清单见 `src/pages/registry.js` 与 `src/lib/nav.js`。
## 唯一允许的公共依赖
```js
import { Button, Card, Table, Form, Modal, Drawer, Select, Input, Tabs, Tag, Space, Typography,
Banner, Descriptions, Popconfirm, Toast, Tooltip, Switch, Checkbox, Radio, RadioGroup,
DatePicker, Progress, Spin, Empty, List, Timeline, Collapse, Pagination, TextArea,
Avatar, Badge, Divider, SideSheet, Tree, TreeSelect, Upload, Slider, Steps, SplitButton,
ButtonGroup, Skeleton, Notification } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh, IconSearch, IconDelete, IconEdit } from '@douyinfe/semi-icons';
```
路由:`react-router-dom` v7(`useNavigate`、`useSearchParams`、`useParams`、`Link`)。
图形:`cytoscape`(仅 deep-assessments / projects 需要)。终端:`@xterm/xterm` + `@xterm/addon-fit`。
Markdown:统一用 `MarkdownView`,不要自己引 marked/dompurify。
不要新增 npm 依赖,不要直接 `fetch`,不要写 `window.xxx` 全局,不要操作 DOM 查询(`document.getElementById`)。
## 公共模块
```js
import { api, downloadFile, postStream, errorMessage } from '../../lib/http';
import { useAuth } from '../../lib/auth'; // { user, roles, hasPermission('x:read'), hasAnyPermission([...]), refresh }
import { useT } from '../../lib/i18n'; // t('key', {n:1}, '中文默认值')
import { useResource, useInterval, useDebounced, useLocalStorage } from '../../components/hooks';
import {
PageHeader, SectionCard, StatGrid, StatCard, DataTable, ErrorBanner, SeverityTag, StatusTag,
CopyButton, MarkdownView, JsonViewer, KeyValueList, toastSuccess, toastWarning, toastError,
confirmAction
} from '../../components/ui';
```
`api` 用法:`api.get('/vulnerabilities', { page: 1, page_size: 20 })`、`api.post('/x', body)`、
`api.put`、`api.del`。路径不带 `/api` 前缀(自动补)。返回值已解析 JSON,非 2xx 抛 `ApiError`。
`useResource(loader, deps)` 返回 `{ data, loading, error, reload, setData }`,列表页统一用它。
`t(key, vars, fallback)` 的 key 取自仓库既有 `web/static/i18n/zh-CN.json`;找不到时用第三个参数的中文兜底。
文案必须走 `t(...)` 或直接写中文,不要硬编码英文。
## 样式
页面私有样式写同目录 `page.css` 并在 `index.jsx` 里 `import './page.css';`。
仅允许少量布局样式(flex/grid/间距),颜色一律使用 Semi 变量:
`var(--semi-color-bg-1)`、`var(--semi-color-border)`、`var(--semi-color-text-2)`、`var(--semi-color-primary)` 等。
不要复制旧版 css 文件,不要自定义整套配色。
## 数据契约来源
后端接口在 `internal/app/app.go`(`setupRoutes`)注册,响应结构看 `internal/handler/*.go`。
旧前端调用方式在 `web/static/js/<模块>.js`,字段名与请求体以旧代码 + handler 为准,不要臆造字段。
页面容器在 `web/templates/index.html`(`id="page-<id>"`)可查既有交互与字段提示。
## 页面完成标准
1. 首屏加载真实数据(GET),有 loading / 空态 / 错误态(`ErrorBanner` + `onRetry`)。
2. 主操作可用:列表 + 详情(Drawer/Modal)+ 新建/编辑表单 + 删除确认 + 刷新;写操作按钮用 `hasPermission('x:write')` 控制禁用或隐藏。
3. 深链接:按 id 定位的页面从 `useSearchParams()` 读取(如 `#/vulnerabilities?id=xxx`),操作后写回 URL。
4. 不改 `src/pages/registry.js`、`src/lib/*`、`src/components/*`、`src/layout/*`、`src/styles/app.css`。
5. 页面目录内可以任意拆分文件,单文件建议 < 500 行。
## 自检(不要跑整站构建,避免与其他页面互相干扰)
```sh
cd web/frontend
npx esbuild src/pages/<page>/index.jsx --bundle --jsx=automatic --format=esm \
--external:react --external:react-dom --external:react-router-dom \
--external:@douyinfe/* --external:cytoscape --external:marked --external:dompurify \
--outdir=/tmp/csai-check-<page>
```
页面 import 了 `page.css` 时必须用 `--outdir`(`--outfile=/dev/null` 会连带写 `/dev/null.css` 而失败)。
该命令只验证语法与本地相对导入,`--external:@douyinfe/*` 会跳过 Semi 导出名解析——
最终以 `npm run build` 为准,命名导入必须是 Semi 真实导出(`Drawer` 请从 `components/ui` 导入,Semi v2 用 `SideSheet`)。
完成后在最终回复里列出:页面 id、使用的接口、验证过的交互、遗留问题。

55
web/frontend/README.md Normal file
View File

@ -0,0 +1,55 @@
# 前端(React 19 + Semi Design)
CyberStrikeAI 的 Web 界面是一个 Vite 构建的 React 单页应用,UI 组件统一来自
[Semi Design](https://semi.design/zh-CN/)。页面不再使用 Go 模板、手写 HTML/CSS/JS 或全局 `window.*` 脚本。
## 目录
```
web/frontend/
├─ index.html # Vite 入口,挂载 #root
├─ vite.config.mjs # base=/static/app/,产物输出到 web/static/app
├─ CONTRACT.md # 页面开发契约(公共模块 / 样式 / 自检)
└─ src/
├─ main.jsx # 主题、i18n、Semi ConfigProvider、HashRouter
├─ App.jsx # 路由与权限守卫
├─ lib/ # http、auth、i18n、theme、nav、format
├─ layout/ # 侧边导航、顶栏、登录页
├─ components/ # PageHeader / DataTable / StatGrid / Markdown 等
├─ pages/<页面 id>/ # 与路由 #/<页面 id> 一一对应
└─ styles/app.css # 外壳与共享组件样式
```
## 开发
```sh
npm ci --prefix web/frontend
npm run --prefix web/frontend dev # 本地热更新,静态资源直接从工作区读取
# 联调时显式指定你实际启动的后端,避免误连占用默认端口的其他应用:
CSAI_API_ORIGIN=http://127.0.0.1:8080 npm run --prefix web/frontend dev
```
后端仍由 Go 提供:`go run ./cmd/server -config config.yaml`。未设置 `CSAI_API_ORIGIN` 时,开发服务器的 API 返回 503,不会连接默认端口上的其他服务。
浏览器回归:`npm run --prefix web/frontend test:ui`(需要本机 Chrome)。测试使用独立浏览器和匿名 fixture,拦截全部 API 与外联,不连接部署环境;报告和截图分别位于 `playwright-report/`、`test-results/`。该测试不替代真实后端联调。
## 构建与发布
```sh
npm run --prefix web/frontend build
```
产物写入 `web/static/app/`(哈希文件名)。Go 服务通过 `router.Static("/static", "./web/static")`
提供静态资源,`GET /` 直接返回 `web/static/app/index.html`;`/api-docs` 302 到 `/#/api-docs`。
构建产物需要随源码一起提交,`internal/app/spa_test.go` 会校验首页引用的资源全部存在。
## 约定
- 路由使用 hash:`#/dashboard`、`#/chat?conversation=<id>`、`#/vulnerabilities?id=<id>`,深链接可直接分享。
- 会话令牌沿用 `localStorage['cyberstrike-auth']`,请求统一走 `src/lib/http.js`(自动附加 `Authorization`)。
- 主题偏好沿用 `localStorage['cyberstrike-theme']`(system/light/dark),语言沿用 `localStorage['csai_lang']`,
词条复用 `web/static/i18n/*.json`。
- 页面只能通过 `api` / `postStream` 访问 `/api`,不得直接 `fetch`;权限判断用 `useAuth().hasPermission(...)`。
- 新增页面:在 `src/pages/<id>/index.jsx` 实现默认导出组件,并在 `src/pages/registry.js` 与 `src/lib/nav.js` 注册。
详细页面契约见 [CONTRACT.md](./CONTRACT.md)。

26
web/frontend/index.html Normal file
View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#3266e3">
<title>CyberStrikeAI</title>
<link rel="icon" href="/static/favicon.ico">
<link rel="manifest" href="/static/site.webmanifest">
<script>
(function () {
try {
var stored = localStorage.getItem('cyberstrike-theme') || 'system';
var dark = stored === 'dark' || (stored !== 'light' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme-preference', stored);
document.documentElement.style.colorScheme = dark ? 'dark' : 'light';
} catch (error) { /* first paint fallback */ }
})();
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

4804
web/frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
web/frontend/package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "cyberstrikeai-frontend",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test:ui": "playwright test"
},
"dependencies": {
"@douyinfe/semi-icons": "2.105.0",
"@douyinfe/semi-ui": "2.105.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"cytoscape": "^3.33.1",
"dompurify": "^3.4.18",
"marked": "^16.4.2",
"react": "19.3.1",
"react-dom": "19.3.1",
"react-router-dom": "7.18.5"
},
"devDependencies": {
"@playwright/test": "^1.65.1",
"@vitejs/plugin-react": "6.3.0",
"esbuild": "^0.27.1",
"vite": "8.3.8"
}
}

View File

@ -0,0 +1,44 @@
import { defineConfig } from '@playwright/test';
import { fileURLToPath } from 'node:url';
const frontend = fileURLToPath(new URL('.', import.meta.url));
export default defineConfig({
testDir: fileURLToPath(new URL('./tests', import.meta.url)),
testMatch: '*.spec.mjs',
outputDir: fileURLToPath(new URL('./test-results', import.meta.url)),
fullyParallel: false,
workers: 1,
retries: 0,
forbidOnly: Boolean(process.env.CI),
timeout: 45_000,
expect: { timeout: 10_000 },
reporter: [
['list'],
['html', { outputFolder: fileURLToPath(new URL('./playwright-report', import.meta.url)), open: 'never' }]
],
use: {
baseURL: 'http://127.0.0.1:5199/static/app/',
browserName: 'chromium',
channel: process.env.CI ? undefined : 'chrome',
headless: true,
viewport: { width: 1440, height: 1000 },
locale: 'zh-CN',
timezoneId: 'Asia/Shanghai',
colorScheme: 'light',
serviceWorkers: 'block',
actionTimeout: 10_000,
navigationTimeout: 30_000,
screenshot: { mode: 'on', fullPage: true },
trace: 'retain-on-failure'
},
webServer: {
command: 'npm run dev -- --host 127.0.0.1 --port 5199 --strictPort',
cwd: frontend,
url: 'http://127.0.0.1:5199/static/app/',
reuseExistingServer: false,
timeout: 60_000,
// Extra protection for a server started here; browser routing also guards reused servers.
env: { CSAI_API_ORIGIN: 'http://127.0.0.1:9' }
}
});

77
web/frontend/src/App.jsx Normal file
View File

@ -0,0 +1,77 @@
import { Suspense, useMemo } from 'react';
import { Navigate, Route, Routes, useParams } from 'react-router-dom';
import { Spin, Typography } from '@douyinfe/semi-ui';
import AppLayout from './layout/AppLayout';
import LoginPage from './layout/LoginPage';
import { useAuth } from './lib/auth';
import { useT } from './lib/i18n';
import { findPage } from './lib/nav';
import { PAGES } from './pages/registry';
const { Title, Text } = Typography;
function Loading() {
return (
<div className="cs-page-loading">
<Spin size="large" />
</div>
);
}
function StatusPage({ code, title, description }) {
return (
<div className="cs-page-loading" style={{ flexDirection: 'column', gap: 8 }}>
<Title heading={2} style={{ margin: 0 }}>{code}</Title>
<Text strong>{title}</Text>
{description && <Text type="tertiary">{description}</Text>}
</div>
);
}
function PageHost() {
const { pageId } = useParams();
const { hasPermission, hasAnyPermission } = useAuth();
const t = useT();
const page = findPage(pageId);
const Component = pageId ? PAGES[pageId] : null;
const allowed = useMemo(() => {
if (!page) return true;
if (page.anyPermission) return hasAnyPermission(page.anyPermission);
if (page.permission) return hasPermission(page.permission);
const parent = page.parent ? findPage(page.parent) : null;
if (parent?.anyPermission) return hasAnyPermission(parent.anyPermission);
return true;
}, [page, hasPermission, hasAnyPermission]);
if (!page) {
return <StatusPage code="404" title={t('common.pageNotFound', null, '页面不存在')} />;
}
if (!Component) {
return <StatusPage code="404" title={page.fallback} description={t('common.pagePending', null, '页面尚未注册')} />;
}
if (!allowed) {
return <StatusPage code="403" title={t('common.forbidden', null, '当前账号没有访问该页面的权限')} />;
}
return (
<Suspense fallback={<Loading />}>
<Component />
</Suspense>
);
}
export default function App() {
const { authenticated, checking } = useAuth();
if (checking) return <Loading />;
if (!authenticated) return <LoginPage />;
return (
<Routes>
<Route element={<AppLayout />}>
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route path="/system-update" element={<Navigate to="/settings?section=update" replace />} />
<Route path="/:pageId" element={<PageHost />} />
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Route>
</Routes>
);
}

View File

@ -0,0 +1,68 @@
/** 通用异步数据装载:统一 loading / error / reload 语义。 */
import { useCallback, useEffect, useRef, useState } from 'react';
export function useResource(loader, deps = [], { initial = null, skip = false } = {}) {
const [data, setData] = useState(initial);
const [loading, setLoading] = useState(!skip);
const [error, setError] = useState(null);
const seq = useRef(0);
const reload = useCallback(async (options = {}) => {
if (skip) return null;
const current = ++seq.current;
if (!options.silent) setLoading(true);
setError(null);
try {
const result = await loader();
if (current === seq.current) setData(result);
return result;
} catch (err) {
if (current === seq.current) setError(err);
return null;
} finally {
if (current === seq.current) setLoading(false);
}
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (skip) { setLoading(false); return; }
reload();
return () => { seq.current += 1; };
}, [reload, skip]);
return { data, setData, loading, error, reload };
}
export function useDebounced(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
export function useInterval(callback, delay) {
const saved = useRef(callback);
useEffect(() => { saved.current = callback; }, [callback]);
useEffect(() => {
if (!delay) return undefined;
const timer = setInterval(() => saved.current(), delay);
return () => clearInterval(timer);
}, [delay]);
}
export function useLocalStorage(key, initial) {
const [value, setValue] = useState(() => {
try {
const raw = localStorage.getItem(key);
return raw === null ? initial : JSON.parse(raw);
} catch (error) {
return initial;
}
});
useEffect(() => {
try { localStorage.setItem(key, JSON.stringify(value)); } catch (error) { /* ignore */ }
}, [key, value]);
return [value, setValue];
}

View File

@ -0,0 +1,255 @@
/**
* 共享展示组件:页面骨架、指标卡、表格、空状态、标签、Markdown 与 JSON 视图。
* 业务页面统一使用这些组件,避免各页重复写样式。
*/
import { useMemo, useState } from 'react';
import {
Banner, Button, Card, Collapsible, Descriptions, Empty, Modal, SideSheet, Skeleton, Space, Table, Tag, Toast, Typography
} from '@douyinfe/semi-ui';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import { IconChevronDown, IconChevronUp, IconCopy, IconInbox, IconRefresh } from '@douyinfe/semi-icons';
import { useT } from '../lib/i18n';
import { SEVERITY_LABEL, severityColor, statusColor } from '../lib/format';
import { errorMessage } from '../lib/http';
const { Title, Text, Paragraph } = Typography;
export function toastSuccess(content) {
Toast.success({ content, duration: 2 });
}
export function toastWarning(content) {
Toast.warning({ content, duration: 3 });
}
export function toastError(error, fallback = '操作失败') {
Toast.error({ content: errorMessage(error, fallback), duration: 4 });
}
export function PageHeader({ title, description, extra, children }) {
return (
<header className="cs-page-header">
<div className="cs-page-header-main">
<Title heading={3} className="cs-page-title">{title}</Title>
{description && <Text type="tertiary" className="cs-page-desc">{description}</Text>}
{children}
</div>
{extra && <Space className="cs-page-header-extra" wrap>{extra}</Space>}
</header>
);
}
export function SectionCard({ title, description, extra, children, className = '', bodyClassName = '' }) {
return (
<Card
className={`cs-section-card ${className}`}
title={title ? <span className="cs-section-title">{title}</span> : undefined}
headerExtraContent={extra}
bordered={false}
>
{description && <Paragraph type="tertiary" className="cs-section-desc">{description}</Paragraph>}
<div className={bodyClassName}>{children}</div>
</Card>
);
}
export function StatGrid({ metrics, columns = 4 }) {
return (
<div className="cs-stat-grid" style={{ '--cs-stat-columns': columns }}>
{metrics.map(metric => (
<StatCard key={metric.id || metric.label} {...metric} />
))}
</div>
);
}
export function StatCard({ label, value, valueTitle, detail, tone, icon, onClick, loading }) {
const content = (
<>
<span className="cs-stat-head">
<Text type="tertiary" className="cs-stat-label">{label}</Text>
{icon && <span className={`cs-stat-icon ${tone ? `tone-${tone}` : ''}`} aria-hidden="true">{icon}</span>}
</span>
<Skeleton loading={loading} placeholder={<Skeleton.Title style={{ width: '60%', height: 36, margin: '8px 0' }} />}>
<span className={`cs-stat-value ${tone ? `tone-${tone}` : ''}`} title={valueTitle}>{value ?? '—'}</span>
</Skeleton>
{detail && <span className="cs-stat-detail">{detail}</span>}
</>
);
return onClick ? (
<Button className="cs-stat-card is-clickable" theme="borderless" onClick={onClick} aria-label={String(label)}>{content}</Button>
) : (
<Card className="cs-stat-card" bordered={false}>{content}</Card>
);
}
export function DataTable({
columns, dataSource, rowKey = 'id', loading, pagination, emptyText, onRefresh,
toolbar, size = 'default', className = '', ...rest
}) {
const t = useT();
const mergedPagination = pagination === false ? false : {
pageSize: 10,
showSizeChanger: true,
pageSizeOpts: [10, 20, 50, 100],
showTotal: true,
...(pagination || {})
};
return (
<div className={`cs-table-wrap ${className}`}>
{(toolbar || onRefresh) && (
<div className="cs-table-toolbar">
<div className="cs-table-toolbar-main">{toolbar}</div>
{onRefresh && (
<Button icon={<IconRefresh />} theme="borderless" onClick={onRefresh} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
)}
</div>
)}
<div className="cs-table-scroll">
<Table
columns={columns}
dataSource={dataSource || []}
rowKey={rowKey}
loading={loading}
pagination={mergedPagination}
size={size}
empty={<Empty image={<IconInbox size="extra-large" />} title={emptyText || t('common.noData', null, '暂无数据')} description={null} className="cs-table-empty" />}
{...rest}
/>
</div>
</div>
);
}
export function ErrorBanner({ error, onRetry }) {
const t = useT();
if (!error) return null;
return (
<Banner
type="danger"
bordered
closeIcon={null}
className="cs-error-banner"
description={<Space wrap>
<span>{errorMessage(error, t('common.loadFailed', null, '加载失败'))}</span>
{onRetry && <Button size="small" onClick={onRetry}>{t('common.refresh', null, '刷新')}</Button>}
</Space>}
/>
);
}
export function SeverityTag({ severity, size = 'small' }) {
const key = String(severity || '').toLowerCase();
return <Tag size={size} color={severityColor(key)} shape="circle">{SEVERITY_LABEL[key] || severity || '—'}</Tag>;
}
export function StatusTag({ status, label, size = 'small' }) {
const key = String(status || '').toLowerCase();
return <Tag size={size} color={statusColor(key)} shape="square">{label || status || '—'}</Tag>;
}
export function CopyButton({ text, label, size = 'default', theme = 'borderless' }) {
const t = useT();
return (
<Button
size={size}
theme={theme}
icon={<IconCopy />}
aria-label={label || t('common.copy', null, '复制')}
onClick={async () => {
try {
await navigator.clipboard.writeText(String(text ?? ''));
toastSuccess(t('common.copied', null, '已复制'));
} catch (error) {
toastError(error, t('common.copyFailed', null, '复制失败'));
}
}}
>
{label}
</Button>
);
}
export function MarkdownView({ content, className = '' }) {
const html = useMemo(() => {
const raw = marked.parse(String(content ?? ''), { breaks: true, gfm: true });
return DOMPurify.sanitize(raw, { ADD_ATTR: ['target', 'rel'] });
}, [content]);
return <div className={`cs-markdown ${className}`} dangerouslySetInnerHTML={{ __html: html }} />;
}
export function JsonViewer({ value, collapsed = false, title }) {
const [open, setOpen] = useState(!collapsed);
const t = useT();
const text = useMemo(() => {
try {
return JSON.stringify(value, null, 2);
} catch (error) {
return String(value);
}
}, [value]);
return (
<div className="cs-json-viewer">
<div className="cs-json-viewer-head">
<Text strong>{title || 'JSON'}</Text>
<Space spacing={4}>
<CopyButton text={text} />
<Button theme="borderless" size="small" icon={open ? <IconChevronUp /> : <IconChevronDown />}
aria-expanded={open} aria-label={t(open ? 'common.collapse' : 'common.expand', null, open ? '收起' : '展开')}
onClick={() => setOpen(current => !current)} />
</Space>
</div>
<Collapsible isOpen={open}>
<pre className="cs-json-viewer-body">{text}</pre>
</Collapsible>
</div>
);
}
export function KeyValueList({ items, columns = 2 }) {
return (
<Descriptions className="cs-description-list" layout="horizontal" align="plain" column={columns}
data={items.filter(Boolean).map(item => ({ key: item.label, value: item.value ?? '—' }))} />
);
}
export function confirmAction({ title, content, okText, danger = true, onOk }) {
Modal.confirm({
title,
content,
okText: okText || '确定',
cancelText: '取消',
okButtonProps: danger ? { type: 'danger' } : undefined,
onOk
});
}
export function useConfirmDelete() {
return (title, onOk) => confirmAction({ title, content: null, onOk });
}
/**
* Drawer:Semi Design v2 以 SideSheet 提供抽屉,这里保留 Drawer 名称,
* 统一 title/visible/onCancel/width/footer 的调用方式,页面无需关心底层组件。
*/
export function Drawer({ title, visible, onCancel, width = 560, footer, children, placement = 'right', bodyStyle, className, style, ...rest }) {
return (
<SideSheet
title={title}
visible={visible}
onCancel={onCancel}
width={width}
footer={footer}
placement={placement}
bodyStyle={bodyStyle}
className={`cs-drawer ${className || ''}`}
style={style}
{...rest}
>
{children}
</SideSheet>
);
}

View File

@ -0,0 +1,370 @@
import { useEffect, useMemo, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
Avatar, Badge, Breadcrumb, Button, Dropdown, Form, Modal, Nav, Popover, SideSheet, Space, Typography
} from '@douyinfe/semi-ui';
import {
IconBell, IconChevronLeft, IconChevronRight, IconExit, IconKey, IconLanguage, IconMenu, IconMoon, IconSun
} from '@douyinfe/semi-icons';
import { useAuth } from '../lib/auth';
import { useI18n, LANGUAGES, useT } from '../lib/i18n';
import { useTheme } from '../lib/theme';
import { NAV_SECTIONS, NAV_TREE, findPage } from '../lib/nav';
import { api } from '../lib/http';
import { toastError, toastSuccess } from '../components/ui';
import { formatDateTime } from '../lib/format';
import { useInterval } from '../components/hooks';
const { Text } = Typography;
function useIsMobile() {
const [mobile, setMobile] = useState(() => window.matchMedia('(max-width: 900px)').matches);
useEffect(() => {
const media = window.matchMedia('(max-width: 900px)');
const onChange = event => setMobile(event.matches);
media.addEventListener('change', onChange);
return () => media.removeEventListener('change', onChange);
}, []);
return mobile;
}
function buildNavItems(tree, t, hasPermission, hasAnyPermission) {
return tree
.filter(item => (!item.anyPermission || hasAnyPermission(item.anyPermission)) && (!item.permission || hasPermission(item.permission)))
.map(item => {
const children = item.children
? item.children.filter(child => !child.permission || hasPermission(child.permission))
: null;
if (children && children.length === 0) return null;
return {
itemKey: children ? item.id : item.id,
text: t(item.i18n, null, item.fallback),
icon: item.icon ? <item.icon aria-hidden="true" /> : undefined,
items: children
? children.map(child => ({ itemKey: child.id, text: t(child.i18n, null, child.fallback) }))
: undefined
};
})
.filter(Boolean);
}
function ThemeMenu() {
const { preference, setPreference } = useTheme();
const t = useT();
const options = [
{ key: 'system', label: t('theme.system', null, '跟随系统') },
{ key: 'light', label: t('theme.light', null, '浅色') },
{ key: 'dark', label: t('theme.dark', null, '暗色') }
];
const current = options.find(option => option.key === preference) || options[0];
return (
<Dropdown
trigger="click"
position="bottomRight"
menu={options.map(option => ({
node: 'item',
name: option.label,
active: option.key === preference,
onClick: () => setPreference(option.key)
}))}
>
<Button theme="borderless" type="tertiary" icon={preference === 'dark' ? <IconMoon /> : <IconSun />} aria-label={current.label} />
</Dropdown>
);
}
function LanguageMenu() {
const { lang, setLanguage } = useI18n();
return (
<Dropdown
trigger="click"
position="bottomRight"
menu={LANGUAGES.map(item => ({
node: 'item',
name: item.label,
active: item.id === lang,
onClick: () => setLanguage(item.id)
}))}
>
<Button theme="borderless" type="tertiary" icon={<IconLanguage />} aria-label={lang} />
</Dropdown>
);
}
function NotificationsBell({ navigate }) {
const t = useT();
const [items, setItems] = useState([]);
const [pending, setPending] = useState(0);
const [visible, setVisible] = useState(false);
const [marking, setMarking] = useState(false);
const load = async () => {
try {
const summary = await api.get('/notifications/summary', { limit: 80, lang: document.documentElement.lang || 'zh-CN' });
const list = Array.isArray(summary?.items) ? summary.items : [];
setItems(list);
setPending(summary?.unreadCount ?? list.filter(item => !item.read).length);
} catch (error) {
/* 通知属于辅助信息,失败不打扰 */
}
};
useEffect(() => { load(); }, []);
useInterval(load, 60000);
const markSeen = async () => {
const ids = items.filter(item => !item.read).map(item => item.id).filter(Boolean);
if (!ids.length || marking) return;
setMarking(true);
try {
await api.post('/notifications/read', { eventIds: ids });
await load();
} catch (error) {
toastError(error);
} finally {
setMarking(false);
}
};
const openItem = item => {
setVisible(false);
if (item.type === 'vulnerability_created' && item.vulnerabilityId) navigate(`/vulnerabilities?id=${encodeURIComponent(item.vulnerabilityId)}`);
else if ((item.type === 'task_completed' || item.type === 'long_running_tasks') && item.conversationId) navigate(`/chat?conversation=${encodeURIComponent(item.conversationId)}`);
else if (item.type === 'task_failed') navigate('/mcp-monitor');
else if (item.type === 'hitl_pending') navigate('/hitl');
else if (item.type === 'c2_session_online') navigate('/c2-sessions');
};
const content = (
<div className="cs-notification-panel">
<div className="cs-notification-head">
<Text strong>{t('notifications.title', null, '通知')}</Text>
<Button size="small" theme="borderless" onClick={markSeen} loading={marking}>{t('notifications.markAllRead', null, '全部标记已读')}</Button>
</div>
<div className="cs-notification-list">
{items.length === 0 && <Text type="tertiary">{t('notifications.empty', null, '暂无新通知')}</Text>}
{items.map(item => (
<button type="button" key={item.id || `${item.type}-${item.ts}`} className="cs-notification-item" onClick={() => openItem(item)}>
<span className={`cs-notification-dot level-${item.level || 'p2'}`} />
<span className="cs-notification-body">
<span className="cs-notification-title">{item.title || item.message || item.type}</span>
<span className="cs-notification-meta">
{item.ts ? formatDateTime(item.ts) : ''}
{item.count > 1 ? ` · ×${item.count}` : ''}
</span>
</span>
</button>
))}
</div>
</div>
);
return (
<Popover content={content} trigger="click" position="bottomRight" visible={visible} onVisibleChange={setVisible}>
<Badge count={pending || null} overflowCount={99} type="danger">
<Button theme="borderless" type="tertiary" icon={<IconBell />} aria-label={t('notifications.title', null, '通知')} />
</Badge>
</Popover>
);
}
function UserMenu({ navigate }) {
const { user, logout, refresh } = useAuth();
const t = useT();
const [passwordOpen, setPasswordOpen] = useState(false);
const [formApi, setFormApi] = useState(null);
const [saving, setSaving] = useState(false);
const submitPassword = async values => {
setSaving(true);
try {
await api.post('/auth/change-password', { oldPassword: values.oldPassword, newPassword: values.newPassword });
toastSuccess(t('auth.passwordChanged', null, '密码已更新'));
setPasswordOpen(false);
formApi?.reset();
} catch (error) {
toastError(error, t('auth.changeFailed', null, '修改密码失败'));
} finally {
setSaving(false);
}
};
return (
<>
<Dropdown
trigger="click"
position="bottomRight"
menu={[
{ node: 'title', name: user?.display_name || user?.username || 'admin' },
{
node: 'item',
name: t('auth.changePassword', null, '修改密码'),
icon: <IconKey />,
onClick: () => setPasswordOpen(true)
},
{
node: 'item',
name: t('auth.refreshSession', null, '刷新会话权限'),
onClick: () => refresh().then(() => toastSuccess(t('auth.sessionRefreshed', null, '会话已刷新'))).catch(error => toastError(error))
},
{ node: 'divider' },
{
node: 'item',
name: t('auth.logout', null, '退出登录'),
icon: <IconExit />,
onClick: async () => { await logout(); navigate('/dashboard'); }
}
]}
>
<Button theme="borderless" type="tertiary" className="cs-user-trigger" aria-label={t('auth.userMenu', null, '用户菜单')}>
<Avatar size="extra-small" color="blue">{(user?.display_name || user?.username || 'A').slice(0, 1).toUpperCase()}</Avatar>
<span className="cs-user-name">{user?.display_name || user?.username || 'admin'}</span>
</Button>
</Dropdown>
<Modal
title={t('auth.changePassword', null, '修改密码')}
visible={passwordOpen}
onCancel={() => setPasswordOpen(false)}
footer={null}
width={420}
>
<Form onSubmit={submitPassword} getFormApi={setFormApi}>
<Form.Input field="oldPassword" label={t('auth.currentPassword', null, '当前密码')} type="password" rules={[{ required: true, message: t('auth.required', null, '必填') }]} />
<Form.Input field="newPassword" label={t('auth.newPassword', null, '新密码')} type="password" rules={[{ required: true, min: 8, message: t('auth.passwordMin', null, '至少 8 位') }]} />
<Form.Input field="confirmPassword" label={t('auth.confirmPassword', null, '确认新密码')} type="password" rules={[
{ required: true, message: t('auth.required', null, '必填') },
{ validator: (rule, value) => value === formApi?.getValue('newPassword'), message: t('auth.passwordMismatch', null, '两次输入不一致') }
]} />
<Button htmlType="submit" theme="solid" type="primary" loading={saving} block>
{t('common.save', null, '保存')}
</Button>
</Form>
</Modal>
</>
);
}
export default function AppLayout() {
const { hasPermission, hasAnyPermission } = useAuth();
const t = useT();
const location = useLocation();
const navigate = useNavigate();
const mobile = useIsMobile();
const [collapsed, setCollapsed] = useState(() => localStorage.getItem('csai-nav-collapsed') === '1');
const [drawerOpen, setDrawerOpen] = useState(false);
const [openKeys, setOpenKeys] = useState([]);
const segments = location.pathname.replace(/^\//, '').split('/');
const pageId = segments[0] || 'dashboard';
const page = findPage(pageId);
const selectedKeys = useMemo(() => [pageId], [pageId]);
const navItems = useMemo(() => buildNavItems(NAV_TREE, t, hasPermission, hasAnyPermission), [t, hasPermission, hasAnyPermission]);
useEffect(() => {
setDrawerOpen(false);
if (page?.parent) setOpenKeys(keys => keys.includes(page.parent) ? keys : [...keys, page.parent]);
}, [location.pathname, page?.parent]);
useEffect(() => {
document.title = `${page ? t(page.i18n, null, page.fallback) : '工作台'} · CyberStrikeAI`;
}, [page, t]);
const onSelect = ({ itemKey }) => {
const search = location.search;
const carry = ['chat', 'vulnerabilities', 'settings', 'deep-assessments'].includes(itemKey) && pageId === itemKey ? search : '';
navigate(`/${itemKey}${carry}`);
};
const toggleCollapsed = () => {
setCollapsed(current => {
localStorage.setItem('csai-nav-collapsed', current ? '0' : '1');
return !current;
});
};
const compact = collapsed && !mobile;
const navNode = (
<div className={`cs-sidebar-inner ${compact ? 'is-compact' : ''}`}>
<Button className="cs-brand" theme="borderless" type="tertiary" onClick={() => navigate('/dashboard')} aria-label="CyberStrikeAI">
<img src="/static/logo.png" alt="" className="cs-brand-logo" />
{!compact && <span className="cs-brand-name">CyberStrike<span>AI</span></span>}
</Button>
<div className="cs-nav-scroll">
{NAV_SECTIONS.map(section => {
const items = navItems.filter(item => section.pages.includes(item.itemKey));
if (!items.length) return null;
return (
<section className="cs-nav-section" key={section.id} aria-label={t(section.i18n, null, section.fallback)}>
{!compact && <div className="cs-nav-section-label">{t(section.i18n, null, section.fallback)}</div>}
<Nav
className="cs-nav"
style={{ width: '100%' }}
items={items}
selectedKeys={selectedKeys}
onSelect={onSelect}
isCollapsed={compact}
openKeys={openKeys}
onOpenChange={({ openKeys: keys }) => setOpenKeys(keys)}
/>
</section>
);
})}
</div>
{!mobile && (
<div className="cs-nav-footer">
<Button theme="borderless" type="tertiary" block icon={compact ? <IconChevronRight /> : <IconChevronLeft />}
aria-label={t(compact ? 'nav.expand' : 'nav.collapse', null, compact ? '展开菜单' : '收起菜单')}
onClick={toggleCollapsed}>
{!compact && t('nav.collapse', null, '收起菜单')}
</Button>
</div>
)}
</div>
);
const title = page ? t(page.i18n, null, page.fallback) : 'CyberStrikeAI';
const parentPage = page?.parent ? findPage(page.parent) : null;
const parentTitle = parentPage ? t(parentPage.i18n, null, parentPage.fallback) : '';
return (
<div className={`cs-shell ${collapsed && !mobile ? 'is-collapsed' : ''}`}>
{!mobile && <aside className="cs-sider">{navNode}</aside>}
{mobile && (
<SideSheet
visible={drawerOpen}
onCancel={() => setDrawerOpen(false)}
placement="left"
width={264}
title={t('nav.navigation', null, '导航')}
bodyStyle={{ padding: 0 }}
className="cs-mobile-nav"
>
{navNode}
</SideSheet>
)}
<div className="cs-main">
<header className="cs-header">
<div className="cs-header-left">
{mobile && (
<Button theme="borderless" icon={<IconMenu />} onClick={() => setDrawerOpen(true)} aria-label={t('common.expandPanel', null, '展开面板')} />
)}
<Breadcrumb className="cs-header-crumb" compact={false}>
<Breadcrumb.Item onClick={() => navigate('/dashboard')}>{t('nav.groupWorkspace', null, '工作台')}</Breadcrumb.Item>
{parentTitle && <Breadcrumb.Item>{parentTitle}</Breadcrumb.Item>}
<Breadcrumb.Item>{title}</Breadcrumb.Item>
</Breadcrumb>
</div>
<Space className="cs-header-actions" spacing={4}>
<NotificationsBell navigate={navigate} />
<LanguageMenu />
<ThemeMenu />
<UserMenu navigate={navigate} />
</Space>
</header>
<main className={`cs-content ${pageId === 'chat' ? 'cs-content-workspace' : ''}`} id="main-content">
<Outlet context={{ navigate, pageId, mobile }} />
</main>
</div>
</div>
);
}

View File

@ -0,0 +1,81 @@
import { useState } from 'react';
import { Banner, Button, Card, Form, Typography } from '@douyinfe/semi-ui';
import { IconArticle, IconBranch, IconBriefcase, IconLock, IconShield, IconUser } from '@douyinfe/semi-icons';
import { useAuth } from '../lib/auth';
import { useT } from '../lib/i18n';
import { errorMessage } from '../lib/http';
const { Title, Text, Paragraph } = Typography;
export default function LoginPage() {
const { login } = useAuth();
const t = useT();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
async function submit(values) {
setLoading(true);
setError('');
try {
await login(values.username, values.password);
} catch (err) {
setError(errorMessage(err, t('login.loginFailed', null, '登录失败')));
} finally {
setLoading(false);
}
}
return (
<main className="cs-login-page">
<section className="cs-login-story">
<div className="cs-login-brand">
<img src="/static/logo.png" alt="" className="cs-login-logo" />
<span className="cs-brand-name">CyberStrike<span>AI</span></span>
</div>
<div className="cs-login-intro">
<span className="cs-login-emblem" aria-hidden="true"><IconShield size="extra-large" /></span>
<Title heading={1} className="cs-login-headline">{t('login.headline', null, '让每一次探索,都有据可循。')}</Title>
<Paragraph type="tertiary">{t('login.intro', null, '从目标梳理到证据归档,在一个工作台中完成你的安全研究。')}</Paragraph>
<div className="cs-login-features">
<div className="cs-login-feature"><IconBriefcase size="large" /><div><strong>{t('login.projectTitle', null, '围绕项目协作')}</strong>{t('login.projectHint', null, '跨会话共享目标、上下文与研究进展')}</div></div>
<div className="cs-login-feature"><IconBranch size="large" /><div><strong>{t('login.assessmentTitle', null, '让探索持续推进')}</strong>{t('login.assessmentHint', null, '规划、执行与人工复核,始终保持可控')}</div></div>
<div className="cs-login-feature"><IconArticle size="large" /><div><strong>{t('login.evidenceTitle', null, '以证据支撑结论')}</strong>{t('login.evidenceHint', null, '保留发现、来源与验收记录')}</div></div>
</div>
</div>
<Text type="tertiary" size="small">{t('login.platformTagline', null, 'AI 驱动的安全研究工作台')}</Text>
</section>
<section className="cs-login-form-panel">
<Card className="cs-login-card" bordered={false}>
<Title heading={2} className="cs-login-form-heading">{t('login.welcome', null, '欢迎回来')}</Title>
<Text type="tertiary">{t('login.welcomeHint', null, '登录你的安全工作台,继续探索。')}</Text>
<Form onSubmit={submit} className="cs-login-form">
{error && <Banner type="danger" description={error} closeIcon={null} className="cs-error-banner" />}
<Form.Input
field="username"
label={t('login.username', null, '用户名')}
prefix={<IconUser />}
placeholder={t('login.usernamePlaceholder', null, '请输入用户名')}
size="large"
autoComplete="username"
rules={[{ required: true, message: t('login.usernameRequired', null, '请输入用户名') }]}
/>
<Form.Input
field="password"
label={t('login.password', null, '密码')}
prefix={<IconLock />}
type="password"
size="large"
autoComplete="current-password"
placeholder={t('login.passwordPlaceholder', null, '请输入密码')}
rules={[{ required: true, message: t('login.passwordRequired', null, '请输入密码') }]}
/>
<Button htmlType="submit" theme="solid" type="primary" size="large" block loading={loading}>
{t('login.submit', null, '登录')}
</Button>
</Form>
<Text type="tertiary" className="cs-login-note">{t('login.authorizedOnly', null, '仅在明确授权的范围内开展安全测试')}</Text>
</Card>
</section>
</main>
);
}

View File

@ -0,0 +1,118 @@
/**
* 会话与权限:Bearer 令牌保存在 localStorage(与历史版本同一存储键),
* 启动时调用 /api/auth/validate 刷新角色与权限,401 时整体退出。
*/
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { api, readStoredAuth, setAuthToken, writeStoredAuth } from './http';
const AuthContext = createContext(null);
function normalizeSession(raw, token) {
if (!raw) return null;
return {
token: token || raw.token,
expiresAt: raw.expires_at || raw.expiresAt || '',
user: raw.user || null,
roles: Array.isArray(raw.roles) ? raw.roles : [],
permissions: Array.isArray(raw.permissions) ? raw.permissions : [],
scope: raw.scope || ''
};
}
export function AuthProvider({ children }) {
const stored = useRef(readStoredAuth()).current;
const [session, setSession] = useState(stored);
const [checking, setChecking] = useState(Boolean(stored));
useEffect(() => {
setAuthToken(stored?.token || null);
if (!stored?.token) { setChecking(false); return; }
let cancelled = false;
api.get('/auth/validate')
.then(payload => {
if (cancelled) return;
const next = normalizeSession(payload, stored.token);
setSession(next);
writeStoredAuth(next);
})
.catch(() => {
if (cancelled) return;
setSession(null);
writeStoredAuth(null);
setAuthToken(null);
})
.finally(() => { if (!cancelled) setChecking(false); });
return () => { cancelled = true; };
}, []);
const clear = useCallback(() => {
setSession(null);
setAuthToken(null);
writeStoredAuth(null);
}, []);
useEffect(() => {
const onUnauthorized = () => clear();
window.addEventListener('csai:unauthorized', onUnauthorized);
return () => window.removeEventListener('csai:unauthorized', onUnauthorized);
}, [clear]);
const login = useCallback(async (username, password) => {
const payload = await api.post('/auth/login', { username: String(username || '').trim(), password });
const next = normalizeSession(payload, payload?.token);
setAuthToken(next?.token || null);
writeStoredAuth(next);
setSession(next);
return next;
}, []);
const logout = useCallback(async () => {
try {
await api.post('/auth/logout', {});
} catch (error) {
/* 令牌已失效也继续清理本地会话 */
}
clear();
}, [clear]);
const permissions = useMemo(() => new Set(session?.permissions || []), [session]);
const hasPermission = useCallback(permission => {
if (!permission) return true;
return String(permission).split(/\s+/).some(item => permissions.has(item));
}, [permissions]);
const hasAnyPermission = useCallback(list => {
const items = Array.isArray(list) ? list : String(list || '').split(/\s+/).filter(Boolean);
if (!items.length) return true;
return items.some(item => permissions.has(item));
}, [permissions]);
const refresh = useCallback(async () => {
if (!session?.token) return null;
const payload = await api.get('/auth/validate');
const next = normalizeSession(payload, session.token);
setSession(next);
writeStoredAuth(next);
return next;
}, [session?.token]);
const value = useMemo(() => ({
session,
user: session?.user || null,
roles: session?.roles || [],
permissions,
hasPermission,
hasAnyPermission,
checking,
authenticated: Boolean(session?.token),
login,
logout,
refresh
}), [session, permissions, hasPermission, hasAnyPermission, checking, login, logout, refresh]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth 必须在 AuthProvider 内使用');
return context;
}

View File

@ -0,0 +1,130 @@
/** 格式化工具:时间、数字、字节、状态色板。 */
export const SEVERITY_ORDER = ['critical', 'high', 'medium', 'low', 'info'];
export const SEVERITY_COLOR = {
critical: 'red',
high: 'orange',
medium: 'amber',
low: 'blue',
info: 'grey'
};
export const SEVERITY_LABEL = {
critical: '严重',
high: '高危',
medium: '中危',
low: '低危',
info: '信息'
};
export const STATUS_COLOR = {
running: 'blue',
pending: 'amber',
queued: 'amber',
paused: 'grey',
success: 'green',
succeeded: 'green',
completed: 'green',
done: 'green',
failed: 'red',
error: 'red',
cancelled: 'grey',
canceled: 'grey',
stopped: 'grey',
active: 'green',
inactive: 'grey',
online: 'green',
offline: 'grey',
open: 'red',
closed: 'green',
archived: 'grey'
};
export function formatDateTime(value, locale = 'zh-CN') {
if (!value) return '—';
const date = value instanceof Date ? value : new Date(value);
if (!Number.isFinite(date.getTime())) return '—';
return date.toLocaleString(locale, { hour12: false });
}
export function formatDate(value, locale = 'zh-CN') {
if (!value) return '—';
const date = value instanceof Date ? value : new Date(value);
if (!Number.isFinite(date.getTime())) return '—';
return date.toLocaleDateString(locale);
}
export function formatTime(value, locale = 'zh-CN') {
if (!value) return '—';
const date = value instanceof Date ? value : new Date(value);
if (!Number.isFinite(date.getTime())) return '—';
return date.toLocaleTimeString(locale, { hour12: false });
}
export function relativeTime(value, t) {
if (!value) return '—';
const date = new Date(value);
if (!Number.isFinite(date.getTime())) return '—';
const diff = Date.now() - date.getTime();
if (diff < 60_000) return t?.('common.justNow', null, '刚刚') || '刚刚';
if (diff < 3_600_000) return t?.('common.minutesAgo', { n: Math.floor(diff / 60_000) }, `${Math.floor(diff / 60_000)} 分钟前`);
if (diff < 86_400_000) return t?.('common.hoursAgo', { n: Math.floor(diff / 3_600_000) }, `${Math.floor(diff / 3_600_000)} 小时前`);
if (diff < 30 * 86_400_000) return t?.('common.daysAgo', { n: Math.floor(diff / 86_400_000) }, `${Math.floor(diff / 86_400_000)} 天前`);
return formatDate(value);
}
export function formatBytes(bytes) {
const value = Number(bytes);
if (!Number.isFinite(value) || value < 0) return '—';
if (value < 1024) return `${value} B`;
const units = ['KB', 'MB', 'GB', 'TB'];
let size = value / 1024;
let index = 0;
while (size >= 1024 && index < units.length - 1) { size /= 1024; index += 1; }
return `${size.toFixed(size >= 100 ? 0 : 1)} ${units[index]}`;
}
export function formatNumber(value, locale = 'zh-CN') {
const number = Number(value);
if (!Number.isFinite(number)) return '—';
return number.toLocaleString(locale);
}
export function formatDuration(seconds) {
const value = Number(seconds);
if (!Number.isFinite(value) || value < 0) return '—';
if (value < 1) return `${Math.round(value * 1000)} ms`;
if (value < 60) return `${value.toFixed(1)} s`;
const minutes = Math.floor(value / 60);
const rest = Math.round(value % 60);
if (minutes < 60) return `${minutes}m ${rest}s`;
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
}
export function formatPercent(value, digits = 1) {
const number = Number(value);
if (!Number.isFinite(number)) return '—';
return `${(number * (number <= 1 ? 100 : 1)).toFixed(digits)}%`;
}
export function severityColor(severity) {
return SEVERITY_COLOR[String(severity || '').toLowerCase()] || 'grey';
}
export function statusColor(status) {
return STATUS_COLOR[String(status || '').toLowerCase()] || 'grey';
}
export function truncate(text, length = 120) {
const value = String(text ?? '');
return value.length > length ? `${value.slice(0, length)}…` : value;
}
export function humanizeKey(key) {
return String(key || '')
.replace(/[_-]+/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.replace(/^\w/, match => match.toUpperCase());
}

View File

@ -0,0 +1,223 @@
/**
* HTTP 访问层:统一注入会话令牌、解析错误、处理 401 失效。
* 所有页面只通过这里访问 /api,不直接调用 fetch。
*/
export const AUTH_STORAGE_KEY = 'cyberstrike-auth';
export function readStoredAuth() {
try {
const raw = localStorage.getItem(AUTH_STORAGE_KEY);
if (!raw) return null;
const stored = JSON.parse(raw);
if (!stored?.token || !stored?.expiresAt) return null;
const expiry = new Date(stored.expiresAt);
if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= Date.now()) return null;
return {
token: stored.token,
expiresAt: expiry.toISOString(),
user: stored.user || null,
roles: Array.isArray(stored.roles) ? stored.roles : [],
permissions: Array.isArray(stored.permissions) ? stored.permissions : [],
scope: stored.scope || ''
};
} catch (error) {
console.warn('读取会话失败:', error);
return null;
}
}
export function writeStoredAuth(session) {
if (!session) {
localStorage.removeItem(AUTH_STORAGE_KEY);
return;
}
localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
}
let currentToken = null;
export function setAuthToken(token) {
currentToken = token || null;
}
export function getAuthToken() {
return currentToken;
}
export class ApiError extends Error {
constructor(message, { status = 0, payload = null, path = '' } = {}) {
super(message);
this.name = 'ApiError';
this.status = status;
this.payload = payload;
this.path = path;
}
}
function buildUrl(path, query) {
const url = path.startsWith('http') ? path : `/api${path.startsWith('/') ? path : `/${path}`}`;
if (!query) return url;
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value === undefined || value === null || value === '') continue;
if (Array.isArray(value)) {
value.forEach(item => params.append(key, item));
} else {
params.append(key, String(value));
}
}
const qs = params.toString();
return qs ? `${url}${url.includes('?') ? '&' : '?'}${qs}` : url;
}
async function readError(response) {
const contentType = response.headers.get('content-type') || '';
try {
if (contentType.includes('application/json')) {
const payload = await response.json();
return { message: payload.error || payload.message || `请求失败(HTTP ${response.status})`, payload };
}
const text = await response.text();
return { message: text?.slice(0, 300) || `请求失败(HTTP ${response.status})`, payload: text };
} catch (error) {
return { message: `请求失败(HTTP ${response.status})`, payload: null };
}
}
export async function request(path, options = {}) {
const { method = 'GET', body, query, headers = {}, signal, raw = false, timeout = 60000 } = options;
const finalHeaders = { Accept: 'application/json', ...headers };
let payload = body;
if (body !== undefined && body !== null && !(body instanceof FormData) && typeof body !== 'string' && !(body instanceof Blob)) {
finalHeaders['Content-Type'] = 'application/json';
payload = JSON.stringify(body);
}
if (currentToken && !finalHeaders.Authorization) {
finalHeaders.Authorization = `Bearer ${currentToken}`;
}
const controller = new AbortController();
const timer = timeout ? setTimeout(() => controller.abort(), timeout) : null;
const abort = () => controller.abort();
if (signal) {
if (signal.aborted) controller.abort();
else signal.addEventListener('abort', abort, { once: true });
}
let response;
try {
response = await fetch(buildUrl(path, query), { method, headers: finalHeaders, body: payload, signal: controller.signal });
} catch (error) {
if (error.name === 'AbortError') throw new ApiError('请求已取消', { path });
throw new ApiError('网络连接失败,请检查服务状态', { path });
} finally {
if (timer) clearTimeout(timer);
if (signal) signal.removeEventListener('abort', abort);
}
if (response.status === 401) {
window.dispatchEvent(new CustomEvent('csai:unauthorized'));
}
if (!response.ok) {
const { message, payload: errorPayload } = await readError(response);
throw new ApiError(message, { status: response.status, payload: errorPayload, path });
}
if (raw) return response;
if (response.status === 204) return null;
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) return response.json();
return response.text();
}
export const api = {
get: (path, query, options = {}) => request(path, { ...options, query }),
post: (path, body, options = {}) => request(path, { ...options, method: 'POST', body }),
put: (path, body, options = {}) => request(path, { ...options, method: 'PUT', body }),
patch: (path, body, options = {}) => request(path, { ...options, method: 'PATCH', body }),
del: (path, options = {}) => request(path, { ...options, method: 'DELETE' }),
raw: (path, options = {}) => request(path, { ...options, raw: true })
};
/** 下载二进制响应并触发浏览器保存。 */
export async function downloadFile(path, { query, filename, method = 'GET', body } = {}) {
const response = await request(path, { method, body, query, raw: true, timeout: 120000 });
const blob = await response.blob();
const disposition = response.headers.get('content-disposition') || '';
const encoded = disposition.match(/filename\*=UTF-8''([^;]+)/i);
const plain = disposition.match(/filename="?([^";]+)"?/i);
const name = filename || (encoded ? decodeURIComponent(encoded[1]) : plain?.[1]) || 'download.bin';
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = name;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
return name;
}
/**
* 消费服务端 SSE 流。服务端每行以 `data: ` 前缀发送 JSON 对象。
* onEvent(payload) 逐条回调,返回 abort 函数。
*/
export function postStream(path, body, { onEvent, onError, onClose, signal } = {}) {
const controller = new AbortController();
if (signal) {
if (signal.aborted) controller.abort();
else signal.addEventListener('abort', () => controller.abort(), { once: true });
}
const headers = { 'Content-Type': 'application/json', Accept: 'text/event-stream' };
if (currentToken) headers.Authorization = `Bearer ${currentToken}`;
(async () => {
try {
const response = await fetch(buildUrl(path), {
method: 'POST',
headers,
body: JSON.stringify(body || {}),
signal: controller.signal
});
if (response.status === 401) window.dispatchEvent(new CustomEvent('csai:unauthorized'));
if (!response.ok) {
const { message } = await readError(response);
throw new ApiError(message, { status: response.status, path });
}
if (!response.body) throw new ApiError('服务端未返回流式响应', { path });
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
let closing = false;
while (!closing) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let index;
while ((index = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, index).replace(/\r$/, '');
buffer = buffer.slice(index + 1);
if (!line.startsWith('data:')) continue;
const data = line.slice(5).trim();
if (!data) continue;
if (data === '[DONE]') { closing = true; break; }
let parsed;
try {
parsed = JSON.parse(data);
} catch (error) {
continue;
}
onEvent?.(parsed);
}
}
onClose?.();
} catch (error) {
if (error.name === 'AbortError') { onClose?.(); return; }
onError?.(error);
}
})();
return () => controller.abort();
}
export function errorMessage(error, fallback = '操作失败') {
if (!error) return fallback;
if (typeof error === 'string') return error;
return error.message || fallback;
}

View File

@ -0,0 +1,102 @@
/**
* 国际化:复用仓库既有 web/static/i18n/*.json 词条,保持与后端/文档一致的键名。
*/
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
export const LANGUAGES = [
{ id: 'zh-CN', label: '简体中文' },
{ id: 'en-US', label: 'English' },
{ id: 'ru-RU', label: 'Русский' },
{ id: 'ar-SA', label: 'العربية' }
];
const STORAGE_KEY = 'csai_lang';
const DEFAULT_LANG = 'zh-CN';
const RESOURCE_PREFIX = '/static/i18n';
const cache = new Map();
export function detectLanguage() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored && LANGUAGES.some(item => item.id === stored)) return stored;
} catch (error) { /* storage unavailable */ }
const nav = String(navigator.language || '').toLowerCase();
if (nav.startsWith('zh')) return 'zh-CN';
if (nav.startsWith('ru')) return 'ru-RU';
if (nav.startsWith('ar')) return 'ar-SA';
if (nav.startsWith('en')) return 'en-US';
return DEFAULT_LANG;
}
function loadResource(lang) {
if (!cache.has(lang)) {
cache.set(lang, fetch(`${RESOURCE_PREFIX}/${lang}.json`, { cache: 'no-cache' })
.then(response => (response.ok ? response.json() : {}))
.catch(() => ({})));
}
return cache.get(lang);
}
function lookup(resource, key) {
if (!resource) return undefined;
let node = resource;
for (const part of String(key).split('.')) {
if (node === null || typeof node !== 'object') return undefined;
node = node[part];
}
return typeof node === 'string' ? node : undefined;
}
function interpolate(template, vars) {
if (!vars) return template;
return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (match, name) => (vars[name] === undefined ? match : String(vars[name])));
}
const I18nContext = createContext({ lang: DEFAULT_LANG, t: key => key, ready: false, setLanguage: () => {} });
export function I18nProvider({ children }) {
const [lang, setLang] = useState(detectLanguage);
const [resources, setResources] = useState({});
const [ready, setReady] = useState(false);
useEffect(() => {
let cancelled = false;
Promise.all([loadResource(lang), loadResource(DEFAULT_LANG), loadResource('en-US')])
.then(([current, fallback, english]) => {
if (cancelled) return;
setResources({ current, fallback, english });
setReady(true);
});
document.documentElement.lang = lang;
document.documentElement.dir = lang === 'ar-SA' ? 'rtl' : 'ltr';
try { localStorage.setItem(STORAGE_KEY, lang); } catch (error) { /* ignore */ }
return () => { cancelled = true; };
}, [lang]);
const t = useCallback((key, vars, fallback) => {
if (!key) return fallback ?? '';
const value = lookup(resources.current, key)
?? lookup(resources.fallback, key)
?? lookup(resources.english, key);
if (value === undefined) return fallback ?? key;
return interpolate(value, vars);
}, [resources]);
const setLanguage = useCallback(next => {
if (!next || next === lang) return;
setReady(false);
setLang(next);
window.dispatchEvent(new CustomEvent('csai:languagechange', { detail: { lang: next } }));
}, [lang]);
const value = useMemo(() => ({ lang, t, ready, setLanguage }), [lang, t, ready, setLanguage]);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}
export function useI18n() {
return useContext(I18nContext);
}
export function useT() {
return useContext(I18nContext).t;
}

100
web/frontend/src/lib/nav.js Normal file
View File

@ -0,0 +1,100 @@
/**
* 导航配置:id 即路由段(#/<id>),与后端页面和权限键保持一致。
*/
import {
IconArticle, IconBolt, IconBook, IconBranch, IconBriefcase, IconCheckList,
IconComment, IconFlag, IconFolder, IconHome, IconLock, IconPuzzle,
IconServer, IconSetting, IconShield, IconTerminal, IconUser, IconUserGroup
} from '@douyinfe/semi-icons';
export const NAV_TREE = [
{ id: 'dashboard', i18n: 'nav.dashboard', fallback: '仪表盘', icon: IconHome },
{ id: 'chat', i18n: 'nav.chat', fallback: '对话', icon: IconComment },
{ id: 'deep-assessments', i18n: 'nav.deepAssessments', fallback: '深度测评', icon: IconArticle },
{
id: 'security', i18n: 'nav.security', fallback: '安全防护', icon: IconShield,
anyPermission: ['hitl:read', 'config:read'],
children: [
{ id: 'hitl', i18n: 'nav.hitl', fallback: '人机协同', permission: 'hitl:read' },
{ id: 'tool-guard', i18n: 'nav.toolGuard', fallback: '调用拦截', permission: 'config:read' }
]
},
{ id: 'projects', i18n: 'nav.projects', fallback: '项目管理', icon: IconBriefcase },
{
id: 'assets', i18n: 'nav.assets', fallback: '资产管理', icon: IconFlag,
anyPermission: ['asset:read', 'fofa:execute'],
children: [
{ id: 'asset-overview', i18n: 'nav.assetOverview', fallback: '资产概览' },
{ id: 'asset-library', i18n: 'nav.assetLibrary', fallback: '资产库' },
{ id: 'info-collect', i18n: 'nav.infoCollect', fallback: '信息收集' }
]
},
{ id: 'vulnerabilities', i18n: 'nav.vulnerabilities', fallback: '漏洞管理', icon: IconShield },
{ id: 'tasks', i18n: 'nav.tasks', fallback: '任务管理', icon: IconCheckList },
{ id: 'workflows', i18n: 'nav.workflows', fallback: '工作流', icon: IconBranch },
{ id: 'webshell', i18n: 'nav.webshell', fallback: 'WebShell管理', icon: IconTerminal },
{
id: 'c2', i18n: 'nav.c2', fallback: 'C2', icon: IconBolt,
children: [
{ id: 'c2-listeners', i18n: 'nav.c2Listeners', fallback: '监听器' },
{ id: 'c2-sessions', i18n: 'nav.c2Sessions', fallback: '会话' },
{ id: 'c2-tasks', i18n: 'nav.c2Tasks', fallback: '任务' },
{ id: 'c2-payloads', i18n: 'nav.c2Payloads', fallback: '载荷' },
{ id: 'c2-events', i18n: 'nav.c2Events', fallback: '事件' },
{ id: 'c2-profiles', i18n: 'nav.c2Profiles', fallback: '流量伪装' }
]
},
{ id: 'chat-files', i18n: 'nav.chatFiles', fallback: '文件管理', icon: IconFolder },
{
id: 'mcp', i18n: 'nav.mcp', fallback: 'MCP', icon: IconServer,
children: [
{ id: 'mcp-monitor', i18n: 'nav.mcpMonitor', fallback: 'MCP状态监控' },
{ id: 'mcp-management', i18n: 'nav.mcpManagement', fallback: 'MCP管理' }
]
},
{
id: 'knowledge', i18n: 'nav.knowledge', fallback: '知识', icon: IconBook,
children: [
{ id: 'knowledge-retrieval-logs', i18n: 'nav.knowledgeRetrievalLogs', fallback: '检索历史' },
{ id: 'knowledge-management', i18n: 'nav.knowledgeManagement', fallback: '知识管理' }
]
},
{
id: 'skills', i18n: 'nav.skills', fallback: '技能', icon: IconPuzzle,
children: [
{ id: 'skills-monitor', i18n: 'nav.skillsMonitor', fallback: '技能状态' },
{ id: 'skills-management', i18n: 'nav.skillsManagement', fallback: '技能管理' }
]
},
{
id: 'agents', i18n: 'nav.agents', fallback: '智能体', icon: IconUserGroup,
children: [
{ id: 'agents-management', i18n: 'nav.agentsManagement', fallback: '智能体管理' }
]
},
{
id: 'roles', i18n: 'nav.roles', fallback: '角色', icon: IconUser,
children: [
{ id: 'roles-management', i18n: 'nav.rolesManagement', fallback: '角色管理' }
]
},
{ id: 'platform-rbac', i18n: 'nav.platformRbac', fallback: '平台权限', icon: IconLock },
{ id: 'settings', i18n: 'nav.settings', fallback: '系统设置', icon: IconSetting },
{ id: 'api-docs', i18n: 'apiDocs.title', fallback: 'API 文档', icon: IconArticle }
];
export const NAV_SECTIONS = [
{ id: 'workspace', i18n: 'nav.groupWorkspace', fallback: '工作台', pages: ['dashboard', 'chat', 'deep-assessments', 'security'] },
{ id: 'operations', i18n: 'nav.groupOperations', fallback: '安全作业', pages: ['projects', 'assets', 'vulnerabilities', 'tasks', 'workflows', 'webshell', 'c2', 'chat-files'] },
{ id: 'capabilities', i18n: 'nav.groupCapabilities', fallback: '能力中心', pages: ['mcp', 'knowledge', 'skills', 'agents', 'roles'] },
{ id: 'platform', i18n: 'nav.groupPlatform', fallback: '平台管理', pages: ['platform-rbac', 'settings', 'api-docs'] }
];
/** 扁平页签列表,用于标题解析和导航高亮。 */
export const NAV_PAGES = NAV_TREE.flatMap(item => (item.children ? item.children.map(child => ({ ...child, parent: item.id })) : [item]));
export function findPage(id) {
return NAV_PAGES.find(item => item.id === id) || NAV_TREE.find(item => item.id === id) || null;
}
export const DEFAULT_PAGE = 'dashboard';

View File

@ -0,0 +1,75 @@
/**
* 主题:沿用既有偏好键 cyberstrike-theme(system/light/dark),
* 通过 body[theme-mode] 驱动 Semi Design 暗色变量,同时同步 html[data-theme]。
*/
import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState } from 'react';
const STORAGE_KEY = 'cyberstrike-theme';
const OPTIONS = ['system', 'light', 'dark'];
function readPreference() {
try {
const stored = localStorage.getItem(STORAGE_KEY);
return OPTIONS.includes(stored) ? stored : 'system';
} catch (error) {
return 'system';
}
}
function systemPrefersDark() {
return typeof window !== 'undefined' && window.matchMedia
? window.matchMedia('(prefers-color-scheme: dark)').matches
: false;
}
export function resolveTheme(preference) {
if (preference === 'dark' || preference === 'light') return preference;
return systemPrefersDark() ? 'dark' : 'light';
}
function apply(preference) {
const resolved = resolveTheme(preference);
const root = document.documentElement;
root.setAttribute('data-theme', resolved);
root.setAttribute('data-theme-preference', preference);
root.style.colorScheme = resolved;
document.body?.setAttribute('theme-mode', resolved === 'dark' ? 'dark' : 'light');
return resolved;
}
const ThemeContext = createContext({ preference: 'system', theme: 'light', setPreference: () => {}, toggle: () => {} });
export function ThemeProvider({ children }) {
const [preference, setPreferenceState] = useState(readPreference);
const [theme, setTheme] = useState(() => resolveTheme(readPreference()));
useLayoutEffect(() => {
setTheme(apply(preference));
try { localStorage.setItem(STORAGE_KEY, preference); } catch (error) { /* ignore */ }
if (preference !== 'system' || !window.matchMedia) return undefined;
const media = window.matchMedia('(prefers-color-scheme: dark)');
const onChange = () => setTheme(apply(preference));
media.addEventListener('change', onChange);
return () => media.removeEventListener('change', onChange);
}, [preference]);
useEffect(() => { document.body?.setAttribute('theme-mode', theme === 'dark' ? 'dark' : 'light'); }, [theme]);
const setPreference = useCallback(next => {
if (OPTIONS.includes(next)) setPreferenceState(next);
}, []);
const toggle = useCallback(() => {
setPreferenceState(current => {
const resolved = resolveTheme(current);
return resolved === 'dark' ? 'light' : 'dark';
});
}, []);
const value = useMemo(() => ({ preference, theme, setPreference, toggle }), [preference, theme, setPreference, toggle]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
return useContext(ThemeContext);
}

40
web/frontend/src/main.jsx Normal file
View File

@ -0,0 +1,40 @@
import '@douyinfe/semi-ui/react19-adapter';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { HashRouter } from 'react-router-dom';
import { ConfigProvider } from '@douyinfe/semi-ui';
import zhCN from '@douyinfe/semi-ui/lib/es/locale/source/zh_CN';
import enUS from '@douyinfe/semi-ui/lib/es/locale/source/en_US';
import ruRU from '@douyinfe/semi-ui/lib/es/locale/source/ru_RU';
import arSA from '@douyinfe/semi-ui/lib/es/locale/source/ar';
import App from './App';
import { AuthProvider } from './lib/auth';
import { I18nProvider, useI18n } from './lib/i18n';
import { ThemeProvider } from './lib/theme';
import './styles/app.css';
const SEMI_LOCALES = { 'zh-CN': zhCN, 'en-US': enUS, 'ru-RU': ruRU, 'ar-SA': arSA };
function Shell() {
const { lang } = useI18n();
return (
<ConfigProvider locale={SEMI_LOCALES[lang] || zhCN} direction={lang === 'ar-SA' ? 'rtl' : 'ltr'}>
<AuthProvider>
<HashRouter>
<App />
</HashRouter>
</AuthProvider>
</ConfigProvider>
);
}
createRoot(document.getElementById('root')).render(
<React.StrictMode>
<ThemeProvider>
<I18nProvider>
<Shell />
</I18nProvider>
</ThemeProvider>
</React.StrictMode>
);

View File

@ -0,0 +1,167 @@
import { useState } from 'react';
import { Button, Form, Input, Modal, Select, Space, Switch, Tag, Typography } from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus, IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import { DataTable, ErrorBanner, JsonViewer, KeyValueList, MarkdownView, PageHeader, SectionCard, confirmAction, toastError, toastSuccess, Drawer } from '../../components/ui';
const { Text } = Typography;
export default function AgentsManagementPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('agents:write');
const canDelete = hasPermission('agents:delete');
const [search, setSearch] = useState('');
const [detail, setDetail] = useState(null);
const [editor, setEditor] = useState(null);
const [saving, setSaving] = useState(false);
const agents = useResource(() => api.get('/multi-agent/markdown-agents'), []);
const rows = (Array.isArray(agents.data?.agents) ? agents.data.agents : []).filter(item => {
if (!search) return true;
const needle = search.toLowerCase();
return [item.name, item.id, item.filename, item.description].some(value => String(value || '').toLowerCase().includes(needle));
});
const openDetail = async record => {
try {
setDetail(await api.get(`/multi-agent/markdown-agents/${encodeURIComponent(record.filename)}`));
} catch (error) {
toastError(error, '读取智能体失败');
}
};
const save = async () => {
const values = await editor.form.validate();
setSaving(true);
try {
await api.post('/multi-agent/markdown-agents', {
filename: values.filename?.trim() || '',
name: values.name.trim(),
description: values.description?.trim() || '',
instruction: values.instruction,
kind: values.kind || 'sub',
tools: String(values.tools || '').split(',').map(item => item.trim()).filter(Boolean)
});
toastSuccess('智能体已保存');
setEditor(null);
agents.reload();
} catch (error) {
toastError(error, '保存智能体失败');
} finally {
setSaving(false);
}
};
const remove = row => confirmAction({
title: `删除智能体「${row.name || row.filename}」?`,
onOk: async () => {
await api.del(`/multi-agent/markdown-agents/${encodeURIComponent(row.filename)}`);
toastSuccess('已删除');
agents.reload();
}
});
const columns = [
{
title: '智能体', dataIndex: 'name', render: (value, record) => (
<Space vertical spacing={0} align="start">
<Space>
<Text strong>{value || record.id}</Text>
{record.is_orchestrator && <Tag size="small" color="purple">编排器</Tag>}
</Space>
<Text type="tertiary">{record.filename}</Text>
</Space>
)
},
{ title: '类型', dataIndex: 'kind', width: 110, render: value => <Tag size="small">{value || 'sub'}</Tag> },
{ title: '描述', dataIndex: 'description', render: value => <Text type="tertiary" ellipsis={{ showTooltip: true }} style={{ maxWidth: 460 }}>{value || '—'}</Text> },
{
title: '操作', width: 180, render: (_, record) => (
<Space>
<Button size="small" theme="borderless" onClick={() => openDetail(record)}>详情</Button>
{canWrite && <Button size="small" theme="borderless" icon={<IconEdit />} onClick={() => setEditor({ record, form: {} })} />}
{canDelete && <Button size="small" theme="borderless" type="danger" icon={<IconDelete />} onClick={() => remove(record)} />}
</Space>
)
}
];
return (
<div>
<PageHeader
title={t('agents.title', null, '智能体管理')}
description={agents.data?.dir ? `目录:${agents.data.dir}` : '以 Markdown 文件定义的子智能体与编排器。'}
extra={(
<Space>
<Button icon={<IconRefresh />} onClick={() => agents.reload()} loading={agents.loading}>刷新</Button>
{canWrite && <Button theme="solid" type="primary" icon={<IconPlus />} onClick={() => setEditor({ record: null, form: {} })}>新建智能体</Button>}
</Space>
)}
/>
{agents.data?.error && <ErrorBanner error={agents.data.error} />}
<SectionCard title={`智能体(${rows.length})`}>
<ErrorBanner error={agents.error} onRetry={() => agents.reload()} />
<DataTable
columns={columns}
dataSource={rows}
rowKey="filename"
loading={agents.loading}
pagination={{ pageSize: 20 }}
toolbar={<Input prefix={<IconSearch />} value={search} onChange={setSearch} placeholder="搜索名称或文件名" style={{ width: 280 }} />}
/>
</SectionCard>
<Modal
title={editor?.record ? '编辑智能体' : '新建智能体'}
visible={Boolean(editor)}
key={editor?.record?.filename || 'new-agent'}
onCancel={() => setEditor(null)}
onOk={save}
confirmLoading={saving}
width={760}
>
<Form
getFormApi={form => setEditor(current => (current ? { ...current, form } : current))}
initValues={editor?.record ? {
filename: editor.record.filename,
name: editor.record.name,
description: editor.record.description,
kind: editor.record.kind || 'sub'
} : { kind: 'sub' }}
>
<Form.Input field="filename" label="文件名(留空自动生成)" placeholder="例如 recon.md" />
<Form.Input field="name" label="名称" rules={[{ required: true, message: '请输入名称' }]} />
<Form.Input field="description" label="描述" />
<Form.Select field="kind" label="类型" optionList={[
{ value: 'sub', label: '子智能体' },
{ value: 'orchestrator', label: '编排器' },
{ value: 'plan_execute', label: '计划执行' }
]} />
<Form.Input field="tools" label="工具(逗号分隔)" placeholder="toolName, mcp::tool" />
<Form.TextArea field="instruction" label="指令(Markdown)" autosize={{ minRows: 8, maxRows: 20 }} />
</Form>
</Modal>
<Drawer title={detail?.name || '智能体详情'} visible={Boolean(detail)} onCancel={() => setDetail(null)} width={720}>
{detail && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<KeyValueList items={[
{ label: '文件名', value: detail.filename },
{ label: 'ID', value: detail.id },
{ label: '类型', value: detail.kind },
{ label: '绑定角色', value: detail.bind_role || '—' },
{ label: '最大迭代', value: detail.max_iterations ?? '—' },
{ label: '工具', value: Array.isArray(detail.tools) && detail.tools.length ? detail.tools.join('、') : '—' }
]} />
<MarkdownView content={detail.instruction || detail.raw || ''} />
<JsonViewer value={detail.raw || detail} title="原始 Markdown" collapsed />
</div>
)}
</Drawer>
</div>
);
}

View File

@ -0,0 +1,263 @@
import { useEffect, useMemo, useState } from 'react';
import {
Button, Card, Divider, Input, Select, Space, Tabs, Tag, TextArea, Typography
} from '@douyinfe/semi-ui';
import { IconRefresh, IconSearch, IconSend } from '@douyinfe/semi-icons';
import { api, errorMessage, request } from '../../lib/http';
import { useT } from '../../lib/i18n';
import { PageHeader, SectionCard, JsonViewer, toastError } from '../../components/ui';
import './page.css';
const { Text, Paragraph } = Typography;
const METHOD_COLOR = {
get: 'blue', post: 'green', put: 'orange', delete: 'red', patch: 'violet', head: 'grey', options: 'grey'
};
function buildOperations(spec) {
const paths = spec?.paths || {};
const operations = [];
Object.entries(paths).forEach(([path, methods]) => {
Object.entries(methods || {}).forEach(([method, op]) => {
if (!op || typeof op !== 'object') return;
operations.push({
id: `${method.toUpperCase()} ${path}`,
method: method.toUpperCase(),
path,
summary: op.summary || op.description || '',
tag: (op.tags && op.tags[0]) || 'default',
operation: op
});
});
});
return operations.sort((a, b) => a.path.localeCompare(b.path) || a.method.localeCompare(b.method));
}
function pathParamNames(path) {
return Array.from(path.matchAll(/\{([^}]+)\}/g)).map(match => match[1]);
}
function TryPanel({ operation, spec }) {
const op = operation.operation || {};
const params = op.parameters || [];
const pathParams = pathParamNames(operation.path);
const [values, setValues] = useState({});
const [body, setBody] = useState('');
const [result, setResult] = useState(null);
const [sending, setSending] = useState(false);
useEffect(() => {
const next = {};
pathParams.forEach(name => {
const declared = params.find(item => item.name === name && item.in === 'path');
next[name] = declared?.schema?.default ?? declared?.example ?? '';
});
params.filter(item => item.in === 'query').forEach(item => {
if (item.schema?.default !== undefined) next[`query:${item.name}`] = String(item.schema.default);
});
setValues(next);
setBody(op.requestBody ? '{\n \n}' : '');
setResult(null);
}, [operation.id]);
const send = async () => {
setSending(true);
setResult(null);
try {
if (pathParams.some(name => String(values[name] ?? '').trim() === '')) {
toastError('请填写路径参数');
return;
}
let path = operation.path;
pathParams.forEach(name => { path = path.replace(`{${name}}`, encodeURIComponent(values[name] ?? '')); });
const query = {};
params.filter(item => item.in === 'query').forEach(item => {
const value = values[`query:${item.name}`];
if (value !== undefined && value !== '') query[item.name] = value;
});
const options = { method: operation.method, query, raw: true, timeout: 120000 };
if (op.requestBody && body.trim()) {
try {
options.body = JSON.parse(body);
} catch (error) {
toastError('请求体不是合法 JSON');
setSending(false);
return;
}
}
if (!path.startsWith('/') || path.startsWith('//')) throw new Error('接口地址必须为站内 API 路径');
const response = await request(path.startsWith('/api/') ? path.slice(4) : path, options);
const contentType = response.headers.get('content-type') || '';
let payload;
if (contentType.includes('application/json')) payload = await response.json();
else payload = await response.text();
setResult({ ok: true, status: response.status, payload });
} catch (error) {
setResult({ ok: false, status: error.status || 0, payload: errorMessage(error) });
} finally {
setSending(false);
}
};
return (
<div className="api-docs-try">
<Divider margin="12px 0" />
<Text strong>在线调试</Text>
{pathParams.length > 0 && (
<div className="api-docs-try-fields">
{pathParams.map(name => (
<label key={name} className="api-docs-try-field">
<span>路径参数 {name}</span>
<Input size="small" value={values[name] ?? ''} onChange={next => setValues(current => ({ ...current, [name]: next }))} />
</label>
))}
</div>
)}
{params.filter(item => item.in === 'query').length > 0 && (
<div className="api-docs-try-fields">
{params.filter(item => item.in === 'query').map(item => (
<label key={item.name} className="api-docs-try-field">
<span>查询参数 {item.name}{item.required ? ' *' : ''}</span>
<Input
size="small"
value={values[`query:${item.name}`] ?? ''}
onChange={next => setValues(current => ({ ...current, [`query:${item.name}`]: next }))}
placeholder={item.description || ''}
/>
</label>
))}
</div>
)}
{op.requestBody && (
<div className="api-docs-try-body">
<span>请求体(JSON)</span>
<TextArea value={body} onChange={setBody} autosize={{ minRows: 5, maxRows: 14 }} />
</div>
)}
<Space>
<Button theme="solid" type="primary" icon={<IconSend />} loading={sending} onClick={send}>发送请求</Button>
<Button onClick={() => setResult(null)}>清空结果</Button>
</Space>
{result && (
<div className="api-docs-try-result">
<Tag color={result.ok ? 'green' : 'red'}>{result.ok ? `HTTP ${result.status}` : `失败 ${result.status || ''}`}</Tag>
<JsonViewer value={result.payload} title="响应" />
</div>
)}
</div>
);
}
export default function ApiDocsPage() {
const t = useT();
const [spec, setSpec] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [keyword, setKeyword] = useState('');
const [method, setMethod] = useState('all');
const [selectedId, setSelectedId] = useState(null);
const load = async () => {
setLoading(true);
setError(null);
try {
const payload = await api.get('/openapi/spec');
setSpec(payload);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
useEffect(() => { load(); }, []);
const operations = useMemo(() => buildOperations(spec), [spec]);
const filtered = useMemo(() => operations.filter(op => {
if (method !== 'all' && op.method !== method) return false;
if (!keyword) return true;
const needle = keyword.toLowerCase();
return op.path.toLowerCase().includes(needle) || op.summary.toLowerCase().includes(needle) || op.method.toLowerCase().includes(needle);
}), [operations, keyword, method]);
const selected = filtered.find(op => op.id === selectedId) || filtered[0] || null;
const grouped = useMemo(() => {
const map = new Map();
filtered.forEach(op => {
if (!map.has(op.tag)) map.set(op.tag, []);
map.get(op.tag).push(op);
});
return [...map.entries()];
}, [filtered]);
return (
<div className="api-docs-page">
<PageHeader
title={t('apiDocs.title', null, 'API 文档')}
description={spec?.info?.description || 'CyberStrikeAI 开放接口'}
extra={<Button icon={<IconRefresh />} onClick={load} loading={loading}>重新加载</Button>}
/>
<div className="api-docs-layout">
<Card className="api-docs-sidebar" bordered={false}>
<Space vertical style={{ width: '100%' }} spacing={8}>
<Input prefix={<IconSearch />} value={keyword} onChange={setKeyword} placeholder="搜索路径或说明" />
<Select
value={method}
onChange={setMethod}
style={{ width: '100%' }}
optionList={[
{ value: 'all', label: '全部方法' },
...['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].map(item => ({ value: item, label: item }))
]}
/>
</Space>
<div className="api-docs-list">
{grouped.map(([tag, items]) => (
<div className="api-docs-group" key={tag}>
<Text type="tertiary" className="api-docs-group-title">{tag}</Text>
{items.map(op => (
<button
type="button"
key={op.id}
className={`api-docs-item ${selected?.id === op.id ? 'is-active' : ''}`}
onClick={() => setSelectedId(op.id)}
>
<Tag size="small" color={METHOD_COLOR[op.method.toLowerCase()]}>{op.method}</Tag>
<span className="api-docs-item-path">{op.path}</span>
</button>
))}
</div>
))}
{!loading && grouped.length === 0 && <Text type="tertiary">没有匹配的接口</Text>}
</div>
</Card>
<div className="api-docs-detail">
{error && <Card bordered={false}><Text type="danger">{errorMessage(error)}</Text></Card>}
{selected ? (
<Card bordered={false}>
<div className="api-docs-detail-head">
<Tag color={METHOD_COLOR[selected.method.toLowerCase()]}>{selected.method}</Tag>
<code className="api-docs-detail-path">{selected.path}</code>
</div>
<Paragraph>{selected.summary || '无说明'}</Paragraph>
<Tabs type="line">
<Tabs.TabPane itemKey="params" tab="参数">
<JsonViewer value={selected.operation.parameters || []} title="Request Parameters" collapsed />
</Tabs.TabPane>
<Tabs.TabPane itemKey="body" tab="请求体">
<JsonViewer value={selected.operation.requestBody || {}} title="Request Body" collapsed />
</Tabs.TabPane>
<Tabs.TabPane itemKey="responses" tab="响应">
<JsonViewer value={selected.operation.responses || {}} title="Responses" collapsed />
</Tabs.TabPane>
</Tabs>
<TryPanel operation={selected} spec={spec} />
</Card>
) : (
<Card bordered={false}><Text type="tertiary">{loading ? '加载中…' : '选择左侧接口查看详情'}</Text></Card>
)}
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,28 @@
.api-docs-page { display: flex; flex-direction: column; }
.api-docs-layout { display: grid; grid-template-columns: 340px minmax(0, 1fr); gap: 16px; align-items: start; }
.api-docs-sidebar { border-radius: 12px; border: 1px solid var(--semi-color-border); position: sticky; top: 0; }
.api-docs-list { margin-top: 10px; max-height: calc(100vh - 220px); overflow: auto; display: flex; flex-direction: column; gap: 10px; }
.api-docs-group { display: flex; flex-direction: column; gap: 2px; }
.api-docs-group-title { font-size: 11px; text-transform: uppercase; letter-spacing: .06em; padding: 4px 6px; }
.api-docs-item {
display: flex; align-items: center; gap: 8px; width: 100%; padding: 6px 8px;
border: none; background: transparent; border-radius: 8px; cursor: pointer; color: inherit; text-align: left;
}
.api-docs-item:hover { background: var(--semi-color-fill-0); }
.api-docs-item.is-active { background: var(--semi-color-primary-light-default); }
.api-docs-item-path { font-size: 12px; font-family: "SFMono-Regular", Consolas, monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.api-docs-detail { display: flex; flex-direction: column; gap: 12px; }
.api-docs-detail > .semi-card { border-radius: 12px; border: 1px solid var(--semi-color-border); }
.api-docs-detail-head { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
.api-docs-detail-path { font-size: 13px; background: var(--semi-color-fill-0); padding: 3px 8px; border-radius: 6px; }
.api-docs-try { display: flex; flex-direction: column; gap: 10px; }
.api-docs-try-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; }
.api-docs-try-field { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--semi-color-text-2); }
.api-docs-try-body { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--semi-color-text-2); }
.api-docs-try-result { display: flex; flex-direction: column; gap: 8px; }
@media (max-width: 900px) {
.api-docs-layout { grid-template-columns: minmax(0, 1fr); }
.api-docs-sidebar { position: static; }
.api-docs-list { max-height: 320px; }
}

View File

@ -0,0 +1,64 @@
/** 资产相关的轻量展示原子:截断文本、风险/状态/协议标签、标签列表。 */
import { Space, Tag, Tooltip, Typography } from '@douyinfe/semi-ui';
import { RISK_COLORS, riskLevelOf, riskLabel, STATUS_LABELS } from './assetConstants';
const { Text } = Typography;
export function TooltipText({ text, max = 42, className = '', placeholder = '—' }) {
const value = String(text ?? '').trim();
if (!value) return <Text type="tertiary">{placeholder}</Text>;
if (value.length <= max) return <span className={className}>{value}</span>;
const clipped = `${value.slice(0, max)}…`;
return (
<Tooltip content={value} position="topLeft">
<span className={className}>{clipped}</span>
</Tooltip>
);
}
export function RiskTag({ asset, size = 'small' }) {
const level = riskLevelOf(asset);
return (
<Tag size={size} color={RISK_COLORS[level] || 'grey'} shape="circle">
{riskLabel(level)}
</Tag>
);
}
export function AssetStatusTag({ status, size = 'small' }) {
const value = String(status || 'active').toLowerCase();
return (
<Tag size={size} color={value === 'inactive' ? 'grey' : 'green'} shape="square">
{STATUS_LABELS[value] || status || '—'}
</Tag>
);
}
export function ProtocolTag({ protocol, port, size = 'small' }) {
const value = String(protocol || '').trim();
const suffix = Number(port || 0) > 0 ? `:${port}` : '';
if (!value && !suffix) return <Text type="tertiary">—</Text>;
return (
<Space spacing={4}>
{value ? <Tag size={size} color="blue" shape="square">{value}</Tag> : null}
{suffix ? <Text type="tertiary" size="small">{suffix}</Text> : null}
</Space>
);
}
export function TagList({ tags, max = 3 }) {
const list = Array.isArray(tags) ? tags.filter(Boolean) : [];
if (!list.length) return <Text type="tertiary">—</Text>;
const visible = list.slice(0, max);
const rest = list.slice(max);
return (
<Space spacing={4} wrap>
{visible.map(tag => <Tag key={tag} size="small" color="violet" shape="square">{tag}</Tag>)}
{rest.length ? (
<Tooltip content={rest.join('、')}>
<span><Tag size="small" shape="square">+{rest.length}</Tag></span>
</Tooltip>
) : null}
</Space>
);
}

View File

@ -0,0 +1,128 @@
/** 批量编辑:PUT /assets/bulk,仅提交填写的字段,空白保持原值。 */
import { useEffect, useMemo, useState } from 'react';
import { Banner, Input, Modal, Select, Typography } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { toastSuccess } from '../../../components/ui';
import { CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, STATUS_OPTIONS } from './assetConstants';
import { splitTags } from './assetTarget';
const { Text } = Typography;
const EMPTY = {
status: '', environment: '', criticality: '',
responsible_person: '', department: '', business_system: '',
add_tags: '', remove_tags: ''
};
export default function AssetBulkEditModal({ visible, assetIds, onClose, onDone }) {
const t = useT();
const [values, setValues] = useState(EMPTY);
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const ids = useMemo(() => (Array.isArray(assetIds) ? assetIds : []), [assetIds]);
useEffect(() => {
if (visible) {
setValues(EMPTY);
setError('');
setBusy(false);
}
}, [visible]);
const patch = next => setValues(prev => ({ ...prev, ...next }));
const submit = async () => {
if (busy || !ids.length) return;
const body = { asset_ids: ids };
['status', 'environment', 'criticality', 'responsible_person', 'department', 'business_system']
.forEach(key => {
const value = String(values[key] || '').trim();
if (value) body[key] = value;
});
const addTags = splitTags(values.add_tags);
const removeTags = splitTags(values.remove_tags);
if (addTags.length) body.add_tags = addTags;
if (removeTags.length) body.remove_tags = removeTags;
if (Object.keys(body).length === 1) {
setError('请至少填写一项需要修改的内容');
return;
}
setBusy(true);
setError('');
try {
const result = await api.put('/assets/bulk', body);
toastSuccess(`已更新 ${Number(result?.updated || ids.length)} 个资产`);
onDone?.();
onClose?.();
} catch (submitError) {
setError(errorMessage(submitError, '批量编辑失败'));
} finally {
setBusy(false);
}
};
return (
<Modal
visible={visible}
title={t('assets.bulkEdit', null, '批量编辑')}
width={620}
onCancel={onClose}
onOk={submit}
confirmLoading={busy}
maskClosable={false}
>
<Text type="tertiary">将修改 {ids.length} 个资产;空白字段保持原值。</Text>
<div className="asset-library-form-grid asset-library-form-grid--bulk">
<Select
value={values.status || undefined}
placeholder={t('assets.status', null, '状态')}
optionList={STATUS_OPTIONS}
showClear
onChange={value => patch({ status: value || '' })}
/>
<Select
value={values.environment || undefined}
placeholder={t('assets.environment', null, '环境')}
optionList={ENVIRONMENT_OPTIONS}
showClear
onChange={value => patch({ environment: value || '' })}
/>
<Select
value={values.criticality || undefined}
placeholder={t('assets.criticality', null, '重要性')}
optionList={CRITICALITY_OPTIONS}
showClear
onChange={value => patch({ criticality: value || '' })}
/>
<Input
value={values.responsible_person}
placeholder={t('assets.responsiblePerson', null, '负责人')}
onChange={value => patch({ responsible_person: value })}
/>
<Input
value={values.department}
placeholder={t('assets.department', null, '部门')}
onChange={value => patch({ department: value })}
/>
<Input
value={values.business_system}
placeholder={t('assets.businessSystem', null, '业务系统')}
onChange={value => patch({ business_system: value })}
/>
<Input
value={values.add_tags}
placeholder="追加标签(逗号分隔)"
onChange={value => patch({ add_tags: value })}
/>
<Input
value={values.remove_tags}
placeholder="移除标签(逗号分隔)"
onChange={value => patch({ remove_tags: value })}
/>
</div>
{error && <Banner type="danger" bordered closeIcon={null} description={error} className="asset-library-form-error" />}
</Modal>
);
}

View File

@ -0,0 +1,119 @@
/** 资产详情抽屉:全字段 + 关联漏洞/项目跳转。 */
import { useNavigate } from 'react-router-dom';
import { Button, Divider, SideSheet, Space, Typography } from '@douyinfe/semi-ui';
import { CopyButton, KeyValueList } from '../../../components/ui';
import { formatDateTime } from '../../../lib/format';
import { useT } from '../../../lib/i18n';
import { AssetStatusTag, ProtocolTag, RiskTag, TagList } from './AssetBits';
import { criticalityLabel, environmentLabel, riskLabel } from './assetConstants';
import { assetServiceLabel, assetTargetLabel } from './assetTarget';
const { Text } = Typography;
export default function AssetDetailDrawer({ asset, visible, onClose, onEdit, onDelete, canWrite, canDelete }) {
const t = useT();
const navigate = useNavigate();
if (!asset) return null;
const openVulnerabilities = () => {
if (asset.last_scan_task_id) {
navigate(`/vulnerabilities?task_id=${encodeURIComponent(asset.last_scan_task_id)}`);
return;
}
if (asset.last_scan_conversation_id) {
navigate(`/vulnerabilities?conversation_id=${encodeURIComponent(asset.last_scan_conversation_id)}`);
return;
}
const host = asset.host || asset.domain || asset.ip || '';
navigate(host ? `/vulnerabilities?host_q=${encodeURIComponent(host)}` : '/vulnerabilities');
};
const items = [
{ label: 'Host', value: asset.host || '—' },
{ label: 'IP', value: asset.ip || '—' },
{ label: t('assets.domain', null, '域名'), value: asset.domain || '—' },
{ label: t('assets.service', null, '服务'), value: <ProtocolTag protocol={asset.protocol} port={asset.port} /> },
{ label: t('assets.project', null, '所属项目'), value: asset.project_name || asset.project_id || '—' },
{ label: t('assets.status', null, '状态'), value: <AssetStatusTag status={asset.status} /> },
{ label: t('assets.riskLevel', null, '风险等级'), value: <RiskTag asset={asset} /> },
{ label: t('assets.environment', null, '环境'), value: environmentLabel(asset.environment) || '—' },
{ label: t('assets.criticality', null, '重要性'), value: criticalityLabel(asset.criticality) || '—' },
{
label: t('assets.location', null, '地区'),
value: [asset.country, asset.province, asset.city].filter(Boolean).join(' / ') || '—'
},
{ label: t('assets.responsiblePerson', null, '负责人'), value: asset.responsible_person || '—' },
{ label: t('assets.department', null, '部门'), value: asset.department || '—' },
{ label: t('assets.businessSystem', null, '业务系统'), value: asset.business_system || '—' },
{ label: t('assets.title', null, '标题/指纹'), value: asset.title || '—' },
{ label: t('assets.server', null, '服务指纹'), value: asset.server || '—' },
{ label: t('assets.source', null, '来源'), value: asset.source || '—' },
{
label: t('assets.sourceQuery', null, '来源查询'),
value: asset.source_query ? <Text code size="small">{asset.source_query}</Text> : '—'
},
{ label: t('assets.tagsLabel', null, '标签'), value: <TagList tags={asset.tags} max={6} /> },
{ label: t('assets.firstSeen', null, '首次发现'), value: formatDateTime(asset.first_seen_at) },
{ label: t('assets.lastSeen', null, '最近发现'), value: formatDateTime(asset.last_seen_at) },
{ label: t('assets.lastScan', null, '上次扫描'), value: formatDateTime(asset.last_scan_at) },
{ label: '创建时间', value: formatDateTime(asset.created_at) },
{ label: '更新时间', value: formatDateTime(asset.updated_at) },
{ label: '资产 ID', value: <Text copyable={{ content: asset.id }} size="small">{asset.id}</Text> }
];
return (
<SideSheet
visible={visible}
onCancel={onClose}
title={t('assets.detailTitle', null, '资产详情')}
width={620}
placement="right"
footer={(
<Space>
{canWrite && <Button onClick={() => onEdit(asset)}>{t('common.edit', null, '编辑')}</Button>}
{canDelete && (
<Button type="danger" onClick={() => onDelete(asset)}>
{t('common.delete', null, '删除')}
</Button>
)}
<Button theme="borderless" onClick={onClose}>{t('common.close', null, '关闭')}</Button>
</Space>
)}
>
<div className="asset-library-detail-target">
<div className="asset-library-detail-target-main">
<Text strong size="large">{assetTargetLabel(asset)}</Text>
<CopyButton text={assetTargetLabel(asset)} />
</div>
<Text type="tertiary">
{[asset.ip, asset.domain, assetServiceLabel(asset)].filter(Boolean).join(' · ') || '—'}
</Text>
<Space spacing={6} wrap className="asset-library-detail-badges">
<AssetStatusTag status={asset.status} />
<RiskTag asset={asset} />
<Text type="tertiary" size="small">
{t('assets.relatedVulnerabilities', null, '相关漏洞')}:
{Number(asset.vulnerability_count || 0)}
{asset.risk_level ? `(${riskLabel(asset.risk_level)})` : ''}
</Text>
</Space>
</div>
<Divider margin="12px" />
<KeyValueList items={items} columns={2} />
<Divider margin="12px" />
<Space>
<Button theme="light" onClick={openVulnerabilities}>
{t('assets.viewRelatedVulnerabilities', null, '查看关联漏洞')}
</Button>
{asset.project_id && (
<Button
theme="borderless"
onClick={() => navigate(`/projects?id=${encodeURIComponent(asset.project_id)}`)}
>
{t('assets.viewProject', null, '查看项目')}
</Button>
)}
</Space>
</SideSheet>
);
}

View File

@ -0,0 +1,301 @@
/** 新建/编辑资产:Form + 目标自动解析(host/ip/domain/port/protocol 联动)。 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { Banner, Button, Form, Modal, Space } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { toastSuccess } from '../../../components/ui';
import {
CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, STATUS_OPTIONS
} from './assetConstants';
import {
isIPv4, isIPv6, normalizeDomain, parseAssetTarget, targetInputFromAsset
} from './assetTarget';
const FORM_CLASS = 'asset-library-editor';
function initialValues(asset) {
return {
target: targetInputFromAsset(asset),
host: asset?.host || '',
ip: asset?.ip || '',
domain: asset?.domain || '',
port: asset?.port ?? undefined,
protocol: asset?.protocol || '',
title: asset?.title || '',
server: asset?.server || '',
project_id: asset?.project_id || '',
status: asset?.status || 'active',
environment: asset?.environment || '',
criticality: asset?.criticality || '',
country: asset?.country || '',
province: asset?.province || '',
city: asset?.city || '',
responsible_person: asset?.responsible_person || '',
department: asset?.department || '',
business_system: asset?.business_system || '',
tags: Array.isArray(asset?.tags) ? asset.tags : []
};
}
export default function AssetEditorModal({ visible, asset, projects, onClose, onSaved }) {
const t = useT();
const [formApi, setFormApi] = useState(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const parsedTarget = useRef(targetInputFromAsset(asset));
const values = useMemo(() => initialValues(asset), [asset, visible]);
const editing = Boolean(asset?.id);
useEffect(() => {
if (!visible) return;
parsedTarget.current = targetInputFromAsset(asset);
setError('');
setBusy(false);
}, [visible, asset]);
const projectOptions = useMemo(
() => (projects || []).map(project => ({ value: project.id, label: project.name || project.id })),
[projects]
);
const applyTarget = (showError) => {
if (!formApi) return null;
const raw = String(formApi.getValue('target') || '').trim();
try {
const parsed = parseAssetTarget(raw);
formApi.setValues({
host: parsed.host,
ip: parsed.ip,
domain: parsed.domain,
port: parsed.port || undefined,
protocol: parsed.protocol
});
parsedTarget.current = raw;
return parsed;
} catch (parseError) {
if (showError) setError(parseError.message);
return null;
}
};
const buildPayload = () => {
const current = formApi.getValue();
const rawTarget = String(current.target || '').trim();
let payload = {
host: String(current.host || '').trim(),
ip: String(current.ip || '').trim().toLowerCase(),
domain: String(current.domain || '').trim(),
port: Number(current.port || 0),
protocol: String(current.protocol || '').trim().toLowerCase(),
title: String(current.title || '').trim(),
server: String(current.server || '').trim(),
status: current.status || 'active',
source: asset?.source || 'manual',
source_query: asset?.source_query || '',
country: String(current.country || '').trim(),
province: String(current.province || '').trim(),
city: String(current.city || '').trim(),
responsible_person: String(current.responsible_person || '').trim(),
department: String(current.department || '').trim(),
business_system: String(current.business_system || '').trim(),
environment: current.environment || '',
criticality: current.criticality || '',
project_id: current.project_id || '',
tags: Array.isArray(current.tags) ? current.tags.map(tag => String(tag).trim()).filter(Boolean) : []
};
if (rawTarget && rawTarget !== parsedTarget.current) {
try {
const parsed = parseAssetTarget(rawTarget);
payload = {
...payload,
host: payload.host || parsed.host,
ip: parsed.ip || payload.ip,
domain: parsed.domain || payload.domain,
port: parsed.port || payload.port,
protocol: parsed.protocol || payload.protocol
};
} catch (parseError) {
throw new Error(parseError.message);
}
}
return payload;
};
const submit = async () => {
if (busy || !formApi) return;
setError('');
try {
await formApi.validate();
} catch (validation) {
return;
}
let payload;
try {
payload = buildPayload();
} catch (buildError) {
setError(buildError.message);
return;
}
setBusy(true);
try {
if (editing) {
await api.put(`/assets/${encodeURIComponent(asset.id)}`, payload);
toastSuccess(t('assets.updatedSuccessfully', null, '资产已更新'));
} else {
const result = await api.post('/assets/import', {
assets: [payload],
source: 'manual'
});
const created = Number(result?.created || 0);
const updated = Number(result?.updated || 0);
const skipped = Number(result?.skipped || 0);
if (!created && !updated && skipped) {
throw new Error(t('assets.assetSkipped', null, '资产未保存,可能已存在且你没有更新权限'));
}
toastSuccess(created
? t('assets.createdSuccessfully', null, '资产已添加')
: t('assets.duplicateMerged', null, '资产已存在,信息已安全合并'));
}
onSaved?.();
onClose?.();
} catch (submitError) {
setError(errorMessage(submitError, t('assets.saveFailed', null, '保存资产失败')));
} finally {
setBusy(false);
}
};
return (
<Modal
visible={visible}
title={editing ? t('assets.editAssetTitle', null, '编辑资产') : t('assets.addAssetTitle', null, '新增资产')}
width={760}
onCancel={onClose}
onOk={submit}
okText={editing ? t('common.save', null, '保存') : t('assets.addAssetAction', null, '添加资产')}
confirmLoading={busy}
closeOnEsc
maskClosable={false}
>
{error && <Banner type="danger" bordered closeIcon={null} description={error} className="asset-library-form-error" />}
<Form
key={`${asset?.id || 'new-asset'}-${visible ? 'open' : 'closed'}`}
className={FORM_CLASS}
initValues={values}
getFormApi={setFormApi}
labelPosition="top"
onSubmit={submit}
>
<div className="asset-library-form-grid asset-library-form-grid--full">
<Form.Input
field="target"
label={t('assets.assetAddress', null, '资产地址')}
placeholder="https://example.com:443 / example.com / 1.1.1.1:22"
helpText={t('assets.assetAddressHint', null, '可识别的 URL、域名、IP 和端口会自动解析')}
onBlur={() => applyTarget(true)}
rules={[
{ required: true, message: t('assets.targetRequired', null, '请输入资产地址') },
{
validator: (rule, value, callback) => {
try {
parseAssetTarget(value);
callback();
} catch (parseError) {
callback(new Error(parseError.message));
}
}
}
]}
/>
</div>
<div className="asset-library-form-grid">
<Form.Input field="host" label={t('assets.hostUrl', null, '完整 URL / Host')} />
<Form.Input
field="ip"
label="IP"
rules={[{
validator: (rule, value, callback) => {
if (!value || isIPv4(value) || isIPv6(value)) callback();
else callback(new Error(t('assets.ipInvalid', null, 'IP 地址格式无效')));
}
}]}
/>
<Form.Input
field="domain"
label={t('assets.domain', null, '域名')}
rules={[{
validator: (rule, value, callback) => {
if (!value || (normalizeDomain(value) && !isIPv4(value) && !isIPv6(value))) callback();
else callback(new Error(t('assets.domainInvalid', null, '域名格式无效')));
}
}]}
/>
<Form.InputNumber
field="port"
label={t('assets.port', null, '端口')}
min={0}
max={65535}
style={{ width: '100%' }}
/>
<Form.Input
field="protocol"
label={t('assets.protocol', null, '协议')}
rules={[{
validator: (rule, value, callback) => {
if (!value || /^[a-z][a-z0-9+.-]{0,31}$/.test(String(value).toLowerCase())) callback();
else callback(new Error(t('assets.protocolInvalid', null, '协议格式无效')));
}
}]}
/>
<Form.Input field="title" label={t('assets.pageTitle', null, '页面标题')} />
<Form.Input field="server" label={t('assets.serverProduct', null, '服务 / 产品')} />
<Form.Select
field="project_id"
label={t('assets.project', null, '所属项目')}
optionList={projectOptions}
filter
showClear
placeholder={t('assets.unboundProject', null, '暂不绑定')}
/>
<Form.Select field="status" label={t('assets.status', null, '状态')} optionList={STATUS_OPTIONS} />
<Form.Select
field="environment"
label={t('assets.environment', null, '环境')}
optionList={ENVIRONMENT_OPTIONS}
showClear
placeholder="—"
/>
<Form.Select
field="criticality"
label={t('assets.criticality', null, '重要性')}
optionList={CRITICALITY_OPTIONS}
showClear
placeholder="—"
/>
<Form.Input field="country" label={t('assets.country', null, '国家/地区')} />
<Form.Input field="province" label={t('assets.province', null, '省份/州')} />
<Form.Input field="city" label={t('assets.city', null, '城市')} />
<Form.Input field="responsible_person" label={t('assets.responsiblePerson', null, '负责人')} />
<Form.Input field="department" label={t('assets.department', null, '部门')} />
<Form.Input field="business_system" label={t('assets.businessSystem', null, '业务系统')} />
</div>
<Form.TagInput
field="tags"
label={t('assets.tagsLabel', null, '标签')}
placeholder={t('assets.tagsPlaceholder', null, '输入后按回车或逗号')}
max={30}
maxLength={64}
addOnBlur
separator=",,"
style={{ width: '100%' }}
/>
<Space className="asset-library-editor-actions">
<Button theme="borderless" onClick={() => applyTarget(true)}>
{t('assets.parseTarget', null, '解析资产地址')}
</Button>
</Space>
</Form>
</Modal>
);
}

View File

@ -0,0 +1,163 @@
/** 资产库筛选栏:常用条件平铺,其余条件收进“高级筛选”。 */
import { useEffect, useMemo, useState } from 'react';
import { Button, Collapse, Input, Select, Space } from '@douyinfe/semi-ui';
import { IconSearch } from '@douyinfe/semi-icons';
import { useT } from '../../../lib/i18n';
import {
CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, PROTOCOL_OPTIONS, RISK_OPTIONS,
SCAN_STATE_OPTIONS, SORT_OPTIONS, STATUS_OPTIONS
} from './assetConstants';
const EMPTY_FILTERS = {
q: '', protocol: '', source: '', project_id: '', tag: '',
status: '', risk_level: '', environment: '', criticality: '',
ip: '', domain: '', port: '', scan: '', sort: 'last_seen_at:desc'
};
export function emptyAssetFilters() {
return { ...EMPTY_FILTERS };
}
export default function AssetFilterBar({ filters, projects, onChange, onReset, disabled }) {
const t = useT();
const [keyword, setKeyword] = useState(filters.q || '');
useEffect(() => { setKeyword(filters.q || ''); }, [filters.q]);
const projectOptions = useMemo(() => (projects || []).map(project => ({
value: project.id,
label: project.name || project.id
})), [projects]);
const advancedCount = ['status', 'risk_level', 'environment', 'criticality', 'ip', 'domain', 'port', 'scan']
.filter(key => filters[key]).length;
return (
<div className="asset-library-filters">
<div className="asset-library-filter-grid">
<Input
prefix={<IconSearch />}
value={keyword}
disabled={disabled}
placeholder={t('assets.searchPlaceholder', null, '搜索主机、IP、域名、标题、服务或标签')}
onChange={value => { setKeyword(value); onChange({ q: value }); }}
showClear
/>
<Select
value={filters.protocol || undefined}
placeholder={t('assets.assetType', null, '类型 / 协议')}
optionList={PROTOCOL_OPTIONS}
filter
allowCreate
showClear
disabled={disabled}
onChange={value => onChange({ protocol: value || '' })}
/>
<Input
value={filters.source}
placeholder={t('assets.source', null, '来源')}
disabled={disabled}
onChange={value => onChange({ source: value })}
showClear
/>
<Select
value={filters.project_id || undefined}
placeholder={t('assets.project', null, '所属项目')}
optionList={projectOptions}
filter
showClear
disabled={disabled}
onChange={value => onChange({ project_id: value || '' })}
/>
<Input
value={filters.tag}
placeholder={t('assets.tagsLabel', null, '标签')}
disabled={disabled}
onChange={value => onChange({ tag: value })}
showClear
/>
<Space spacing={8} className="asset-library-filter-actions">
<Button onClick={onReset} disabled={disabled}>
{t('assets.resetFilters', null, '重置')}
</Button>
</Space>
</div>
<Collapse className="asset-library-filter-advanced" keepDOM={false}>
<Collapse.Panel
itemKey="advanced"
header={`${t('assets.advancedFilters', null, '高级筛选')}${advancedCount ? `(${advancedCount})` : ''}`}
>
<div className="asset-library-filter-grid asset-library-filter-grid--advanced">
<Select
value={filters.status || undefined}
placeholder={t('assets.allStatuses', null, '全部状态')}
optionList={STATUS_OPTIONS}
showClear
disabled={disabled}
onChange={value => onChange({ status: value || '' })}
/>
<Select
value={filters.risk_level || undefined}
placeholder={t('assets.allRisks', null, '全部风险')}
optionList={RISK_OPTIONS}
showClear
disabled={disabled}
onChange={value => onChange({ risk_level: value || '' })}
/>
<Select
value={filters.environment || undefined}
placeholder={t('assets.allEnvironments', null, '全部环境')}
optionList={ENVIRONMENT_OPTIONS}
showClear
disabled={disabled}
onChange={value => onChange({ environment: value || '' })}
/>
<Select
value={filters.criticality || undefined}
placeholder={t('assets.allCriticalities', null, '全部级别')}
optionList={CRITICALITY_OPTIONS}
showClear
disabled={disabled}
onChange={value => onChange({ criticality: value || '' })}
/>
<Input
value={filters.ip}
placeholder="IP"
disabled={disabled}
onChange={value => onChange({ ip: value })}
showClear
/>
<Input
value={filters.domain}
placeholder={t('assets.domain', null, '域名')}
disabled={disabled}
onChange={value => onChange({ domain: value })}
showClear
/>
<Input
value={filters.port}
placeholder={t('assets.port', null, '端口')}
disabled={disabled}
onChange={value => onChange({ port: String(value || '').replace(/[^\d]/g, '') })}
showClear
/>
<Select
value={filters.scan || ''}
placeholder={t('assets.scanState', null, '扫描状态')}
optionList={SCAN_STATE_OPTIONS}
disabled={disabled}
onChange={value => onChange({ scan: value || '' })}
/>
<Select
value={filters.sort || 'last_seen_at:desc'}
optionList={SORT_OPTIONS}
disabled={disabled}
onChange={value => onChange({ sort: value || 'last_seen_at:desc' })}
/>
</div>
</Collapse.Panel>
</Collapse>
</div>
);
}

View File

@ -0,0 +1,216 @@
/** 批量导入:CSV / JSON 文本或文件上传,先校验预览再提交 /assets/import。 */
import { useMemo, useRef, useState } from 'react';
import {
Banner, Button, Modal, RadioGroup, Space, Table, TextArea, Typography
} from '@douyinfe/semi-ui';
import { IconCloudUploadStroked } from '@douyinfe/semi-icons';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { toastSuccess } from '../../../components/ui';
import { assetTargetLabel } from './assetTarget';
import { csvTemplate, downloadTextFile, recordsFromCsv, recordsFromJson } from './assetCsv';
const { Text } = Typography;
const PREVIEW_COLUMNS = (t) => [
{ title: t('assets.rowNumber', null, '行号'), dataIndex: 'rowNumber', width: 70 },
{
title: t('assets.target', null, '目标'),
dataIndex: 'target',
render: (_, record) => assetTargetLabel(record.asset || { target: record.values?.target })
},
{
title: t('assets.project', null, '所属项目'),
dataIndex: 'project',
render: (_, record) => record.projectName || record.values?.project || '—'
},
{
title: t('assets.status', null, '状态'),
dataIndex: 'status',
render: (_, record) => record.asset?.status || record.values?.status || '—'
},
{
title: t('assets.validationResult', null, '校验结果'),
dataIndex: 'error',
render: value => (value
? <Text type="danger" size="small">{value}</Text>
: <Text type="success" size="small">{t('assets.validationPassed', null, '通过')}</Text>)
}
];
export default function AssetImportModal({ visible, projects, onClose, onDone }) {
const t = useT();
const [format, setFormat] = useState('csv');
const [text, setText] = useState('');
const [fileName, setFileName] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const fileInputRef = useRef(null);
const parsed = useMemo(() => {
if (!String(text || '').trim()) return { records: [], error: '' };
try {
const records = format === 'csv'
? recordsFromCsv(text, { projects, source: 'manual-import' })
: recordsFromJson(text, { projects, source: 'manual-import' });
return { records, error: '' };
} catch (parseError) {
return { records: [], error: parseError.message };
}
}, [text, format, projects]);
const records = parsed.records;
const valid = records.filter(record => !record.error);
const invalid = records.length - valid.length;
const displayError = error || parsed.error;
const reset = () => {
setText('');
setFileName('');
setFormat('csv');
setError('');
setBusy(false);
};
const close = () => {
if (busy) return;
reset();
onClose?.();
};
const handleFile = async file => {
if (!file) return;
setError('');
const name = String(file.name || '');
const extension = name.split('.').pop().toLowerCase();
if (!['csv', 'json', 'txt'].includes(extension)) {
setError('仅支持 .csv / .json / .txt 文件');
return;
}
if (file.size > 100 * 1024 * 1024) {
setError(t('assets.fileTooLarge', null, '文件不能超过 100 MB'));
return;
}
try {
const content = await file.text();
setFormat(extension === 'json' ? 'json' : 'csv');
setText(content);
setFileName(name);
} catch (readError) {
setError(errorMessage(readError, t('assets.fileParseFailed', null, '无法解析文件,请确认文件格式正确')));
}
};
const submit = async () => {
if (busy || !valid.length) return;
setError('');
setBusy(true);
try {
const result = await api.post('/assets/import', {
assets: valid.map(record => record.asset),
source: 'manual-import',
source_query: fileName || 'paste'
});
const skipped = Number(result?.skipped || 0) + invalid;
toastSuccess(t('assets.bulkImportDone', {
created: Number(result?.created || 0),
updated: Number(result?.updated || 0),
skipped
}, `导入完成:新增 ${Number(result?.created || 0)} 条,更新 ${Number(result?.updated || 0)} 条,跳过 ${skipped} 条`));
reset();
onDone?.();
onClose?.();
} catch (submitError) {
setError(errorMessage(submitError, t('assets.importFailed', null, '资产入库失败')));
} finally {
setBusy(false);
}
};
return (
<Modal
visible={visible}
title={t('assets.bulkImportTitle', null, '批量导入资产')}
width={880}
onCancel={close}
onOk={submit}
okText={t('assets.importValidRowsCount', { count: valid.length }, `导入 ${valid.length} 条有效数据`)}
okButtonProps={{ disabled: !valid.length }}
confirmLoading={busy}
maskClosable={false}
>
<Text type="tertiary">
{t('assets.bulkImportSubtitle', null, '支持 CSV / JSON 文本粘贴或文件上传,提交前会先校验并预览数据')}
</Text>
{displayError && (
<Banner type="danger" bordered closeIcon={null} description={displayError} className="asset-library-form-error" />
)}
<Space vertical align="start" spacing={10} className="asset-library-import-body">
<Space>
<RadioGroup
type="button"
value={format}
options={[
{ value: 'csv', label: 'CSV' },
{ value: 'json', label: 'JSON' }
]}
onChange={event => { setFormat(event.target.value); setError(''); }}
/>
<Button
icon={<IconCloudUploadStroked />}
onClick={() => fileInputRef.current?.click()}
>
{t('assets.chooseOrDropFile', null, '选择文件')}
</Button>
<input
ref={fileInputRef}
type="file"
accept=".csv,.json,.txt"
className="asset-library-file-input"
onChange={event => {
handleFile(event.target.files?.[0]);
event.target.value = '';
}}
/>
<Button
theme="borderless"
onClick={() => downloadTextFile('asset-import-template.csv', csvTemplate())}
>
{t('assets.downloadCsv', null, '下载 CSV 模板')}
</Button>
{fileName && <Text type="tertiary" size="small">{fileName}</Text>}
</Space>
<TextArea
value={text}
rows={8}
className="asset-library-import-textarea"
placeholder={format === 'csv'
? 'target,project,tags,host,ip,domain,port,protocol,title,server,country,province,city,responsible_person,department,business_system,environment,criticality,status'
: '[{"host":"https://example.com","ip":"1.1.1.1","port":443,"protocol":"https","tags":["prod"]}]'}
onChange={value => { setText(value); setError(''); }}
/>
{records.length > 0 && (
<div className="asset-library-import-preview">
<Text strong>
{t('assets.importPreviewSummary', {
total: records.length, valid: valid.length, invalid
}, `共 ${records.length} 行,${valid.length} 行有效,${invalid} 行需修正`)}
</Text>
<Table
columns={PREVIEW_COLUMNS(t)}
dataSource={records.slice(0, 10).map((record, index) => ({ ...record, id: index }))}
rowKey="id"
size="small"
pagination={false}
/>
{records.length > 10 && (
<Text type="tertiary" size="small">
{t('assets.previewLimitedShort', { count: records.length }, `仅展示前 10 行;提交时将处理全部 ${records.length} 行`)}
</Text>
)}
</div>
)}
</Space>
</Modal>
);
}

View File

@ -0,0 +1,84 @@
/** 合并重复资产:选择主资产,POST /assets/merge(后端要求两条资产共享域名/IP/Host)。 */
import { useEffect, useMemo, useState } from 'react';
import { Banner, Modal, Radio, RadioGroup, Space, Typography } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { toastSuccess } from '../../../components/ui';
import { assetTargetLabel } from './assetTarget';
const { Text } = Typography;
export default function AssetMergeModal({ visible, assets, onClose, onDone }) {
const t = useT();
const list = useMemo(() => (Array.isArray(assets) ? assets : []), [assets]);
const [primaryId, setPrimaryId] = useState('');
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
useEffect(() => {
if (visible) {
setPrimaryId(list[0]?.id || '');
setError('');
setBusy(false);
}
}, [visible, list]);
const submit = async () => {
if (busy || list.length < 2) return;
setBusy(true);
setError('');
try {
const result = await api.post('/assets/merge', {
asset_ids: list.map(item => item.id),
primary_id: primaryId || list[0].id
});
toastSuccess(`已合并 ${Number(result?.merged || list.length)} 个资产`);
onDone?.();
onClose?.();
} catch (submitError) {
setError(errorMessage(submitError, '合并资产失败'));
} finally {
setBusy(false);
}
};
return (
<Modal
visible={visible}
title={t('assets.mergeDuplicates', null, '合并重复资产')}
width={560}
onCancel={onClose}
onOk={submit}
okText={t('assets.merge', null, '合并')}
okButtonProps={{ disabled: list.length < 2 }}
confirmLoading={busy}
maskClosable={false}
>
{list.length < 2 ? (
<Banner
type="warning"
bordered
closeIcon={null}
description={t('assets.mergeRequiresMultiple', null, '请至少选择两个重复资产')}
/>
) : (
<Space vertical align="start" spacing={8} style={{ width: '100%' }}>
<Text type="tertiary">
{t('assets.mergeHint', null, '将保留一个主资产,其余资产的空字段与标签会合并进来,然后删除被合并记录。所选资产必须共享域名、IP 或 Host。')}
</Text>
<RadioGroup value={primaryId} onChange={event => setPrimaryId(event.target.value)}>
<Space vertical align="start" spacing={4}>
{list.map(item => (
<Radio key={item.id} value={item.id}>
{assetTargetLabel(item)}
{item.project_name ? ` · ${item.project_name}` : ''}
</Radio>
))}
</Space>
</RadioGroup>
</Space>
)}
{error && <Banner type="danger" bordered closeIcon={null} description={error} className="asset-library-form-error" />}
</Modal>
);
}

View File

@ -0,0 +1,89 @@
/** 批量绑定项目:PUT /assets/project-binding,支持解绑(project_id 置空)。 */
import { useEffect, useMemo, useState } from 'react';
import { Banner, Modal, Select, Space, Switch, Typography } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { toastSuccess } from '../../../components/ui';
const { Text } = Typography;
export default function AssetProjectModal({ visible, projects, assetIds, onClose, onDone }) {
const t = useT();
const [projectId, setProjectId] = useState('');
const [unbind, setUnbind] = useState(false);
const [error, setError] = useState('');
const [busy, setBusy] = useState(false);
const ids = useMemo(() => (Array.isArray(assetIds) ? assetIds : []), [assetIds]);
const projectOptions = useMemo(
() => (projects || []).map(project => ({ value: project.id, label: project.name || project.id })),
[projects]
);
useEffect(() => {
if (visible) {
setProjectId('');
setUnbind(false);
setError('');
setBusy(false);
}
}, [visible]);
const submit = async () => {
if (busy || !ids.length) return;
if (!unbind && !projectId) {
setError(t('assets.selectProjectRequired', null, '请选择要绑定的项目'));
return;
}
setBusy(true);
setError('');
try {
await api.put('/assets/project-binding', {
asset_ids: ids,
project_id: unbind ? '' : projectId
});
toastSuccess(t('assets.bindProjectDone', { count: ids.length }, `已更新 ${ids.length} 个资产`));
onDone?.();
onClose?.();
} catch (submitError) {
setError(errorMessage(submitError, t('assets.bindProjectFailed', null, '绑定项目失败')));
} finally {
setBusy(false);
}
};
return (
<Modal
visible={visible}
title={t('assets.bindProjectTitle', null, '绑定项目')}
width={520}
onCancel={onClose}
onOk={submit}
okText={unbind ? t('assets.unbindProject', null, '解除绑定') : t('assets.confirmBinding', null, '确认绑定')}
confirmLoading={busy}
maskClosable={false}
>
<Space vertical align="start" spacing={10} style={{ width: '100%' }}>
<Text type="tertiary">
{t('assets.bindProjectCount', { count: ids.length }, `将更新 ${ids.length} 个资产`)}
</Text>
<Select
value={projectId || undefined}
optionList={projectOptions}
filter
showClear
disabled={unbind}
placeholder={t('assets.chooseProject', null, '请选择项目')}
onChange={value => setProjectId(value || '')}
style={{ width: '100%' }}
/>
<Space>
<Switch checked={unbind} onChange={setUnbind} size="small" />
<Text size="small">{t('assets.unbindProject', null, '解除项目绑定')}</Text>
</Space>
<Text type="tertiary" size="small">{t('assets.bindProjectHint', null, '所选资产将统一更新为该项目归属。')}</Text>
</Space>
{error && <Banner type="danger" bordered closeIcon={null} description={error} className="asset-library-form-error" />}
</Modal>
);
}

View File

@ -0,0 +1,124 @@
/** 资产库表格:7 列以内,长字段截断,行内查看/编辑/删除。 */
import { Button, Space, Typography } from '@douyinfe/semi-ui';
import { formatDateTime } from '../../../lib/format';
import { useT } from '../../../lib/i18n';
import { DataTable, confirmAction, toastError } from '../../../components/ui';
import { AssetStatusTag, ProtocolTag, RiskTag, TooltipText } from './AssetBits';
import { assetTargetLabel } from './assetTarget';
const { Text } = Typography;
export default function AssetTable({
assets, loading, total, page, pageSize, onPageChange, onPageSizeChange,
selectedRowKeys, onSelectionChange, onView, onEdit, onDelete, onRefresh, canWrite, canDelete
}) {
const t = useT();
const handleDelete = record => {
confirmAction({
title: t('assets.deleteConfirm', null, '确定删除该资产吗?'),
content: assetTargetLabel(record),
okText: t('common.delete', null, '删除'),
onOk: () => {
Promise.resolve(onDelete(record)).catch(error => toastError(error, t('assets.deleteFailed', null, '删除资产失败')));
}
});
};
const columns = [
{
title: t('assets.target', null, '目标'),
dataIndex: 'host',
width: 260,
render: (_, record) => (
<div className="asset-library-target">
<TooltipText text={assetTargetLabel(record)} max={38} />
<Text type="tertiary" size="small">
{[record.ip, record.domain].filter(Boolean).join(' · ') || '—'}
</Text>
</div>
)
},
{
title: t('assets.service', null, '服务'),
dataIndex: 'protocol',
width: 150,
render: (_, record) => <ProtocolTag protocol={record.protocol} port={record.port} />
},
{
title: t('assets.project', null, '所属项目'),
dataIndex: 'project_name',
width: 160,
render: value => <TooltipText text={value} max={18} />
},
{
title: t('assets.source', null, '来源'),
dataIndex: 'source',
width: 120,
render: value => <TooltipText text={value} max={14} />
},
{
title: t('assets.riskLevel', null, '风险等级'),
dataIndex: 'risk_level',
width: 150,
render: (_, record) => (
<Space spacing={6}>
<RiskTag asset={record} />
<Text type="tertiary" size="small">{Number(record.vulnerability_count || 0)}</Text>
</Space>
)
},
{
title: t('assets.lastSeen', null, '最近发现'),
dataIndex: 'last_seen_at',
width: 170,
render: value => <Text size="small">{formatDateTime(value)}</Text>
},
{
title: t('common.actions', null, '操作'),
dataIndex: 'id',
width: 190,
render: (_, record) => (
<Space spacing={4}>
<Button theme="borderless" size="small" onClick={() => onView(record)}>
{t('common.view', null, '查看')}
</Button>
{canWrite && (
<Button theme="borderless" size="small" onClick={() => onEdit(record)}>
{t('common.edit', null, '编辑')}
</Button>
)}
{canDelete && (
<Button theme="borderless" type="danger" size="small" onClick={() => handleDelete(record)}>
{t('common.delete', null, '删除')}
</Button>
)}
</Space>
)
}
];
return (
<DataTable
columns={columns}
dataSource={assets}
loading={loading}
rowKey="id"
onRefresh={onRefresh}
rowSelection={{
selectedRowKeys,
onChange: (keys, rows) => onSelectionChange(keys, rows)
}}
pagination={{
currentPage: page,
pageSize,
total: total || 0,
showSizeChanger: true,
pageSizeOpts: [10, 20, 50, 100],
onPageChange,
onPageSizeChange
}}
emptyText={t('common.noData', null, '暂无数据')}
/>
);
}

View File

@ -0,0 +1,159 @@
/**
* 资产共用常量:枚举文案、筛选项、导入表头别名。
* 仅被 asset-overview / asset-library / info-collect 三个页面目录引用。
*/
export const ASSET_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
export const ASSET_DEFAULT_PAGE_SIZE = 20;
export const STATUS_LABELS = { active: '活跃', inactive: '停用' };
export const STATUS_OPTIONS = [
{ value: 'active', label: STATUS_LABELS.active },
{ value: 'inactive', label: STATUS_LABELS.inactive }
];
export const ENVIRONMENT_LABELS = {
production: '生产',
staging: '预发布',
testing: '测试',
development: '开发',
other: '其他'
};
export const ENVIRONMENT_OPTIONS = Object.entries(ENVIRONMENT_LABELS)
.map(([value, label]) => ({ value, label }));
export const CRITICALITY_LABELS = {
critical: '核心',
high: '重要',
medium: '一般',
low: '低'
};
export const CRITICALITY_OPTIONS = Object.entries(CRITICALITY_LABELS)
.map(([value, label]) => ({ value, label }));
export const RISK_LABELS = {
critical: '严重',
high: '高危',
medium: '中危',
low: '低危',
info: '提示',
normal: '正常',
unassessed: '未评估'
};
export const RISK_COLORS = {
critical: 'red',
high: 'orange',
medium: 'amber',
low: 'blue',
info: 'grey',
normal: 'green',
unassessed: 'grey'
};
export const RISK_OPTIONS = Object.entries(RISK_LABELS)
.map(([value, label]) => ({ value, label }));
export function riskLevelOf(asset) {
const level = String(asset?.risk_level || '').toLowerCase();
return RISK_LABELS[level] ? level : 'unassessed';
}
export function riskLabel(level) {
return RISK_LABELS[String(level || '').toLowerCase()] || RISK_LABELS.unassessed;
}
/** 常见协议(FOFA/资产库里的 protocol 字段值)。 */
export const PROTOCOL_OPTIONS = [
'http', 'https', 'ssh', 'ftp', 'smtp', 'dns', 'ldap', 'smb',
'telnet', 'rdp', 'mysql', 'postgresql', 'mssql', 'redis', 'mongodb'
].map(value => ({ value, label: value }));
export const SORT_OPTIONS = [
{ value: 'last_seen_at:desc', label: '最近发现(新到旧)' },
{ value: 'last_seen_at:asc', label: '最近发现(旧到新)' },
{ value: 'last_scan_at:asc', label: '最久未扫描优先' },
{ value: 'last_scan_at:desc', label: '最近扫描优先' },
{ value: 'risk_level:desc', label: '风险从高到低' },
{ value: 'vulnerability_count:desc', label: '漏洞数量从多到少' },
{ value: 'first_seen_at:desc', label: '首次发现(新到旧)' },
{ value: 'host:asc', label: '目标名称' },
{ value: 'port:asc', label: '端口' }
];
/** 扫描状态筛选:never / scanned / overdue:N,对应 handler 的 scan_state 与 scan_overdue_days。 */
export const SCAN_STATE_OPTIONS = [
{ value: '', label: '全部' },
{ value: 'never', label: '从未扫描' },
{ value: 'scanned', label: '已扫描' },
{ value: 'overdue:30', label: '30 天未扫描' },
{ value: 'overdue:60', label: '60 天未扫描' },
{ value: 'overdue:90', label: '90 天未扫描' }
];
export function applyScanStateParam(query, value) {
const raw = String(value || '');
if (!raw) return query;
const overdue = raw.match(/^overdue:(\d+)$/);
if (overdue) return { ...query, scan_overdue_days: overdue[1] };
return { ...query, scan_state: raw };
}
/** 批量导入列(与旧版模板一致)。 */
export const IMPORT_COLUMNS = [
'target', 'project', 'tags', 'host', 'ip', 'domain', 'port', 'protocol', 'title',
'server', 'country', 'province', 'city', 'responsible_person', 'department',
'business_system', 'environment', 'criticality', 'status'
];
export const IMPORT_HEADER_ALIASES = {
target: ['target', 'asset', 'assetaddress', '目标', '资产', '资产地址'],
project: ['project', 'projectname', 'projectid', '项目', '项目名称', '项目id', '所属项目'],
tags: ['tags', 'tag', '标签'],
host: ['host', 'url', '完整url', '完整urlhost', '主机'],
ip: ['ip', 'ipaddress', 'ip地址'],
domain: ['domain', '域名'],
port: ['port', '端口'],
protocol: ['protocol', 'scheme', '协议'],
title: ['title', 'pagetitle', '标题', '页面标题', '标题指纹'],
server: ['server', 'service', 'product', '服务', '产品', '服务指纹'],
country: ['country', 'countryregion', '国家', '国家地区'],
province: ['province', 'state', '省份', '省份州', '州'],
city: ['city', '城市'],
responsible_person: ['responsibleperson', 'owner', '负责人', '责任人'],
department: ['department', '部门'],
business_system: ['businesssystem', 'system', '业务系统', '系统'],
environment: ['environment', 'env', '环境'],
source: ['source', '来源'],
criticality: ['criticality', 'importance', '重要性', '重要等级'],
status: ['status', '状态']
};
export const MAX_IMPORT_ROWS = 100000;
/** 导出列与表头(CSV 全字段)。 */
export const EXPORT_COLUMNS = [
['target', '目标'], ['host', '完整 URL / Host'], ['ip', 'IP 地址'], ['domain', '域名'],
['port', '端口'], ['protocol', '协议'], ['title', '标题/指纹'], ['server', '服务指纹'],
['project', '所属项目'], ['responsible_person', '负责人'], ['department', '部门'],
['business_system', '业务系统'], ['environment', '环境'], ['criticality', '重要性'],
['country', '国家/地区'], ['province', '省份/州'], ['city', '城市'], ['source', '来源'],
['status', '状态'], ['tags', '标签'], ['risk_level', '风险等级'],
['vulnerability_count', '漏洞数量'], ['first_seen_at', '首次发现'],
['last_seen_at', '最近发现'], ['last_scan_at', '上次扫描']
];
export function environmentLabel(value) {
return ENVIRONMENT_LABELS[value] || value || '';
}
export function criticalityLabel(value) {
return CRITICALITY_LABELS[value] || value || '';
}
export function statusLabel(value) {
return STATUS_LABELS[value] || value || '';
}

View File

@ -0,0 +1,257 @@
/**
* 资产 CSV/JSON 导入解析与 CSV 导出。
* 旧版支持 .xlsx/.csv;新前端不引入表格库,改为 CSV/JSON 文本与文件上传统一解析。
*/
import {
CRITICALITY_LABELS, ENVIRONMENT_LABELS, EXPORT_COLUMNS, IMPORT_COLUMNS,
IMPORT_HEADER_ALIASES, MAX_IMPORT_ROWS, STATUS_LABELS,
criticalityLabel, environmentLabel, riskLabel, statusLabel
} from './assetConstants';
import {
assetDedupKey, assetTargetLabel, isIPv4, isIPv6, normalizeDomain, parseAssetTarget,
splitTags, validateAssetPayload
} from './assetTarget';
const FIELD_LIMITS = {
host: 500, title: 500, domain: 253, protocol: 32, server: 255, country: 255,
province: 255, city: 255, responsible_person: 255, department: 255, business_system: 255
};
function normalizeHeader(value) {
return String(value ?? '')
.replace(/^\uFEFF/, '')
.trim()
.toLowerCase()
.replace(/[\s_\-/.()()]+/g, '');
}
export function columnForHeader(value) {
const normalized = normalizeHeader(value);
if (!normalized) return '';
return IMPORT_COLUMNS.find(column => (IMPORT_HEADER_ALIASES[column] || [])
.some(alias => normalizeHeader(alias) === normalized)) || '';
}
/** RFC4180 风格 CSV 解析(支持引号、转义引号、CRLF/BOM)。 */
export function parseCsv(text) {
const source = String(text ?? '').replace(/^\uFEFF/, '');
const rows = [];
let row = [];
let field = '';
let quoted = false;
for (let index = 0; index < source.length; index += 1) {
const char = source[index];
if (quoted) {
if (char === '"') {
if (source[index + 1] === '"') {
field += '"';
index += 1;
} else {
quoted = false;
}
} else {
field += char;
}
continue;
}
if (char === '"') {
quoted = true;
} else if (char === ',') {
row.push(field);
field = '';
} else if (char === '\n') {
row.push(field);
rows.push(row);
row = [];
field = '';
} else if (char !== '\r') {
field += char;
}
}
if (field !== '' || row.length) {
row.push(field);
rows.push(row);
}
return rows.filter(columns => columns.some(value => String(value ?? '').trim() !== ''));
}
function localizedEnum(value, labels, fallback = '') {
const raw = String(value ?? '').trim();
if (!raw) return fallback;
const lower = raw.toLowerCase();
if (labels[lower]) return lower;
const matched = Object.entries(labels).find(([, label]) => label === raw);
return matched ? matched[0] : null;
}
function resolveProject(value, projects) {
const raw = String(value ?? '').trim();
if (!raw) return { projectId: '', projectName: '', error: '' };
const lower = raw.toLowerCase();
const project = (projects || []).find(item => String(item.id).toLowerCase() === lower
|| String(item.name || '').trim().toLowerCase() === lower);
if (!project) return { projectId: '', projectName: '', error: `项目不存在或无权访问:${raw}` };
return { projectId: project.id, projectName: project.name, error: '' };
}
function buildRecord(values, rowNumber, { projects, source }) {
const fail = message => ({ rowNumber, values, asset: null, error: message });
const target = values.target || values.host || values.domain || values.ip || '';
if (!target) return fail('缺少目标地址');
let parsed;
try {
parsed = parseAssetTarget(target);
} catch (error) {
return fail(error.message);
}
const rawPort = String(values.port ?? '').trim();
const port = rawPort === '' ? Number(parsed.port || 0) : Number(rawPort);
if (!Number.isInteger(port) || port < 0 || port > 65535) return fail('端口必须在 0–65535 之间');
const ip = String(values.ip || parsed.ip || '').trim().toLowerCase();
if (ip && !isIPv4(ip) && !isIPv6(ip)) return fail('IP 地址格式无效');
const rawDomain = String(values.domain || parsed.domain || '').trim();
const domain = rawDomain ? normalizeDomain(rawDomain) : '';
if (rawDomain && !domain) return fail('域名格式无效');
const protocol = String(values.protocol || parsed.protocol || '').trim().toLowerCase();
if (protocol && !/^[a-z][a-z0-9+.-]{0,31}$/.test(protocol)) return fail('协议格式无效');
const status = localizedEnum(values.status, STATUS_LABELS, 'active');
if (!status) return fail('状态仅支持 active 或 inactive');
const environment = localizedEnum(values.environment, ENVIRONMENT_LABELS, '');
if (environment === null) return fail('环境值无效');
const criticality = localizedEnum(values.criticality, CRITICALITY_LABELS, '');
if (criticality === null) return fail('重要性值无效');
const project = resolveProject(values.project, projects);
if (project.error) return fail(project.error);
const tags = splitTags(values.tags);
if (tags.length > 30) return fail('标签最多 30 个');
if (tags.some(tag => Array.from(tag).length > 64)) return fail('单个标签最多 64 个字符');
const asset = {
host: String(values.host || parsed.host || '').trim(),
ip,
domain,
port,
protocol,
title: String(values.title || '').trim(),
server: String(values.server || '').trim(),
country: String(values.country || '').trim(),
province: String(values.province || '').trim(),
city: String(values.city || '').trim(),
responsible_person: String(values.responsible_person || '').trim(),
department: String(values.department || '').trim(),
business_system: String(values.business_system || '').trim(),
environment,
criticality,
status,
tags,
project_id: project.projectId,
source: source || 'manual-import'
};
const oversized = Object.keys(FIELD_LIMITS)
.find(key => Array.from(String(asset[key] || '')).length > FIELD_LIMITS[key]);
if (oversized) return fail(`字段 ${oversized} 内容过长`);
const invalid = validateAssetPayload(asset);
if (invalid) return fail(invalid);
return { rowNumber, values, asset, projectName: project.projectName, error: '' };
}
function markDuplicates(records) {
const seen = new Map();
return records.map(record => {
if (record.error || !record.asset) return record;
const key = assetDedupKey(record.asset);
if (seen.has(key)) {
return { ...record, error: `与第 ${seen.get(key)} 行重复` };
}
seen.set(key, record.rowNumber);
return record;
});
}
/** CSV 文本 → 导入行(含逐行校验)。 */
export function recordsFromCsv(text, options = {}) {
const matrix = parseCsv(text);
if (matrix.length < 2) throw new Error('文件中没有可导入的数据');
const headers = matrix[0].map(columnForHeader);
if (!headers.some(Boolean)) throw new Error('未识别到模板字段,请检查表头');
const dataRows = matrix.slice(1);
if (dataRows.length > MAX_IMPORT_ROWS) throw new Error(`数据不能超过 ${MAX_IMPORT_ROWS} 行`);
const records = dataRows.map((row, index) => {
const values = {};
headers.forEach((column, columnIndex) => {
if (column && values[column] == null) values[column] = String(row[columnIndex] ?? '').trim();
});
return buildRecord(values, index + 2, options);
});
return markDuplicates(records);
}
/** JSON 文本 → 导入行;支持 {assets:[...]}、数组与单个对象。 */
export function recordsFromJson(text, options = {}) {
let parsed;
try {
parsed = JSON.parse(String(text ?? ''));
} catch (error) {
throw new Error('JSON 解析失败:' + error.message);
}
const list = Array.isArray(parsed) ? parsed : (Array.isArray(parsed?.assets) ? parsed.assets : [parsed]);
const items = list.filter(item => item && typeof item === 'object');
if (!items.length) throw new Error('文件中没有可导入的数据');
if (items.length > MAX_IMPORT_ROWS) throw new Error(`数据不能超过 ${MAX_IMPORT_ROWS} 行`);
const records = items.map((item, index) => {
const values = {
target: item.target || item.host || item.domain || item.ip || '',
host: item.host, ip: item.ip, domain: item.domain, port: item.port,
protocol: item.protocol, title: item.title, server: item.server,
country: item.country, province: item.province, city: item.city,
responsible_person: item.responsible_person, department: item.department,
business_system: item.business_system, environment: item.environment,
criticality: item.criticality, status: item.status,
tags: Array.isArray(item.tags) ? item.tags.join(',') : item.tags,
project: item.project_id || item.project || item.project_name
};
return buildRecord(values, index + 1, options);
});
return markDuplicates(records);
}
export function csvTemplate() {
return `${IMPORT_COLUMNS.join(',')}\r\n`;
}
function csvCell(value) {
const text = String(value ?? '');
return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
}
function exportValue(asset, key) {
if (key === 'target') return assetTargetLabel(asset);
if (key === 'project') return asset.project_name || asset.project_id || '';
if (key === 'tags') return (asset.tags || []).join(',');
if (key === 'status') return statusLabel(asset.status);
if (key === 'environment') return environmentLabel(asset.environment);
if (key === 'criticality') return criticalityLabel(asset.criticality);
if (key === 'risk_level') return riskLabel(asset.risk_level);
if (key === 'vulnerability_count') return Number(asset.vulnerability_count || 0);
return asset[key] ?? '';
}
export function assetsToCsv(assets) {
const rows = [EXPORT_COLUMNS.map(([, label]) => csvCell(label)).join(',')];
(assets || []).forEach(asset => {
rows.push(EXPORT_COLUMNS.map(([key]) => csvCell(exportValue(asset, key))).join(','));
});
return `\uFEFF${rows.join('\r\n')}`;
}
/** 触发浏览器下载(仅创建临时 a 元素,不查询 DOM)。 */
export function downloadTextFile(filename, content, mime = 'text/csv;charset=utf-8') {
const blob = new Blob([content], { type: mime });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}

View File

@ -0,0 +1,154 @@
/**
* 资产目标解析:URL / 域名 / IP / IPv6 / 端口互转。
* 规则与旧版 assets.js(parseAssetEditorTarget)保持一致,供编辑器、导入与 FOFA 入库共用。
*/
export const DEFAULT_PORTS = {
http: 80, https: 443, ssh: 22, ftp: 21, smtp: 25, rdp: 3389,
mysql: 3306, postgresql: 5432, redis: 6379, mongodb: 27017
};
export const PROTOCOL_BY_PORT = Object.entries(DEFAULT_PORTS)
.reduce((acc, [protocol, port]) => ({ ...acc, [port]: protocol }), {});
export function defaultPortForProtocol(protocol) {
return DEFAULT_PORTS[String(protocol || '').toLowerCase()] || 0;
}
export function protocolForPort(port) {
return PROTOCOL_BY_PORT[Number(port)] || '';
}
export function isIPv4(value) {
const parts = String(value || '').split('.');
return parts.length === 4 && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255);
}
export function isIPv6(value) {
const candidate = String(value || '').replace(/^\[|\]$/g, '');
if (!candidate.includes(':') || !/^[0-9a-f:.]+$/i.test(candidate)) return false;
try {
return new URL(`http://[${candidate}]/`).hostname.length > 2;
} catch (error) {
return false;
}
}
export function normalizeDomain(value) {
const raw = String(value || '').trim().replace(/\.$/, '');
if (!raw || raw.length > 253 || raw.includes('_') || /[/?#@]/.test(raw)) return '';
try {
const hostname = new URL(`http://${raw}/`).hostname.toLowerCase().replace(/\.$/, '');
if (!hostname || hostname.length > 253) return '';
const labels = hostname.split('.');
const valid = labels.every(label => label
&& label.length <= 63
&& /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(label));
return valid ? hostname : '';
} catch (error) {
return '';
}
}
/**
* 解析用户输入的资产目标。始终返回结构体,格式无法识别时按不透明 host 处理;
* 端口越界会抛出错误(与旧版行为一致)。
*/
export function parseAssetTarget(value) {
const raw = String(value || '').trim();
if (!raw) throw new Error('请输入资产地址');
if (/\s/.test(raw)) throw new Error('资产地址不能包含空格');
const opaque = () => ({ host: raw, ip: '', domain: '', port: 0, protocol: '' });
let hostname = '';
let port = 0;
let protocol = '';
let host = '';
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
let parsed;
try {
parsed = new URL(raw);
} catch (error) {
return opaque();
}
if (!parsed.hostname || parsed.username || parsed.password) return opaque();
protocol = parsed.protocol.replace(':', '').toLowerCase();
hostname = parsed.hostname.replace(/^\[|\]$/g, '');
port = parsed.port ? Number(parsed.port) : defaultPortForProtocol(protocol);
host = raw;
} else {
const authority = raw.replace(/\/$/, '');
const bracketed = authority.match(/^\[([^\]]+)](?::(\d+))?$/);
if (bracketed) {
hostname = bracketed[1];
port = Number(bracketed[2] || 0);
} else if ((authority.match(/:/g) || []).length === 1 && /:\d+$/.test(authority)) {
const splitAt = authority.lastIndexOf(':');
hostname = authority.slice(0, splitAt);
port = Number(authority.slice(splitAt + 1));
} else {
hostname = authority;
}
protocol = protocolForPort(port);
}
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('端口必须在 0–65535 之间');
const ipAddress = isIPv4(hostname) || isIPv6(hostname);
const domain = ipAddress ? '' : normalizeDomain(hostname);
if (!ipAddress && (!domain || isIPv4(domain) || isIPv6(domain))) return opaque();
return {
host,
ip: ipAddress ? hostname.toLowerCase() : '',
domain,
port,
protocol
};
}
export function assetTargetLabel(asset) {
return asset?.host || asset?.domain || asset?.ip || asset?.target || '-';
}
export function assetServiceLabel(asset) {
if (!asset) return '';
const protocol = String(asset.protocol || '').trim();
const port = Number(asset.port || 0);
if (!protocol && !port) return '';
return `${protocol}${port ? `:${port}` : ''}`;
}
/** 编辑弹窗的目标输入初始值:优先 host,其次 domain/ip + 端口。 */
export function targetInputFromAsset(asset) {
if (!asset) return '';
if (asset.host) return String(asset.host);
const base = asset.domain || asset.ip || '';
if (!base) return '';
const wrapped = String(base).includes(':') && !String(base).startsWith('[') ? `[${base}]` : base;
return `${wrapped}${Number(asset.port || 0) > 0 ? `:${asset.port}` : ''}`;
}
/** 资产去重键(与服务端 dedup_key 同构,仅用于导入前的前端提示)。 */
export function assetDedupKey(asset) {
const target = String(asset?.domain || asset?.ip || asset?.host || '').toLowerCase();
return `${target}|${Number(asset?.port || 0)}|${String(asset?.protocol || '').toLowerCase()}`;
}
export function splitTags(raw) {
return String(raw || '')
.split(/[,,;;|]/)
.map(item => item.trim())
.filter(Boolean);
}
export function validateAssetPayload(asset) {
if (!asset) return '资产不能为空';
if (!asset.host && !asset.ip && !asset.domain) return '资产目标不能为空';
if (asset.ip && !isIPv4(asset.ip) && !isIPv6(asset.ip)) return 'IP 地址格式无效';
if (asset.domain && (!normalizeDomain(asset.domain) || isIPv4(asset.domain) || isIPv6(asset.domain))) {
return '域名格式无效';
}
if (asset.protocol && !/^[a-z][a-z0-9+.-]{0,31}$/.test(asset.protocol)) return '协议格式无效';
if (Number(asset.port) < 0 || Number(asset.port) > 65535) return '端口必须在 0–65535 之间';
const tags = Array.isArray(asset.tags) ? asset.tags : [];
if (tags.length > 30) return '标签最多 30 个';
if (tags.some(tag => Array.from(String(tag)).length > 64)) return '单个标签最多 64 个字符';
return '';
}

View File

@ -0,0 +1,78 @@
/** FOFA/ZoomEye/Quake/Shodan 结果行 → 资产结构,并批量入库。 */
import { api } from '../../../lib/http';
import { isIPv4, isIPv6, normalizeDomain } from './assetTarget';
function cellValue(row, fields, name) {
if (row && !Array.isArray(row) && typeof row === 'object') {
const value = row[name];
if (Array.isArray(value)) return value.filter(Boolean).join(',');
return value == null ? '' : String(value).trim();
}
const index = Array.isArray(fields) ? fields.indexOf(name) : -1;
if (index < 0 || !Array.isArray(row)) return '';
const value = row[index];
return value == null ? '' : String(value).trim();
}
function firstValue(row, fields, names) {
for (const name of names) {
const value = cellValue(row, fields, name);
if (value) return value;
}
return '';
}
/** 把一条检索结果转换成 /assets/import 可接受的资产对象。 */
export function fofaRowToAsset(row, fields, provider = 'fofa') {
const port = Number.parseInt(cellValue(row, fields, 'port'), 10);
const rawIP = firstValue(row, fields, ['ip', 'ip_str']);
const ip = isIPv4(rawIP) || isIPv6(rawIP) ? rawIP.toLowerCase() : '';
const rawDomain = firstValue(row, fields, ['domain', 'hostname', 'hostnames', 'domains'])
.split(',')[0]
.replace(/^\[|\]$/g, '')
.replace(/^"|"$/g, '');
const domain = rawDomain && !isIPv4(rawDomain) && !isIPv6(rawDomain)
? normalizeDomain(rawDomain)
: '';
const rawProtocol = firstValue(row, fields, ['protocol', 'service.name', 'transport']).toLowerCase();
const rawHost = firstValue(row, fields, ['host', 'hostname']);
return {
host: rawHost.split(',')[0].trim(),
ip,
port: Number.isFinite(port) ? port : 0,
domain,
protocol: /^[a-z][a-z0-9+.-]{0,31}$/.test(rawProtocol) ? rawProtocol : '',
title: firstValue(row, fields, ['title', 'service.http.title']),
server: firstValue(row, fields, ['server', 'product']),
country: firstValue(row, fields, ['country', 'location.country_cn', 'location.country_name']),
province: firstValue(row, fields, ['region', 'province', 'location.province_cn']),
city: firstValue(row, fields, ['city', 'location.city_cn', 'location.city']),
source: provider || 'fofa',
status: 'active'
};
}
/**
* 将选中的结果行入库。
* 返回 { assets, invalidCount, created, updated, skipped }。
*/
export async function importFofaRows(rows, { fields, provider, query }) {
const converted = (rows || []).map(row => fofaRowToAsset(row, fields, provider));
const assets = converted.filter(asset => asset.host || asset.ip || asset.domain);
const invalidCount = converted.length - assets.length;
if (!assets.length) {
return { assets, invalidCount, created: 0, updated: 0, skipped: 0 };
}
const result = await api.post('/assets/import', {
assets,
source: provider || 'fofa',
source_query: query || ''
});
return {
assets,
invalidCount,
created: Number(result?.created || 0),
updated: Number(result?.updated || 0),
skipped: Number(result?.skipped || 0)
};
}

View File

@ -0,0 +1,21 @@
/** 项目下拉数据:资产绑定/筛选共用,失败时降级为空列表。 */
import { api } from '../../../lib/http';
import { useResource } from '../../../components/hooks';
export function useAssetProjects() {
const { data, loading, reload } = useResource(
() => api.get('/projects', { limit: 200 }),
[],
{ initial: { projects: [] } }
);
return {
projects: Array.isArray(data?.projects) ? data.projects : [],
loading,
reload
};
}
export async function fetchAssetProjects() {
const payload = await api.get('/projects', { limit: 200 });
return Array.isArray(payload?.projects) ? payload.projects : [];
}

View File

@ -0,0 +1,422 @@
/** 资产库:筛选、分页、行内操作、详情、新建/编辑、批量、导入、合并、绑定项目、导出。 */
import { useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useSearchParams } from 'react-router-dom';
import { Banner, Button, Space, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh, IconCloudUploadStroked } from '@douyinfe/semi-icons';
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useDebounced, useResource } from '../../components/hooks';
import {
ErrorBanner, PageHeader, SectionCard, confirmAction, toastError, toastSuccess, toastWarning
} from '../../components/ui';
import AssetFilterBar, { emptyAssetFilters } from './components/AssetFilterBar';
import AssetTable from './components/AssetTable';
import AssetDetailDrawer from './components/AssetDetailDrawer';
import AssetEditorModal from './components/AssetEditorModal';
import AssetImportModal from './components/AssetImportModal';
import AssetMergeModal from './components/AssetMergeModal';
import AssetProjectModal from './components/AssetProjectModal';
import AssetBulkEditModal from './components/AssetBulkEditModal';
import { useAssetProjects } from './components/useAssetProjects';
import { applyScanStateParam } from './components/assetConstants';
import { assetsToCsv, downloadTextFile } from './components/assetCsv';
import './page.css';
const { Text } = Typography;
export function buildAssetQuery(filters, page, pageSize) {
let query = {
page,
page_size: pageSize,
q: filters.q,
protocol: filters.protocol,
source: filters.source,
project_id: filters.project_id,
tag: filters.tag,
status: filters.status,
risk_level: filters.risk_level,
environment: filters.environment,
criticality: filters.criticality,
ip: filters.ip,
domain: filters.domain,
port: filters.port
};
query = applyScanStateParam(query, filters.scan);
const [sortBy, sortOrder] = String(filters.sort || 'last_seen_at:desc').split(':');
query.sort_by = sortBy;
query.sort_order = sortOrder || 'desc';
return query;
}
export default function AssetLibraryPage() {
const t = useT();
const { hasPermission } = useAuth();
const canRead = hasPermission('asset:read');
const canWrite = hasPermission('asset:write');
const canDelete = hasPermission('asset:delete');
const [searchParams, setSearchParams] = useSearchParams();
const location = useLocation();
const deepId = searchParams.get('id') || '';
const linkedAsset = location.state?.asset || null;
const [filters, setFilters] = useState(() => ({
...emptyAssetFilters(),
q: searchParams.get('q') || ''
}));
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [tick, setTick] = useState(0);
const [selection, setSelection] = useState({ keys: [], rows: [] });
const [detailAsset, setDetailAsset] = useState(null);
const [editorOpen, setEditorOpen] = useState(false);
const [editorAsset, setEditorAsset] = useState(null);
const [importOpen, setImportOpen] = useState(false);
const [mergeOpen, setMergeOpen] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
const [bulkOpen, setBulkOpen] = useState(false);
const [exporting, setExporting] = useState(false);
const debouncedFilters = useDebounced(filters, 300);
const query = useMemo(
() => buildAssetQuery(debouncedFilters, page, pageSize),
[debouncedFilters, page, pageSize]
);
const { data, loading, error, reload } = useResource(
() => api.get('/assets', query),
[query, tick],
{ skip: !canRead }
);
const { projects, reload: reloadProjects } = useAssetProjects();
const assets = useMemo(() => (Array.isArray(data?.assets) ? data.assets : []), [data]);
const total = Number(data?.total || 0);
const resolvedDeep = useRef('');
useEffect(() => {
if (!deepId || !linkedAsset?.id || linkedAsset.id !== deepId || resolvedDeep.current === deepId) return;
resolvedDeep.current = deepId;
setDetailAsset(linkedAsset);
}, [deepId, linkedAsset]);
useEffect(() => {
if (!deepId || deepId === resolvedDeep.current) return undefined;
const inPage = assets.find(item => item.id === deepId);
if (inPage) {
resolvedDeep.current = deepId;
setDetailAsset(inPage);
return undefined;
}
let cancelled = false;
(async () => {
for (let current = 1; current <= 5 && !cancelled; current += 1) {
const payload = await api.get('/assets', { page_size: 100, page: current });
const hit = (payload?.assets || []).find(item => item.id === deepId);
if (hit) {
if (!cancelled) {
resolvedDeep.current = deepId;
setDetailAsset(hit);
}
return;
}
if (current >= Number(payload?.total_pages || 1)) break;
}
if (!cancelled) resolvedDeep.current = deepId;
})().catch(() => { resolvedDeep.current = deepId; });
return () => { cancelled = true; };
}, [deepId, assets]);
const changeFilters = patch => {
setFilters(prev => ({ ...prev, ...patch }));
setPage(1);
setSelection({ keys: [], rows: [] });
};
const resetFilters = () => {
setFilters(emptyAssetFilters());
setPage(1);
setSelection({ keys: [], rows: [] });
};
const refresh = () => setTick(value => value + 1);
const writeDeepLink = assetId => {
const next = new URLSearchParams(searchParams);
if (assetId) next.set('id', assetId);
else next.delete('id');
setSearchParams(next, { replace: true });
};
const openDetail = asset => {
setDetailAsset(asset);
if (asset?.id) writeDeepLink(asset.id);
};
const closeDetail = () => {
setDetailAsset(null);
if (deepId) {
resolvedDeep.current = '';
writeDeepLink('');
}
};
const openEditor = asset => {
setEditorAsset(asset || null);
setEditorOpen(true);
if (canWrite) reloadProjects();
};
const afterWrite = async () => {
setSelection({ keys: [], rows: [] });
await reload();
};
const deleteAsset = async asset => {
await api.del(`/assets/${encodeURIComponent(asset.id)}`);
toastSuccess(t('assets.deleted', null, '资产已删除'));
if (detailAsset?.id === asset.id) closeDetail();
await afterWrite();
};
const batchDelete = () => {
const ids = selection.keys;
if (!ids.length) return;
confirmAction({
title: t('assets.deleteConfirm', null, '确定删除所选资产吗?'),
content: `将永久删除 ${ids.length} 个资产。`,
okText: t('common.delete', null, '删除'),
onOk: async () => {
try {
const result = await api.post('/assets/batch-delete', { asset_ids: ids });
toastSuccess(`已删除 ${Number(result?.deleted || ids.length)} 个资产`);
await afterWrite();
} catch (deleteError) {
toastError(deleteError, '批量删除失败');
}
}
});
};
const selectionQuery = useMemo(() => {
const { page: _page, page_size: _size, ...rest } = buildAssetQuery(debouncedFilters, 1, pageSize);
return rest;
}, [debouncedFilters, pageSize]);
const selectAllMatching = async () => {
try {
const payload = await api.get('/assets/selection', selectionQuery);
const rows = Array.isArray(payload?.assets) ? payload.assets : [];
setSelection({ keys: rows.map(item => item.id), rows });
toastSuccess(t('assets.allResultsSelected', { count: rows.length }, `已选择 ${rows.length} 项`));
} catch (selectionError) {
toastError(selectionError, '选择全部结果失败');
}
};
const exportCsv = async all => {
if (exporting) return;
setExporting(true);
try {
let rows = selection.rows;
if (all) {
const payload = await api.get('/assets/selection', selectionQuery);
rows = Array.isArray(payload?.assets) ? payload.assets : [];
} else if (!rows.length) {
rows = assets;
}
if (!rows.length) {
toastWarning('没有可导出的资产');
return;
}
const stamp = new Date().toISOString().slice(0, 10);
downloadTextFile(`assets-${stamp}.csv`, assetsToCsv(rows));
toastSuccess(`已导出 ${rows.length} 个资产`);
} catch (exportError) {
toastError(exportError, '导出失败');
} finally {
setExporting(false);
}
};
const onSelectionChange = (keys, rows) => {
setSelection({ keys: keys || [], rows: rows || [] });
};
const selectedCount = selection.keys.length;
if (!canRead) {
return (
<div className="asset-library-page">
<PageHeader title={t('assets.libraryTitle', null, '资产库')} description="资产列表、批量操作与导入需要资产读取权限。" />
<Banner
type="warning"
bordered
closeIcon={null}
description={t('assets.readDenied', null, '当前账号没有 asset:read 权限,无法读取资产库;请联系管理员授权。')}
/>
</div>
);
}
return (
<div className="asset-library-page">
<PageHeader
title={t('assets.libraryTitle', null, '资产库')}
description="统一维护域名、IP、端口与服务资产,支持批量入库、合并与项目绑定。"
extra={(
<Space>
<Button icon={<IconRefresh />} onClick={refresh} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>
{canWrite && (
<Button icon={<IconCloudUploadStroked />} onClick={() => setImportOpen(true)}>
{t('assets.bulkImport', null, '批量导入')}
</Button>
)}
{canWrite && (
<Button theme="solid" type="primary" icon={<IconPlus />} onClick={() => openEditor(null)}>
{t('assets.addAsset', null, '新增资产')}
</Button>
)}
</Space>
)}
/>
<ErrorBanner error={error} onRetry={refresh} />
<SectionCard title={t('assets.filterTitle', null, '筛选条件')}>
<AssetFilterBar
filters={filters}
projects={projects}
onChange={changeFilters}
onReset={resetFilters}
/>
</SectionCard>
<SectionCard
title={`${t('assets.libraryTitle', null, '资产库')}(${total})`}
extra={(
<Space>
<Button
theme="borderless"
disabled={!selectedCount}
onClick={() => setSelection({ keys: [], rows: [] })}
>
{t('assets.clearSelection', null, '清除选择')}
</Button>
<Button theme="borderless" onClick={() => exportCsv(false)} loading={exporting}>
{t('assets.exportCsv', null, '导出 CSV')}
</Button>
<Button theme="borderless" onClick={() => exportCsv(true)} loading={exporting}>
{t('assets.exportAll', null, '导出全部筛选结果')}
</Button>
</Space>
)}
>
<div className="asset-library-toolbar">
<Space>
<Text type="tertiary">
{selectedCount
? t('assets.selectedCount', { count: selectedCount }, `已选择 ${selectedCount} 项`)
: t('assets.selectedCount', { count: 0 }, '已选择 0 项')}
</Text>
<Button theme="borderless" size="small" onClick={selectAllMatching}>
{t('assets.selectAllResults', { count: total }, `选择全部 ${total} 项`)}
</Button>
</Space>
<Space>
{canWrite && (
<Button size="small" disabled={selectedCount < 2} onClick={() => setMergeOpen(true)}>
{t('assets.mergeDuplicates', null, '合并重复资产')}
</Button>
)}
{canWrite && (
<Button size="small" disabled={!selectedCount} onClick={() => setProjectOpen(true)}>
{t('assets.bindProject', null, '绑定项目')}
</Button>
)}
{canWrite && (
<Button size="small" disabled={!selectedCount} onClick={() => setBulkOpen(true)}>
{t('assets.bulkEdit', null, '批量编辑')}
</Button>
)}
{canDelete && (
<Button size="small" type="danger" disabled={!selectedCount} onClick={batchDelete}>
{t('assets.batchDelete', null, '批量删除…')}
</Button>
)}
</Space>
</div>
<AssetTable
assets={assets}
loading={loading}
total={total}
page={page}
pageSize={pageSize}
onPageChange={next => { setPage(next); setSelection({ keys: [], rows: [] }); }}
onPageSizeChange={next => { setPageSize(next); setPage(1); setSelection({ keys: [], rows: [] }); }}
selectedRowKeys={selection.keys}
onSelectionChange={onSelectionChange}
onView={openDetail}
onEdit={openEditor}
onDelete={deleteAsset}
onRefresh={refresh}
canWrite={canWrite}
canDelete={canDelete}
/>
</SectionCard>
<AssetDetailDrawer
asset={detailAsset}
visible={Boolean(detailAsset)}
onClose={closeDetail}
onEdit={asset => { closeDetail(); openEditor(asset); }}
onDelete={asset => {
confirmAction({
title: t('assets.deleteConfirm', null, '确定删除该资产吗?'),
content: asset.host || asset.domain || asset.ip,
okText: t('common.delete', null, '删除'),
onOk: () => deleteAsset(asset).catch(deleteError => toastError(deleteError, t('assets.deleteFailed', null, '删除资产失败')))
});
}}
canWrite={canWrite}
canDelete={canDelete}
/>
<AssetEditorModal
visible={editorOpen}
asset={editorAsset}
projects={projects}
onClose={() => setEditorOpen(false)}
onSaved={afterWrite}
/>
<AssetImportModal
visible={importOpen}
projects={projects}
onClose={() => setImportOpen(false)}
onDone={afterWrite}
/>
<AssetMergeModal
visible={mergeOpen}
assets={selection.rows}
onClose={() => setMergeOpen(false)}
onDone={afterWrite}
/>
<AssetProjectModal
visible={projectOpen}
projects={projects}
assetIds={selection.keys}
onClose={() => setProjectOpen(false)}
onDone={afterWrite}
/>
<AssetBulkEditModal
visible={bulkOpen}
assetIds={selection.keys}
onClose={() => setBulkOpen(false)}
onDone={afterWrite}
/>
</div>
);
}

View File

@ -0,0 +1,58 @@
/* 资产库页面私有布局样式(颜色一律使用 Semi 变量)。 */
.asset-library-page { display: flex; flex-direction: column; gap: 0; }
.asset-library-filters { display: flex; flex-direction: column; gap: 8px; }
.asset-library-filter-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 10px;
align-items: center;
}
.asset-library-filter-actions { justify-content: flex-end; }
.asset-library-filter-advanced { margin-top: 2px; }
.asset-library-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
padding-bottom: 8px;
border-bottom: 1px solid var(--semi-color-border);
margin-bottom: 10px;
}
.asset-library-target { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.asset-library-form-error { margin: 8px 0; }
.asset-library-editor .semi-form-field { margin-bottom: 12px; }
.asset-library-form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: 4px 14px;
}
.asset-library-form-grid--full { grid-template-columns: minmax(0, 1fr); }
.asset-library-form-grid--bulk {
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin: 12px 0;
}
.asset-library-editor-actions { margin-top: 4px; }
.asset-library-import-body { width: 100%; margin-top: 10px; }
.asset-library-import-textarea textarea {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.asset-library-import-preview { width: 100%; display: flex; flex-direction: column; gap: 6px; }
.asset-library-file-input { display: none; }
.asset-library-detail-target { display: flex; flex-direction: column; gap: 4px; }
.asset-library-detail-target-main { display: flex; align-items: center; gap: 6px; }
.asset-library-detail-badges { margin-top: 4px; }
@media (max-width: 900px) {
.asset-library-filter-grid { grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.asset-library-toolbar { flex-direction: column; align-items: flex-start; }
}

View File

@ -0,0 +1,274 @@
/** 资产概览:统计卡、协议分布、扫描覆盖、最近资产。 */
import { useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Banner, Button, Empty, Progress, RadioGroup, Space, Typography } from '@douyinfe/semi-ui';
import { IconArrowRight, IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { formatNumber, relativeTime } from '../../lib/format';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import {
DataTable, ErrorBanner, PageHeader, SectionCard, StatGrid
} from '../../components/ui';
import { ProtocolTag, RiskTag, TooltipText } from '../asset-library/components/AssetBits';
import { assetTargetLabel } from '../asset-library/components/assetTarget';
import './page.css';
const { Text } = Typography;
const PERIODS = [
{ value: 7, label: '7 天' },
{ value: 30, label: '30 天' },
{ value: 90, label: '90 天' }
];
function percentOf(count, total) {
const value = Number(count || 0);
const base = Number(total || 0);
if (!base) return 0;
return Math.round((value / base) * 1000) / 10;
}
export default function AssetOverviewPage() {
const t = useT();
const navigate = useNavigate();
const { hasPermission, hasAnyPermission } = useAuth();
const canRead = hasPermission('asset:read');
const canCollect = hasAnyPermission(['asset:read', 'fofa:execute']);
const [days, setDays] = useState(30);
const statsRes = useResource(() => api.get('/assets/stats', { days }), [days], { skip: !canRead });
const recentRes = useResource(
() => api.get('/assets', { page: 1, page_size: 10, sort_by: 'last_seen_at', sort_order: 'desc' }),
[],
{ skip: !canRead }
);
const stats = statsRes.data || {};
const coverage = stats.coverage || {};
const protocols = Array.isArray(stats.protocols) ? stats.protocols : [];
const protocolTotal = useMemo(
() => protocols.reduce((sum, item) => sum + Number(item.count || 0), 0),
[protocols]
);
const recentAssets = Array.isArray(recentRes.data?.assets) ? recentRes.data.assets : [];
const metrics = [
{
id: 'total',
label: t('assets.totalAssets', null, '资产总数'),
value: formatNumber(stats.total || 0),
detail: t('assets.totalAssetsHint', null, '当前纳入持续监测的资产'),
loading: statsRes.loading
},
{
id: 'ips',
label: t('assets.ipCount', null, 'IP 数量'),
value: formatNumber(stats.ips || 0),
loading: statsRes.loading
},
{
id: 'domains',
label: t('assets.domainCount', null, '域名数量'),
value: formatNumber(stats.domains || 0),
loading: statsRes.loading
},
{
id: 'ports',
label: t('assets.portCount', null, '端口数量'),
value: formatNumber(stats.ports || 0),
loading: statsRes.loading
},
{
id: 'protocols',
label: t('assets.serviceTypes', null, '服务类型'),
value: formatNumber(protocols.length),
detail: protocols[0] ? `${t('assets.topProtocol', null, '主要协议')}:${protocols[0].name}` : undefined,
loading: statsRes.loading
},
{
id: 'recent',
label: t('assets.recentCount', null, '近 7 天发现'),
value: formatNumber(stats.recent || 0),
detail: t('assets.recentShare', { percent: percentOf(stats.recent, stats.total) }, `占当前资产总量的 ${percentOf(stats.recent, stats.total)}%`),
loading: statsRes.loading
}
];
const goLibrary = asset => {
const suffix = asset?.id ? `?id=${encodeURIComponent(asset.id)}` : '';
navigate(`/asset-library${suffix}`, asset ? { state: { asset } } : undefined);
};
const columns = [
{
title: t('assets.target', null, '目标'),
dataIndex: 'host',
render: (_, record) => (
<div className="asset-overview-target">
<TooltipText text={assetTargetLabel(record)} max={34} />
<Text type="tertiary" size="small">{[record.ip, record.domain].filter(Boolean).join(' · ') || '—'}</Text>
</div>
)
},
{
title: t('assets.service', null, '服务'),
dataIndex: 'protocol',
width: 150,
render: (_, record) => <ProtocolTag protocol={record.protocol} port={record.port} />
},
{
title: t('assets.source', null, '来源'),
dataIndex: 'source',
width: 120,
render: value => <TooltipText text={value} max={14} />
},
{
title: t('assets.riskLevel', null, '风险等级'),
dataIndex: 'risk_level',
width: 120,
render: (_, record) => <RiskTag asset={record} />
},
{
title: t('assets.lastSeen', null, '最近发现'),
dataIndex: 'last_seen_at',
width: 130,
render: value => <Text size="small">{relativeTime(value, t)}</Text>
},
{
title: t('common.actions', null, '操作'),
dataIndex: 'id',
width: 100,
render: (_, record) => (
<Button theme="borderless" size="small" onClick={() => goLibrary(record)}>
{t('common.view', null, '查看')}
</Button>
)
}
];
const coverageItems = [
{ label: t('assets.scannedAssets', null, '已扫描资产'), value: formatNumber(coverage.scanned || 0) },
{ label: t('assets.recentlyScanned', null, '近 30 天覆盖'), value: formatNumber(coverage.scanned_30d || 0) },
{ label: t('assets.neverScanned', null, '从未扫描'), value: formatNumber(coverage.never_scanned || 0) },
{ label: t('assets.staleScans', null, '超过 30 天未扫描'), value: formatNumber(coverage.stale || 0) }
];
return (
<div className="asset-overview-page">
<PageHeader
title={t('assets.overviewTitle', null, '资产概览')}
description="汇总资产规模、服务类型、扫描覆盖与最近发现情况。"
extra={(
<Space>
<RadioGroup
type="button"
value={days}
options={PERIODS}
onChange={event => setDays(Number(event.target.value) || 30)}
/>
<Button icon={<IconRefresh />} onClick={() => { statsRes.reload(); recentRes.reload(); }}>
{t('common.refresh', null, '刷新')}
</Button>
<Button icon={<IconArrowRight />} onClick={() => navigate('/asset-library')}>
{t('assets.viewLibrary', null, '查看资产库')}
</Button>
{canCollect && (
<Button theme="solid" type="primary" icon={<IconSearch />} onClick={() => navigate('/info-collect')}>
{t('nav.infoCollect', null, '信息收集')}
</Button>
)}
</Space>
)}
/>
{!canRead && (
<Banner
type="warning"
bordered
closeIcon={null}
description={t('assets.readDenied', null, '当前账号没有 asset:read 权限,无法读取资产统计;请联系管理员授权。')}
/>
)}
{canRead && <ErrorBanner error={statsRes.error} onRetry={() => statsRes.reload()} />}
{canRead && <StatGrid metrics={metrics} columns={6} />}
{canRead && (<div className="asset-overview-columns">
<SectionCard
className="asset-overview-card"
title={t('assets.protocolDistribution', null, '协议分布')}
description={t('assets.protocolDistributionHint', null, '按已识别服务查看资产暴露构成')}
extra={<Text type="tertiary" size="small">{t('assets.protocolKinds', { count: protocols.length }, `${protocols.length} 种协议`)}</Text>}
>
{protocols.length === 0 ? (
<Empty title={t('common.noData', null, '暂无数据')} description={null} style={{ padding: 24 }} />
) : (
<div className="asset-overview-bars">
{protocols.map(item => {
const percent = percentOf(item.count, stats.total || protocolTotal);
return (
<div className="asset-overview-bar-row" key={item.name}>
<Text size="small" className="asset-overview-bar-label">
{item.name || 'unknown'}
</Text>
<Progress percent={percent} showInfo={false} stroke="var(--semi-color-primary)" />
<Text type="tertiary" size="small" className="asset-overview-bar-value">
{formatNumber(item.count || 0)} · {percent}%
</Text>
</div>
);
})}
</div>
)}
</SectionCard>
<SectionCard
className="asset-overview-card"
title={t('assets.scanCoverage', null, '扫描覆盖')}
description={t('assets.scanCoverageHint', null, '识别未扫描与长期未复查的资产缺口')}
extra={<Text type="tertiary" size="small">{t('assets.coverageMeta', { scanned: coverage.scanned || 0, total: stats.total || 0 }, `${coverage.scanned || 0} / ${stats.total || 0} 已覆盖`)}</Text>}
>
<div className="asset-overview-coverage">
<div className="asset-overview-coverage-main">
<Text type="tertiary" size="small">{t('assets.overallCoverage', null, '总体覆盖率')}</Text>
<Progress
percent={Number(coverage.rate || 0)}
stroke={Number(coverage.rate || 0) >= 80 ? 'var(--semi-color-success)' : undefined}
format={percent => `${percent}%`}
/>
</div>
<div className="asset-overview-coverage-grid">
{coverageItems.map(item => (
<div key={item.label} className="asset-overview-coverage-item">
<Text type="tertiary" size="small">{item.label}</Text>
<Text strong>{item.value}</Text>
</div>
))}
</div>
</div>
</SectionCard>
</div>)}
{canRead && (<SectionCard
title={t('assets.recentAssets', null, '最近资产')}
description="按最近发现时间排列的前 10 条资产。"
extra={(
<Button theme="borderless" onClick={() => navigate('/asset-library')}>
{t('assets.viewLibrary', null, '查看资产库')}
</Button>
)}
>
<ErrorBanner error={recentRes.error} onRetry={() => recentRes.reload()} />
<DataTable
columns={columns}
dataSource={recentAssets}
loading={recentRes.loading}
rowKey="id"
pagination={false}
onRefresh={() => recentRes.reload()}
emptyText={t('common.noData', null, '暂无数据')}
/>
</SectionCard>)}
</div>
);
}

View File

@ -0,0 +1,42 @@
/* 资产概览页面私有布局样式。 */
.asset-overview-page { display: flex; flex-direction: column; }
.asset-overview-columns {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
gap: 12px;
}
.asset-overview-card { margin-bottom: 0; }
.asset-overview-bars { display: flex; flex-direction: column; gap: 10px; }
.asset-overview-bar-row {
display: grid;
grid-template-columns: 88px minmax(0, 1fr) 108px;
align-items: center;
gap: 10px;
}
.asset-overview-bar-label { text-transform: lowercase; }
.asset-overview-bar-value { text-align: right; white-space: nowrap; }
.asset-overview-coverage { display: flex; flex-direction: column; gap: 14px; }
.asset-overview-coverage-main { display: flex; flex-direction: column; gap: 6px; }
.asset-overview-coverage-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 10px;
}
.asset-overview-coverage-item {
display: flex;
flex-direction: column;
gap: 2px;
padding: 8px 10px;
border: 1px solid var(--semi-color-border);
border-radius: var(--semi-border-radius-small, 4px);
background: var(--semi-color-fill-0);
}
.asset-overview-target { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
@media (max-width: 900px) {
.asset-overview-bar-row { grid-template-columns: 70px minmax(0, 1fr) 88px; }
}

View File

@ -0,0 +1,258 @@
/**
* C2 事件审计:按级别/类别/会话/时间窗筛选,5 秒轮询并支持批量删除。
*/
import { useMemo, useState } from 'react';
import { Button, Input, Select, SideSheet, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useInterval, useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, StatGrid, DataTable, ErrorBanner, JsonViewer,
confirmAction, toastError, toastSuccess
} from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import * as c2 from '../c2-sessions/components/c2-api';
import {
EVENT_CATEGORY_OPTIONS, EVENT_LEVEL_COLOR, EVENT_LEVEL_OPTIONS, TimePresetBar,
TimeText, presetToSince
} from '../c2-sessions/components/c2-shared';
import './page.css';
const { Text } = Typography;
export default function C2EventsPage() {
const t = useT();
const { hasPermission } = useAuth();
const canDelete = hasPermission('c2:delete') || hasPermission('c2:write');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [level, setLevel] = useState('');
const [category, setCategory] = useState('');
const [preset, setPreset] = useState('24h');
const [sessionInput, setSessionInput] = useState('');
const [sessionFilter, setSessionFilter] = useState('');
const [selectedKeys, setSelectedKeys] = useState([]);
const [detail, setDetail] = useState(null);
const query = useMemo(() => ({
page,
page_size: pageSize,
level: level || undefined,
category: category || undefined,
session_id: sessionFilter || undefined,
since: presetToSince(preset) || undefined
}), [page, pageSize, level, category, sessionFilter, preset]);
const { data, loading, error, reload } = useResource(() => c2.listEvents(query), [query]);
const events = Array.isArray(data?.events) ? data.events : [];
const total = Number(data?.total ?? events.length);
const counts = data?.level_counts || {};
useInterval(() => reload({ silent: true }), 5000);
const applyFilters = () => {
setSessionFilter(sessionInput.trim());
setPage(1);
setSelectedKeys([]);
};
const resetFilters = () => {
setLevel('');
setCategory('');
setPreset('24h');
setSessionInput('');
setSessionFilter('');
setPage(1);
setSelectedKeys([]);
};
const metrics = [
{ id: 'total', label: t('c2.events.statTotal', null, '当前筛选'), value: total },
{ id: 'info', label: t('c2.events.info', null, '信息'), value: counts.info || 0 },
{ id: 'warn', label: t('c2.events.warn', null, '警告'), value: counts.warn || 0, tone: 'warning' },
{ id: 'critical', label: t('c2.events.critical', null, '严重'), value: counts.critical || 0, tone: 'danger' }
];
const remove = ids => {
confirmAction({
title: t('c2.events.batchDelete', null, '删除事件'),
content: ids.length > 1
? t('c2.events.confirmBatchDelete', null, '确定删除选中的事件吗?此操作不可恢复。').replace('{{n}}', String(ids.length))
: t('c2.events.confirmDeleteOne', null, '确定删除该条事件吗?此操作不可恢复。'),
onOk: async () => {
try {
const result = await c2.deleteEvents(ids);
toastSuccess(t('c2.events.toastDeleted', null, '已删除').replace('{{n}}', String(result?.deleted ?? ids.length)));
setSelectedKeys(current => current.filter(key => !ids.includes(key)));
reload();
} catch (err) {
toastError(err);
}
}
});
};
const columns = [
{
title: t('c2.events.level', null, '级别'),
dataIndex: 'level',
width: 90,
render: value => <Tag size="small" color={EVENT_LEVEL_COLOR[value] || 'grey'}>{t(`c2.events.${value || 'info'}`, null, value || '—')}</Tag>
},
{ title: t('c2.events.category', null, '类别'), dataIndex: 'category', width: 110 },
{
title: t('c2.events.message', null, '消息'),
dataIndex: 'message',
render: (value, record) => (
<button type="button" className="c2-event-message" onClick={() => setDetail(record)} title={value}>
{value || '—'}
</button>
)
},
{
title: t('c2.events.colSession', null, '会话'),
dataIndex: 'sessionId',
width: 150,
render: value => <span className="c2-mono">{value || '—'}</span>
},
{
title: t('c2.events.colTask', null, '任务'),
dataIndex: 'taskId',
width: 150,
render: value => <span className="c2-mono">{value || '—'}</span>
},
{ title: t('c2.events.time', null, '时间'), dataIndex: 'createdAt', width: 130, render: value => <TimeText value={value} /> },
{
title: t('c2.tasks.colActions', null, '操作'),
dataIndex: 'actions',
width: 130,
render: (_, record) => (
<Space spacing={4}>
<Button size="small" theme="borderless" onClick={() => setDetail(record)}>{t('c2.events.view', null, '查看')}</Button>
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove([record.id])}>
{t('c2.events.deleteOne', null, '删除')}
</Button>
</Space>
)
}
];
return (
<div className="c2-page" id="page-c2-events">
<PageHeader
title={t('c2.events.title', null, '事件审计')}
description={t('c2.events.pageDesc', null, '监听器、会话、任务与 OPSEC 事件留痕,5 秒自动刷新')}
extra={[
<Button key="refresh" icon={<IconRefresh />} onClick={() => reload()} loading={loading}>{t('c2.events.refresh', null, '刷新')}</Button>,
<Button
key="delete"
type="danger"
disabled={!canDelete || !selectedKeys.length}
onClick={() => remove(selectedKeys)}
>
{t('c2.events.batchDelete', null, '批量删除')}
</Button>
]}
/>
<StatGrid metrics={metrics} columns={4} />
<ErrorBanner error={error} onRetry={() => reload()} />
<SectionCard
title={t('c2.events.filterTitle', null, '筛选')}
extra={<TimePresetBar value={preset} onChange={value => { setPreset(value); setPage(1); }} ns="events" />}
>
<div className="c2-toolbar-fields">
<div className="c2-field">
<span className="c2-field-label">{t('c2.events.level', null, '级别')}</span>
<Select
value={level}
onChange={value => { setLevel(value || ''); setPage(1); }}
style={{ width: 150 }}
optionList={[{ value: '', label: t('c2.events.filterAllLevels', null, '全部级别') }, ...EVENT_LEVEL_OPTIONS]}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.events.category', null, '类别')}</span>
<Select
value={category}
onChange={value => { setCategory(value || ''); setPage(1); }}
style={{ width: 150 }}
optionList={[{ value: '', label: t('c2.events.filterAllCategories', null, '全部类别') }, ...EVENT_CATEGORY_OPTIONS]}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.events.filterSession', null, '会话 ID')}</span>
<Input
value={sessionInput}
onChange={setSessionInput}
onEnterPress={applyFilters}
placeholder={t('c2.events.filterSessionPlaceholder', null, 's_xxxxxxxx')}
style={{ width: 190 }}
/>
</div>
<Space spacing={8}>
<Button theme="solid" type="primary" onClick={applyFilters}>{t('c2.events.applyFilters', null, '应用筛选')}</Button>
<Button onClick={resetFilters}>{t('c2.events.resetFilters', null, '重置')}</Button>
</Space>
</div>
</SectionCard>
<SectionCard title={t('c2.events.listTitle', null, '事件列表')}>
<DataTable
columns={columns}
dataSource={events}
rowKey="id"
loading={loading}
onRefresh={() => reload()}
rowSelection={{
selectedRowKeys: selectedKeys,
onChange: keys => setSelectedKeys(keys)
}}
pagination={{
currentPage: page,
pageSize,
total,
onPageChange: next => setPage(next),
onPageSizeChange: size => { setPageSize(size); setPage(1); }
}}
emptyText={t('c2.events.empty', null, '暂无事件')}
/>
</SectionCard>
<SideSheet
visible={Boolean(detail)}
title={t('c2.events.detailTitle', null, '事件详情')}
width={560}
onCancel={() => setDetail(null)}
>
{detail && (
<div className="c2-event-detail">
<div className="c2-event-detail-head">
<Tag size="small" color={EVENT_LEVEL_COLOR[detail.level] || 'grey'}>{detail.level}</Tag>
<Tag size="small">{detail.category}</Tag>
<Text type="tertiary" size="small">{formatDateTime(detail.createdAt)}</Text>
</div>
<Text>{detail.message}</Text>
<div className="c2-field-label">{t('c2.events.colId', null, '事件 ID')}</div>
<Text className="c2-mono" copyable={{ text: detail.id }}>{detail.id}</Text>
{detail.sessionId && (
<>
<div className="c2-field-label">{t('c2.events.colSession', null, '会话')}</div>
<Text className="c2-mono">{detail.sessionId}</Text>
</>
)}
{detail.data && Object.keys(detail.data).length > 0 && (
<>
<div className="c2-field-label">{t('c2.events.detailData', null, '附加数据')}</div>
<JsonViewer value={detail.data} />
</>
)}
</div>
)}
</SideSheet>
</div>
);
}

View File

@ -0,0 +1,31 @@
/* C2 事件页面私有样式(c2- 前缀)。 */
.c2-event-message {
border: none;
background: none;
padding: 0;
text-align: left;
cursor: pointer;
color: var(--semi-color-text-0);
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.c2-event-message:hover {
color: var(--semi-color-primary);
}
.c2-event-detail {
display: flex;
flex-direction: column;
gap: 8px;
}
.c2-event-detail-head {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}

View File

@ -0,0 +1,154 @@
/**
* C2 监听器表单:创建 / 编辑,覆盖绑定端口、回连地址与关键 OPSEC 参数。
*/
import { useState } from 'react';
import { Button, Form, Modal, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { LISTENER_TYPES } from '../c2-sessions/components/c2-shared';
const { Text } = Typography;
function parseConfig(record) {
if (!record?.configJson) return {};
try {
return JSON.parse(record.configJson) || {};
} catch (error) {
return {};
}
}
function toValues(record) {
const config = parseConfig(record);
return {
name: record?.name || '',
type: record?.type || 'http_beacon',
project_id: record?.project_id || '',
bind_host: record?.bindHost || '127.0.0.1',
bind_port: String(record?.bindPort ?? '4444'),
callback_host: config.callback_host || '',
profile_id: record?.profileId || '',
remark: record?.remark || '',
default_sleep: String(config.default_sleep ?? 5),
default_jitter: String(config.default_jitter ?? 0),
max_concurrent_tasks: String(config.max_concurrent_tasks ?? 0),
allow_legacy_shell: Boolean(config.allow_legacy_shell)
};
}
export default function ListenerForm({ visible, record, projects, profiles, submitting, onCancel, onSubmit }) {
const t = useT();
const [formApi, setFormApi] = useState(null);
const [type, setType] = useState(record?.type || 'http_beacon');
const submit = values => {
const port = Number(values.bind_port);
onSubmit({
name: String(values.name || '').trim(),
type: values.type,
project_id: values.project_id || '',
bind_host: String(values.bind_host || '').trim() || '127.0.0.1',
bind_port: Number.isFinite(port) ? port : 0,
callback_host: String(values.callback_host || '').trim(),
profile_id: values.profile_id || '',
remark: String(values.remark || '').trim(),
config: {
callback_host: String(values.callback_host || '').trim(),
default_sleep: Number(values.default_sleep) || 5,
default_jitter: Number(values.default_jitter) || 0,
max_concurrent_tasks: Number(values.max_concurrent_tasks) || 0,
allow_legacy_shell: Boolean(values.allow_legacy_shell)
}
});
};
return (
<Modal
visible={visible}
title={record ? t('c2.listeners.editTitle', null, '编辑监听器') : t('c2.listeners.modalCreateTitle', null, '创建监听器')}
footer={null}
width={620}
onCancel={onCancel}
>
<Form
key={record?.id || 'new'}
initValues={toValues(record)}
onSubmit={submit}
getFormApi={setFormApi}
labelPosition="top"
onValueChange={changed => { if (changed.type) setType(changed.type); }}
>
<div className="c2-form-row">
<Form.Input
field="name"
label={t('c2.listeners.name', null, '名称')}
placeholder={t('c2.listeners.placeholderNameExample', null, '例如 http-beacon-01')}
rules={[{ required: true, message: t('c2.listeners.nameRequired', null, '请输入监听器名称') }]}
/>
<Form.Select
field="type"
label={t('c2.listeners.type', null, '类型')}
optionList={LISTENER_TYPES}
disabled={Boolean(record)}
style={{ width: '100%' }}
/>
</div>
<div className="c2-form-row">
<Form.Input field="bind_host" label={t('c2.listeners.bindHost', null, '绑定地址')} placeholder="127.0.0.1" />
<Form.Input
field="bind_port"
label={t('c2.listeners.bindPort', null, '绑定端口')}
placeholder={t('c2.listeners.placeholderPort', null, '输入端口号')}
rules={[{
required: true,
validator: (rule, value) => {
const port = Number(value);
return Number.isInteger(port) && port > 0 && port <= 65535;
},
message: t('c2.listeners.portInvalid', null, '端口必须为 1–65535 的整数')
}]}
/>
</div>
<Text type="tertiary" size="small">{t('c2.listeners.bindHintExternal', null, '使用 0.0.0.0 允许外部访问')}</Text>
<div className="c2-form-row">
<Form.Input field="callback_host" label={t('c2.listeners.callbackHost', null, '回连地址(可选)')} placeholder="公网 IP 或域名" />
<Form.Select
field="profile_id"
label={t('c2.listeners.malleableProfile', null, 'Malleable Profile')}
optionList={[{ value: '', label: t('c2.listeners.malleableProfileNone', null, '不使用') },
...profiles.map(item => ({ value: item.id, label: item.name || item.id }))]}
style={{ width: '100%' }}
/>
</div>
<div className="c2-form-row">
<Form.Select
field="project_id"
label={t('c2.listeners.project', null, '所属项目')}
optionList={[{ value: '', label: t('c2.listeners.projectNone', null, '不绑定项目') },
...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
style={{ width: '100%' }}
/>
<Form.Input field="remark" label={t('c2.listeners.remark', null, '备注')} placeholder={t('c2.listeners.placeholderRemarkLong', null, '可选的备注说明')} />
</div>
<div className="c2-form-row">
<Form.Input field="default_sleep" label="默认 Sleep(秒)" placeholder="5" />
<Form.Input field="default_jitter" label="默认 Jitter(%)" placeholder="0" />
</div>
<div className="c2-form-row">
<Form.Input field="max_concurrent_tasks" label="单会话并发任务上限(0 不限)" placeholder="0" />
{type === 'tcp_reverse' && (
<Form.Switch
field="allow_legacy_shell"
label={t('c2.listeners.allowLegacyShell', null, '允许未加密经典反弹 Shell(内网实验)')}
/>
)}
</div>
<Space className="c2-form-actions">
<Button onClick={onCancel}>{t('c2.common.cancel', null, '取消')}</Button>
<Button theme="solid" type="primary" loading={submitting} onClick={() => formApi?.submitForm()}>
{record ? t('c2.listeners.save', null, '保存') : t('c2.listeners.submitCreate', null, '创建')}
</Button>
</Space>
</Form>
</Modal>
);
}

View File

@ -0,0 +1,245 @@
/**
* C2 监听器管理:列表、创建/编辑、启动/停止与删除。
*/
import { useMemo, useState } from 'react';
import { Button, Modal, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, StatGrid, DataTable, ErrorBanner, CopyButton,
confirmAction, toastError, toastSuccess
} from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import * as c2 from '../c2-sessions/components/c2-api';
import { LISTENER_STATUS_COLOR, LISTENER_STATUS_LABEL, LISTENER_TYPES } from '../c2-sessions/components/c2-shared';
import ListenerForm from './ListenerForm';
import './page.css';
const { Text } = Typography;
const typeLabel = value => (LISTENER_TYPES.find(item => item.value === value)?.label || value || '—');
export default function C2ListenersPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('c2:write');
const canDelete = hasPermission('c2:delete') || canWrite;
const [form, setForm] = useState({ visible: false, record: null });
const [submitting, setSubmitting] = useState(false);
const [busyId, setBusyId] = useState('');
const [tokenInfo, setTokenInfo] = useState(null);
const { data, loading, error, reload } = useResource(
() => Promise.all([c2.listListeners(), c2.listProfiles().catch(() => ({ profiles: [] })), c2.listProjects()]),
[]
);
const listeners = Array.isArray(data?.[0]?.listeners) ? data[0].listeners : [];
const profiles = Array.isArray(data?.[1]?.profiles) ? data[1].profiles : [];
const projects = Array.isArray(data?.[2]) ? data[2] : [];
const metrics = useMemo(() => {
const running = listeners.filter(item => item.status === 'running').length;
const failed = listeners.filter(item => item.status === 'error').length;
return [
{ id: 'total', label: t('c2.listeners.statTotal', null, '监听器总数'), value: listeners.length },
{ id: 'running', label: t('c2.listeners.running', null, '运行中'), value: running, tone: running ? 'success' : undefined },
{ id: 'stopped', label: t('c2.listeners.stopped', null, '已停止'), value: listeners.length - running - failed },
{ id: 'error', label: t('c2.listeners.statusError', null, '异常'), value: failed, tone: failed ? 'danger' : undefined }
];
}, [listeners, t]);
const toggle = async (record, action) => {
setBusyId(record.id);
try {
if (action === 'start') {
await c2.startListener(record.id);
toastSuccess(t('c2.listeners.toastStarted', null, '监听器已启动'));
} else {
await c2.stopListener(record.id);
toastSuccess(t('c2.listeners.toastStopped', null, '监听器已停止'));
}
reload();
} catch (err) {
toastError(err, action === 'start' ? t('c2.listeners.start', null, '启动失败') : t('c2.listeners.stop', null, '停止失败'));
} finally {
setBusyId('');
}
};
const remove = record => {
confirmAction({
title: t('c2.listeners.delete', null, '删除监听器'),
content: t('c2.listeners.confirmDelete', null, '确定删除此监听器?相关会话与任务将被清除。'),
onOk: async () => {
try {
await c2.deleteListener(record.id);
toastSuccess(t('c2.listeners.toastDeleted', null, '监听器已删除'));
reload();
} catch (err) {
toastError(err);
}
}
});
};
const submit = async values => {
setSubmitting(true);
try {
if (form.record?.id) {
await c2.updateListener(form.record.id, values);
toastSuccess(t('c2.listeners.toastUpdated', null, '监听器已更新'));
} else {
const payload = await c2.createListener(values);
toastSuccess(t('c2.listeners.toastCreated', null, '监听器已创建'));
if (payload?.implant_token) {
setTokenInfo({ name: payload.listener?.name || values.name, token: payload.implant_token });
}
}
setForm({ visible: false, record: null });
reload();
} catch (err) {
toastError(err, t('c2.listeners.saveFailed', null, '监听器保存失败'));
} finally {
setSubmitting(false);
}
};
const columns = [
{
title: t('c2.listeners.name', null, '名称'),
dataIndex: 'name',
render: (name, record) => (
<div className="c2-listener-name">
<Text strong>{name || record.id}</Text>
{record.remark && <Text type="tertiary" size="small">{record.remark}</Text>}
</div>
)
},
{ title: t('c2.listeners.type', null, '类型'), dataIndex: 'type', width: 140, render: typeLabel },
{
title: t('c2.listeners.bindEndpoint', null, '监听地址'),
dataIndex: 'bindPort',
width: 200,
render: (port, record) => <span className="c2-mono">{record.bindHost}:{port}</span>
},
{
title: t('c2.listeners.callbackShort', null, '回连'),
dataIndex: 'configJson',
width: 160,
render: value => {
try {
const config = JSON.parse(value || '{}');
return config.callback_host ? <span className="c2-mono">{config.callback_host}</span> : <Text type="tertiary">—</Text>;
} catch (error) {
return <Text type="tertiary">—</Text>;
}
}
},
{
title: t('c2.listeners.status', null, '状态'),
dataIndex: 'status',
width: 120,
render: (status, record) => (
<div className="c2-listener-status">
<Tag size="small" color={LISTENER_STATUS_COLOR[status] || 'grey'}>
{LISTENER_STATUS_LABEL[status] || status || '—'}
</Tag>
{record.lastError && <Text type="danger" size="small">{record.lastError}</Text>}
</div>
)
},
{
title: t('c2.listeners.startedAtPrefix', null, '启动于'),
dataIndex: 'startedAt',
width: 180,
render: value => (value ? formatDateTime(value) : <Text type="tertiary">—</Text>)
},
{
title: t('c2.listeners.actions', null, '操作'),
dataIndex: 'actions',
width: 220,
render: (_, record) => {
const running = record.status === 'running';
return (
<Space spacing={4} wrap>
<Button
size="small"
theme="borderless"
disabled={!canWrite}
loading={busyId === record.id}
onClick={() => toggle(record, running ? 'stop' : 'start')}
>
{running ? t('c2.listeners.stop', null, '停止') : t('c2.listeners.start', null, '启动')}
</Button>
<Button size="small" theme="borderless" disabled={!canWrite} onClick={() => setForm({ visible: true, record })}>
{t('c2.listeners.edit', null, '编辑')}
</Button>
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(record)}>
{t('c2.listeners.delete', null, '删除')}
</Button>
</Space>
);
}
}
];
return (
<div className="c2-page" id="page-c2-listeners">
<PageHeader
title={t('c2.listeners.title', null, '监听器管理')}
description={t('c2.listeners.pageDesc', null, '创建并启停 C2 监听器,启停状态即时同步到后端')}
extra={[
<Button key="refresh" icon={<IconRefresh />} onClick={reload} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>,
<Button key="create" theme="solid" type="primary" icon={<IconPlus />} disabled={!canWrite} onClick={() => setForm({ visible: true, record: null })}>
{t('c2.listeners.create', null, '创建监听器')}
</Button>
]}
/>
<StatGrid metrics={metrics} columns={4} />
<ErrorBanner error={error} onRetry={reload} />
<SectionCard title={t('c2.listeners.title', null, '监听器列表')}>
<DataTable
columns={columns}
dataSource={listeners}
rowKey="id"
loading={loading}
onRefresh={reload}
pagination={{ pageSize: 10 }}
emptyText={t('c2.listeners.emptyTitle', null, '暂无监听器')}
/>
</SectionCard>
<ListenerForm
visible={form.visible}
record={form.record}
projects={projects}
profiles={profiles}
submitting={submitting}
onCancel={() => setForm({ visible: false, record: null })}
onSubmit={submit}
/>
<Modal
visible={Boolean(tokenInfo)}
title={t('c2.listeners.implantTokenTitle', null, '植入体 Token')}
onCancel={() => setTokenInfo(null)}
footer={<Button onClick={() => setTokenInfo(null)}>{t('c2.listeners.close', null, '关闭')}</Button>}
>
<Text type="tertiary">
{t('c2.listeners.implantTokenHint', null, '该 Token 仅在此处显示一次,请立即保存;后续可通过重新创建监听器获取。')}
</Text>
<div className="c2-listener-token">
<span className="c2-mono">{tokenInfo?.token}</span>
<CopyButton text={tokenInfo?.token || ''} />
</div>
</Modal>
</div>
);
}

View File

@ -0,0 +1,25 @@
/* C2 监听器页面私有样式(c2- 前缀)。 */
.c2-listener-name {
display: flex;
flex-direction: column;
gap: 2px;
}
.c2-listener-status {
display: flex;
flex-direction: column;
gap: 4px;
}
.c2-listener-token {
display: flex;
align-items: center;
gap: 8px;
margin-top: 12px;
padding: 10px;
border-radius: 6px;
background: var(--semi-color-fill-0);
border: 1px solid var(--semi-color-border);
word-break: break-all;
}

View File

@ -0,0 +1,270 @@
/**
* C2 载荷生成:单行反弹命令(oneliner)与跨平台 Beacon 编译下载。
*/
import { useMemo, useState } from 'react';
import { Button, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, DataTable, ErrorBanner, CopyButton,
toastError, toastSuccess, toastWarning
} from '../../components/ui';
import { formatBytes } from '../../lib/format';
import * as c2 from '../c2-sessions/components/c2-api';
import { LISTENER_TYPES, ONELINER_KINDS } from '../c2-sessions/components/c2-shared';
import './page.css';
const { Text, Title } = Typography;
const OS_OPTIONS = [
{ value: 'linux', label: 'Linux' },
{ value: 'windows', label: 'Windows' },
{ value: 'darwin', label: 'macOS' }
];
const ARCH_OPTIONS = [
{ value: 'amd64', label: 'AMD64' },
{ value: 'arm64', label: 'ARM64' },
{ value: '386', label: '386' }
];
const typeLabel = value => LISTENER_TYPES.find(item => item.value === value)?.label || value || '—';
export default function C2PayloadsPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('c2:write');
const { data, loading, error, reload } = useResource(() => c2.listListeners(), []);
const listeners = Array.isArray(data?.listeners) ? data.listeners : [];
const [onelinerForm, setOnelinerForm] = useState({ listenerId: '', kind: '', host: '' });
const [oneliner, setOneliner] = useState(null);
const [onelinerBusy, setOnelinerBusy] = useState(false);
const [buildForm, setBuildForm] = useState({ listenerId: '', host: '', os: 'linux', arch: 'amd64' });
const [buildResult, setBuildResult] = useState(null);
const [buildBusy, setBuildBusy] = useState(false);
const [artifacts, setArtifacts] = useState([]);
const activeListener = useMemo(
() => listeners.find(item => item.id === (onelinerForm.listenerId || listeners[0]?.id)) || null,
[listeners, onelinerForm.listenerId]
);
const kindOptions = ONELINER_KINDS[activeListener?.type] || [];
const listenerOptions = listeners.map(item => ({
value: item.id,
label: `${item.name || item.id} · ${typeLabel(item.type)}`
}));
const generateOneliner = async () => {
const listenerId = onelinerForm.listenerId || listeners[0]?.id;
if (!listenerId) {
toastWarning(t('c2.payloads.toastPickListener', null, '请先选择一个监听器'));
return;
}
const kind = onelinerForm.kind || kindOptions[0]?.value;
if (!kind) {
toastWarning(t('c2.payloads.noKindOption', null, '无可用类型'));
return;
}
setOnelinerBusy(true);
try {
const payload = await c2.buildOneliner({ listener_id: listenerId, kind, host: onelinerForm.host.trim() });
setOneliner(payload);
} catch (err) {
toastError(err, t('c2.payloads.toastOnelinerFail', null, '生成 Oneliner 失败'));
} finally {
setOnelinerBusy(false);
}
};
const buildBeacon = async () => {
const listenerId = buildForm.listenerId || listeners[0]?.id;
if (!listenerId) {
toastWarning(t('c2.payloads.toastPickListener', null, '请先选择一个监听器'));
return;
}
setBuildBusy(true);
try {
const payload = await c2.buildPayload({
listener_id: listenerId,
host: buildForm.host.trim(),
os: buildForm.os,
arch: buildForm.arch,
sleep_seconds: 5,
jitter_percent: 0
});
const result = payload?.payload || null;
setBuildResult(result);
if (result) {
const fileName = String(result.output_path || '').split(/[\\/]/).pop();
setArtifacts(current => [
{
id: result.payload_id || fileName,
fileName,
listenerId,
os: result.os,
arch: result.arch,
size: result.size_bytes
},
...current
]);
toastSuccess(t('c2.payloads.toastBuildSuccess', null, '构建成功').replace('{{bytes}}', String(result.size_bytes || 0)));
}
} catch (err) {
toastError(err, t('c2.payloads.toastBuildFail', null, '构建 Beacon 失败'));
} finally {
setBuildBusy(false);
}
};
const download = async artifact => {
if (!artifact.fileName?.startsWith('beacon_')) {
toastWarning(t('c2.payloads.invalidArtifact', null, '该产物不可下载'));
return;
}
try {
await c2.downloadPayload(artifact.fileName, artifact.fileName);
toastSuccess(t('c2.payloads.toastDownloadQueued', null, '下载任务已排队'));
} catch (err) {
toastError(err, t('c2.payloads.download', null, '下载失败'));
}
};
const artifactColumns = [
{ title: t('c2.payloads.fileName', null, '文件'), dataIndex: 'fileName', render: value => <span className="c2-mono">{value || '—'}</span> },
{ title: t('c2.payloads.os', null, '系统'), dataIndex: 'os', width: 100 },
{ title: t('c2.payloads.arch', null, '架构'), dataIndex: 'arch', width: 100 },
{ title: t('c2.payloads.size', null, '大小'), dataIndex: 'size', width: 110, render: value => formatBytes(value) },
{
title: t('c2.tasks.colActions', null, '操作'),
dataIndex: 'actions',
width: 120,
render: (_, artifact) => (
<Button size="small" theme="borderless" onClick={() => download(artifact)}>{t('c2.payloads.download', null, '下载')}</Button>
)
}
];
return (
<div className="c2-page" id="page-c2-payloads">
<PageHeader
title={t('c2.payloads.title', null, 'Payload 生成')}
description={t('c2.payloads.pageDesc', null, '生成单行反弹命令,或交叉编译完整 Beacon 二进制')}
extra={[
<Button key="refresh" onClick={reload} loading={loading}>{t('common.refresh', null, '刷新')}</Button>
]}
/>
<ErrorBanner error={error} onRetry={reload} />
<div className="c2-payload-grid">
<SectionCard title={t('c2.payloads.oneliner', null, '单行 Payload')} description={t('c2.payloads.onelinerDesc', null, '生成可在目标机直接执行的反弹命令')}>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.listener', null, '监听器')}</span>
<Select
value={onelinerForm.listenerId || listeners[0]?.id || ''}
onChange={value => setOnelinerForm(form => ({ ...form, listenerId: value, kind: '' }))}
optionList={listenerOptions}
placeholder={t('c2.payloads.noListenersOption', null, '暂无可用监听器')}
style={{ width: '100%' }}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.kind', null, '类型')}</span>
<Select
value={onelinerForm.kind || kindOptions[0]?.value || ''}
onChange={value => setOnelinerForm(form => ({ ...form, kind: value }))}
optionList={kindOptions}
placeholder={t('c2.payloads.noKindOption', null, '无可用类型')}
style={{ width: '100%' }}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.hostOptional', null, '回连地址(可选)')}</span>
<Input
value={onelinerForm.host}
onChange={value => setOnelinerForm(form => ({ ...form, host: value }))}
placeholder={t('c2.payloads.placeholderListenerHost', null, '留空则使用监听器回连地址')}
/>
</div>
<Button theme="solid" type="primary" block disabled={!canWrite} loading={onelinerBusy} onClick={generateOneliner}>
{t('c2.payloads.generateOnelinerBtn', null, '生成 Oneliner')}
</Button>
{oneliner?.oneliner && (
<div className="c2-oneliner-result">
<div className="c2-oneliner-head">
<Space spacing={6}>
<Tag size="small">{oneliner.kind}</Tag>
<Text type="tertiary" size="small">{oneliner.host}:{oneliner.port}</Text>
</Space>
<CopyButton text={oneliner.oneliner} label={t('c2.payloads.copy', null, '复制')} size="small" />
</div>
<pre className="c2-pre">{oneliner.oneliner}</pre>
</div>
)}
</SectionCard>
<SectionCard title={t('c2.payloads.build', null, '编译 Beacon')} description={t('c2.payloads.buildDesc', null, '交叉编译多平台完整 Beacon 可执行文件')}>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.listener', null, '监听器')}</span>
<Select
value={buildForm.listenerId || listeners[0]?.id || ''}
onChange={value => setBuildForm(form => ({ ...form, listenerId: value }))}
optionList={listenerOptions}
placeholder={t('c2.payloads.noListenersOption', null, '暂无可用监听器')}
style={{ width: '100%' }}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.hostOptional', null, '回连地址(可选)')}</span>
<Input
value={buildForm.host}
onChange={value => setBuildForm(form => ({ ...form, host: value }))}
placeholder={t('c2.payloads.placeholderListenerHost', null, '留空则使用监听器回连地址')}
/>
</div>
<div className="c2-form-row">
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.os', null, '目标系统')}</span>
<Select value={buildForm.os} onChange={value => setBuildForm(form => ({ ...form, os: value }))} optionList={OS_OPTIONS} style={{ width: '100%' }} />
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.payloads.arch', null, '目标架构')}</span>
<Select value={buildForm.arch} onChange={value => setBuildForm(form => ({ ...form, arch: value }))} optionList={ARCH_OPTIONS} style={{ width: '100%' }} />
</div>
</div>
<Button theme="solid" type="primary" block disabled={!canWrite} loading={buildBusy} onClick={buildBeacon}>
{t('c2.payloads.buildBeaconBtn', null, '构建 Beacon')}
</Button>
{buildResult && (
<div className="c2-build-result">
<Title heading={6}>{t('c2.payloads.buildSuccessTitle', null, '构建成功')}</Title>
<Text type="tertiary" size="small">
{t('c2.payloads.buildMetaOsArch', null, '系统 / 架构').replace('{{os}}', buildResult.os || '—').replace('{{arch}}', buildResult.arch || '—')}
</Text>
<Text type="tertiary" size="small">{t('c2.payloads.buildSize', null, '大小').replace('{{bytes}}', String(buildResult.size_bytes || 0))}</Text>
<pre className="c2-pre">{buildResult.output_path}</pre>
<Button size="small" onClick={() => download({ fileName: String(buildResult.output_path || '').split(/[\\/]/).pop(), ...buildResult })}>
{t('c2.payloads.download', null, '下载')}
</Button>
</div>
)}
</SectionCard>
</div>
<SectionCard title={t('c2.payloads.artifacts', null, '本次会话构建产物')}>
<DataTable
columns={artifactColumns}
dataSource={artifacts}
rowKey="id"
pagination={{ pageSize: 10 }}
emptyText={t('c2.payloads.noArtifacts', null, '暂无构建产物')}
/>
</SectionCard>
</div>
);
}

View File

@ -0,0 +1,35 @@
/* C2 载荷页面私有样式(c2- 前缀)。 */
.c2-payload-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
gap: 12px;
align-items: start;
}
.c2-payload-grid .semi-card-body > * + * {
margin-top: 10px;
}
.c2-oneliner-result {
display: flex;
flex-direction: column;
gap: 6px;
}
.c2-oneliner-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.c2-build-result {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px;
border-radius: 6px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
}

View File

@ -0,0 +1,126 @@
/**
* C2 流量伪装 Profile 表单:UA、URI、请求/响应头与 Jitter 范围。
*/
import { useState } from 'react';
import { Button, Form, Modal, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { toastWarning } from '../../components/ui';
const { Text } = Typography;
function toValues(record) {
return {
name: record?.name || '',
user_agent: record?.userAgent || '',
uris: Array.isArray(record?.uris) ? record.uris.join('\n') : '',
jitter_min: String(record?.jitterMinMs ?? 0),
jitter_max: String(record?.jitterMaxMs ?? 0),
request_headers: record?.requestHeaders ? JSON.stringify(record.requestHeaders, null, 2) : '',
response_headers: record?.responseHeaders ? JSON.stringify(record.responseHeaders, null, 2) : '',
body_template: record?.bodyTemplate || ''
};
}
function parseHeaders(text, t) {
const raw = String(text || '').trim();
if (!raw) return {};
try {
const parsed = JSON.parse(raw);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('not an object');
}
return parsed;
} catch (error) {
toastWarning(t('c2.profiles.toastInvalidHeadersJson', null, '响应头 JSON 无效'));
return null;
}
}
export default function ProfileForm({ visible, record, submitting, onCancel, onSubmit }) {
const t = useT();
const [formApi, setFormApi] = useState(null);
const submit = values => {
const min = Number(values.jitter_min);
const max = Number(values.jitter_max);
if (!Number.isInteger(min) || !Number.isInteger(max) || min < 0 || max < min) {
toastWarning(t('c2.profiles.toastInvalidJitter', null, 'Jitter 必须为整数,且满足 0 <= 最小值 <= 最大值'));
return;
}
const requestHeaders = parseHeaders(values.request_headers, t);
if (requestHeaders === null) return;
const responseHeaders = parseHeaders(values.response_headers, t);
if (responseHeaders === null) return;
onSubmit({
name: String(values.name || '').trim(),
userAgent: String(values.user_agent || '').trim(),
uris: String(values.uris || '').split(/\r?\n/).map(item => item.trim()).filter(Boolean),
jitterMinMs: min,
jitterMaxMs: max,
requestHeaders,
responseHeaders,
bodyTemplate: String(values.body_template || '')
});
};
return (
<Modal
visible={visible}
title={record ? t('c2.profiles.editTitle', null, '编辑 Profile') : t('c2.profiles.modalCreateTitle', null, '创建 Malleable Profile')}
footer={null}
width={640}
onCancel={onCancel}
>
<Form
key={record?.id || 'new'}
initValues={toValues(record)}
onSubmit={submit}
getFormApi={setFormApi}
labelPosition="top"
>
<Form.Input
field="name"
label={t('c2.profiles.profileNameLabel', null, 'Profile 名称')}
placeholder={t('c2.profiles.placeholderProfileName', null, '例如 cdn-fronting')}
rules={[{ required: true, message: t('c2.profiles.toastNameRequired', null, '请填写 Profile 名称') }]}
/>
<Form.Input field="user_agent" label={t('c2.profiles.userAgent', null, 'User-Agent')} placeholder="Mozilla/5.0 ..." />
<Form.TextArea
field="uris"
label={t('c2.profiles.labelBeaconUris', null, 'Beacon URI(每行一个)')}
placeholder="/api/v1/ping"
autosize={{ minRows: 2, maxRows: 5 }}
/>
<div className="c2-form-row">
<Form.Input field="jitter_min" label={t('c2.profiles.labelJitterMin', null, 'Jitter 最小值 (ms)')} placeholder="0" />
<Form.Input field="jitter_max" label={t('c2.profiles.labelJitterMax', null, 'Jitter 最大值 (ms)')} placeholder="0" />
</div>
<Form.TextArea
field="request_headers"
label={t('c2.profiles.requestHeadersJson', null, '自定义请求头 (JSON)')}
placeholder='{"X-Forwarded-For":"127.0.0.1"}'
autosize={{ minRows: 2, maxRows: 6 }}
/>
<Form.TextArea
field="response_headers"
label={t('c2.profiles.labelRespHeaders', null, '自定义响应头 (JSON)')}
placeholder='{"Server":"nginx"}'
autosize={{ minRows: 2, maxRows: 6 }}
/>
<Form.TextArea
field="body_template"
label={t('c2.profiles.bodyTemplate', null, '响应体模板')}
placeholder='{"status":"ok"}'
autosize={{ minRows: 2, maxRows: 6 }}
/>
<Text type="tertiary" size="small">{t('c2.profiles.hintHeaders', null, '用于伪装为合法服务的 HTTP 响应头')}</Text>
<Space className="c2-form-actions">
<Button onClick={onCancel}>{t('c2.common.cancel', null, '取消')}</Button>
<Button theme="solid" type="primary" loading={submitting} onClick={() => formApi?.submitForm()}>
{record ? t('c2.profiles.save', null, '保存') : t('c2.profiles.submitCreate', null, '创建')}
</Button>
</Space>
</Form>
</Modal>
);
}

View File

@ -0,0 +1,183 @@
/**
* C2 流量伪装(Malleable Profile):列表、创建、编辑与删除。
*/
import { useMemo, useState } from 'react';
import { Button, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, StatGrid, DataTable, ErrorBanner,
confirmAction, toastError, toastSuccess, JsonViewer
} from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import * as c2 from '../c2-sessions/components/c2-api';
import ProfileForm from './ProfileForm';
import '../c2-sessions/components/c2-shared.css';
import './page.css';
const { Text } = Typography;
export default function C2ProfilesPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('c2:write');
const canDelete = hasPermission('c2:delete') || canWrite;
const [form, setForm] = useState({ visible: false, record: null });
const [submitting, setSubmitting] = useState(false);
const [preview, setPreview] = useState(null);
const { data, loading, error, reload } = useResource(() => c2.listProfiles(), []);
const profiles = Array.isArray(data?.profiles) ? data.profiles : [];
const metrics = useMemo(() => [
{ id: 'total', label: t('c2.profiles.total', null, 'Profile 总数'), value: profiles.length },
{
id: 'jitter',
label: t('c2.profiles.withJitter', null, '启用 Jitter'),
value: profiles.filter(item => Number(item.jitterMaxMs) > 0).length
},
{
id: 'uris',
label: t('c2.profiles.withUris', null, '自定义 URI'),
value: profiles.filter(item => Array.isArray(item.uris) && item.uris.length > 0).length
},
{
id: 'headers',
label: t('c2.profiles.withHeaders', null, '自定义响应头'),
value: profiles.filter(item => item.responseHeaders && Object.keys(item.responseHeaders).length > 0).length
}
], [profiles, t]);
const submit = async values => {
setSubmitting(true);
try {
if (form.record?.id) {
await c2.updateProfile(form.record.id, values);
toastSuccess(t('c2.profiles.toastUpdated', null, 'Profile 已更新'));
} else {
await c2.createProfile(values);
toastSuccess(t('c2.profiles.toastCreated', null, 'Profile 已创建'));
}
setForm({ visible: false, record: null });
reload();
} catch (err) {
toastError(err, t('c2.profiles.saveFailed', null, 'Profile 保存失败'));
} finally {
setSubmitting(false);
}
};
const remove = record => {
confirmAction({
title: t('c2.profiles.delete', null, '删除 Profile'),
content: t('c2.profiles.confirmDelete', null, '确定删除此 Profile?'),
onOk: async () => {
try {
await c2.deleteProfile(record.id);
toastSuccess(t('c2.profiles.toastDeleted', null, 'Profile 已删除'));
reload();
} catch (err) {
toastError(err);
}
}
});
};
const columns = [
{
title: t('c2.profiles.name', null, '名称'),
dataIndex: 'name',
render: (name, record) => (
<button type="button" className="c2-profile-name" onClick={() => setPreview(record)}>
{name || record.id}
</button>
)
},
{
title: t('c2.profiles.userAgent', null, 'User-Agent'),
dataIndex: 'userAgent',
render: value => <span className="c2-mono c2-profile-ua" title={value}>{value || '—'}</span>
},
{
title: t('c2.profiles.uris', null, 'URI 路径'),
dataIndex: 'uris',
width: 220,
render: value => (Array.isArray(value) && value.length
? <Space spacing={4} wrap>{value.slice(0, 3).map(uri => <Tag key={uri} size="small">{uri}</Tag>)}</Space>
: <Text type="tertiary">—</Text>)
},
{
title: t('c2.profiles.jitter', null, 'Jitter 范围'),
dataIndex: 'jitterMinMs',
width: 140,
render: (value, record) => `${value || 0} – ${record.jitterMaxMs || 0} ms`
},
{ title: t('c2.profiles.createdAt', null, '创建时间'), dataIndex: 'createdAt', width: 170, render: value => formatDateTime(value) },
{
title: t('c2.tasks.colActions', null, '操作'),
dataIndex: 'actions',
width: 180,
render: (_, record) => (
<Space spacing={4}>
<Button size="small" theme="borderless" onClick={() => setPreview(record)}>{t('c2.profiles.view', null, '查看')}</Button>
<Button size="small" theme="borderless" disabled={!canWrite} onClick={() => setForm({ visible: true, record })}>
{t('c2.profiles.edit', null, '编辑')}
</Button>
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(record)}>
{t('c2.profiles.delete', null, '删除')}
</Button>
</Space>
)
}
];
return (
<div className="c2-page" id="page-c2-profiles">
<PageHeader
title={t('c2.profiles.title', null, '流量伪装')}
description={t('c2.profiles.pageDesc', null, '维护 HTTP/HTTPS Beacon 的 UA、URI 与响应头模板')}
extra={[
<Button key="refresh" icon={<IconRefresh />} onClick={reload} loading={loading}>{t('common.refresh', null, '刷新')}</Button>,
<Button key="create" theme="solid" type="primary" icon={<IconPlus />} disabled={!canWrite} onClick={() => setForm({ visible: true, record: null })}>
{t('c2.profiles.createBtn', null, '创建 Profile')}
</Button>
]}
/>
<StatGrid metrics={metrics} columns={4} />
<ErrorBanner error={error} onRetry={reload} />
<SectionCard title={t('c2.profiles.listTitle', null, 'Profile 列表')}>
<DataTable
columns={columns}
dataSource={profiles}
rowKey="id"
loading={loading}
onRefresh={reload}
pagination={{ pageSize: 10 }}
emptyText={t('c2.profiles.empty', null, '暂无 Profile')}
/>
</SectionCard>
{preview && (
<SectionCard
title={`${t('c2.profiles.detailTitle', null, 'Profile 详情')} · ${preview.name || preview.id}`}
extra={<Button size="small" onClick={() => setPreview(null)}>{t('c2.profiles.close', null, '收起')}</Button>}
>
<JsonViewer value={preview} />
</SectionCard>
)}
<ProfileForm
visible={form.visible}
record={form.record}
submitting={submitting}
onCancel={() => setForm({ visible: false, record: null })}
onSubmit={submit}
/>
</div>
);
}

View File

@ -0,0 +1,20 @@
/* C2 流量伪装页面私有样式(c2- 前缀)。 */
.c2-profile-name {
border: none;
background: none;
padding: 0;
cursor: pointer;
color: var(--semi-color-link);
font-weight: 600;
text-align: left;
}
.c2-profile-ua {
display: inline-block;
max-width: 320px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: bottom;
}

View File

@ -0,0 +1,171 @@
/**
* C2 会话工作区:头部元信息 + 终端/文件/任务/信息四个 Tab。
*/
import { useState } from 'react';
import { Button, Input, Modal, Space, Tabs, Tag, TextArea, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
import { useResource } from '../../components/hooks';
import { ErrorBanner, confirmAction, toastError, toastSuccess, toastWarning } from '../../components/ui';
import * as c2 from './components/c2-api';
import { SESSION_STATUS_COLOR } from './components/c2-shared';
import SessionTerminal from './SessionTerminal';
import SessionFiles from './SessionFiles';
import SessionTasks from './SessionTasks';
import SessionInfo from './SessionInfo';
const { Text } = Typography;
export default function SessionDetail({ session, canWrite, canDelete, onChanged, onDeleted }) {
const t = useT();
const [tab, setTab] = useState('terminal');
const [sleepModal, setSleepModal] = useState(null);
const [noteModal, setNoteModal] = useState(null);
const [saving, setSaving] = useState(false);
const { data, loading, error, reload } = useResource(() => c2.getSession(session.id), [session.id]);
const detail = data?.session || session;
const openSleep = () => setSleepModal({
sleepSeconds: String(detail.sleepSeconds || 5),
jitterPercent: String(detail.jitterPercent || 0)
});
const openNote = () => setNoteModal({ note: detail.note || '' });
const saveSleep = async () => {
const sleepSeconds = Number(sleepModal.sleepSeconds);
const jitterPercent = Number(sleepModal.jitterPercent);
if (!Number.isFinite(sleepSeconds) || sleepSeconds < 1) {
toastWarning(t('c2.sessions.toastSleepInvalid', null, 'Sleep 间隔至少为 1 秒'));
return;
}
if (!Number.isFinite(jitterPercent) || jitterPercent < 0 || jitterPercent > 100) {
toastWarning(t('c2.sessions.toastSleepInvalid', null, '抖动百分比需在 0–100 之间'));
return;
}
setSaving(true);
try {
await c2.setSessionSleep(detail.id, { sleepSeconds, jitterPercent });
toastSuccess(t('c2.sessions.toastSleepUpdated', null, 'Sleep 设置已更新'));
setSleepModal(null);
reload({ silent: true });
onChanged?.();
} catch (err) {
toastError(err);
} finally {
setSaving(false);
}
};
const saveNote = async () => {
const note = String(noteModal.note || '').trim();
if (note.length > 2000) {
toastWarning(t('c2.sessions.toastNoteTooLong', null, '备注最多 2000 字'));
return;
}
setSaving(true);
try {
await c2.setSessionNote(detail.id, note);
toastSuccess(t('c2.sessions.toastNoteSaved', null, '备注已保存'));
setNoteModal(null);
reload({ silent: true });
onChanged?.();
} catch (err) {
toastError(err);
} finally {
setSaving(false);
}
};
const remove = () => {
confirmAction({
title: t('c2.sessions.cardDeleteSession', null, '删除会话'),
content: t('c2.sessions.confirmDeleteSession', null, '从服务器删除此会话及其关联任务与文件记录?'),
onOk: async () => {
try {
await c2.deleteSession(detail.id);
toastSuccess(t('c2.sessions.toastSessionDeleted', null, '会话记录已删除'));
onDeleted?.();
} catch (err) {
toastError(err);
}
}
});
};
const items = [
{ tab: t('c2.sessions.terminal', null, '终端'), itemKey: 'terminal', children: <SessionTerminal session={detail} canWrite={canWrite} onTaskCreated={reload} /> },
{ tab: t('c2.sessions.files', null, '文件'), itemKey: 'files', children: <SessionFiles session={detail} canWrite={canWrite} /> },
{ tab: t('c2.sessions.tasks', null, '任务'), itemKey: 'tasks', children: <SessionTasks session={detail} canDelete={canDelete} onChanged={reload} /> },
{ tab: t('c2.sessions.info', null, '信息'), itemKey: 'info', children: <SessionInfo session={detail} canWrite={canWrite} onEditNote={openNote} /> }
];
return (
<div className="c2-session-detail">
<div className="c2-session-head">
<div className="c2-session-title">
<Text strong className="c2-session-hostname">{detail.hostname || t('c2.sessions.unknownHost', null, '未知主机')}</Text>
<Space spacing={6} wrap>
<Tag size="small" color={SESSION_STATUS_COLOR[detail.status] || 'grey'}>
{t(`c2.sessions.${detail.status || 'active'}`, null, detail.status || '—')}
</Tag>
<Tag size="small">{detail.os || '—'}/{detail.arch || '—'}</Tag>
{detail.isAdmin && <Tag size="small" color="red">{t('c2.sessions.rootBadge', null, 'ROOT')}</Tag>}
<Text type="tertiary" size="small">{detail.username || '—'}@{detail.internalIp || detail.externalIp || '—'}</Text>
<Text type="tertiary" size="small">sleep {detail.sleepSeconds || 0}s ± {detail.jitterPercent || 0}%</Text>
</Space>
</div>
<Space spacing={6} wrap>
<Button size="small" icon={<IconRefresh />} loading={loading} onClick={() => reload()}>{t('common.refresh', null, '刷新')}</Button>
<Button size="small" disabled={!canWrite} onClick={openSleep}>{t('c2.sessions.btnSleep', null, 'Sleep')}</Button>
<Button size="small" disabled={!canWrite} onClick={openNote}>{t('c2.sessions.noteEdit', null, '备注')}</Button>
<Button size="small" type="danger" disabled={!canDelete} onClick={remove}>{t('c2.sessions.cardDeleteSession', null, '删除会话')}</Button>
</Space>
</div>
<ErrorBanner error={error} onRetry={reload} />
<Tabs type="button" activeKey={tab} onChange={setTab} items={items} />
<Modal
visible={Boolean(sleepModal)}
title={t('c2.sessions.sleepModalTitle', null, '心跳配置')}
width={440}
onCancel={() => setSleepModal(null)}
onOk={saveSleep}
confirmLoading={saving}
>
<Text type="tertiary" size="small">{t('c2.sessions.sleepModalHint', null, '保存后将写入服务端并下发 sleep 任务。')}</Text>
<div className="c2-session-modal-field">
<Text size="small">{t('c2.sessions.promptSleepSeconds', null, 'Sleep 间隔(秒)')}</Text>
<Input
value={sleepModal?.sleepSeconds || ''}
onChange={value => setSleepModal(current => ({ ...current, sleepSeconds: value }))}
/>
</div>
<div className="c2-session-modal-field">
<Text size="small">{t('c2.sessions.promptJitterPercent', null, '抖动百分比(0–100)')}</Text>
<Input
value={sleepModal?.jitterPercent || ''}
onChange={value => setSleepModal(current => ({ ...current, jitterPercent: value }))}
/>
</div>
</Modal>
<Modal
visible={Boolean(noteModal)}
title={t('c2.sessions.infoNote', null, '备注')}
width={480}
onCancel={() => setNoteModal(null)}
onOk={saveNote}
confirmLoading={saving}
>
<TextArea
value={noteModal?.note || ''}
onChange={value => setNoteModal(current => ({ ...current, note: value }))}
placeholder={t('c2.sessions.notePlaceholder', null, '添加备注,便于识别该会话…')}
autosize={{ minRows: 4, maxRows: 10 }}
/>
</Modal>
</div>
);
}

View File

@ -0,0 +1,174 @@
/**
* C2 会话文件浏览:通过 ls / download 任务读取远端目录与文件。
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { Button, Input, Space, Typography } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
import { DataTable, ErrorBanner, toastError, toastSuccess, toastWarning } from '../../components/ui';
import * as c2 from './components/c2-api';
import { joinRemotePath, normalizeRemotePath, parseC2Listing, remoteParentPath } from './components/c2-ls';
const { Text } = Typography;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
async function waitTask(taskId) {
let delay = 600;
for (let attempt = 0; attempt < 40; attempt += 1) {
const payload = await c2.getTask(taskId);
const task = payload?.task;
if (!task) return null;
if (['success', 'failed', 'cancelled'].includes(task.status)) return task;
await sleep(delay);
delay = Math.min(Math.round(delay * 1.4), 4000);
}
return null;
}
export default function SessionFiles({ session, canWrite }) {
const t = useT();
const [path, setPath] = useState('.');
const [pathInput, setPathInput] = useState('.');
const [items, setItems] = useState([]);
const [raw, setRaw] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [filter, setFilter] = useState('');
const alive = useRef(true);
useEffect(() => () => { alive.current = false; }, []);
const load = useCallback(async nextPath => {
const target = normalizeRemotePath(nextPath ?? path);
setLoading(true);
setError(null);
try {
const created = await c2.createTask({ session_id: session.id, task_type: 'ls', payload: { path: target } });
const taskId = created?.task?.id;
if (!taskId) throw new Error(t('c2.files.failed', null, '列目录失败'));
const task = await waitTask(taskId);
if (!alive.current) return;
if (!task) {
setError(t('c2.files.timeout', null, '加载文件超时'));
return;
}
if (task.status !== 'success') {
setError(task.error || t('c2.files.failed', null, '列目录失败'));
setItems([]);
setRaw(task.resultText || '');
return;
}
setRaw(task.resultText || '');
setItems(parseC2Listing(task.resultText || ''));
setPath(target);
setPathInput(target);
} catch (err) {
if (alive.current) setError(err);
} finally {
if (alive.current) setLoading(false);
}
}, [session.id, path, t]);
useEffect(() => {
setPath('.');
setPathInput('.');
setItems([]);
load('.');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [session.id]);
const download = async item => {
if (!canWrite) {
toastWarning(t('c2.files.writeRequired', null, '当前账号没有下发任务的权限'));
return;
}
const remote = joinRemotePath(path, item.name);
try {
const created = await c2.createTask({ session_id: session.id, task_type: 'download', payload: { path: remote } });
const taskId = created?.task?.id;
if (!taskId) throw new Error(t('c2.files.failed', null, '下载失败'));
const task = await waitTask(taskId);
if (!task || task.status !== 'success') {
throw new Error(task?.error || t('c2.files.failed', null, '下载失败'));
}
await c2.downloadTaskResult(task.id, item.name);
toastSuccess(t('c2.files.downloadOk', null, '下载成功'));
} catch (err) {
toastError(err, t('c2.files.failed', null, '下载失败'));
}
};
const visible = items.filter(item => {
const keyword = filter.trim().toLowerCase();
return !keyword || item.name.toLowerCase().includes(keyword);
});
const columns = [
{
title: t('c2.files.colName', null, '名称'),
dataIndex: 'name',
render: (name, item) => (
<button
type="button"
className={`c2-file-name ${item.isDir ? 'is-dir' : ''}`}
onClick={() => (item.isDir ? load(joinRemotePath(path, name)) : download(item))}
>
{name}{item.isDir ? '/' : ''}
</button>
)
},
{ title: t('c2.files.colSize', null, '大小'), dataIndex: 'size', width: 120 },
{ title: t('c2.files.colMode', null, '权限'), dataIndex: 'mode', width: 160 },
{
title: t('c2.files.colActions', null, '操作'),
dataIndex: 'actions',
width: 160,
render: (_, item) => (
item.isDir
? <Button size="small" theme="borderless" onClick={() => load(joinRemotePath(path, item.name))}>{t('c2.files.open', null, '打开')}</Button>
: <Button size="small" theme="borderless" disabled={!canWrite} onClick={() => download(item)}>{t('c2.files.download', null, '下载')}</Button>
)
}
];
return (
<div className="c2-files">
<div className="c2-files-toolbar">
<Space spacing={8} wrap>
<Button size="small" onClick={() => load(remoteParentPath(path))}>{t('c2.files.parent', null, '上级目录')}</Button>
<Button size="small" icon={<IconRefresh />} loading={loading} onClick={() => load(path)}>{t('c2.files.refresh', null, '刷新')}</Button>
<Input
size="small"
value={pathInput}
onChange={setPathInput}
onEnterPress={() => load(pathInput)}
className="c2-files-path"
/>
<Button size="small" onClick={() => load(pathInput)}>{t('c2.files.go', null, '跳转')}</Button>
<Input
size="small"
value={filter}
onChange={setFilter}
placeholder={t('c2.files.filter', null, '过滤名称')}
className="c2-files-filter"
/>
</Space>
</div>
<Text type="tertiary" size="small">{t('c2.files.currentPath', null, '当前目录')}:{path}</Text>
<ErrorBanner error={error} onRetry={() => load(path)} />
{items.length === 0 && raw.trim() && !loading ? (
<pre className="c2-pre">{raw}</pre>
) : (
<DataTable
columns={columns}
dataSource={visible}
rowKey="name"
loading={loading}
pagination={{ pageSize: 20 }}
emptyText={t('c2.files.emptyDir', null, '空目录')}
/>
)}
</div>
);
}

View File

@ -0,0 +1,67 @@
/**
* C2 会话信息:身份、系统环境、网络与信标、时间线与备注。
*/
import { Button, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { JsonViewer, KeyValueList, SectionCard } from '../../components/ui';
import { formatDateTime } from '../../lib/format';
const { Text } = Typography;
export default function SessionInfo({ session, canWrite, onEditNote }) {
const t = useT();
const identity = [
{ label: t('c2.sessions.infoSessionId', null, '会话 ID'), value: <Text copyable={{ text: session.id }} className="c2-mono">{session.id}</Text> },
{ label: t('c2.sessions.infoImplantUuid', null, '植入体 UUID'), value: <Text className="c2-mono">{session.implantUuid || '—'}</Text> },
{ label: t('c2.sessions.infoHostname', null, '主机名'), value: session.hostname || '—' },
{ label: t('c2.sessions.infoUsername', null, '用户名'), value: session.username || '—' },
{ label: t('c2.sessions.infoProcess', null, '进程'), value: session.processName || '—' },
{ label: t('c2.sessions.infoPid', null, 'PID'), value: session.pid || '—' }
];
const system = [
{ label: t('c2.sessions.infoOs', null, '操作系统'), value: session.os || '—' },
{ label: t('c2.sessions.infoArch', null, '架构'), value: session.arch || '—' },
{ label: t('c2.sessions.infoAdmin', null, '管理员'), value: session.isAdmin ? t('c2.sessions.adminYes', null, '是') : t('c2.sessions.adminNo', null, '否') },
{ label: t('c2.sessions.infoInternalIp', null, '内网 IP'), value: <span className="c2-mono">{session.internalIp || '—'}</span> },
{ label: t('c2.sessions.ip', null, '外网 IP'), value: <span className="c2-mono">{session.externalIp || '—'}</span> },
{ label: t('c2.sessions.infoSleep', null, 'Sleep'), value: `${session.sleepSeconds || 0}s ± ${session.jitterPercent || 0}%` }
];
const timeline = [
{ label: t('c2.sessions.infoFirstSeen', null, '首次上线'), value: formatDateTime(session.firstSeenAt) },
{ label: t('c2.sessions.infoLastCheckin', null, '上次心跳'), value: formatDateTime(session.lastCheckIn) },
{ label: t('c2.sessions.status', null, '状态'), value: session.status || '—' },
{ label: t('c2.sessions.listener', null, '监听器'), value: <span className="c2-mono">{session.listenerId || '—'}</span> }
];
return (
<div className="c2-session-info">
<SectionCard title={t('c2.sessions.infoSectionIdentity', null, '身份信息')}>
<KeyValueList items={identity} columns={2} />
</SectionCard>
<SectionCard title={t('c2.sessions.infoSectionSystem', null, '系统环境')}>
<KeyValueList items={system} columns={2} />
</SectionCard>
<SectionCard title={t('c2.sessions.infoSectionNetwork', null, '网络与信标')}>
<KeyValueList items={timeline} columns={2} />
</SectionCard>
<SectionCard
title={t('c2.sessions.infoSectionNote', null, '备注')}
extra={(
<Space>
<Button size="small" disabled={!canWrite} onClick={onEditNote}>{t('c2.sessions.noteEdit', null, '编辑')}</Button>
</Space>
)}
>
<Text type={session.note ? undefined : 'tertiary'}>{session.note || t('c2.sessions.infoNoteEmpty', null, '暂无备注')}</Text>
</SectionCard>
{session.metadata && Object.keys(session.metadata).length > 0 && (
<SectionCard title={t('c2.sessions.infoMetadata', null, '原始元数据')}>
<JsonViewer value={session.metadata} collapsed />
</SectionCard>
)}
</div>
);
}

View File

@ -0,0 +1,138 @@
/**
* C2 会话任务列表:查看结果、取消与删除单条任务。
*/
import { useState } from 'react';
import { Button, Modal, Space, Tag } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { useInterval, useResource } from '../../components/hooks';
import { DataTable, ErrorBanner, JsonViewer, confirmAction, toastError, toastSuccess } from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import * as c2 from './components/c2-api';
import { TASK_STATUS_COLOR, TimeText, formatDurationMs } from './components/c2-shared';
export default function SessionTasks({ session, canDelete, onChanged }) {
const t = useT();
const [detail, setDetail] = useState(null);
const { data, loading, error, reload } = useResource(
() => c2.listTasks({ session_id: session.id, limit: 100 }),
[session.id]
);
const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
useInterval(() => reload({ silent: true }), 5000);
const cancel = async task => {
try {
await c2.cancelTask(task.id);
toastSuccess(t('c2.tasks.toastCancelled', null, '任务已取消'));
reload({ silent: true });
onChanged?.();
} catch (err) {
toastError(err);
}
};
const remove = task => {
confirmAction({
title: t('c2.tasks.deleteOne', null, '删除任务'),
content: t('c2.tasks.confirmDeleteOne', null, '确定从服务器删除该任务记录吗?此操作不可恢复。'),
onOk: async () => {
try {
await c2.deleteTasks([task.id]);
toastSuccess(t('c2.tasks.toastDeleted', null, '已删除 {{n}} 条').replace('{{n}}', '1'));
reload({ silent: true });
onChanged?.();
} catch (err) {
toastError(err);
}
}
});
};
const columns = [
{ title: t('c2.tasks.colType', null, '类型'), dataIndex: 'taskType', width: 120 },
{
title: t('c2.tasks.colCommand', null, '命令'),
dataIndex: 'payload',
render: value => {
const command = value?.command || value?.path || '';
return <span className="c2-mono">{command || '—'}</span>;
}
},
{
title: t('c2.tasks.colStatus', null, '状态'),
dataIndex: 'status',
width: 110,
render: status => <Tag size="small" color={TASK_STATUS_COLOR[status] || 'grey'}>{t(`c2.tasks.${status || 'queued'}`, null, status || '—')}</Tag>
},
{
title: t('c2.tasks.colDuration', null, '耗时'),
dataIndex: 'durationMs',
width: 100,
render: value => formatDurationMs(value)
},
{ title: t('c2.tasks.colCreated', null, '创建时间'), dataIndex: 'createdAt', width: 140, render: value => <TimeText value={value} /> },
{
title: t('c2.tasks.colActions', null, '操作'),
dataIndex: 'actions',
width: 200,
render: (_, task) => (
<Space spacing={4} wrap>
<Button size="small" theme="borderless" onClick={() => setDetail(task)}>{t('c2.tasks.view', null, '查看')}</Button>
{['queued', 'sent', 'running'].includes(task.status) && (
<Button size="small" theme="borderless" onClick={() => cancel(task)}>{t('c2.tasks.cancelBtn', null, '取消')}</Button>
)}
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(task)}>
{t('c2.tasks.deleteBtn', null, '删除')}
</Button>
</Space>
)
}
];
return (
<div className="c2-session-tasks">
<ErrorBanner error={error} onRetry={() => reload()} />
<DataTable
columns={columns}
dataSource={tasks}
rowKey="id"
loading={loading}
onRefresh={() => reload()}
pagination={{ pageSize: 10 }}
emptyText={t('c2.tasks.emptySession', null, '该会话暂无任务')}
/>
<Modal
visible={Boolean(detail)}
title={t('c2.tasks.modalTitle', null, '任务详情')}
width={720}
onCancel={() => setDetail(null)}
footer={<Button onClick={() => setDetail(null)}>{t('c2.tasks.close', null, '关闭')}</Button>}
>
{detail && (
<div className="c2-task-detail">
<div className="c2-task-detail-meta">
<span className="c2-mono">{detail.id}</span>
<Tag size="small" color={TASK_STATUS_COLOR[detail.status] || 'grey'}>{detail.status}</Tag>
<span className="c2-muted">{formatDateTime(detail.createdAt)}</span>
</div>
{detail.payload && <JsonViewer title={t('c2.tasks.labelPayload', null, '参数')} value={detail.payload} collapsed />}
{detail.resultText && (
<>
<div className="c2-field-label">{t('c2.tasks.labelResult', null, '输出')}</div>
<pre className="c2-pre">{detail.resultText}</pre>
</>
)}
{detail.error && (
<>
<div className="c2-field-label">{t('c2.tasks.labelError', null, '错误')}</div>
<pre className="c2-pre c2-pre-error">{detail.error}</pre>
</>
)}
</div>
)}
</Modal>
</div>
);
}

View File

@ -0,0 +1,137 @@
/**
* C2 会话终端:下发 shell 任务并轮询任务结果,输出回显到本地终端视图。
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { Button, Input, Space, Tag } from '@douyinfe/semi-ui';
import { IconSend } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
import { toastError, toastWarning } from '../../components/ui';
import * as c2 from './components/c2-api';
let seq = 0;
const nextId = () => { seq += 1; return seq; };
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
export default function SessionTerminal({ session, canWrite, onTaskCreated }) {
const t = useT();
const [entries, setEntries] = useState([]);
const [command, setCommand] = useState('');
const [running, setRunning] = useState(false);
const [currentTaskId, setCurrentTaskId] = useState('');
const alive = useRef(true);
const logRef = useRef(null);
useEffect(() => () => { alive.current = false; }, []);
useEffect(() => {
const node = logRef.current;
if (node) node.scrollTop = node.scrollHeight;
}, [entries]);
const append = useCallback(entry => {
setEntries(current => [...current, { id: nextId(), ...entry }]);
}, []);
const waitResult = async taskId => {
let delay = 600;
for (let attempt = 0; attempt < 40; attempt += 1) {
if (!alive.current) return null;
const payload = await c2.getTask(taskId);
const task = payload?.task;
if (!task) return null;
if (['success', 'failed', 'cancelled'].includes(task.status)) return task;
await sleep(delay);
delay = Math.min(Math.round(delay * 1.4), 4000);
}
return null;
};
const run = async raw => {
const cmd = String(raw ?? command).trim();
if (!cmd) return;
if (!canWrite) {
toastWarning(t('c2.sessions.writeRequired', null, '当前账号没有下发任务的权限'));
return;
}
setCommand('');
append({ kind: 'cmd', text: cmd });
setRunning(true);
try {
const created = await c2.createSessionTask(session.id, {
task_type: 'shell',
payload: { command: cmd, timeout_seconds: 60 }
});
const taskId = created?.task?.id;
if (!taskId) {
append({ kind: 'err', text: t('c2.sessions.termNoSession', null, '下发失败:未返回任务 ID') });
return;
}
setCurrentTaskId(taskId);
onTaskCreated?.();
const task = await waitResult(taskId);
if (!task) {
append({ kind: 'warn', text: t('c2.sessions.termWaitTimeout', null, '[等待结果超时]') });
return;
}
if (task.resultText) append({ kind: task.status === 'success' ? 'out' : 'warn', text: task.resultText });
if (task.error) append({ kind: 'err', text: task.error });
if (task.status === 'cancelled') append({ kind: 'warn', text: t('c2.tasks.cancelled', null, '已取消') });
} catch (error) {
append({ kind: 'err', text: error?.message || t('c2.sessions.termStatusErr', null, '执行失败') });
toastError(error);
} finally {
if (alive.current) {
setRunning(false);
setCurrentTaskId('');
}
}
};
const cancel = async () => {
if (!currentTaskId) return;
try {
await c2.cancelTask(currentTaskId);
append({ kind: 'warn', text: t('c2.tasks.toastCancelled', null, '任务已取消') });
} catch (err) {
toastError(err);
}
};
return (
<div className="c2-terminal">
<div className="c2-terminal-bar">
<Space spacing={8}>
<Tag size="small" color={running ? 'amber' : 'green'}>
{running ? t('c2.sessions.termStatusExec', null, '执行中…') : t('c2.sessions.termStatusReady', null, '就绪')}
</Tag>
<Button size="small" theme="borderless" onClick={() => setEntries([])}>{t('c2.sessions.clearTerminal', null, '清屏')}</Button>
{running && currentTaskId && <Button size="small" theme="borderless" type="danger" onClick={cancel}>{t('c2.tasks.cancelBtn', null, '取消')}</Button>}
</Space>
</div>
<div className="c2-terminal-log" ref={logRef}>
<div className="c2-terminal-welcome">
{t('c2.sessions.terminalWelcome', null, 'C2 终端 — 回车执行;命令以 shell 任务下发并等待结果')}
</div>
{entries.map(entry => (
<pre key={entry.id} className={`c2-terminal-line kind-${entry.kind}`}>
{entry.kind === 'cmd' ? `$ ${entry.text}` : entry.text}
</pre>
))}
</div>
<div className="c2-terminal-input">
<Input
value={command}
onChange={setCommand}
onEnterPress={() => (running ? toastWarning(t('c2.sessions.termWaitFinish', null, '请等待当前命令执行完成')) : run())}
placeholder={t('c2.sessions.commandPlaceholder', null, '输入命令后回车下发')}
disabled={running || !canWrite}
prefix="$"
/>
<Button theme="solid" type="primary" icon={<IconSend />} loading={running} disabled={!canWrite} onClick={() => run()}>
{t('c2.sessions.execute', null, '执行命令')}
</Button>
</div>
</div>
);
}

View File

@ -0,0 +1,60 @@
/**
* C2 六个页面共用的接口层:监听器、会话、任务、载荷、事件、流量伪装。
*/
import { api, downloadFile } from '../../../lib/http';
const enc = encodeURIComponent;
/* ------------------------------- 监听器 ------------------------------- */
export const listListeners = query => api.get('/c2/listeners', query);
export const getListener = id => api.get(`/c2/listeners/${enc(id)}`);
export const createListener = body => api.post('/c2/listeners', body);
export const updateListener = (id, body) => api.put(`/c2/listeners/${enc(id)}`, body);
export const deleteListener = id => api.del(`/c2/listeners/${enc(id)}`);
export const startListener = id => api.post(`/c2/listeners/${enc(id)}/start`, {});
export const stopListener = id => api.post(`/c2/listeners/${enc(id)}/stop`, {});
/* -------------------------------- 会话 -------------------------------- */
export const listSessions = query => api.get('/c2/sessions', query);
export const getSession = id => api.get(`/c2/sessions/${enc(id)}`);
export const deleteSession = id => api.del(`/c2/sessions/${enc(id)}`);
export const deleteSessions = ids => api.del('/c2/sessions', { body: { ids } });
export const setSessionSleep = (id, { sleepSeconds, jitterPercent }) =>
api.put(`/c2/sessions/${enc(id)}/sleep`, { sleep_seconds: sleepSeconds, jitter_percent: jitterPercent });
export const setSessionNote = (id, note) => api.put(`/c2/sessions/${enc(id)}/note`, { note });
/* -------------------------------- 任务 -------------------------------- */
export const listTasks = query => api.get('/c2/tasks', query);
export const getTask = id => api.get(`/c2/tasks/${enc(id)}`);
export const createTask = body => api.post('/c2/tasks', body);
export const createSessionTask = (sessionId, body) => api.post(`/c2/sessions/${enc(sessionId)}/tasks`, body);
export const cancelTask = id => api.post(`/c2/tasks/${enc(id)}/cancel`, {});
export const waitTask = (id, timeout = 30) => api.get(`/c2/tasks/${enc(id)}/wait`, { timeout }, { timeout: (timeout + 10) * 1000 });
export const deleteTasks = ids => api.del('/c2/tasks', { body: { ids } });
export const downloadTaskResult = (id, filename) => downloadFile(`/c2/tasks/${enc(id)}/result-file`, { filename });
/* -------------------------------- 载荷 -------------------------------- */
export const buildOneliner = body => api.post('/c2/payloads/oneliner', body);
export const buildPayload = body => api.post('/c2/payloads/build', body);
export const downloadPayload = (id, filename) => downloadFile(`/c2/payloads/${enc(id)}/download`, { filename });
/* -------------------------------- 事件 -------------------------------- */
export const listEvents = query => api.get('/c2/events', query);
export const deleteEvents = ids => api.del('/c2/events', { body: { ids } });
/* ------------------------------ 流量伪装 ------------------------------ */
export const listProfiles = () => api.get('/c2/profiles');
export const getProfile = id => api.get(`/c2/profiles/${enc(id)}`);
export const createProfile = body => api.post('/c2/profiles', body);
export const updateProfile = (id, body) => api.put(`/c2/profiles/${enc(id)}`, body);
export const deleteProfile = id => api.del(`/c2/profiles/${enc(id)}`);
/* -------------------------------- 项目 -------------------------------- */
export async function listProjects() {
try {
const payload = await api.get('/projects', { limit: 200 });
return Array.isArray(payload?.projects) ? payload.projects : [];
} catch (error) {
return [];
}
}

View File

@ -0,0 +1,74 @@
/**
* 解析 C2 `ls` 任务输出:优先识别 Beacon 结构化行(type\tmode\tsize\tname),
* 否则回退到原生 `ls -l` 输出。
*/
export function parseC2Listing(rawOutput) {
const lines = String(rawOutput || '').split(/\r?\n/);
const items = [];
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || /^total\s+\d+/i.test(trimmed)) continue;
const tabParts = trimmed.split('\t');
if (tabParts.length >= 4) {
const name = tabParts.slice(3).join('\t').trim();
if (!name || name === '.' || name === '..') continue;
const type = tabParts[0].trim();
const mode = tabParts[1].trim();
items.push({
name,
size: tabParts[2].trim(),
mode: mode || type,
isDir: type.startsWith('d') || mode.startsWith('d')
});
continue;
}
const match = trimmed.match(/^\S{1,10}\s+\d+\s+\S+\s+\S+\s+\d+\s+\S+\s+\S+\s+\S+\s+(.+)$/);
if (!match) continue;
let name = match[1].trim();
const arrow = name.indexOf(' -> ');
if (arrow > 0) name = name.slice(0, arrow).trim();
if (!name || name === '.' || name === '..') continue;
const parts = trimmed.split(/\s+/);
items.push({
name,
size: parts[4] || '',
mode: parts[0] || '',
isDir: (parts[0] || '').startsWith('d')
});
}
return items;
}
/** 规范化远端路径,兼容 Windows 反斜杠与相对路径。 */
export function normalizeRemotePath(input) {
let value = String(input ?? '').trim();
if (!value) return '.';
if (/^[A-Za-z]:/.test(value)) return value.replace(/\\+$/, '') || value;
value = value.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
if (value.length > 1) value = value.replace(/\/+$/, '');
return value || '.';
}
export function joinRemotePath(base, name) {
const dir = normalizeRemotePath(base);
if (!name) return dir;
if (/^[A-Za-z]:/.test(name) || name.startsWith('/')) return normalizeRemotePath(name);
if (dir === '.' || dir === '') return normalizeRemotePath(name);
const sep = dir.includes('\\') ? '\\' : '/';
return normalizeRemotePath(`${dir}${sep}${name}`);
}
export function remoteParentPath(input) {
const value = normalizeRemotePath(input);
if (value === '.' || value === '/') return value;
if (/^[A-Za-z]:$/.test(value)) return value;
const sep = value.includes('\\') ? '\\' : '/';
const index = value.lastIndexOf(sep);
if (index < 0) return '.';
if (index === 0) return '/';
const head = value.slice(0, index);
return /^[A-Za-z]:$/.test(head) ? `${head}${sep}` : head;
}

View File

@ -0,0 +1,149 @@
/* C2 六个页面共享的布局样式(类名统一 c2- 前缀)。 */
.c2-page {
display: flex;
flex-direction: column;
gap: 12px;
}
.c2-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.c2-toolbar-fields {
display: flex;
align-items: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.c2-field {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 140px;
}
.c2-field-label {
font-size: 12px;
color: var(--semi-color-text-2);
}
.c2-time-presets {
align-items: center;
}
.c2-time-text {
color: var(--semi-color-text-2);
font-size: 12px;
white-space: nowrap;
}
.c2-muted {
color: var(--semi-color-text-2);
font-size: 12px;
}
.c2-mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
word-break: break-all;
}
.c2-pre {
margin: 0;
padding: 10px;
border-radius: 6px;
background: var(--semi-color-fill-0);
border: 1px solid var(--semi-color-border);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-all;
max-height: 420px;
overflow: auto;
}
.c2-pre-error {
border-color: var(--semi-color-danger);
}
.c2-task-detail {
display: flex;
flex-direction: column;
gap: 8px;
}
.c2-task-detail-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.c2-form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.c2-form-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.c2-cards {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 12px;
}
.c2-card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
}
.c2-card-title {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.c2-card-name {
font-weight: 600;
font-size: 14px;
}
.c2-card-meta {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 8px 0;
}
.c2-card-actions {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 8px;
}
.c2-empty {
padding: 40px 0;
}
@media (max-width: 900px) {
.c2-form-row {
grid-template-columns: 1fr;
}
}

View File

@ -0,0 +1,159 @@
/**
* C2 页面共享常量、时间快捷筛选与展示小工具。
*/
import { Button, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../../lib/i18n';
import { formatDateTime, relativeTime } from '../../../lib/format';
import './c2-shared.css';
const { Text } = Typography;
export const LISTENER_TYPES = [
{ value: 'http_beacon', label: 'HTTP Beacon' },
{ value: 'https_beacon', label: 'HTTPS Beacon' },
{ value: 'tcp_reverse', label: 'TCP 反向' },
{ value: 'websocket', label: 'WebSocket' }
];
export const LISTENER_STATUS_LABEL = {
running: '运行中',
stopped: '已停止',
error: '异常'
};
export const HEARTBEAT_TYPES = new Set(['http_beacon', 'https_beacon', 'websocket']);
export const ONELINER_KINDS = {
tcp_reverse: [
{ value: 'bash', label: 'Bash (/dev/tcp)' },
{ value: 'nc', label: 'Netcat (-e)' },
{ value: 'nc_mkfifo', label: 'Netcat (mkfifo)' },
{ value: 'python', label: 'Python' },
{ value: 'perl', label: 'Perl' },
{ value: 'powershell', label: 'PowerShell' }
],
http_beacon: [{ value: 'curl_beacon', label: 'Curl Beacon (HTTP)' }],
https_beacon: [{ value: 'curl_beacon', label: 'Curl Beacon (HTTP)' }],
websocket: [{ value: 'curl_beacon', label: 'Curl Beacon (HTTP)' }]
};
export const TASK_TYPES = [
{ value: 'shell', label: 'shell' },
{ value: 'exec', label: 'exec' },
{ value: 'ls', label: 'ls' },
{ value: 'pwd', label: 'pwd' },
{ value: 'cd', label: 'cd' },
{ value: 'ps', label: 'ps' },
{ value: 'kill_proc', label: 'kill_proc' },
{ value: 'download', label: 'download' },
{ value: 'upload', label: 'upload' },
{ value: 'screenshot', label: 'screenshot' },
{ value: 'sleep', label: 'sleep' },
{ value: 'exit', label: 'exit' },
{ value: 'self_delete', label: 'self_delete' },
{ value: 'port_fwd', label: 'port_fwd' },
{ value: 'socks_start', label: 'socks_start' },
{ value: 'socks_stop', label: 'socks_stop' },
{ value: 'load_assembly', label: 'load_assembly' },
{ value: 'persist', label: 'persist' }
];
export const TASK_STATUS_OPTIONS = [
{ value: 'queued', label: '队列中' },
{ value: 'sent', label: '已发送' },
{ value: 'running', label: '执行中' },
{ value: 'success', label: '成功' },
{ value: 'failed', label: '失败' },
{ value: 'cancelled', label: '已取消' }
];
export const EVENT_LEVEL_OPTIONS = [
{ value: 'info', label: '信息' },
{ value: 'warn', label: '警告' },
{ value: 'critical', label: '严重' }
];
export const EVENT_CATEGORY_OPTIONS = [
{ value: 'listener', label: '监听器' },
{ value: 'session', label: '会话' },
{ value: 'task', label: '任务' },
{ value: 'payload', label: 'Payload' },
{ value: 'opsec', label: 'OPSEC' }
];
export const SESSION_STATUS_OPTIONS = [
{ value: 'active', label: '活跃' },
{ value: 'sleeping', label: '休眠' },
{ value: 'dead', label: '离线' },
{ value: 'killed', label: '已终止' }
];
/** 任务/事件轮询间隔:需求要求 5 秒轮询。 */
export const POLL_INTERVAL = 5000;
export const TIME_PRESETS = [
{ value: '15m', label: '最近15分钟', ms: 15 * 60 * 1000 },
{ value: '1h', label: '最近1小时', ms: 60 * 60 * 1000 },
{ value: '24h', label: '最近24小时', ms: 24 * 60 * 60 * 1000 },
{ value: '7d', label: '最近7天', ms: 7 * 24 * 60 * 60 * 1000 },
{ value: 'all', label: '全部', ms: 0 }
];
/** 快捷时间窗 → since(RFC3339);all 返回空串。 */
export function presetToSince(preset) {
const item = TIME_PRESETS.find(entry => entry.value === preset);
if (!item || !item.ms) return '';
return new Date(Date.now() - item.ms).toISOString();
}
export function TimePresetBar({ value, onChange, ns = 'tasks' }) {
const t = useT();
return (
<Space spacing={6} wrap className="c2-time-presets">
<Text type="tertiary" size="small">{t('c2.tasks.timePresets', null, '快捷')}</Text>
{TIME_PRESETS.map(preset => (
<Button
key={preset.value}
size="small"
theme={preset.value === value ? 'solid' : 'borderless'}
type={preset.value === value ? 'primary' : 'tertiary'}
onClick={() => onChange(preset.value)}
>
{t(`c2.${ns}.preset${preset.value === 'all' ? 'All' : preset.value}`, null, preset.label)}
</Button>
))}
</Space>
);
}
export function formatDurationMs(ms) {
const value = Number(ms);
if (!Number.isFinite(value) || value <= 0) return '—';
if (value < 1000) return `${Math.round(value)}ms`;
if (value < 60_000) return `${(value / 1000).toFixed(1)}秒`;
return `${Math.round(value / 60_000)}分钟`;
}
export function TimeText({ value }) {
const t = useT();
if (!value) return <Text type="tertiary">—</Text>;
return (
<span className="c2-time-text" title={formatDateTime(value)}>
{relativeTime(value, t)}
</span>
);
}
export function truncateMiddle(text, max = 42) {
const value = String(text || '');
if (value.length <= max) return value;
const side = Math.floor((max - 1) / 2);
return `${value.slice(0, side)}…${value.slice(value.length - side)}`;
}
export const LISTENER_STATUS_COLOR = { running: 'green', stopped: 'grey', error: 'red' };
export const TASK_STATUS_COLOR = {
queued: 'amber', sent: 'blue', running: 'blue', success: 'green', failed: 'red', cancelled: 'grey'
};
export const SESSION_STATUS_COLOR = { active: 'green', sleeping: 'amber', dead: 'grey', killed: 'red' };
export const EVENT_LEVEL_COLOR = { info: 'blue', warn: 'amber', critical: 'red' };

View File

@ -0,0 +1,194 @@
/**
* C2 会话管理:左侧筛选后的会话列表,右侧会话工作区(终端/文件/任务/信息)。
*/
import { useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, Checkbox, Empty, Input, Select, Spin, Tag, Typography } from '@douyinfe/semi-ui';
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useDebounced, useInterval, useResource } from '../../components/hooks';
import { PageHeader, ErrorBanner, confirmAction, toastError, toastSuccess } from '../../components/ui';
import * as c2 from './components/c2-api';
import { SESSION_STATUS_COLOR, SESSION_STATUS_OPTIONS, TimeText } from './components/c2-shared';
import SessionDetail from './SessionDetail';
import './page.css';
const { Text } = Typography;
export default function C2SessionsPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('c2:write');
const canDelete = hasPermission('c2:delete') || canWrite;
const [searchParams, setSearchParams] = useSearchParams();
const selectedId = searchParams.get('id') || '';
const [status, setStatus] = useState('');
const [listenerId, setListenerId] = useState('');
const [suspicious, setSuspicious] = useState(false);
const [keyword, setKeyword] = useState('');
const [autoRefresh, setAutoRefresh] = useState(true);
const search = useDebounced(keyword, 300);
const query = useMemo(() => ({
status: status || undefined,
listener_id: listenerId || undefined,
search: search || undefined,
suspicious: suspicious ? '1' : undefined,
limit: 200
}), [status, listenerId, search, suspicious]);
const { data, loading, error, reload } = useResource(
() => Promise.all([c2.listSessions(query), c2.listListeners().catch(() => ({ listeners: [] }))]),
[query]
);
const sessions = Array.isArray(data?.[0]?.sessions) ? data[0].sessions : [];
const listeners = Array.isArray(data?.[1]?.listeners) ? data[1].listeners : [];
useInterval(() => { if (autoRefresh) reload({ silent: true }); }, autoRefresh ? 10000 : 0);
const selected = useMemo(() => sessions.find(item => item.id === selectedId) || null, [sessions, selectedId]);
const select = id => {
const next = new URLSearchParams(searchParams);
if (id) next.set('id', id);
else next.delete('id');
setSearchParams(next, { replace: true });
};
const removeFiltered = () => {
if (!sessions.length) {
toastError(t('c2.sessions.toastSelectFirst', null, '没有可删除的会话'));
return;
}
confirmAction({
title: t('c2.sessions.deleteFiltered', null, '删除筛选结果'),
content: t('c2.sessions.confirmDeleteFiltered', null, '确定删除当前筛选结果中的全部会话?').replace('{{n}}', String(sessions.length)),
onOk: async () => {
try {
const result = await c2.deleteSessions(sessions.map(item => item.id));
toastSuccess(t('c2.sessions.toastBatchDeleted', null, '已删除 {{n}} 个会话').replace('{{n}}', String(result?.deleted ?? sessions.length)));
select('');
reload();
} catch (err) {
toastError(err);
}
}
});
};
return (
<div className="c2-page" id="page-c2-sessions">
<PageHeader
title={t('c2.sessions.title', null, '会话管理')}
description={t('c2.sessions.pageDesc', null, '查看上线会话,下发命令、浏览文件并管理任务历史')}
extra={[
<Button key="refresh" icon={<IconRefresh />} onClick={reload} loading={loading}>
{t('common.refresh', null, '刷新')}
</Button>,
<Button key="delete" type="danger" disabled={!canDelete || !sessions.length} onClick={removeFiltered}>
{t('c2.sessions.deleteFiltered', null, '删除筛选结果')}
</Button>
]}
/>
<ErrorBanner error={error} onRetry={reload} />
<div className="c2-session-layout">
<aside className="c2-session-sidebar">
<div className="c2-session-filters">
<Select
size="small"
value={status}
onChange={value => setStatus(value || '')}
style={{ width: '100%' }}
optionList={[{ value: '', label: t('c2.sessions.filterAllStatus', null, '全部状态') },
...SESSION_STATUS_OPTIONS]}
/>
<Select
size="small"
value={listenerId}
onChange={value => setListenerId(value || '')}
style={{ width: '100%' }}
optionList={[{ value: '', label: t('c2.sessions.filterAllListeners', null, '全部监听器') },
...listeners.map(item => ({ value: item.id, label: item.name || item.id }))]}
/>
<Input
size="small"
value={keyword}
onChange={setKeyword}
prefix={<IconSearch />}
placeholder={t('c2.sessions.filterSearchPlaceholder', null, '搜索主机名 / 用户 / IP')}
/>
<div className="c2-session-filter-foot">
<Checkbox checked={suspicious} onChange={event => setSuspicious(Boolean(event.target.checked))}>
<Text size="small">{t('c2.sessions.filterSuspicious', null, '疑似误报')}</Text>
</Checkbox>
<Checkbox checked={autoRefresh} onChange={event => setAutoRefresh(Boolean(event.target.checked))}>
<Text size="small">{t('c2.sessions.autoRefresh', null, '自动刷新')}</Text>
</Checkbox>
</div>
<Text type="tertiary" size="small">
{t('c2.sessions.listCount', null, '共 {{n}} 条').replace('{{n}}', String(sessions.length))}
</Text>
</div>
<div className="c2-session-list">
{loading && !sessions.length && <div className="c2-session-loading"><Spin /></div>}
{!loading && sessions.length === 0 && (
<Empty
title={keyword || status || listenerId ? t('c2.sessions.emptyFilter', null, '没有符合筛选条件的会话') : t('c2.sessions.listEmpty', null, '暂无会话')}
description={null}
style={{ padding: 24 }}
/>
)}
{sessions.map(session => (
<button
type="button"
key={session.id}
className={`c2-session-item ${session.id === selectedId ? 'is-active' : ''}`}
onClick={() => select(session.id)}
>
<div className="c2-session-item-head">
<span className="c2-session-host">{session.hostname || t('c2.sessions.unknownHost', null, '未知')}</span>
<Tag size="small" color={SESSION_STATUS_COLOR[session.status] || 'grey'}>
{t(`c2.sessions.${session.status || 'active'}`, null, session.status || '—')}
</Tag>
</div>
<div className="c2-session-item-meta">
<span>{session.username || '—'}</span>
<span>{session.os || '—'}/{session.arch || '—'}</span>
{session.isAdmin && <Tag size="small" color="red">ROOT</Tag>}
</div>
<div className="c2-session-item-foot">
<span className="c2-mono">{session.internalIp || session.externalIp || '—'}</span>
<TimeText value={session.lastCheckIn} />
</div>
</button>
))}
</div>
</aside>
<section className="c2-session-main">
{selected ? (
<SessionDetail
key={selected.id}
session={selected}
canWrite={canWrite}
canDelete={canDelete}
onChanged={reload}
onDeleted={() => { select(''); reload(); }}
/>
) : (
<Empty
title={t('c2.sessions.selectPromptTitle', null, '选择会话')}
description={t('c2.sessions.selectPromptHint', null, '在左侧列表中点击一个会话,查看终端、文件与任务详情。')}
style={{ padding: 64 }}
/>
)}
</section>
</div>
</div>
);
}

View File

@ -0,0 +1,240 @@
/* C2 会话页面私有样式(c2- 前缀)。 */
.c2-session-layout {
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
gap: 12px;
align-items: start;
}
.c2-session-sidebar {
display: flex;
flex-direction: column;
gap: 8px;
padding: 10px;
border: 1px solid var(--semi-color-border);
border-radius: 8px;
background: var(--semi-color-bg-1);
min-height: 560px;
}
.c2-session-filters {
display: flex;
flex-direction: column;
gap: 6px;
}
.c2-session-filter-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.c2-session-list {
display: flex;
flex-direction: column;
gap: 6px;
overflow-y: auto;
max-height: 620px;
}
.c2-session-loading {
display: flex;
justify-content: center;
padding: 24px 0;
}
.c2-session-item {
display: flex;
flex-direction: column;
gap: 4px;
padding: 8px 10px;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
cursor: pointer;
text-align: left;
color: inherit;
}
.c2-session-item:hover {
background: var(--semi-color-fill-0);
}
.c2-session-item.is-active {
border-color: var(--semi-color-primary);
background: var(--semi-color-primary-light-default);
}
.c2-session-item-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
}
.c2-session-host {
font-weight: 600;
font-size: 13px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.c2-session-item-meta,
.c2-session-item-foot {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
font-size: 11px;
color: var(--semi-color-text-2);
}
.c2-session-main {
min-height: 560px;
padding: 12px;
border: 1px solid var(--semi-color-border);
border-radius: 8px;
background: var(--semi-color-bg-1);
}
.c2-session-detail {
display: flex;
flex-direction: column;
gap: 10px;
}
.c2-session-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding-bottom: 8px;
border-bottom: 1px solid var(--semi-color-border);
}
.c2-session-title {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.c2-session-hostname {
font-size: 15px;
}
.c2-session-modal-field {
display: flex;
flex-direction: column;
gap: 4px;
margin-top: 10px;
}
/* 终端 */
.c2-terminal {
display: flex;
flex-direction: column;
gap: 8px;
}
.c2-terminal-bar {
display: flex;
align-items: center;
justify-content: space-between;
}
.c2-terminal-log {
height: 340px;
overflow: auto;
padding: 10px;
border: 1px solid var(--semi-color-border);
border-radius: 6px;
background: var(--semi-color-fill-0);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.c2-terminal-welcome {
color: var(--semi-color-text-2);
margin-bottom: 8px;
}
.c2-terminal-line {
margin: 0;
white-space: pre-wrap;
word-break: break-all;
line-height: 1.5;
}
.c2-terminal-line.kind-cmd {
color: var(--semi-color-primary);
}
.c2-terminal-line.kind-err {
color: var(--semi-color-danger);
}
.c2-terminal-line.kind-warn {
color: var(--semi-color-warning);
}
.c2-terminal-input {
display: flex;
gap: 8px;
}
/* 文件 */
.c2-files {
display: flex;
flex-direction: column;
gap: 8px;
}
.c2-files-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.c2-files-path {
min-width: 240px;
}
.c2-files-filter {
max-width: 180px;
}
.c2-file-name {
border: none;
background: none;
padding: 0;
cursor: pointer;
color: var(--semi-color-link);
text-align: left;
}
.c2-file-name.is-dir {
font-weight: 600;
}
/* 任务与信息 */
.c2-session-tasks,
.c2-session-info {
display: flex;
flex-direction: column;
gap: 10px;
}
@media (max-width: 1100px) {
.c2-session-layout {
grid-template-columns: 1fr;
}
}

View File

@ -0,0 +1,91 @@
/**
* C2 任务下发:POST /c2/tasks,按任务类型组织 payload。
*/
import { useState } from 'react';
import { Button, Form, Modal, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { TASK_TYPES } from '../c2-sessions/components/c2-shared';
const { Text } = Typography;
const COMMAND_TYPES = new Set(['shell', 'exec']);
const PATH_TYPES = new Set(['ls', 'download', 'cd']);
export default function CreateTaskModal({ visible, defaultSessionId, onCancel, onSubmit, submitting }) {
const t = useT();
const [formApi, setFormApi] = useState(null);
const [taskType, setTaskType] = useState('shell');
const submit = values => {
const payload = {};
const command = String(values.command || '').trim();
if (COMMAND_TYPES.has(values.task_type)) {
payload.command = command;
const timeout = Number(values.timeout_seconds);
if (Number.isFinite(timeout) && timeout > 0) payload.timeout_seconds = timeout;
} else if (PATH_TYPES.has(values.task_type)) {
payload.path = command;
} else if (command) {
payload.path = command;
}
const extra = String(values.extra || '').trim();
if (extra) {
try {
Object.assign(payload, JSON.parse(extra));
} catch (error) {
payload.raw = extra;
}
}
onSubmit({
session_id: String(values.session_id || '').trim(),
task_type: values.task_type || 'shell',
payload,
source: 'manual'
});
};
return (
<Modal
visible={visible}
title={t('c2.tasks.createTitle', null, '下发任务')}
footer={null}
width={560}
onCancel={onCancel}
>
<Form
key={visible ? 'open' : 'closed'}
initValues={{ session_id: defaultSessionId || '', task_type: 'shell', command: '', timeout_seconds: '60', extra: '' }}
onSubmit={submit}
getFormApi={setFormApi}
labelPosition="top"
onValueChange={changed => { if (changed.task_type) setTaskType(changed.task_type); }}
>
<Form.Input
field="session_id"
label={t('c2.tasks.labelSession', null, '会话')}
placeholder="s_xxxxxxxx"
rules={[{ required: true, message: t('c2.tasks.labelSession', null, '请填写会话 ID') }]}
/>
<Form.Select field="task_type" label={t('c2.tasks.labelType', null, '类型')} optionList={TASK_TYPES} style={{ width: '100%' }} />
<Form.Input
field="command"
label={COMMAND_TYPES.has(taskType) ? t('c2.tasks.labelCommand', null, '命令') : t('c2.tasks.labelPath', null, '路径')}
placeholder={COMMAND_TYPES.has(taskType) ? 'whoami' : '/etc/passwd'}
/>
{COMMAND_TYPES.has(taskType) && (
<Form.Input field="timeout_seconds" label={t('c2.tasks.labelTimeout', null, '超时(秒)')} placeholder="60" />
)}
<Form.Input field="extra" label={t('c2.tasks.labelExtraPayload', null, '附加参数(JSON,可选)')} placeholder='{"key":"value"}' />
<Text type="tertiary" size="small">
{t('c2.tasks.createHint', null, '任务入队后由植入体在下次心跳拉取;危险类型可能需要人机协同审批。')}
</Text>
<Space className="c2-form-actions">
<Button onClick={onCancel}>{t('c2.tasks.cancelFilters', null, '取消')}</Button>
<Button theme="solid" type="primary" loading={submitting} onClick={() => formApi?.submitForm()}>
{t('c2.tasks.createSubmit', null, '下发')}
</Button>
</Space>
</Form>
</Modal>
);
}

View File

@ -0,0 +1,330 @@
/**
* C2 任务管理:服务端分页筛选、任务详情、取消、下载结果文件与批量删除。
*/
import { useMemo, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { Button, Input, Modal, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useInterval, useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, StatGrid, DataTable, ErrorBanner,
confirmAction, toastError, toastSuccess
} from '../../components/ui';
import { formatDateTime } from '../../lib/format';
import * as c2 from '../c2-sessions/components/c2-api';
import {
TASK_STATUS_COLOR, TASK_STATUS_OPTIONS, TASK_TYPES, TimePresetBar, TimeText,
formatDurationMs, presetToSince
} from '../c2-sessions/components/c2-shared';
import CreateTaskModal from './CreateTaskModal';
import './page.css';
const { Text } = Typography;
export default function C2TasksPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('c2:write');
const canDelete = hasPermission('c2:delete') || canWrite;
const [searchParams, setSearchParams] = useSearchParams();
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [status, setStatus] = useState('');
const [taskType, setTaskType] = useState('');
const [preset, setPreset] = useState('all');
const [sessionInput, setSessionInput] = useState(searchParams.get('session_id') || '');
const [sessionFilter, setSessionFilter] = useState(searchParams.get('session_id') || '');
const [detail, setDetail] = useState(null);
const [creating, setCreating] = useState(false);
const [submitting, setSubmitting] = useState(false);
const query = useMemo(() => ({
page,
page_size: pageSize,
status: status || undefined,
task_type: taskType || undefined,
session_id: sessionFilter || undefined,
since: presetToSince(preset) || undefined
}), [page, pageSize, status, taskType, sessionFilter, preset]);
const { data, loading, error, reload } = useResource(() => c2.listTasks(query), [query]);
const tasks = Array.isArray(data?.tasks) ? data.tasks : [];
const total = Number(data?.total ?? tasks.length);
const counts = data?.status_counts || {};
useInterval(() => reload({ silent: true }), 5000);
const applyFilters = () => {
setSessionFilter(sessionInput.trim());
setPage(1);
const next = new URLSearchParams(searchParams);
if (sessionInput.trim()) next.set('session_id', sessionInput.trim());
else next.delete('session_id');
setSearchParams(next, { replace: true });
};
const resetFilters = () => {
setStatus('');
setTaskType('');
setPreset('all');
setSessionInput('');
setSessionFilter('');
setPage(1);
setSearchParams(new URLSearchParams(), { replace: true });
};
const metrics = [
{ id: 'total', label: t('c2.tasks.statTotal', null, '当前筛选'), value: total },
{ id: 'success', label: t('c2.tasks.success', null, '成功'), value: counts.success || 0, tone: 'success' },
{ id: 'failed', label: t('c2.tasks.failed', null, '失败'), value: counts.failed || 0, tone: 'danger' },
{
id: 'pending',
label: t('c2.tasks.pending', null, '待处理'),
value: (counts.queued || 0) + (counts.sent || 0) + (counts.running || 0),
tone: 'warning'
}
];
const cancel = async task => {
try {
await c2.cancelTask(task.id);
toastSuccess(t('c2.tasks.toastCancelled', null, '任务已取消'));
reload({ silent: true });
} catch (err) {
toastError(err);
}
};
const remove = task => {
confirmAction({
title: t('c2.tasks.deleteOne', null, '删除任务'),
content: t('c2.tasks.confirmDeleteOne', null, '确定从服务器删除该任务记录吗?此操作不可恢复。'),
onOk: async () => {
try {
await c2.deleteTasks([task.id]);
toastSuccess(t('c2.tasks.toastDeleted', null, '已删除 {{n}} 条').replace('{{n}}', '1'));
reload();
} catch (err) {
toastError(err);
}
}
});
};
const waitForTask = async task => {
try {
const payload = await c2.waitTask(task.id, 20);
if (payload?.task) setDetail(payload.task);
toastSuccess(t('c2.tasks.toastWaited', null, '已获取最新任务状态'));
reload({ silent: true });
} catch (err) {
toastError(err, t('c2.tasks.waitTimeout', null, '等待任务完成超时'));
}
};
const downloadResult = async task => {
try {
await c2.downloadTaskResult(task.id);
toastSuccess(t('c2.tasks.downloadOk', null, '已开始下载'));
} catch (err) {
toastError(err, t('c2.tasks.labelResult', null, '下载结果文件失败'));
}
};
const createTask = async values => {
setSubmitting(true);
try {
await c2.createTask(values);
toastSuccess(t('c2.tasks.toastCreated', null, '任务已下发'));
setCreating(false);
reload();
} catch (err) {
toastError(err, t('c2.tasks.createFailed', null, '下发任务失败'));
} finally {
setSubmitting(false);
}
};
const columns = [
{
title: t('c2.tasks.colTask', null, '任务'),
dataIndex: 'id',
width: 150,
render: id => <span className="c2-mono">{id}</span>
},
{
title: t('c2.tasks.colSession', null, '会话'),
dataIndex: 'sessionId',
width: 150,
render: value => <span className="c2-mono">{value || '—'}</span>
},
{ title: t('c2.tasks.colType', null, '类型'), dataIndex: 'taskType', width: 110 },
{
title: t('c2.tasks.colCommand', null, '命令'),
dataIndex: 'payload',
render: value => {
const command = value?.command || value?.path || '';
return <span className="c2-mono c2-task-command" title={command}>{command || '—'}</span>;
}
},
{
title: t('c2.tasks.colStatus', null, '状态'),
dataIndex: 'status',
width: 110,
render: value => (
<Tag size="small" color={TASK_STATUS_COLOR[value] || 'grey'}>
{t(`c2.tasks.${value || 'queued'}`, null, value || '—')}
</Tag>
)
},
{ title: t('c2.tasks.colDuration', null, '耗时'), dataIndex: 'durationMs', width: 100, render: value => formatDurationMs(value) },
{ title: t('c2.tasks.colCreated', null, '创建时间'), dataIndex: 'createdAt', width: 130, render: value => <TimeText value={value} /> },
{
title: t('c2.tasks.colActions', null, '操作'),
dataIndex: 'actions',
width: 210,
render: (_, task) => (
<Space spacing={4} wrap>
<Button size="small" theme="borderless" onClick={() => setDetail(task)}>{t('c2.tasks.view', null, '查看')}</Button>
{['queued', 'sent', 'running'].includes(task.status) && (
<Button size="small" theme="borderless" onClick={() => cancel(task)}>{t('c2.tasks.cancelBtn', null, '取消')}</Button>
)}
{task.resultBlobPath && (
<Button size="small" theme="borderless" onClick={() => downloadResult(task)}>{t('c2.tasks.downloadResult', null, '结果文件')}</Button>
)}
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(task)}>
{t('c2.tasks.deleteBtn', null, '删除')}
</Button>
</Space>
)
}
];
return (
<div className="c2-page" id="page-c2-tasks">
<PageHeader
title={t('c2.tasks.title', null, '任务管理')}
description={t('c2.tasks.pageDesc', null, '按状态、类型、会话与时间窗筛选任务,5 秒自动轮询最新状态')}
extra={[
<Button key="refresh" icon={<IconRefresh />} onClick={() => reload()} loading={loading}>{t('c2.tasks.refresh', null, '刷新任务')}</Button>,
<Button key="create" theme="solid" type="primary" icon={<IconPlus />} disabled={!canWrite} onClick={() => setCreating(true)}>
{t('c2.tasks.createTitle', null, '下发任务')}
</Button>
]}
/>
<StatGrid metrics={metrics} columns={4} />
<ErrorBanner error={error} onRetry={() => reload()} />
<SectionCard
title={t('c2.tasks.filterTitle', null, '筛选')}
extra={<TimePresetBar value={preset} onChange={value => { setPreset(value); setPage(1); }} ns="tasks" />}
>
<div className="c2-toolbar-fields">
<div className="c2-field">
<span className="c2-field-label">{t('c2.tasks.colStatus', null, '状态')}</span>
<Select
value={status}
onChange={value => { setStatus(value || ''); setPage(1); }}
style={{ width: 160 }}
optionList={[{ value: '', label: t('c2.tasks.filterAllStatuses', null, '全部状态') }, ...TASK_STATUS_OPTIONS]}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.tasks.colType', null, '类型')}</span>
<Select
value={taskType}
onChange={value => { setTaskType(value || ''); setPage(1); }}
style={{ width: 160 }}
optionList={[{ value: '', label: t('c2.tasks.filterAllTypes', null, '全部类型') }, ...TASK_TYPES]}
/>
</div>
<div className="c2-field">
<span className="c2-field-label">{t('c2.tasks.filterSession', null, '会话 ID')}</span>
<Input
value={sessionInput}
onChange={setSessionInput}
onEnterPress={applyFilters}
placeholder={t('c2.tasks.filterSessionPlaceholder', null, 's_xxxxxxxx')}
style={{ width: 190 }}
/>
</div>
<Space spacing={8}>
<Button theme="solid" type="primary" onClick={applyFilters}>{t('c2.tasks.applyFilters', null, '应用筛选')}</Button>
<Button onClick={resetFilters}>{t('c2.tasks.resetFilters', null, '重置')}</Button>
</Space>
</div>
</SectionCard>
<SectionCard title={t('c2.tasks.listTitle', null, '任务列表')}>
<DataTable
columns={columns}
dataSource={tasks}
rowKey="id"
loading={loading}
onRefresh={() => reload()}
pagination={{
currentPage: page,
pageSize,
total,
onPageChange: next => setPage(next),
onPageSizeChange: size => { setPageSize(size); setPage(1); }
}}
emptyText={t('c2.tasks.emptyAll', null, '暂无任务')}
/>
</SectionCard>
<CreateTaskModal
visible={creating}
defaultSessionId={sessionFilter}
submitting={submitting}
onCancel={() => setCreating(false)}
onSubmit={createTask}
/>
<Modal
visible={Boolean(detail)}
title={t('c2.tasks.modalTitle', null, '任务详情')}
width={760}
onCancel={() => setDetail(null)}
footer={(
<Space>
{detail && ['queued', 'sent', 'running'].includes(detail.status) && (
<Button onClick={() => waitForTask(detail)}>{t('c2.tasks.waitBtn', null, '等待完成')}</Button>
)}
{detail?.resultBlobPath && <Button onClick={() => downloadResult(detail)}>{t('c2.tasks.downloadResult', null, '下载结果文件')}</Button>}
<Button onClick={() => setDetail(null)}>{t('c2.tasks.close', null, '关闭')}</Button>
</Space>
)}
>
{detail && (
<div className="c2-task-detail">
<div className="c2-task-detail-meta">
<span className="c2-mono">{detail.id}</span>
<Tag size="small" color={TASK_STATUS_COLOR[detail.status] || 'grey'}>{detail.status}</Tag>
<Text type="tertiary" size="small">{formatDateTime(detail.createdAt)}</Text>
<Text type="tertiary" size="small">{formatDurationMs(detail.durationMs)}</Text>
</div>
<div className="c2-field-label">{t('c2.tasks.labelPayload', null, '参数')}</div>
<pre className="c2-pre">{JSON.stringify(detail.payload || {}, null, 2)}</pre>
{detail.resultText && (
<>
<div className="c2-field-label">{t('c2.tasks.labelResult', null, '输出')}</div>
<pre className="c2-pre">{detail.resultText}</pre>
</>
)}
{detail.error && (
<>
<div className="c2-field-label">{t('c2.tasks.labelError', null, '错误')}</div>
<pre className="c2-pre c2-pre-error">{detail.error}</pre>
</>
)}
</div>
)}
</Modal>
</div>
);
}

View File

@ -0,0 +1,23 @@
/* C2 任务页面私有样式(c2- 前缀)。 */
.c2-task-command {
display: inline-block;
max-width: 320px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: bottom;
}
.c2-task-detail {
display: flex;
flex-direction: column;
gap: 8px;
}
.c2-task-detail-meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}

View File

@ -0,0 +1,125 @@
/**
* 附件预览 Drawer:文本走 /chat-uploads/content,图片走 /chat-uploads/download 二进制。
*/
import { useEffect, useState } from 'react';
import { Button, SideSheet, Spin, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { CopyButton, ErrorBanner, toastError } from '../../components/ui';
import { formatBytes } from '../../lib/format';
import { downloadFileByPath, fetchBlobUrl, getContent } from './api';
const { Text } = Typography;
const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|svg|ico)$/i;
const TEXT_EXT = /\.(txt|log|md|markdown|json|ya?ml|csv|tsv|xml|html?|css|jsx?|tsx?|py|go|java|c|h|cpp|sh|sql|ini|conf|toml|env|pem)$/i;
function kindOf(item) {
const name = item?.name || '';
if (IMAGE_EXT.test(name)) return 'image';
if (TEXT_EXT.test(name)) return 'text';
return 'binary';
}
export default function PreviewDrawer({ item, onClose }) {
const t = useT();
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [text, setText] = useState('');
const [imageUrl, setImageUrl] = useState('');
const [mode, setMode] = useState('text');
useEffect(() => {
let revoked = '';
let cancelled = false;
if (!item) {
setText('');
setImageUrl('');
setError(null);
return () => {};
}
const kind = kindOf(item);
setMode(kind);
setLoading(true);
setError(null);
setText('');
setImageUrl('');
const load = async () => {
try {
if (kind === 'image') {
const result = await fetchBlobUrl(item.relativePath);
if (cancelled) {
URL.revokeObjectURL(result.url);
return;
}
revoked = result.url;
setImageUrl(result.url);
} else if (kind === 'text') {
const payload = await getContent(item.relativePath);
if (cancelled) return;
setText(payload?.content ?? '');
}
} catch (err) {
if (!cancelled) {
setError(err);
// 文本接口拒绝二进制内容时退化为提示下载
if (kind === 'text') setMode('binary');
}
} finally {
if (!cancelled) setLoading(false);
}
};
load();
return () => {
cancelled = true;
if (revoked) URL.revokeObjectURL(revoked);
};
}, [item]);
const download = async () => {
if (!item) return;
try {
await downloadFileByPath(item.relativePath, item.name);
} catch (err) {
toastError(err, t('chatFilesPage.errorGeneric', null, '操作失败,请稍后重试。'));
}
};
return (
<SideSheet
visible={Boolean(item)}
title={item?.name || t('chatFilesPage.previewTitle', null, '文件预览')}
width={720}
onCancel={onClose}
footer={(
<Button onClick={download}>{t('chatFilesPage.download', null, '下载')}</Button>
)}
>
{item && (
<div className="chat-files-preview">
<div className="chat-files-preview-meta">
<Text type="tertiary" size="small">{formatBytes(item.size)}</Text>
<Text type="tertiary" size="small" className="chat-files-mono">{item.relativePath}</Text>
<CopyButton text={item.relativePath} label={t('chatFilesPage.copyPath', null, '复制路径')} size="small" />
</div>
<ErrorBanner error={mode === 'binary' ? null : error} />
{loading && <div className="chat-files-preview-loading"><Spin /></div>}
{!loading && mode === 'image' && imageUrl && (
<img className="chat-files-preview-image" src={imageUrl} alt={item.name} />
)}
{!loading && mode === 'text' && (
<pre className="chat-files-preview-text">{text}</pre>
)}
{!loading && mode === 'binary' && (
<Text type="tertiary">
{t('chatFilesPage.editBinaryHint', null, '图片、压缩包等二进制文件无法在此以文本方式编辑,请使用「下载」后在本地查看或处理。')}
</Text>
)}
</div>
)}
</SideSheet>
);
}

View File

@ -0,0 +1,46 @@
/**
* 对话附件(chat_uploads)接口封装:列表、上传、目录、内容、下载、导出与路径解析。
*/
import { api, downloadFile } from '../../lib/http';
export function listFiles(query) {
return api.get('/chat-uploads', query);
}
export function uploadFile(file, { relativeDir } = {}) {
const form = new FormData();
form.append('file', file, file.name);
if (relativeDir) form.append('relativeDir', relativeDir);
return api.post('/chat-uploads', form);
}
export function makeDirectory(parent, name) {
return api.post('/chat-uploads/mkdir', { parent: parent || '', name });
}
export function deleteFile(path) {
return api.del('/chat-uploads', { body: { path } });
}
export function getContent(path) {
return api.get('/chat-uploads/content', { path });
}
export function resolvePath(path, kind = 'file') {
return api.get('/chat-uploads/path', { path, kind });
}
export function exportFiles(query) {
return downloadFile('/chat-uploads/export', { query, filename: 'chat-files-export.zip' });
}
export function downloadFileByPath(path, filename) {
return downloadFile('/chat-uploads/download', { query: { path }, filename });
}
/** 取二进制内容(图片预览用),返回 objectURL,调用方负责 revoke。 */
export async function fetchBlobUrl(path) {
const response = await api.raw('/chat-uploads/download', { query: { path }, timeout: 120000 });
const blob = await response.blob();
return { url: URL.createObjectURL(blob), type: blob.type, size: blob.size };
}

View File

@ -0,0 +1,424 @@
/**
* 对话附件管理:列表/分页/搜索、文件夹浏览、上传、建目录、预览、下载、导出与删除。
*/
import { useMemo, useRef, useState } from 'react';
import { Button, Input, Modal, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconPlus, IconRefresh, IconSearch, IconUpload } from '@douyinfe/semi-icons';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { useDebounced, useResource } from '../../components/hooks';
import {
PageHeader, SectionCard, DataTable, ErrorBanner,
confirmAction, toastError, toastSuccess, toastWarning
} from '../../components/ui';
import { formatBytes, formatDateTime } from '../../lib/format';
import * as api from './api';
import PreviewDrawer from './PreviewDrawer';
import './page.css';
const { Text } = Typography;
const SOURCE_OPTIONS = [
{ value: 'all', label: '全部' },
{ value: 'upload', label: '对话附件' },
{ value: 'reduction', label: '工具输出' },
{ value: 'workspace', label: '工作目录' },
{ value: 'conversation_artifact', label: '会话产物' }
];
const SOURCE_LABEL = {
upload: '对话附件',
reduction: '工具输出',
workspace: '工作目录',
conversation_artifact: '会话产物'
};
function dirOf(relativePath) {
const parts = String(relativePath || '').split('/');
parts.pop();
return parts.join('/');
}
function baseName(relativePath) {
const parts = String(relativePath || '').split('/');
return parts[parts.length - 1] || relativePath;
}
export default function ChatFilesPage() {
const t = useT();
const { hasPermission } = useAuth();
const canWrite = hasPermission('files:write');
const canDelete = hasPermission('files:delete') || canWrite;
const fileInputRef = useRef(null);
const [mode, setMode] = useState('list');
const [conversation, setConversation] = useState('');
const [project, setProject] = useState('');
const [source, setSource] = useState('all');
const [keyword, setKeyword] = useState('');
const [currentDir, setCurrentDir] = useState('');
const [page, setPage] = useState(1);
const [pageSize, setPageSize] = useState(20);
const [preview, setPreview] = useState(null);
const [mkdir, setMkdir] = useState(null);
const [uploading, setUploading] = useState(false);
const search = useDebounced(keyword, 300);
const query = useMemo(() => {
const base = {
conversation: conversation.trim() || undefined,
project: project.trim() || undefined,
source: source === 'all' ? undefined : source,
search: search.trim() || undefined
};
return mode === 'browse'
? { ...base, page: 1, pageSize: 'all' }
: { ...base, page, pageSize };
}, [mode, conversation, project, source, search, page, pageSize]);
const { data, loading, error, reload } = useResource(() => api.listFiles(query), [query]);
const files = Array.isArray(data?.files) ? data.files : [];
const folders = Array.isArray(data?.folders) ? data.folders : [];
const total = Number(data?.total ?? files.length);
const browsed = useMemo(() => {
if (mode !== 'browse') return { folders: [], files };
return {
folders: folders.filter(folder => dirOf(folder) === currentDir),
files: files.filter(file => dirOf(file.relativePath) === currentDir)
};
}, [mode, folders, files, currentDir]);
const breadcrumb = useMemo(() => {
const parts = currentDir ? currentDir.split('/') : [];
const items = [{ label: t('chatFilesPage.browseRoot', null, '文件'), path: '' }];
parts.forEach((part, index) => items.push({ label: part, path: parts.slice(0, index + 1).join('/') }));
return items;
}, [currentDir, t]);
const copyPath = async item => {
try {
const payload = await api.resolvePath(item.relativePath, 'file');
await navigator.clipboard.writeText(payload?.absolutePath || item.relativePath);
toastSuccess(t('chatFilesPage.pathCopied', null, '路径已复制,可到对话中粘贴使用'));
} catch (err) {
toastError(err, t('chatFilesPage.errorGeneric', null, '操作失败,请稍后重试。'));
}
};
const download = async item => {
try {
await api.downloadFileByPath(item.relativePath, item.name);
} catch (err) {
toastError(err, t('chatFilesPage.errorGeneric', null, '操作失败,请稍后重试。'));
}
};
const remove = item => {
confirmAction({
title: t('chatFilesPage.confirmDelete', null, '确定删除该文件?'),
content: item.relativePath,
onOk: async () => {
try {
await api.deleteFile(item.relativePath);
toastSuccess(t('chatFilesPage.deleted', null, '已删除'));
reload();
} catch (err) {
toastError(err);
}
}
});
};
const pickFiles = () => fileInputRef.current?.click();
const onFilesPicked = async event => {
const list = Array.from(event.target.files || []);
event.target.value = '';
if (!list.length) return;
setUploading(true);
try {
for (const file of list) {
await api.uploadFile(file, { relativeDir: mode === 'browse' ? currentDir : '' });
}
toastSuccess(t('chatFilesPage.uploadOkHint', null, '上传成功。点击「复制路径」可复制绝对路径到剪贴板。'));
reload();
} catch (err) {
toastError(err, t('chatFilesPage.errorGeneric', null, '操作失败,请稍后重试。'));
} finally {
setUploading(false);
}
};
const submitMkdir = async () => {
const name = String(mkdir?.name || '').trim();
if (!name || name.includes('/') || name.includes('\\') || name === '.' || name === '..') {
toastWarning(t('chatFilesPage.mkdirInvalidName', null, '名称无效:不能为空,且不能包含 /、\\ 或 . / ..'));
return;
}
try {
await api.makeDirectory(mode === 'browse' ? currentDir : '', name);
toastSuccess(t('chatFilesPage.mkdirOk', null, '文件夹已创建'));
setMkdir(null);
reload();
} catch (err) {
toastError(err, t('chatFilesPage.errorGeneric', null, '操作失败,请稍后重试。'));
}
};
const exportCurrent = async () => {
try {
await api.exportFiles({
conversation: conversation.trim() || undefined,
project: project.trim() || undefined,
source: source === 'all' ? undefined : source,
search: search.trim() || undefined
});
toastSuccess(t('chatFilesPage.exportStarted', null, '已开始导出当前文件'));
} catch (err) {
toastError(err, t('chatFilesPage.exportEmpty', null, '没有可导出的文件'));
}
};
const fileColumns = [
{
title: t('chatFilesPage.colName', null, '文件名'),
dataIndex: 'name',
render: (name, item) => (
<button type="button" className="chat-files-name" onClick={() => setPreview(item)} title={item.relativePath}>
{name || baseName(item.relativePath)}
</button>
)
},
{
title: t('chatFilesPage.sourceFilter', null, '来源'),
dataIndex: 'source',
width: 110,
render: value => <Tag size="small">{(SOURCE_LABEL[value] || value || '对话附件')}</Tag>
},
{
title: t('chatFilesPage.colConversation', null, '会话'),
dataIndex: 'conversationTitle',
width: 180,
render: (value, item) => <Text type="tertiary" size="small" ellipsis={{ showTooltip: true }}>{value || item.conversationId || '—'}</Text>
},
{
title: t('chatFilesPage.colSubPath', null, '路径'),
dataIndex: 'relativePath',
width: 220,
render: value => <span className="chat-files-path">{value}</span>
},
{ title: t('chatFilesPage.colSize', null, '大小'), dataIndex: 'size', width: 100, render: value => formatBytes(value) },
{
title: t('chatFilesPage.colModified', null, '修改时间'),
dataIndex: 'modifiedUnix',
width: 170,
render: value => formatDateTime(value ? value * 1000 : null)
},
{
title: t('chatFilesPage.colActions', null, '操作'),
dataIndex: 'actions',
width: 260,
render: (_, item) => (
<Space spacing={4} wrap>
<Button size="small" theme="borderless" onClick={() => setPreview(item)}>{t('chatFilesPage.preview', null, '预览')}</Button>
<Button size="small" theme="borderless" onClick={() => copyPath(item)}>{t('chatFilesPage.copyPath', null, '复制路径')}</Button>
<Button size="small" theme="borderless" onClick={() => download(item)}>{t('chatFilesPage.download', null, '下载')}</Button>
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(item)}>
{t('chatFilesPage.delete', null, '删除')}
</Button>
</Space>
)
}
];
const browseColumns = [
{
title: t('chatFilesPage.colName', null, '文件名'),
dataIndex: 'name',
render: (name, item) => (item.isDir ? (
<button type="button" className="chat-files-name is-dir" onClick={() => setCurrentDir(item.path)}>
{name}/
</button>
) : (
<button type="button" className="chat-files-name" onClick={() => setPreview(item)} title={item.relativePath}>
{name}
</button>
))
},
{ title: t('chatFilesPage.colSize', null, '大小'), dataIndex: 'size', width: 110, render: value => (value === undefined ? '—' : formatBytes(value)) },
{
title: t('chatFilesPage.colModified', null, '修改时间'),
dataIndex: 'modifiedUnix',
width: 180,
render: value => (value ? formatDateTime(value * 1000) : '—')
},
{
title: t('chatFilesPage.colActions', null, '操作'),
dataIndex: 'actions',
width: 240,
render: (_, item) => (item.isDir ? (
<Space spacing={4}>
<Button size="small" theme="borderless" onClick={() => setCurrentDir(item.path)}>{t('chatFilesPage.enterFolder', null, '进入')}</Button>
</Space>
) : (
<Space spacing={4} wrap>
<Button size="small" theme="borderless" onClick={() => setPreview(item)}>{t('chatFilesPage.preview', null, '预览')}</Button>
<Button size="small" theme="borderless" onClick={() => copyPath(item)}>{t('chatFilesPage.copyPath', null, '复制路径')}</Button>
<Button size="small" theme="borderless" onClick={() => download(item)}>{t('chatFilesPage.download', null, '下载')}</Button>
<Button size="small" theme="borderless" type="danger" disabled={!canDelete} onClick={() => remove(item)}>
{t('chatFilesPage.delete', null, '删除')}
</Button>
</Space>
))
}
];
const browseRows = [
...browsed.folders.map(folder => ({
rowKey: `dir:${folder}`,
isDir: true,
path: folder,
name: baseName(folder)
})),
...browsed.files.map(item => ({ ...item, rowKey: item.relativePath }))
];
const rows = mode === 'browse' ? browseRows : files;
return (
<div className="chat-files-page" id="page-chat-files">
<PageHeader
title={t('chatFilesPage.title', null, '文件管理')}
description={t('chatFilesPage.intro', null, '管理在对话中上传的文件,可复制路径供 AI 引用')}
extra={[
<Button key="export" onClick={exportCurrent}>{t('chatFilesPage.export', null, '导出当前结果')}</Button>,
<Button key="mkdir" icon={<IconPlus />} disabled={!canWrite} onClick={() => setMkdir({ name: '' })}>
{t('chatFilesPage.newFolderButton', null, '新建文件夹')}
</Button>,
<Button key="upload" theme="solid" type="primary" icon={<IconUpload />} loading={uploading} disabled={!canWrite} onClick={pickFiles}>
{t('chatFilesPage.upload', null, '上传文件')}
</Button>,
<Button key="refresh" icon={<IconRefresh />} onClick={reload} loading={loading}>{t('common.refresh', null, '刷新')}</Button>
]}
/>
<input ref={fileInputRef} type="file" multiple hidden onChange={onFilesPicked} />
<ErrorBanner error={error} onRetry={reload} />
<SectionCard title={t('chatFilesPage.filterTitle', null, '筛选')}>
<div className="chat-files-fields">
<div className="chat-files-field">
<span className="chat-files-field-label">{t('chatFilesPage.conversationFilter', null, '会话 ID')}</span>
<Input
value={conversation}
onChange={value => { setConversation(value); setPage(1); }}
placeholder={t('chatFilesPage.conversationPlaceholder', null, '留空表示全部')}
style={{ width: 200 }}
/>
</div>
<div className="chat-files-field">
<span className="chat-files-field-label">{t('chatFilesPage.projectFilter', null, '项目 ID')}</span>
<Input
value={project}
onChange={value => { setProject(value); setPage(1); }}
placeholder={t('chatFilesPage.projectPlaceholder', null, '留空表示全部')}
style={{ width: 200 }}
/>
</div>
<div className="chat-files-field">
<span className="chat-files-field-label">{t('chatFilesPage.searchName', null, '文件名')}</span>
<Input
value={keyword}
onChange={value => { setKeyword(value); setPage(1); }}
prefix={<IconSearch />}
placeholder={t('chatFilesPage.searchNamePlaceholder', null, '筛选文件名')}
style={{ width: 200 }}
/>
</div>
<div className="chat-files-field">
<span className="chat-files-field-label">{t('chatFilesPage.sourceFilter', null, '来源')}</span>
<Select
value={source}
onChange={value => { setSource(value || 'all'); setPage(1); }}
optionList={SOURCE_OPTIONS}
style={{ width: 160 }}
/>
</div>
<div className="chat-files-field">
<span className="chat-files-field-label">{t('chatFilesPage.groupBy', null, '分组方式')}</span>
<Select
value={mode}
onChange={value => { setMode(value || 'list'); setPage(1); setCurrentDir(''); }}
optionList={[
{ value: 'list', label: t('chatFilesPage.groupNone', null, '不分组(平铺)') },
{ value: 'browse', label: t('chatFilesPage.groupByFolder', null, '按文件夹(路径浏览)') }
]}
style={{ width: 200 }}
/>
</div>
</div>
</SectionCard>
{mode === 'browse' && (
<nav className="chat-files-breadcrumb" aria-label="breadcrumb">
{breadcrumb.map((segment, index) => (
<span key={segment.path || 'root'} className="chat-files-breadcrumb-item">
{index > 0 && <span className="chat-files-breadcrumb-sep">/</span>}
<button type="button" onClick={() => setCurrentDir(segment.path)}>{segment.label}</button>
</span>
))}
</nav>
)}
<SectionCard
title={mode === 'browse'
? t('chatFilesPage.browseRoot', null, '文件')
: t('chatFilesPage.listTitle', null, '附件列表')}
extra={<Text type="tertiary" size="small">{t('chatFilesPage.paginationInfo', null, '显示 {{start}}-{{end}} / {{total}} 个文件')
.replace('{{start}}', rows.length ? '1' : '0')
.replace('{{end}}', String(rows.length))
.replace('{{total}}', String(mode === 'browse' ? rows.length : total))}</Text>}
>
<DataTable
columns={mode === 'browse' ? browseColumns : fileColumns}
dataSource={rows}
rowKey={item => item.rowKey || item.relativePath}
loading={loading}
onRefresh={reload}
pagination={mode === 'browse' ? false : {
currentPage: page,
pageSize,
total,
onPageChange: next => setPage(next),
onPageSizeChange: size => { setPageSize(size); setPage(1); }
}}
emptyText={mode === 'browse'
? t('chatFilesPage.folderEmpty', null, '此文件夹为空')
: t('chatFilesPage.empty', null, '暂无对话附件')}
/>
</SectionCard>
<PreviewDrawer item={preview} onClose={() => setPreview(null)} />
<Modal
visible={Boolean(mkdir)}
title={t('chatFilesPage.newFolderTitle', null, '新建文件夹')}
width={420}
onCancel={() => setMkdir(null)}
onOk={submitMkdir}
>
<Text type="tertiary" size="small">
{t('chatFilesPage.newFolderLocation', null, '位置')}:{mode === 'browse' && currentDir ? currentDir : '/'}
</Text>
<Input
value={mkdir?.name || ''}
onChange={value => setMkdir({ name: value })}
placeholder={t('chatFilesPage.newFolderNamePlaceholder', null, '仅名称,不含 /')}
style={{ marginTop: 8 }}
/>
</Modal>
</div>
);
}

View File

@ -0,0 +1,116 @@
/* 对话附件页面私有样式(chat-files- 前缀)。 */
.chat-files-page {
display: flex;
flex-direction: column;
gap: 12px;
}
.chat-files-fields {
display: flex;
align-items: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.chat-files-field {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 160px;
}
.chat-files-field-label {
font-size: 12px;
color: var(--semi-color-text-2);
}
.chat-files-name {
border: none;
background: none;
padding: 0;
cursor: pointer;
color: var(--semi-color-link);
text-align: left;
word-break: break-all;
}
.chat-files-name.is-dir {
font-weight: 600;
}
.chat-files-path {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
color: var(--semi-color-text-2);
word-break: break-all;
}
.chat-files-breadcrumb {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 2px;
font-size: 12px;
}
.chat-files-breadcrumb-item button {
border: none;
background: none;
padding: 2px 4px;
cursor: pointer;
color: var(--semi-color-link);
}
.chat-files-breadcrumb-sep {
color: var(--semi-color-text-3);
}
.chat-files-preview {
display: flex;
flex-direction: column;
gap: 10px;
}
.chat-files-preview-meta {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.chat-files-mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
word-break: break-all;
}
.chat-files-preview-loading {
display: flex;
justify-content: center;
padding: 32px 0;
}
.chat-files-preview-text {
margin: 0;
padding: 10px;
border-radius: 6px;
border: 1px solid var(--semi-color-border);
background: var(--semi-color-fill-0);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
white-space: pre-wrap;
word-break: break-all;
max-height: 60vh;
overflow: auto;
}
.chat-files-preview-image {
max-width: 100%;
max-height: 60vh;
object-fit: contain;
border: 1px solid var(--semi-color-border);
border-radius: 6px;
background: var(--semi-color-fill-0);
}

Some files were not shown because too many files have changed in this diff Show More