feat(projects): link project memory and vulnerability archives

This commit is contained in:
Sycun 2026-11-26 17:50:36 +08:00
parent 6e0a6854fb
commit 480f1ae7e2
65 changed files with 557 additions and 118 deletions

View File

@ -1404,6 +1404,7 @@ func setupRoutes(
protected.POST("/vulnerabilities", vulnerabilityHandler.CreateVulnerability)
protected.POST("/vulnerabilities/:id/retest", vulnerabilityHandler.CreateRetest)
protected.PUT("/vulnerabilities/:id", vulnerabilityHandler.UpdateVulnerability)
protected.PUT("/vulnerabilities/:id/archive", vulnerabilityHandler.SetVulnerabilityArchived)
protected.DELETE("/vulnerabilities/:id", vulnerabilityHandler.DeleteVulnerability)
// 项目管理与事实黑板

View File

@ -26,6 +26,13 @@ func projectIDFromConversation(db *database.DB, ctx context.Context) (string, er
if strings.TrimSpace(pid) == "" {
return "", fmt.Errorf("当前对话未绑定项目,请先在对话中选择项目或创建带项目的对话")
}
p, err := db.GetProject(pid)
if err != nil {
return "", err
}
if p.Status == database.ProjectStatusArchived {
return "", fmt.Errorf("项目已归档,恢复项目后可在对话中使用项目事实")
}
return pid, nil
}

View File

@ -62,7 +62,9 @@ func buildVulnerabilityListFilter(db *database.DB, ctx context.Context, args map
}
}
archived := false
filter := database.VulnerabilityListFilter{
Archived: &archived,
Severity: strings.TrimSpace(strArg(args, "severity")),
Status: strings.TrimSpace(strArg(args, "status")),
}

View File

@ -2,6 +2,7 @@ package database
import (
"database/sql"
"errors"
"fmt"
"regexp"
"strings"
@ -12,6 +13,10 @@ import (
var factKeyPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._/-]*$`)
const ProjectStatusArchived = "archived"
var ErrProjectNotFound = errors.New("项目不存在")
// ValidateFactKey 校验事实 key(项目内唯一标识)。
func ValidateFactKey(key string) error {
if key != strings.TrimSpace(key) {
@ -101,7 +106,10 @@ func (db *DB) SaveContextCheckpoint(f *ProjectFact) error {
result, err := db.Exec(`INSERT INTO project_facts
(id, project_id, fact_key, category, summary, body, confidence, source_conversation_id, pinned, created_at, updated_at)
SELECT ?, ?, ?, 'note', ?, ?, 'tentative', ?, 0, ?, ?
WHERE EXISTS (SELECT 1 FROM conversations WHERE id = ? AND project_id = ?)
WHERE EXISTS (
SELECT 1 FROM conversations c JOIN projects p ON p.id = c.project_id
WHERE c.id = ? AND c.project_id = ? AND p.status != 'archived'
)
ON CONFLICT(project_id, fact_key) DO UPDATE SET
category = 'note', summary = excluded.summary, body = excluded.body,
confidence = 'tentative', source_conversation_id = excluded.source_conversation_id,
@ -116,7 +124,7 @@ func (db *DB) SaveContextCheckpoint(f *ProjectFact) error {
return err
}
if changed == 0 {
return fmt.Errorf("checkpoint project does not match current conversation binding")
return fmt.Errorf("checkpoint requires a matching project that is not archived")
}
return nil
}
@ -165,7 +173,7 @@ func (db *DB) GetProject(id string) (*Project, error) {
).Scan(&p.ID, &p.Name, &p.Description, &p.ScopeJSON, &p.Status, &pinned, &createdAt, &updatedAt)
if err != nil {
if err == sql.ErrNoRows {
return nil, fmt.Errorf("项目不存在")
return nil, ErrProjectNotFound
}
return nil, fmt.Errorf("获取项目失败: %w", err)
}
@ -327,17 +335,33 @@ func (db *DB) ListProjectsForAccess(status, search string, limit, offset int, us
return out, rows.Err()
}
// UpdateProject 更新项目。
func (db *DB) UpdateProject(p *Project) error {
p.UpdatedAt = time.Now()
_, err := db.Exec(
`UPDATE projects SET name = ?, description = ?, scope_json = ?, status = ?, pinned = ?, updated_at = ? WHERE id = ?`,
p.Name, p.Description, p.ScopeJSON, p.Status, boolToInt(p.Pinned), p.UpdatedAt, p.ID,
// ProjectUpdate contains only the fields supplied for a partial update.
type ProjectUpdate struct {
Name *string `json:"name"`
Description *string `json:"description"`
ScopeJSON *string `json:"scope_json"`
Status *string `json:"status"`
Pinned *bool `json:"pinned"`
}
func (db *DB) UpdateProject(id string, update ProjectUpdate) (*Project, error) {
result, err := db.Exec(
`UPDATE projects SET name = COALESCE(?, name), description = COALESCE(?, description),
scope_json = COALESCE(?, scope_json), status = COALESCE(NULLIF(?, ''), status),
pinned = COALESCE(?, pinned), updated_at = ? WHERE id = ?`,
update.Name, update.Description, update.ScopeJSON, update.Status, update.Pinned, time.Now(), id,
)
if err != nil {
return fmt.Errorf("更新项目失败: %w", err)
return nil, fmt.Errorf("更新项目失败: %w", err)
}
return nil
count, err := result.RowsAffected()
if err != nil {
return nil, err
}
if count == 0 {
return nil, ErrProjectNotFound
}
return db.GetProject(id)
}
// DeleteProject 删除项目(级联删除事实;对话 project_id 置空由 FK 处理;其他资源 project_id 置空)。

View File

@ -528,6 +528,7 @@ CREATE TABLE vulnerabilities (
description TEXT,
severity TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'open',
manually_archived INTEGER NOT NULL DEFAULT 0,
vulnerability_type TEXT,
target TEXT,
targets_json TEXT NOT NULL DEFAULT '[]',

View File

@ -18,8 +18,17 @@ import (
var ErrVulnerabilityNotFound = errors.New("漏洞不存在")
// Project archiving is inherited so that restoring a project preserves manual archives.
const vulnerabilityProjectArchivedSQL = `EXISTS (
SELECT 1 FROM projects archive_project
WHERE archive_project.id = vulnerabilities.project_id AND archive_project.status = 'archived'
)`
const vulnerabilityArchivedSQL = "(vulnerabilities.manually_archived != 0 OR " + vulnerabilityProjectArchivedSQL + ")"
// VulnerabilityListFilter 列表/统计/导出共用的筛选条件
type VulnerabilityListFilter struct {
Archived *bool // nil includes active and archived records
BrowserSelection string
AssessmentID string
AssessmentStepID string
@ -52,6 +61,10 @@ func escapeVulnerabilityLikePattern(s string) string {
func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) (string, []interface{}) {
query, args = appendVulnerabilitySelection(query, args, f.BrowserSelection)
if f.Archived != nil {
query += " AND " + vulnerabilityArchivedSQL + " = ?"
args = append(args, *f.Archived)
}
if host := strings.TrimSpace(f.HostQuery); host != "" {
query += ` AND EXISTS (SELECT 1 FROM json_each(targets_json) jt WHERE json_extract(jt.value,'$.host') LIKE ? ESCAPE '\')`
args = append(args, escapeVulnerabilityLikePattern(strings.ToLower(host)))
@ -190,6 +203,8 @@ type Vulnerability struct {
Description string `json:"description"`
Severity string `json:"severity"` // critical, high, medium, low, info
Status string `json:"status"` // open, confirmed, fixed, false_positive, ignored
Archived bool `json:"archived"`
ProjectArchived bool `json:"project_archived"`
Type string `json:"type"`
Target string `json:"target"`
TargetHost *string `json:"target_host,omitempty"`
@ -271,6 +286,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) {
var targets string
query := `
SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, COALESCE(description,''), severity, status,
manually_archived, ` + vulnerabilityProjectArchivedSQL + `,
COALESCE(conversation_tag,''), COALESCE(task_tag,''), COALESCE(vulnerability_type,''), COALESCE(target,''),
COALESCE(preconditions,''), COALESCE(reproduction_steps,''), COALESCE(evidence,''),
COALESCE(impact,''), COALESCE(recommendation,''), COALESCE(retest_notes,''), COALESCE(retest_log,''),
@ -282,9 +298,10 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) {
WHERE id = ?
`
var manuallyArchived bool
err := db.QueryRow(query, id).Scan(
&vuln.ID, &vuln.ConversationID, &vuln.ProjectID, &vuln.Title, &vuln.Description,
&vuln.Severity, &vuln.Status, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target,
&vuln.Severity, &vuln.Status, &manuallyArchived, &vuln.ProjectArchived, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target,
&vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes,
&vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID,
&vuln.CreatedAt, &vuln.UpdatedAt, &targets, &vuln.CaseID, &vuln.CaseTitle,
@ -297,6 +314,7 @@ func (db *DB) GetVulnerability(id string) (*Vulnerability, error) {
return nil, fmt.Errorf("获取漏洞失败: %w", err)
}
vuln.Archived = manuallyArchived || vuln.ProjectArchived
if vuln.AssessmentID != "" {
vuln.AssessmentReviews, err = db.AssessmentFindingReviews(vuln.ID)
if err != nil {
@ -455,7 +473,8 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln
details = "'','','','','','',''"
}
query := prefix + `
SELECT vulnerabilities.id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, ` + description + `, severity, status, COALESCE(conversation_tag,''), COALESCE(task_tag,''),
SELECT vulnerabilities.id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, ` + description + `, severity, status,
manually_archived, ` + vulnerabilityProjectArchivedSQL + `, COALESCE(conversation_tag,''), COALESCE(task_tag,''),
COALESCE(vulnerability_type,''), COALESCE(target,''),
` + details + `,
` + vulnerabilityTaskIDExpr + ` AS task_id,
@ -486,9 +505,10 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln
for rows.Next() {
var vuln Vulnerability
var targets string
var manuallyArchived bool
err := rows.Scan(
&vuln.ID, &vuln.ConversationID, &vuln.ProjectID, &vuln.Title, &vuln.Description,
&vuln.Severity, &vuln.Status, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target,
&vuln.Severity, &vuln.Status, &manuallyArchived, &vuln.ProjectArchived, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target,
&vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes,
&vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, &vuln.TaskQueueTitle,
&vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost, &targets, &vuln.CaseID, &vuln.CaseTitle,
@ -498,6 +518,7 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln
db.logger.Warn("扫描漏洞记录失败", zap.Error(err))
continue
}
vuln.Archived = manuallyArchived || vuln.ProjectArchived
if vuln.TargetHost != nil {
vuln.TargetDomain = *vuln.TargetHost
if _, err := netip.ParseAddr(*vuln.TargetHost); err != nil {
@ -536,6 +557,19 @@ func (db *DB) CountVulnerabilitiesForAccess(filter VulnerabilityListFilter, acce
return count, nil
}
// SetVulnerabilityArchived updates only the manual archive flag.
func (db *DB) SetVulnerabilityArchived(id string, archived bool) error {
result, err := db.Exec("UPDATE vulnerabilities SET manually_archived = ? WHERE id = ?", archived, id)
if err != nil {
return err
}
count, err := result.RowsAffected()
if err == nil && count == 0 {
return ErrVulnerabilityNotFound
}
return err
}
// UpdateVulnerability 更新漏洞
func (db *DB) UpdateVulnerability(id string, vuln *Vulnerability) error {
vuln.UpdatedAt = time.Now()
@ -733,10 +767,10 @@ func (db *DB) GetVulnerabilityStatsForAccess(filter VulnerabilityListFilter, acc
// GetVulnerabilityFilterOptions 获取漏洞筛选建议项
func (db *DB) GetVulnerabilityFilterOptions() (map[string][]string, error) {
return db.GetVulnerabilityFilterOptionsForAccess(RBACListAccess{})
return db.GetVulnerabilityFilterOptionsForAccess(RBACListAccess{}, nil)
}
func (db *DB) GetVulnerabilityFilterOptionsForAccess(access RBACListAccess) (map[string][]string, error) {
func (db *DB) GetVulnerabilityFilterOptionsForAccess(access RBACListAccess, archived *bool) (map[string][]string, error) {
collect := func(query string, args ...interface{}) ([]string, error) {
rows, err := db.Query(query, args...)
if err != nil {
@ -757,8 +791,7 @@ func (db *DB) GetVulnerabilityFilterOptionsForAccess(access RBACListAccess) (map
return items, nil
}
where := "WHERE 1=1"
accessArgs := []interface{}{}
where, accessArgs := (VulnerabilityListFilter{Archived: archived}).appendWhere("WHERE 1=1", nil)
where, accessArgs = appendVulnerabilityAccessFilter(where, accessArgs, access)
vulnIDs, err := collect(`SELECT DISTINCT id FROM vulnerabilities `+where+` ORDER BY created_at DESC LIMIT 500`, accessArgs...)

View File

@ -45,6 +45,12 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
},
},
}
vulnerabilityArchiveParameter := map[string]interface{}{
"name": "archived",
"in": "query",
"description": "false 仅查看未归档漏洞,true 仅查看已归档漏洞,all 查看全部。",
"schema": map[string]interface{}{"type": "string", "enum": []string{"false", "true", "all"}, "default": "false"},
}
spec := map[string]interface{}{
"openapi": "3.0.0",
@ -310,6 +316,8 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"description": "状态",
"enum": []string{"open", "confirmed", "fixed", "false_positive", "ignored"},
},
"archived": map[string]interface{}{"type": "boolean", "description": "漏洞已单独归档或随所属项目归档"},
"project_archived": map[string]interface{}{"type": "boolean", "description": "所属项目处于归档状态"},
"target": map[string]interface{}{
"type": "string",
"description": "受影响的目标",
@ -2448,6 +2456,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"description": "获取漏洞列表,支持分页和筛选",
"operationId": "listVulnerabilities",
"parameters": []map[string]interface{}{
vulnerabilityArchiveParameter,
{
"name": "limit",
"in": "query",
@ -2586,6 +2595,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
"summary": "获取漏洞统计",
"description": "获取漏洞统计信息",
"operationId": "getVulnerabilityStats",
"parameters": []map[string]interface{}{vulnerabilityArchiveParameter},
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "获取成功",
@ -2603,6 +2613,32 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
},
},
},
"/api/vulnerabilities/{id}/archive": map[string]interface{}{
"put": map[string]interface{}{
"tags": []string{"漏洞管理"},
"summary": "归档或恢复单条漏洞",
"description": "更新漏洞的单独归档状态。所属项目归档时,漏洞随项目保持归档。",
"operationId": "setVulnerabilityArchived",
"parameters": []map[string]interface{}{{
"name": "id", "in": "path", "required": true,
"schema": map[string]interface{}{"type": "string"},
}},
"requestBody": map[string]interface{}{
"required": true,
"content": map[string]interface{}{"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object", "required": []string{"archived"},
"properties": map[string]interface{}{"archived": map[string]interface{}{"type": "boolean"}},
},
}},
},
"responses": map[string]interface{}{
"200": map[string]interface{}{"description": "归档状态已保存"},
"400": map[string]interface{}{"description": "缺少有效的 archived 字段"},
"404": map[string]interface{}{"description": "漏洞不存在"},
},
},
},
"/api/vulnerabilities/{id}": map[string]interface{}{
"get": map[string]interface{}{
"tags": []string{"漏洞管理"},

View File

@ -43,15 +43,6 @@ type createProjectRequest struct {
Status string `json:"status"`
}
// updateProjectRequest 部分更新:字段省略表示不修改;传 null 或 "" 可清空字符串字段。
type updateProjectRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
ScopeJSON *string `json:"scope_json"`
Status *string `json:"status"`
Pinned *bool `json:"pinned"`
}
// CreateProject POST /api/projects
func (h *ProjectHandler) CreateProject(c *gin.Context) {
var req createProjectRequest
@ -186,13 +177,7 @@ func (h *ProjectHandler) GetProject(c *gin.Context) {
// UpdateProject PUT /api/projects/:id
func (h *ProjectHandler) UpdateProject(c *gin.Context) {
id := c.Param("id")
p, err := h.db.GetProject(id)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "项目不存在"})
return
}
var req updateProjectRequest
var req database.ProjectUpdate
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@ -203,23 +188,22 @@ func (h *ProjectHandler) UpdateProject(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "项目名称不能为空"})
return
}
p.Name = s
req.Name = &s
}
if req.Description != nil {
p.Description = clampProjectDescription(*req.Description)
}
if req.ScopeJSON != nil {
p.ScopeJSON = *req.ScopeJSON
s := clampProjectDescription(*req.Description)
req.Description = &s
}
if req.Status != nil {
if s := strings.TrimSpace(*req.Status); s != "" {
p.Status = s
}
s := strings.TrimSpace(*req.Status)
req.Status = &s
}
if req.Pinned != nil {
p.Pinned = *req.Pinned
p, err := h.db.UpdateProject(c.Param("id"), req)
if err == database.ErrProjectNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
if err := h.db.UpdateProject(p); err != nil {
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}

View File

@ -168,6 +168,7 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt
q = strings.TrimSpace(c.Query("search"))
}
return database.VulnerabilityListFilter{
Archived: vulnerabilityArchiveFilter(c),
ProjectID: c.Query("project_id"),
ID: c.Query("id"),
Search: q,
@ -185,6 +186,15 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt
}
}
func vulnerabilityArchiveFilter(c *gin.Context) *bool {
value := c.Query("archived")
if value == "all" {
return nil
}
archived := value == "true"
return &archived
}
// ListVulnerabilities 列出漏洞
func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
limitStr := c.DefaultQuery("limit", "20")
@ -399,6 +409,38 @@ func (h *VulnerabilityHandler) UpdateVulnerability(c *gin.Context) {
c.JSON(http.StatusOK, updated)
}
// SetVulnerabilityArchived PUT /api/vulnerabilities/:id/archive
func (h *VulnerabilityHandler) SetVulnerabilityArchived(c *gin.Context) {
id := c.Param("id")
var req struct {
Archived *bool `json:"archived" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := h.db.SetVulnerabilityArchived(id, *req.Archived)
if err == database.ErrVulnerabilityNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
return
}
if err != nil {
h.logger.Error("更新漏洞归档状态失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "更新漏洞归档状态失败"})
return
}
if h.audit != nil {
action, message := "archive", "归档漏洞"
if !*req.Archived {
action, message = "restore", "恢复漏洞"
}
h.audit.RecordOK(c, "vulnerability", action, message, "vulnerability", id, nil)
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// DeleteVulnerability 删除漏洞
func (h *VulnerabilityHandler) DeleteVulnerability(c *gin.Context) {
id := c.Param("id")
@ -473,7 +515,7 @@ func (h *VulnerabilityHandler) GetVulnerabilityStats(c *gin.Context) {
// GetVulnerabilityFilterOptions 获取漏洞筛选建议项
func (h *VulnerabilityHandler) GetVulnerabilityFilterOptions(c *gin.Context) {
options, err := h.db.GetVulnerabilityFilterOptionsForAccess(vulnerabilityAccessFromContext(c))
options, err := h.db.GetVulnerabilityFilterOptionsForAccess(vulnerabilityAccessFromContext(c), vulnerabilityArchiveFilter(c))
if err != nil {
h.logger.Error("获取漏洞筛选建议失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})

View File

@ -0,0 +1,140 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/project"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestProjectArchiveFollowsProjectAndPreservesManualVulnerabilityArchive(t *testing.T) {
logger := zap.NewNop()
db, err := database.NewDB(filepath.Join(t.TempDir(), "archive.db"), logger)
if err != nil {
t.Fatal(err)
}
defer db.Close()
p, err := db.CreateProject(&database.Project{Name: "Archive example"})
if err != nil {
t.Fatal(err)
}
conv, err := db.CreateConversation("Example", database.ConversationCreateMeta{ProjectID: p.ID})
if err != nil {
t.Fatal(err)
}
memory := &database.ProjectFact{ProjectID: p.ID, FactKey: "note/context-example", Summary: "Original memory", SourceConversationID: conv.ID}
if err := db.SaveContextCheckpoint(memory); err != nil {
t.Fatal(err)
}
for _, v := range []*database.Vulnerability{
{ID: "linked", ConversationID: conv.ID, Title: "Linked record", Description: "Saved description", Severity: "medium", Status: "confirmed", TaskTag: "linked-task"},
{ID: "manual", ProjectID: p.ID, Title: "Manual archive", Severity: "low"},
{ID: "unbound", Title: "Independent record", Severity: "low", TaskTag: "unbound-task"},
} {
if _, err := db.CreateVulnerability(v); err != nil {
t.Fatal(err)
}
}
vulns := NewVulnerabilityHandler(db, logger)
projects := NewProjectHandler(db, logger)
router := gin.New()
router.PUT("/projects/:id", projects.UpdateProject)
router.GET("/vulnerabilities/:id", vulns.GetVulnerability)
router.GET("/vulnerabilities", vulns.ListVulnerabilities)
router.GET("/vulnerabilities/stats", vulns.GetVulnerabilityStats)
router.GET("/vulnerabilities/filter-options", vulns.GetVulnerabilityFilterOptions)
router.GET("/vulnerabilities/export", vulns.ExportVulnerabilities)
router.PUT("/vulnerabilities/:id/archive", vulns.SetVulnerabilityArchived)
request := func(method, path, body string, status int, into any) {
t.Helper()
w := httptest.NewRecorder()
router.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
if w.Code != status {
t.Fatalf("%s %s: got %d, want %d, body %s", method, path, w.Code, status, w.Body)
}
if into != nil {
if err := json.Unmarshal(w.Body.Bytes(), into); err != nil {
t.Fatal(err)
}
}
}
request(http.MethodPut, "/vulnerabilities/manual/archive", `{}`, http.StatusBadRequest, nil)
request(http.MethodPut, "/vulnerabilities/manual/archive", `{"archived":true}`, http.StatusOK, nil)
request(http.MethodPut, "/projects/"+p.ID, `{"status":"archived"}`, http.StatusOK, nil)
request(http.MethodPut, "/projects/"+p.ID, `{"description":"Retained"}`, http.StatusOK, nil)
request(http.MethodPut, "/vulnerabilities/linked/archive", `{"archived":false}`, http.StatusOK, nil)
cfg := config.ProjectConfig{Enabled: true}
block, err := project.BuildFactIndexBlock(db, p.ID, cfg, conv.ID)
if err != nil || block != "" {
t.Fatalf("archived memory was injected: %q, %v", block, err)
}
memory.Summary = "New checkpoint after archive"
if err := db.SaveContextCheckpoint(memory); err == nil {
t.Fatal("archived project accepted a new automatic checkpoint")
}
var active, archived ListVulnerabilitiesResponse
const listURL = "/vulnerabilities?pagination=records&group_by=task"
request(http.MethodGet, listURL, "", http.StatusOK, &active)
request(http.MethodGet, listURL+"&archived=true", "", http.StatusOK, &archived)
if active.Total != 1 || len(active.Vulnerabilities) != 1 || active.Vulnerabilities[0].ID != "unbound" ||
len(active.Navigation) != 1 || active.Navigation[0].Key != "tag:unbound-task" || archived.Total != 2 || len(archived.Vulnerabilities) != 2 {
t.Fatalf("archive listing or grouping mismatch: active %+v, archived %+v", active, archived)
}
for _, v := range archived.Vulnerabilities {
if !v.Archived || !v.ProjectArchived {
t.Fatalf("missing archive fields on %s", v.ID)
}
}
var linked database.Vulnerability
request(http.MethodGet, "/vulnerabilities/linked", "", http.StatusOK, &linked)
if !linked.Archived || !linked.ProjectArchived || linked.Status != "confirmed" || linked.Description != "Saved description" {
t.Fatalf("archiving changed the finding or lost its status: %+v", linked)
}
var count struct{ Total int }
request(http.MethodGet, "/vulnerabilities/stats", "", http.StatusOK, &count)
if count.Total != 1 {
t.Fatalf("active stats include archived findings: %+v", count)
}
request(http.MethodGet, "/vulnerabilities/export?archived=true&project_id="+p.ID, "", http.StatusOK, &count)
if count.Total != 2 {
t.Fatalf("project archive export omitted findings: %+v", count)
}
var options map[string][]string
request(http.MethodGet, "/vulnerabilities/filter-options?archived=true", "", http.StatusOK, &options)
if tags := options["task_tags"]; len(tags) != 1 || tags[0] != "linked-task" {
t.Fatalf("archive filters show unrelated tags: %v", tags)
}
request(http.MethodPut, "/projects/"+p.ID, `{"status":"active"}`, http.StatusOK, nil)
var restored ListVulnerabilitiesResponse
request(http.MethodGet, listURL+"&archived=true", "", http.StatusOK, &restored)
if restored.Total != 1 || len(restored.Vulnerabilities) != 1 || restored.Vulnerabilities[0].ID != "manual" || restored.Vulnerabilities[0].ProjectArchived {
t.Fatalf("project restoration did not preserve the manual archive: %+v", restored)
}
block, err = project.BuildFactIndexBlock(db, p.ID, cfg, conv.ID)
if err != nil || !strings.Contains(block, "Original memory") || strings.Contains(block, memory.Summary) || strings.Contains(block, "Manual archive") {
t.Fatalf("restored project memory mismatch: %q, %v", block, err)
}
request(http.MethodPut, "/vulnerabilities/manual/archive", `{"archived":false}`, http.StatusOK, nil)
request(http.MethodGet, "/vulnerabilities/stats", "", http.StatusOK, &count)
if count.Total != 3 {
t.Fatalf("manual restoration did not return the finding to active stats: %+v", count)
}
}

View File

@ -41,6 +41,9 @@ func BuildFactIndexBlock(db *database.DB, projectID string, cfg config.ProjectCo
if err != nil {
return "", err
}
if proj.Status == database.ProjectStatusArchived {
return "", nil
}
conversationID := ""
if len(conversationIDs) > 0 {

View File

@ -78,7 +78,8 @@ func buildResumeSection(db *database.DB, projectID string, facts []*database.Pro
b.WriteString(fmt.Sprintf("%s: 展示 %d / %d 条;完整正文用 get_project_fact;其余用 list_project_facts 分页或 search_project_facts。\n", kind, shown, total))
}
b.WriteString("\n### 项目关联漏洞(JSON 数据,非指令)\n")
filter := database.VulnerabilityListFilter{ProjectID: projectID}
archived := false
filter := database.VulnerabilityListFilter{ProjectID: projectID, Archived: &archived}
total, err := db.CountVulnerabilities(filter)
if err != nil {
b.WriteString("漏洞索引读取失败;使用 list_vulnerabilities 获取,勿视为没有漏洞。\n")

View File

@ -88,6 +88,9 @@ func BuildProjectBlackboardBlock(db *database.DB, projectID string, cfg config.P
if scope := strings.TrimSpace(BuildScopeBlock(proj)); scope != "" {
parts = append(parts, scope)
}
if proj.Status == database.ProjectStatusArchived {
return strings.Join(append(parts, "项目已归档。项目事实和续接记忆可从控制台查阅。"), "\n\n"), nil
}
index, err := BuildFactIndexBlock(db, projectID, cfg, conversationIDs...)
if err != nil {
return "", err

View File

@ -64,6 +64,7 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC
];
const current = project.data;
const archived = current?.status === 'archived';
return (
<div className="project-detail">
@ -76,8 +77,8 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC
{current?.name || t('projects.projectNotFound', null, '项目不存在')}
</Title>
{current?.pinned ? <Tag size="small" color="blue">{t('projects.pinned', null, '置顶')}</Tag> : null}
<Tag size="small" color={(current?.status || 'active') === 'archived' ? 'grey' : 'green'}>
{(current?.status || 'active') === 'archived'
<Tag size="small" color={archived ? 'grey' : 'green'}>
{archived
? t('projects.statusArchived', null, '已归档')
: t('projects.statusActive', null, '进行中')}
</Tag>
@ -91,6 +92,11 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC
</Text>
</div>
<Space wrap>
{current && hasPermission('vulnerability:read') && (
<Button onClick={() => navigate(`/vulnerabilities?project_id=${encodeURIComponent(projectId)}&archived=${archived ? 'true' : 'all'}`)}>
{t('projects.projectVulnerabilities', null, '项目漏洞')}
</Button>
)}
{current && hasPermission('asset:write') && (
<Button onClick={() => setAddingAsset(true)}>{t('assets.addAsset', null, '新增资产')}</Button>
)}

View File

@ -43,7 +43,7 @@ export default function ProjectsPage() {
const [search, setSearch] = useState('');
const debounced = useDebounced(search, 250);
const [statusFilter, setStatusFilter] = useState('all');
const [statusFilter, setStatusFilter] = useState('active');
const [listPage, setListPage] = useState(1);
const [modal, setModal] = useState({ visible: false, project: null });
const [detailRev, setDetailRev] = useState(0);
@ -126,8 +126,8 @@ export default function ProjectsPage() {
confirmAction({
title: archived ? t('projects.restoreProjectActive', null, '恢复为进行中') : t('projects.archiveProject', null, '归档'),
content: archived
? t('projects.confirmRestoreProjectActive', null, '恢复为 active?')
: t('projects.confirmArchiveProject', null, '归档后默认不再出现在活跃列表,是否继续?'),
? t('projects.confirmRestoreProjectActive', null, '恢复后,项目记忆与随项目归档的漏洞将重新启用。单独归档的漏洞仍保留在归档列表。')
: t('projects.confirmArchiveProject', null, '项目记忆和关联漏洞将随项目归档,可从已归档项目中查阅。是否继续?'),
okText: t('common.confirm', null, '确认'),
danger: !archived,
onOk: async () => {
@ -253,7 +253,7 @@ export default function ProjectsPage() {
rowKey="id"
loading={overview.loading}
pagination={false}
emptyText={search || statusFilter !== 'all'
emptyText={search || projects.length > 0
? t('projects.noMatchingProjects', null, '无匹配项目')
: t('projects.noProjects', null, '暂无项目')}
onRow={record => ({

View File

@ -65,7 +65,7 @@ export default function SettingsPanel({ project, canWrite, canDelete, onChanged,
name,
description: form.description,
scope_json: scopeRaw,
status: form.status,
...(form.status !== (project.status || 'active') ? { status: form.status } : {}),
pinned: Boolean(form.pinned)
});
toastSuccess(t('projects.saved', null, '已保存'));
@ -83,8 +83,8 @@ export default function SettingsPanel({ project, canWrite, canDelete, onChanged,
confirmAction({
title: archived ? t('projects.restoreProjectActive', null, '恢复为进行中') : t('projects.archiveProject', null, '归档'),
content: archived
? t('projects.confirmRestoreProjectActive', null, '恢复为 active?')
: t('projects.confirmArchiveProject', null, '归档后默认不再出现在活跃列表,是否继续?'),
? t('projects.confirmRestoreProjectActive', null, '恢复后,项目记忆与随项目归档的漏洞将重新启用。单独归档的漏洞仍保留在归档列表。')
: t('projects.confirmArchiveProject', null, '项目记忆和关联漏洞将随项目归档,可从已归档项目中查阅。是否继续?'),
okText: t('common.confirm', null, '确认'),
danger: !archived,
onOk: async () => {
@ -196,7 +196,7 @@ export default function SettingsPanel({ project, canWrite, canDelete, onChanged,
<Text strong>{t('projects.dangerZoneTitle', null, '危险操作')}</Text>
<div>
<Text type="tertiary" size="small">
{t('projects.dangerZoneHint', null, '归档后需在列表勾选「显示已归档」才能查看;删除将清除全部事实且不可恢复。')}
{t('projects.dangerZoneHint', null, '在项目列表选择「已归档」可查看归档项目。删除项目会永久删除项目记忆。')}
</Text>
</div>
</div>

View File

@ -1,7 +1,7 @@
/** 漏洞详情抽屉:概览 / 复现与证据 / 关联 / 下载报告(GET /:id/context 提供上下文)。 */
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Collapse, Radio, RadioGroup, SideSheet, Space, Spin, Tabs, Timeline, Typography } from '@douyinfe/semi-ui';
import { Button, Collapse, Radio, RadioGroup, SideSheet, Space, Spin, Tabs, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlay, IconRefresh } from '@douyinfe/semi-icons';
import { api, downloadFile } from '../../lib/http';
import { formatDateTime } from '../../lib/format';
@ -79,7 +79,7 @@ function Narrative({ title, content, code }) {
}
export default function DetailDrawer({
visible, vulnId, refreshKey, onClose, onEdit, onDelete, onOpenVuln,
visible, vulnId, refreshKey, onClose, onEdit, onArchive, onDelete, onOpenVuln,
canWrite, canDelete, t, projectNames
}) {
const navigate = useNavigate();
@ -181,13 +181,20 @@ export default function DetailDrawer({
<span className="vulnerability-drawer-meta">
<SeverityTag severity={vuln.severity} />
<StatusTag status={vuln.status} label={statusText(t, vuln.status)} />
{vuln.archived && (
<Tag size="small" color="grey">
{vuln.project_archived
? t('vulnerabilityPage.archivedWithProject', null, '随项目归档')
: t('projects.statusArchived', null, '已归档')}
</Tag>
)}
{vuln.type ? <Text type="tertiary">{vuln.type}</Text> : null}
</span>
)}
</div>
)}
footer={(
<Space>
<Space wrap>
<Button onClick={onClose}>{t('common.close', null, '关闭')}</Button>
<Button icon={<IconRefresh />} onClick={() => context.reload()} loading={context.loading}>
{t('common.refresh', null, '刷新')}
@ -208,6 +215,11 @@ export default function DetailDrawer({
{t('common.edit', null, '编辑')}
</Button>
)}
{canWrite && vuln && !vuln.project_archived && (
<Button onClick={() => onArchive(vuln)}>
{vuln.archived ? t('projects.restore', null, '恢复') : t('projects.archiveProject', null, '归档')}
</Button>
)}
{canDelete && (
<Button type="danger" icon={<IconDelete />} disabled={!vuln} onClick={() => onDelete(vuln)}>
{t('common.delete', null, '删除')}

View File

@ -1,5 +1,5 @@
/** 漏洞筛选栏:关键词 + 级别/状态/项目/来源/任务标签/深度测评,选项来自 filter-options。 */
import { useEffect, useRef, useState } from 'react';
import { useEffect, useId, useRef, useState } from 'react';
import { Button, Input, Select } from '@douyinfe/semi-ui';
import { IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { useDebounced } from '../../components/hooks';
@ -10,6 +10,7 @@ function withEmpty(label, options) {
}
export default function FilterBar({ t, filters, options, projectOptions, hasGroupFilters, onChange, onReset }) {
const archiveLabel = useId();
const [keyword, setKeyword] = useState(filters.q);
const debounced = useDebounced(keyword, 380);
const lastEmitted = useRef(filters.q);
@ -57,6 +58,18 @@ export default function FilterBar({ t, filters, options, projectOptions, hasGrou
optionList={withEmpty(t('dashboard.allStatuses', null, '全部状态'), statusOptions(t))}
onChange={value => onChange('status', value || '')}
/>
<span id={archiveLabel} hidden>{t('vulnerabilityPage.archiveStatus', null, '归档状态')}</span>
<Select
className="vulnerability-filter-select"
value={filters.archived}
aria-labelledby={archiveLabel}
optionList={[
{ value: '', label: t('vulnerabilityPage.unarchived', null, '未归档') },
{ value: 'true', label: t('projects.statusArchived', null, '已归档') },
{ value: 'all', label: t('vulnerabilityPage.allArchiveStates', null, '全部归档状态') }
]}
onChange={value => onChange('archived', value || '')}
/>
<Select
className="vulnerability-filter-select vulnerability-filter-select--wide"
value={filters.project_id}

View File

@ -29,7 +29,7 @@ function SourceCell({ record }) {
export default function VulnTable({
t, data, loading, page, pageSize, total, selection, onSelectionChange,
onOpen, onEdit, onDelete, onDownload, sort, onSort, canWrite, canDelete,
onOpen, onEdit, onArchive, onDelete, onDownload, sort, onSort, canWrite, canDelete,
onPageChange, onPageSizeChange, toolbar, onRefresh
}) {
const columns = [
@ -43,6 +43,7 @@ export default function VulnTable({
{record.type || '—'}
{record.case_id ? ` · ${t('vulnerabilityPage.mergedRecord', null, '已归并')}` : ''}
{record.assessment_id ? ` · ${t('vulnerabilityPage.assessmentTask', null, '深度测评')}` : ''}
{record.archived ? ` · ${t('projects.statusArchived', null, '已归档')}` : ''}
</span>
</div>
)
@ -93,7 +94,7 @@ export default function VulnTable({
{
title: t('vulnerabilityPage.tableActions', null, '操作'),
dataIndex: 'id',
width: 200,
width: canWrite ? 250 : 200,
render: (_, record) => (
<div className="vulnerability-row-actions">
<Button size="small" theme="borderless" onClick={event => { event.stopPropagation(); onOpen(record.id); }}>
@ -115,6 +116,15 @@ export default function VulnTable({
{t('common.edit', null, '编辑')}
</Button>
)}
{canWrite && !record.project_archived && (
<Button
size="small"
theme="borderless"
onClick={event => { event.stopPropagation(); onArchive(record); }}
>
{record.archived ? t('projects.restore', null, '恢复') : t('projects.archiveProject', null, '归档')}
</Button>
)}
{canDelete && (
<Button
size="small"

View File

@ -39,6 +39,7 @@ export default function VulnerabilitiesPage() {
q: params.get('q') || '',
severity: params.get('severity') || '',
status: params.get('status') || '',
archived: ['true', 'all'].includes(params.get('archived')) ? params.get('archived') : '',
project_id: params.get('project_id') || '',
conversation_tag: params.get('conversation_tag') || '',
task_tag: params.get('task_tag') || '',
@ -129,7 +130,10 @@ export default function VulnerabilitiesPage() {
const stats = useResource(() => api.get('/vulnerabilities/stats', statQuery), [statKey]);
const [optionsVersion, setOptionsVersion] = useState(0);
const options = useResource(() => api.get('/vulnerabilities/filter-options'), [optionsVersion]);
const options = useResource(
() => api.get('/vulnerabilities/filter-options', filters.archived ? { archived: filters.archived } : {}),
[optionsVersion, filters.archived]
);
const projects = useResource(async () => {
try {
@ -207,6 +211,19 @@ export default function VulnerabilitiesPage() {
reloadStats({ silent: true });
}, [reloadList, reloadStats, t]);
const handleArchive = useCallback(async record => {
try {
await api.put(`/vulnerabilities/${encodeURIComponent(record.id)}/archive`, { archived: !record.archived });
toastSuccess(t('vulnerabilityPage.saveSuccess', null, '已保存'));
setSelection(previous => previous.filter(id => id !== record.id));
setDetailVersion(value => value + 1);
setOptionsVersion(value => value + 1);
await Promise.all([reloadList({ silent: true }), reloadStats({ silent: true })]);
} catch (error) {
toastError(error, t('vulnerabilityPage.archiveFailed', null, '更新归档状态失败'));
}
}, [reloadList, reloadStats, t]);
const handleDelete = useCallback(record => {
if (!record?.id) return;
confirmAction({
@ -505,6 +522,7 @@ export default function VulnerabilitiesPage() {
onSelectionChange={setSelection}
onOpen={openDetail}
onEdit={openEditor}
onArchive={handleArchive}
onDelete={handleDelete}
onDownload={handleDownload}
sort={filters.sort}
@ -527,6 +545,7 @@ export default function VulnerabilitiesPage() {
onClose={closeDetail}
onOpenVuln={openDetail}
onEdit={openEditor}
onArchive={handleArchive}
onDelete={handleDelete}
canWrite={canWrite}
canDelete={canDelete}

View File

@ -7,7 +7,7 @@ import { SEVERITY_LABEL } from '../../lib/format';
export const SEVERITY_CODES = ['critical', 'high', 'medium', 'low', 'info'];
export const STATUS_CODES = ['open', 'confirmed', 'fixed', 'ignored', 'false_positive'];
export const FILTER_KEYS = ['q', 'severity', 'status', 'project_id', 'conversation_tag', 'task_tag', 'assessment_id'];
export const FILTER_KEYS = ['q', 'severity', 'status', 'archived', 'project_id', 'conversation_tag', 'task_tag', 'assessment_id'];
export const DEFAULT_PAGE_SIZE = 20;
export const PAGE_SIZE_OPTIONS = [10, 20, 50, 100];

View File

@ -1820,6 +1820,11 @@ test('project: compact pagination supports selection, filtering and a shrinking
const rows = list.locator('.semi-table-tbody > tr');
const next = pager.getByRole('button', { name: 'Next', exact: true });
const previous = pager.getByRole('button', { name: 'Previous', exact: true });
const status = list.locator('.project-toolbar .semi-select');
await expect(status).toContainText(label('projects.statusActive', '进行中'));
await expect(pager).toContainText('1/1');
await status.click();
await page.getByRole('option').filter({ hasText: label('projects.all', '全部') }).click();
await expect(rows).toHaveCount(10);
await expect(pager).toContainText('1/2');
const listBox = await list.boundingBox();
@ -1843,7 +1848,6 @@ test('project: compact pagination supports selection, filtering and a shrinking
await expect(rows).toHaveCount(10);
await expect(pager).toContainText('1/2');
await next.click();
const status = list.locator('.project-toolbar .semi-select');
await status.click();
await page.getByRole('option').filter({ hasText: label('projects.statusActive', '进行中') }).click();
await expect(rows).toHaveCount(10);

View File

@ -0,0 +1,74 @@
import { expect, FACT, label, PROJECT, test, visit, VULNERABILITY } from './fixtures.mjs';
test('project archive keeps history accessible and preserves a manual vulnerability archive', async ({ page, mockApi }) => {
const project = { ...PROJECT };
const projectPath = `/api/projects/${project.id}`;
const manual = { ...VULNERABILITY, id: 'manual-finding', title: '单独归档的示例漏洞' };
const manualPath = `/api/vulnerabilities/${manual.id}/archive`;
let manuallyArchived = false;
const records = () => [VULNERABILITY, manual].map(record => ({
...record,
archived: project.status === 'archived' || (record.id === manual.id && manuallyArchived),
project_archived: project.status === 'archived'
}));
mockApi.respond('GET', '/api/projects', () => ({ json: { projects: [project], total: 1 } }));
mockApi.respond('GET', projectPath, () => ({ json: project }));
mockApi.respond('PUT', projectPath, ({ body }) => {
project.status = body.status;
return { json: project };
});
mockApi.respond('PUT', manualPath, ({ body }) => {
manuallyArchived = body.archived;
return { json: { success: true } };
});
mockApi.respond('GET', '/api/vulnerabilities', (_, url) => {
const filter = url.searchParams.get('archived');
const vulnerabilities = records().filter(record => filter === 'all' || record.archived === (filter === 'true'));
return { json: { vulnerabilities, total: vulnerabilities.length, page: 1 } };
});
mockApi.respond('GET', `/api/vulnerabilities/${VULNERABILITY.id}/context`, () => ({
json: { vulnerability: records()[0], history: [], members: [], assets: [] }
}));
const vulnerabilities = await visit(page, 'vulnerabilities');
const manualRow = vulnerabilities.getByRole('row').filter({ hasText: manual.title });
const archive = label('projects.archiveProject', '归档');
const restore = label('projects.restore', '恢复');
await manualRow.getByRole('button', { name: archive, exact: true }).click();
await expect(manualRow).toHaveCount(0);
await expect(vulnerabilities.getByText(VULNERABILITY.title, { exact: true })).toBeVisible();
const projects = await visit(page, 'projects');
const list = projects.locator('.project-list-card');
const projectRow = list.getByRole('row').filter({ hasText: project.name });
await projectRow.getByRole('button', { name: archive, exact: true }).click();
await page.getByRole('dialog').getByRole('button', { name: label('common.confirm', '确认'), exact: true }).click();
await expect(projectRow).toHaveCount(0);
await expect(projects.getByText(FACT.summary, { exact: true })).toBeVisible();
await expect(projects.locator('.project-detail-title-row')).toContainText(label('projects.statusArchived', '已归档'));
await projects.getByRole('button', { name: label('projects.projectVulnerabilities', '项目漏洞'), exact: true }).click();
await expect(page).toHaveURL(/archived=true/);
await expect(vulnerabilities.getByText(VULNERABILITY.title, { exact: true })).toBeVisible();
await vulnerabilities.getByText(VULNERABILITY.title, { exact: true }).click();
const detail = page.getByRole('dialog');
await expect(detail.getByText(label('vulnerabilityPage.archivedWithProject', '随项目归档'), { exact: true })).toBeVisible();
await expect(detail.getByRole('button', { name: restore, exact: true })).toHaveCount(0);
await visit(page, 'projects');
await list.locator('.project-toolbar .semi-select').click();
await page.getByRole('option').filter({ hasText: label('projects.statusArchived', '已归档') }).click();
await projectRow.getByRole('button', { name: restore, exact: true }).click();
await page.getByRole('dialog').getByRole('button', { name: label('common.confirm', '确认'), exact: true }).click();
await expect(projectRow).toHaveCount(0);
await visit(page, 'vulnerabilities');
await expect(vulnerabilities.getByText(VULNERABILITY.title, { exact: true })).toBeVisible();
await expect(manualRow).toHaveCount(0);
await vulnerabilities.getByRole('combobox', { name: label('vulnerabilityPage.archiveStatus', '归档状态') }).click();
await page.getByRole('option').filter({ hasText: label('projects.statusArchived', '已归档') }).click();
await expect(vulnerabilities.getByText(VULNERABILITY.title, { exact: true })).toHaveCount(0);
await manualRow.getByRole('button', { name: restore, exact: true }).click();
await expect(manualRow).toHaveCount(0);
expect(mockApi.calls('PUT', manualPath).map(call => call.body)).toEqual([{ archived: true }, { archived: false }]);
expect(mockApi.calls('PUT', projectPath).map(call => call.body)).toEqual([{ status: 'archived' }, { status: 'active' }]);
});

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-DpoRSPP9.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-BZrJi-2j.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-DpoRSPP9.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
import{I as e,L as t}from"./index-BZrJi-2j.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-DpoRSPP9.js";import"./c2-shared-DX7U8sqg.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={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)`}]},p=[{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`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-BZrJi-2j.js";import"./c2-shared-DBmpvtOo.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={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)`}]},p=[{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`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-DpoRSPP9.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-BZrJi-2j.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-DpoRSPP9.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-BZrJi-2j.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};

View File

@ -1,4 +1,4 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{$t as a,A as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,c as h,f as g,h as _,kt as v,m as y,ot as b,p as x,s as S,st as ee,u as C,v as w,x as T,z as E}from"./semi-CHxO7u8f.js";import{A as te,D,E as O,F as ne,I as k,L as A,M as j,N as M,P as re,R as N,S as P,T as F,_ as ie,a as I,b as L,d as R,j as ae,l as z,m as B,n as V,o as H,p as U,s as W,u as G,x as oe,y as se}from"./index-DpoRSPP9.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var K=e(t(),1),q=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function me(e){return JSON.stringify(String(e))}function he(e){let t=String(e);return pe(t)?t:me(t)}function ge(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):me(String(e));let t=String(e);return pe(t)?t:me(t)}function _e(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ve(e,t,n,r){let i=` `.repeat(n),a=he(e);if(_e(t))r.push(`${i}${a}: ${ge(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),xe(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ye(t,n+2,r)):r.push(`${i}${a}: {}`)}function ye(e,t,n){for(let[r,i]of Object.entries(e))ve(r,i,t,n)}function be(e,t,n){let r=` `.repeat(t);if(_e(e)){n.push(`${r}- ${ge(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),xe(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);_e(o)?n.push(`${r}- ${he(a)}: ${ge(o)}`):(n.push(`${r}-`),ve(a,o,t+2,n));for(let[e,r]of s)ve(e,r,t+2,n)}function xe(e,t,n){for(let r of e)be(r,t,n)}function Se(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{$t as a,A as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,c as h,f as g,h as _,kt as v,m as y,ot as b,p as x,s as S,st as ee,u as C,v as w,x as T,z as E}from"./semi-CHxO7u8f.js";import{A as te,D,E as O,F as ne,I as k,L as A,M as j,N as M,P as re,R as N,S as P,T as F,_ as ie,a as I,b as L,d as R,j as ae,l as z,m as B,n as V,o as H,p as U,s as W,u as G,x as oe,y as se}from"./index-BZrJi-2j.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var K=e(t(),1),q=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function me(e){return JSON.stringify(String(e))}function he(e){let t=String(e);return pe(t)?t:me(t)}function ge(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):me(String(e));let t=String(e);return pe(t)?t:me(t)}function _e(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ve(e,t,n,r){let i=` `.repeat(n),a=he(e);if(_e(t))r.push(`${i}${a}: ${ge(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),xe(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ye(t,n+2,r)):r.push(`${i}${a}: {}`)}function ye(e,t,n){for(let[r,i]of Object.entries(e))ve(r,i,t,n)}function be(e,t,n){let r=` `.repeat(t);if(_e(e)){n.push(`${r}- ${ge(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),xe(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);_e(o)?n.push(`${r}- ${he(a)}: ${ge(o)}`):(n.push(`${r}-`),ve(a,o,t+2,n));for(let[e,r]of s)ve(e,r,t+2,n)}function xe(e,t,n){for(let r of e)be(r,t,n)}function Se(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
`).split(`
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return _e(e)?(n.push(ge(e)),`${n.join(`
`)}\n`):Array.isArray(e)?(e.length?xe(e,0,n):n.push(`[]`),`${n.join(`

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-DpoRSPP9.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-BZrJi-2j.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -18,7 +18,7 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-DpoRSPP9.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-BZrJi-2j.js"></script>
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CHxO7u8f.js">

View File

@ -718,8 +718,9 @@
"scopeNoteAuthorizedWebOnly": "مُصرَّح به لاختبار طبقة تطبيقات الويب فقط",
"invalidScopeJson": "نطاق JSON غير صالح، يُرجى إصلاحه أولاً أو النقر على تنسيق",
"saved": "تم الحفظ",
"confirmArchiveProject": "بعد الأرشفة، يُخفى هذا المشروع من القائمة النشطة افتراضياً. المتابعة؟",
"confirmRestoreProjectActive": "الاستعادة إلى الحالة النشطة؟",
"projectVulnerabilities": "ثغرات المشروع",
"confirmArchiveProject": "ستُؤرشف ذاكرة المشروع والثغرات المرتبطة به معه. يمكنك مراجعتها من المشروع المؤرشف. هل تريد المتابعة؟",
"confirmRestoreProjectActive": "ستُستعاد ذاكرة المشروع والثغرات التي أُرشفت معه إلى الحالة النشطة. ستبقى الثغرات المؤرشفة بشكل منفصل في الأرشيف.",
"confirmDeleteProject": "حذف هذا المشروع؟ ستُحذف الحقائق وتُفصل المحادثات.",
"deleteFailed": "فشل الحذف",
"addFact": "إضافة حقيقة",
@ -757,7 +758,7 @@
"scopeJsonLabel": "نطاق JSON",
"scopeFootnote": "يدعم الأهداف والاستثناءات والملاحظات وغيرها. الفارغ يعني عدم وجود حدّ للنطاق.",
"dangerZoneTitle": "منطقة الخطر",
"dangerZoneHint": "تُخفى المشاريع المؤرشفة ما لم يُفعَّل ”عرض المؤرشفة“؛ ويزيل الحذف جميع الحقائق نهائياً.",
"dangerZoneHint": "اختر «مؤرشفة» في قائمة المشاريع لعرض المشاريع المؤرشفة. يؤدي حذف المشروع إلى حذف ذاكرته نهائيًا.",
"archiveRestore": "أرشفة / استعادة",
"archiveProject": "أرشفة",
"editProject": "تعديل",
@ -2789,6 +2790,11 @@
"errorGeneric": "حدث خطأ ما. يُرجى المحاولة مرة أخرى."
},
"vulnerabilityPage": {
"archiveStatus": "حالة الأرشفة",
"unarchived": "غير مؤرشفة",
"allArchiveStates": "كل حالات الأرشفة",
"archivedWithProject": "مؤرشفة مع المشروع",
"archiveFailed": "تعذّر تحديث حالة الأرشفة",
"viewFinding": "عرض التفاصيل",
"taskSearch": "البحث في المهام أو قوائم الانتظار أو الوسوم…",
"allTasks": "جميع المهام",

View File

@ -719,8 +719,9 @@
"scopeNoteAuthorizedWebOnly": "Authorized for Web application layer testing only",
"invalidScopeJson": "Invalid scope JSON, please fix it first or click Format",
"saved": "Saved",
"confirmArchiveProject": "After archiving, this project is hidden from active list by default. Continue?",
"confirmRestoreProjectActive": "Restore to active?",
"projectVulnerabilities": "Project vulnerabilities",
"confirmArchiveProject": "Project memory and linked vulnerabilities will be archived with this project. You can review them from the archived project. Continue?",
"confirmRestoreProjectActive": "Project memory and vulnerabilities archived with the project will become active. Individually archived vulnerabilities will stay in the archive.",
"confirmDeleteProject": "Delete this project? Facts will be deleted and conversations unbound.",
"deleteFailed": "Delete failed",
"addFact": "Add fact",
@ -758,7 +759,7 @@
"scopeJsonLabel": "Scope JSON",
"scopeFootnote": "Supports targets, exclude, notes and more. Empty means no scope limit.",
"dangerZoneTitle": "Danger zone",
"dangerZoneHint": "Archived projects are hidden unless 'Show archived' is enabled; deletion removes all facts permanently.",
"dangerZoneHint": "Select Archived in the project list to find archived projects. Deleting a project permanently removes its project memory.",
"archiveRestore": "Archive / Restore",
"archiveProject": "Archive",
"editProject": "Edit",
@ -2932,6 +2933,11 @@
"errorGeneric": "Something went wrong. Please try again."
},
"vulnerabilityPage": {
"archiveStatus": "Archive status",
"unarchived": "Unarchived",
"allArchiveStates": "All archive states",
"archivedWithProject": "Archived with project",
"archiveFailed": "Failed to update archive status",
"viewFinding": "View details",
"taskSearch": "Search tasks, queues or tags…",
"allTasks": "All tasks",

View File

@ -731,8 +731,9 @@
"scopeNoteAuthorizedWebOnly": "Разрешено только тестирование уровня веб-приложения",
"invalidScopeJson": "Некорректный JSON области. Исправьте его или нажмите «Форматировать».",
"saved": "Сохранено",
"confirmArchiveProject": "После архивации проект по умолчанию скрыт из активного списка. Продолжить?",
"confirmRestoreProjectActive": "Вернуть в активные?",
"projectVulnerabilities": "Уязвимости проекта",
"confirmArchiveProject": "Память проекта и связанные уязвимости будут архивированы вместе с проектом. Их можно просмотреть в архиве проекта. Продолжить?",
"confirmRestoreProjectActive": "Память проекта и уязвимости, архивированные вместе с ним, снова станут активными. Уязвимости, архивированные отдельно, останутся в архиве.",
"confirmDeleteProject": "Удалить этот проект? Факты будут удалены, диалоги отвязаны.",
"deleteFailed": "Не удалось удалить",
"addFact": "Добавить факт",
@ -770,7 +771,7 @@
"scopeJsonLabel": "JSON области",
"scopeFootnote": "Доступны targets, exclude, notes и другие поля. Пусто — без ограничения области.",
"dangerZoneTitle": "Опасная зона",
"dangerZoneHint": "Архивные проекты скрыты, пока не включено «Показывать архив». Удаление безвозвратно стирает все факты.",
"dangerZoneHint": "Для просмотра архивных проектов выберите «В архиве» в списке проектов. Удаление проекта навсегда удаляет его память.",
"archiveRestore": "Архив и восстановление",
"archiveProject": "В архив",
"editProject": "Изменить",
@ -2945,6 +2946,11 @@
"errorGeneric": "Что-то пошло не так. Повторите попытку."
},
"vulnerabilityPage": {
"archiveStatus": "Статус архивации",
"unarchived": "Вне архива",
"allArchiveStates": "Все статусы архивации",
"archivedWithProject": "В архиве вместе с проектом",
"archiveFailed": "Не удалось обновить статус архивации",
"viewFinding": "Подробнее",
"taskSearch": "Поиск задач, очередей или тегов…",
"allTasks": "Все задачи",

View File

@ -707,8 +707,9 @@
"scopeNoteAuthorizedWebOnly": "仅授权 Web 应用层测试",
"invalidScopeJson": "测试范围 JSON 无效,请先修正或点击「格式化」",
"saved": "已保存",
"confirmArchiveProject": "归档后默认不再出现在活跃列表,是否继续?",
"confirmRestoreProjectActive": "恢复为 active?",
"projectVulnerabilities": "项目漏洞",
"confirmArchiveProject": "项目记忆和关联漏洞将随项目归档,可从已归档项目中查阅。是否继续?",
"confirmRestoreProjectActive": "恢复后,项目记忆与随项目归档的漏洞将重新启用。单独归档的漏洞仍保留在归档列表。",
"confirmDeleteProject": "确定删除该项目?事实将一并删除,对话将解除绑定。",
"deleteFailed": "删除失败",
"addFact": "添加事实",
@ -746,7 +747,7 @@
"scopeJsonLabel": "范围 JSON",
"scopeFootnote": "支持 targets、exclude、notes 等字段,留空表示不限制范围。",
"dangerZoneTitle": "危险操作",
"dangerZoneHint": "归档后需在列表勾选「显示已归档」才能查看;删除将清除全部事实且不可恢复。",
"dangerZoneHint": "在项目列表选择「已归档」可查看归档项目。删除项目会永久删除项目记忆。",
"archiveRestore": "归档 / 恢复",
"archiveProject": "归档",
"editProject": "编辑",
@ -2920,6 +2921,11 @@
"errorGeneric": "操作失败,请稍后重试。"
},
"vulnerabilityPage": {
"archiveStatus": "归档状态",
"unarchived": "未归档",
"allArchiveStates": "全部归档状态",
"archivedWithProject": "随项目归档",
"archiveFailed": "更新归档状态失败",
"viewFinding": "查看详情",
"taskSearch": "搜索任务、队列或标签…",
"allTasks": "全部任务",