From 2e2ed49158a0510b3e0f91b61a52cf0cd3b6a0dd Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:31:21 +0800 Subject: [PATCH] feat(vulnerabilities): add domain browser and risk overview --- internal/database/rbac_access_test.go | 2 +- internal/database/vulnerability.go | 48 ++- internal/handler/vulnerability.go | 12 +- internal/handler/vulnerability_group_test.go | 45 ++- web/static/css/style.css | 321 ++++++++++++++++++ web/static/i18n/ar-SA.json | 19 ++ web/static/i18n/en-US.json | 19 ++ web/static/i18n/ru-RU.json | 19 ++ web/static/i18n/zh-CN.json | 19 ++ .../js/vulnerability-host-view.test.cjs | 38 +++ web/static/js/vulnerability.js | 273 ++++++++++++++- web/templates/index.html | 21 +- 12 files changed, 814 insertions(+), 22 deletions(-) create mode 100644 web/static/js/vulnerability-host-view.test.cjs diff --git a/internal/database/rbac_access_test.go b/internal/database/rbac_access_test.go index 504a9e62..8734bfc8 100644 --- a/internal/database/rbac_access_test.go +++ b/internal/database/rbac_access_test.go @@ -232,7 +232,7 @@ func TestRBACVulnerabilityAccessInheritsProject(t *testing.T) { } for _, group := range []string{"host", "task"} { access := RBACListAccess{UserID: user.ID, Scope: RBACScopeAssigned} - items, err := db.ListVulnerabilitiesByGroupForAccess(1, 0, VulnerabilityListFilter{}, access, group) + items, err := db.ListVulnerabilitiesByGroupForAccess(1, 0, VulnerabilityListFilter{}, access, group, "severity") if err != nil || len(items) != 1 || items[0].ID != v1.ID { t.Fatalf("group %s returned %#v, %v; want only %s", group, items, err, v1.ID) } diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index e0e285d9..eeb9286e 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -12,12 +12,14 @@ import ( "github.com/google/uuid" "go.uber.org/zap" "golang.org/x/net/idna" + "golang.org/x/net/publicsuffix" ) // VulnerabilityListFilter 列表/统计/导出共用的筛选条件 type VulnerabilityListFilter struct { ID string Search string // 关键词模糊匹配(标题、描述、类型、目标等) + HostQuery string ConversationID string ProjectID string Severity string @@ -40,6 +42,10 @@ func escapeVulnerabilityLikePattern(s string) string { } func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) (string, []interface{}) { + if host := strings.TrimSpace(f.HostQuery); host != "" { + query += ` AND vulnerability_target_host(target) LIKE ? ESCAPE '\'` + args = append(args, escapeVulnerabilityLikePattern(strings.ToLower(host))) + } if f.ID != "" { query += " AND id = ?" args = append(args, f.ID) @@ -148,6 +154,7 @@ type Vulnerability struct { Type string `json:"type"` Target string `json:"target"` TargetHost *string `json:"target_host,omitempty"` + TargetDomain string `json:"target_domain,omitempty"` Preconditions string `json:"preconditions"` ReproSteps string `json:"reproduction_steps"` Evidence string `json:"evidence"` @@ -239,7 +246,7 @@ func (db *DB) ListVulnerabilities(limit, offset int, filter VulnerabilityListFil } func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess) ([]*Vulnerability, error) { - return db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, "") + return db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, "", "") } func vulnerabilityTargetHost(target string) string { @@ -291,6 +298,10 @@ func vulnerabilityTargetHost(target string) string { const vulnerabilityTaskIDExpr = `COALESCE((SELECT bt.id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '')` +const vulnerabilitySeverityRankExpr = `CASE severity + WHEN 'critical' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 + WHEN 'low' THEN 3 WHEN 'info' THEN 4 ELSE 5 END` + func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAccess, groupBy string) (string, []interface{}) { var key string switch groupBy { @@ -304,7 +315,8 @@ func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAcce default: return "", nil } - query := "SELECT id, " + key + " AS group_key FROM vulnerabilities WHERE 1=1" + query := "SELECT id, created_at, " + vulnerabilitySeverityRankExpr + " AS severity_rank, " + + key + " AS group_key FROM vulnerabilities WHERE 1=1" query, args := filter.appendWhere(query, nil) return appendVulnerabilityAccessFilter(query, args, access) } @@ -319,28 +331,38 @@ func (db *DB) CountVulnerabilityGroupsForAccess(filter VulnerabilityListFilter, return count, err } -func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy string) ([]*Vulnerability, error) { +func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy, sortBy string) ([]*Vulnerability, error) { hostExpr, order := "NULL", "created_at DESC" + itemOrder := "created_at DESC, id" + groupOrder := "group_key = '', group_key" + switch sortBy { + case "severity": + itemOrder = vulnerabilitySeverityRankExpr + ", created_at DESC, id" + groupOrder = "group_severity, group_latest DESC, " + groupOrder + case "latest": + groupOrder = "group_latest DESC, " + groupOrder + } groupQuery, args := vulnerabilityGroupQuery(filter, access, groupBy) var prefix, join string if groupQuery != "" { prefix = `WITH scoped AS (` + groupQuery + `), page_groups AS ( - SELECT group_key FROM scoped GROUP BY group_key - ORDER BY group_key = '', group_key LIMIT ? OFFSET ? + SELECT group_key, MIN(severity_rank) AS group_severity, MAX(created_at) AS group_latest + FROM scoped GROUP BY group_key + ORDER BY ` + groupOrder + ` LIMIT ? OFFSET ? ), page_items AS ( - SELECT scoped.id, scoped.group_key + SELECT scoped.id, scoped.group_key, page_groups.group_severity, page_groups.group_latest FROM scoped JOIN page_groups USING (group_key) )` args = append(args, limit, offset) join = " JOIN page_items USING (id)" - order = "group_key = '', group_key, created_at DESC, id" + order = groupOrder + ", " + itemOrder if groupBy == "host" { hostExpr = "group_key" } - } else if groupBy == "none" { - order = "created_at DESC, id" + } else if groupBy == "none" || sortBy != "" { + order = itemOrder } query := prefix + ` SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, conversation_tag, task_tag, @@ -383,6 +405,14 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln db.logger.Warn("扫描漏洞记录失败", zap.Error(err)) continue } + if vuln.TargetHost != nil { + vuln.TargetDomain = *vuln.TargetHost + if _, err := netip.ParseAddr(*vuln.TargetHost); err != nil { + if domain, err := publicsuffix.EffectiveTLDPlusOne(*vuln.TargetHost); err == nil { + vuln.TargetDomain = domain + } + } + } vulnerabilities = append(vulnerabilities, &vuln) } diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index d68538f3..7d54a73a 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -168,6 +168,7 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt ProjectID: c.Query("project_id"), ID: c.Query("id"), Search: q, + HostQuery: c.Query("host_q"), ConversationID: c.Query("conversation_id"), Severity: c.Query("severity"), Status: c.Query("status"), @@ -185,6 +186,11 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { filter := parseVulnerabilityListFilter(c) access := vulnerabilityAccessFromContext(c) groupBy := c.Query("group_by") + sortBy := c.Query("sort") + if sortBy != "" && sortBy != "severity" && sortBy != "latest" { + c.JSON(http.StatusBadRequest, gin.H{"error": "sort must be severity or latest"}) + return + } limit, _ := strconv.Atoi(limitStr) if limit <= 0 || limit > 100 { @@ -209,8 +215,8 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { total, err := h.db.CountVulnerabilityGroupsForAccess(filter, access, groupBy) if err != nil { h.logger.Error("获取漏洞总数失败", zap.Error(err)) - // 继续执行,使用0作为总数 - total = 0 + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return } // 计算总页数 @@ -228,7 +234,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { page = totalPages offset = (page - 1) * limit } - vulnerabilities, err := h.db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, groupBy) + vulnerabilities, err := h.db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, groupBy, sortBy) if err != nil { h.logger.Error("获取漏洞列表失败", zap.Error(err)) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) diff --git a/internal/handler/vulnerability_group_test.go b/internal/handler/vulnerability_group_test.go index bc7f31aa..5ada4cdb 100644 --- a/internal/handler/vulnerability_group_test.go +++ b/internal/handler/vulnerability_group_test.go @@ -57,7 +57,7 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { t.Helper() w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) - c.Request = httptest.NewRequest(http.MethodGet, "/api/vulnerabilities?severity=high&limit=2&"+query, nil) + c.Request = httptest.NewRequest(http.MethodGet, "/api/vulnerabilities?limit=2&"+query, nil) h.ListVulnerabilities(c) if w.Code != http.StatusOK { t.Fatalf("status = %d, body = %s", w.Code, w.Body.String()) @@ -82,7 +82,7 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { {"page=1", 1, 5, 3, []string{"unknown", "ipv6"}, nil}, } { t.Run(tc.query, func(t *testing.T) { - result := fetch(tc.query) + result := fetch("severity=high&" + tc.query) if result.Total != tc.total || result.TotalPages != tc.pages || result.Page != tc.page || result.PageSize != 2 || len(result.Vulnerabilities) != len(tc.ids) { t.Fatalf("unexpected pagination: %+v", result) @@ -97,6 +97,47 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) { } } else if v.TargetHost == nil || *v.TargetHost != tc.hosts[i] { t.Fatalf("target_host for %q = %v, want %q", v.ID, v.TargetHost, tc.hosts[i]) + } else if v.ID == "subdomain" && v.TargetDomain != "example.com" { + t.Fatalf("subdomain parent = %q", v.TargetDomain) + } + } + }) + } + + // Differing severities and timestamps ensure sorting selects entire groups + // before applying the page boundary, including when a filter hides rows. + for id, severity := range map[string]string{ + "domain-old": "critical", "domain-new": "medium", "ipv6": "info", + } { + if _, err := db.Exec("UPDATE vulnerabilities SET severity = ? WHERE id = ?", severity, id); err != nil { + t.Fatal(err) + } + } + for _, tc := range []struct { + query string + ids []string + }{ + {"group_by=host&sort=severity&page=1", []string{"domain-old", "domain-new", "filtered", "unknown"}}, + {"group_by=host&sort=severity&page=2", []string{"subdomain", "ipv6"}}, + {"group_by=task&sort=severity&page=1", []string{"domain-old", "subdomain", "unknown"}}, + {"group_by=task&sort=severity&page=2", []string{"domain-new", "filtered", "ipv6"}}, + {"group_by=host&sort=latest", []string{"filtered", "domain-new", "domain-old", "unknown"}}, + {"group_by=task&sort=latest", []string{"filtered", "ipv6", "domain-new", "unknown"}}, + {"group_by=none&sort=severity", []string{"domain-old", "unknown"}}, + {"group_by=host&sort=severity&severity=high", []string{"unknown", "subdomain"}}, + {"group_by=host&sort=latest&q=missing", []string{}}, + {"group_by=host&host_q=example.com", []string{"filtered", "domain-new", "domain-old", "subdomain"}}, + {"group_by=host&host_q=%25", []string{}}, + {"group_by=host&host_q=missing", []string{}}, + } { + t.Run(tc.query, func(t *testing.T) { + result := fetch(tc.query) + if len(result.Vulnerabilities) != len(tc.ids) { + t.Fatalf("got %d records, want %d", len(result.Vulnerabilities), len(tc.ids)) + } + for i, id := range tc.ids { + if result.Vulnerabilities[i].ID != id { + t.Fatalf("record %d = %q, want %q", i, result.Vulnerabilities[i].ID, id) } } }) diff --git a/web/static/css/style.css b/web/static/css/style.css index bf59ecab..b95b874e 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -27541,6 +27541,327 @@ tr.mcp-stats-tool-row[data-tool-name]:focus-visible { padding: 0 12px 12px; } +.vulnerability-list-toolbar, +.vulnerability-list-tools, +.vulnerability-group-controls, +.vulnerability-sort-label { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.vulnerability-list-toolbar { + justify-content: space-between; + margin-bottom: 12px; + color: var(--text-secondary); + font-size: 0.8125rem; +} + +.vulnerability-sort-label select { + width: auto; + min-width: 112px; + padding: 7px 10px; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--bg-primary); + color: var(--text-primary); + font: inherit; +} + +.vulnerability-group-controls[hidden] { + display: none; +} + +.vulnerability-group-risk { + display: inline-flex; + flex-wrap: wrap; + gap: 6px; + margin: 4px 8px; + vertical-align: middle; +} + +.vulnerability-group-pending { + font-size: 0.8125rem; + color: var(--text-secondary); + white-space: nowrap; +} + +.vulnerability-group-tags { + display: block; + margin-top: 6px; + color: var(--text-secondary); + font-size: 0.8125rem; + overflow-wrap: anywhere; +} + +.vulnerability-host-browser { + display: grid; + grid-template-columns: minmax(210px, 25%) minmax(0, 1fr); + align-items: start; + gap: 16px; +} + +.vulnerability-host-sidebar { + background: var(--bg-primary); + border: 1px solid var(--border-color); + border-radius: 10px; + padding: 12px; + position: sticky; + top: 0; +} + +#vulnerability-host-search { + width: 100%; + min-width: 0; + margin-bottom: 10px; + padding: 8px 10px; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--bg-primary); + color: var(--text-primary); + font: inherit; + font-size: 0.8125rem; +} + +.vulnerability-host-tree { + max-height: 65vh; + overflow-y: auto; +} + +.vulnerability-host-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + width: 100%; + padding: 8px; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--text-primary); + font: inherit; + font-size: 0.8125rem; + text-align: start; + cursor: pointer; + overflow-wrap: anywhere; +} + +.vulnerability-host-option:hover, +.vulnerability-host-option[aria-pressed="true"] { + background: var(--bg-secondary); +} + +.vulnerability-host-option[aria-pressed="true"] { + color: var(--accent-color); + font-weight: 600; +} + +.vulnerability-host-number { + color: var(--text-muted); + flex-shrink: 0; + font-size: 0.75rem; + margin-inline-start: 6px; +} + +.vulnerability-host-option-name { + min-width: 0; +} + +.vulnerability-host-risk-dot { + display: inline-block; + width: 7px; + height: 7px; + border-radius: 50%; + margin-inline-end: 7px; + vertical-align: middle; +} + +.vulnerability-host-risk-dot.severity-critical { background: #dc3545; } +.vulnerability-host-risk-dot.severity-high { background: #fd7e14; } +.vulnerability-host-risk-dot.severity-medium { background: #d69e00; } +.vulnerability-host-risk-dot.severity-low { background: #0d9488; } +.vulnerability-host-risk-dot.severity-info { background: #6c757d; } + +.vulnerability-host-overview, +#vulnerability-host-risk-summary { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; +} + +.vulnerability-host-overview { + justify-content: space-between; + margin-bottom: 10px; +} + +.vulnerability-domain-branch > summary { + cursor: pointer; + padding: 8px; + font-size: 0.8125rem; + overflow-wrap: anywhere; +} + +.vulnerability-domain-branch > .vulnerability-host-option { + padding-inline-start: 24px; +} + +.vulnerability-host-results { + min-width: 0; +} + +.vulnerability-host-results-heading { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 10px; +} + +.vulnerability-host-results-heading h3 { + font-size: 0.9375rem; + margin: 0; + overflow-wrap: anywhere; +} + +#vulnerability-host-selection-count { + color: var(--text-muted); + font-size: 0.8125rem; +} + +.vulnerability-table-scroll { + overflow-x: auto; + border: 1px solid var(--border-color); + border-radius: 10px; + background: var(--bg-primary); +} + +.vulnerability-table-scroll:has(.vuln-status-picker.open) { + padding-bottom: 200px; +} + +.vulnerability-host-table { + width: 100%; + min-width: 850px; + border-collapse: collapse; + table-layout: fixed; + font-size: 0.8125rem; +} + +.vulnerability-host-table th, +.vulnerability-host-table td { + padding: 12px 10px; + text-align: start; + border-bottom: 1px solid var(--border-color); + vertical-align: middle; +} + +.vulnerability-host-table th { + font-weight: 500; + color: var(--text-secondary); + background: var(--bg-secondary); +} + +.vulnerability-host-table th:nth-child(1) { width: 9%; } +.vulnerability-host-table th:nth-child(2) { width: 29%; } +.vulnerability-host-table th:nth-child(3) { width: 17%; } +.vulnerability-host-table th:nth-child(4) { width: 12%; } +.vulnerability-host-table th:nth-child(5) { width: 12%; } +.vulnerability-host-table th:nth-child(6) { width: 10%; } +.vulnerability-host-table th:nth-child(7) { width: 11%; } + +.vulnerability-row-toggle { + display: flex; + align-items: start; + gap: 8px; + width: 100%; + border: 0; + background: transparent; + color: var(--text-primary); + text-align: start; + font: inherit; + font-weight: 600; + cursor: pointer; + overflow-wrap: anywhere; +} + +.vulnerability-row-caret { + display: inline-block; + flex-shrink: 0; + transition: transform 0.15s; +} + +.vulnerability-table-title p, +.vulnerability-table-task, +.vulnerability-table-target { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-secondary); + margin: 4px 0 0; +} + +.vulnerability-table-target { + background: var(--bg-secondary); + border-radius: 4px; + padding: 3px 5px; +} + +.vulnerability-table-date { + color: var(--text-muted); +} + +.vulnerability-table-actions { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.vulnerability-table-actions .btn-ghost { + padding: 2px; + font-size: 0.75rem; +} + +.vulnerability-table-detail[hidden] { + display: none; +} + +.vulnerability-table-detail .vulnerability-content { + padding: 8px; + margin: 0; +} + +@media (max-width: 1100px) { + .vulnerability-host-browser { + grid-template-columns: minmax(0, 1fr); + } + .vulnerability-host-sidebar { + position: static; + } + .vulnerability-host-tree { + max-height: 220px; + } +} + +@media (max-width: 768px) { + #page-vulnerabilities .page-header-actions { + flex-direction: row; + flex-wrap: wrap; + } + .vulnerability-header { + flex-wrap: wrap; + gap: 8px; + } + .vulnerability-title-section { + min-width: 0; + flex-basis: 100%; + overflow-wrap: anywhere; + } +} + .vulnerability-card { background: var(--bg-primary); border: 1px solid var(--border-color); diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index c25b7f22..5039ea8d 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -2721,6 +2721,17 @@ "errorGeneric": "حدث خطأ ما. يُرجى المحاولة مرة أخرى." }, "vulnerabilityPage": { + "exportVisibleHosts": "تصدير النتائج المعروضة", + "tableDownload": "تنزيل", + "pageAllHosts": "جميع مضيفي هذه الصفحة", + "hostSearch": "البحث في جميع المضيفين…", + "domainAll": "جميع مضيفي النطاق في هذه الصفحة", + "tableSeverity": "الخطورة", + "tableTitle": "اسم الثغرة", + "tableStatus": "الحالة", + "tableTask": "المهمة", + "tableDate": "وقت الاكتشاف", + "tableActions": "الإجراءات", "alertTitle": "تنبيهات الثغرات عبر الروبوت", "alertDescription": "إرسال الثغرات المكتشفة حديثًا إلى الروبوتات المرتبطة بهذا الحساب، مع التصفية حسب الخطورة.", "alertHint": "إرسال الثغرات المكتشفة حديثًا التي تبلغ هذه الخطورة أو أعلى إلى حسابات الروبوت المرتبطة بك.", @@ -2771,6 +2782,14 @@ "noRecords": "لا توجد سجلات ثغرات", "unknownHost": "مضيف غير معروف", "groupPageCount": "الثغرات: {{count}}", + "pageFindings": "{{count}} ثغرة في هذه الصفحة", + "groupPending": "قيد المعالجة: {{count}}", + "sortLabel": "الترتيب", + "sortDefault": "الترتيب الافتراضي", + "sortSeverity": "الأعلى خطورة أولاً", + "sortLatest": "الأحدث أولاً", + "expandPage": "توسيع الصفحة", + "collapsePage": "طي الصفحة", "hostPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المضيف", "taskPagination": "عرض {{start}}–{{end}} من أصل {{total}} مجموعة حسب المهمة", "recordPagination": "عرض {{start}}–{{end}} من أصل {{total}} سجل ثغرة", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 130ccd32..a713df55 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -2864,6 +2864,17 @@ "errorGeneric": "Something went wrong. Please try again." }, "vulnerabilityPage": { + "exportVisibleHosts": "Export displayed findings", + "tableDownload": "Download", + "pageAllHosts": "All hosts on this page", + "hostSearch": "Search all hosts…", + "domainAll": "All hosts in this domain on this page", + "tableSeverity": "Severity", + "tableTitle": "Finding", + "tableStatus": "Status", + "tableTask": "Task", + "tableDate": "Discovered", + "tableActions": "Actions", "alertTitle": "Robot vulnerability alerts", "alertDescription": "Push newly discovered vulnerabilities to robots bound to this account, filtered by severity.", "alertHint": "Send newly discovered vulnerabilities at or above this severity to your bound robot accounts.", @@ -2914,6 +2925,14 @@ "noRecords": "No vulnerability records", "unknownHost": "Unknown host", "groupPageCount": "Findings: {{count}}", + "pageFindings": "{{count}} findings on this page", + "groupPending": "Pending: {{count}}", + "sortLabel": "Sort", + "sortDefault": "Default order", + "sortSeverity": "Severity first", + "sortLatest": "Newest findings", + "expandPage": "Expand page", + "collapsePage": "Collapse page", "hostPagination": "Showing {{start}}–{{end}} of {{total}} host groups", "taskPagination": "Showing {{start}}–{{end}} of {{total}} task groups", "recordPagination": "Showing {{start}}–{{end}} of {{total}} findings", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 64dcad98..d5a907b7 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -2877,6 +2877,17 @@ "errorGeneric": "Что-то пошло не так. Повторите попытку." }, "vulnerabilityPage": { + "exportVisibleHosts": "Экспорт показанных записей", + "tableDownload": "Скачать", + "pageAllHosts": "Все хосты на странице", + "hostSearch": "Поиск по всем хостам…", + "domainAll": "Все хосты домена на странице", + "tableSeverity": "Критичность", + "tableTitle": "Уязвимость", + "tableStatus": "Статус", + "tableTask": "Задача", + "tableDate": "Обнаружено", + "tableActions": "Действия", "alertTitle": "Оповещения робота об уязвимостях", "alertDescription": "Отправлять новые уязвимости роботам, привязанным к этой учётной записи, с фильтром по серьёзности.", "alertHint": "Отправлять новые уязвимости не ниже выбранной серьёзности на привязанные учётные записи роботов.", @@ -2927,6 +2938,14 @@ "noRecords": "Нет записей об уязвимостях", "unknownHost": "Неизвестный хост", "groupPageCount": "Уязвимостей: {{count}}", + "pageFindings": "На странице {{count}} уязвимостей", + "groupPending": "В обработке: {{count}}", + "sortLabel": "Сортировка", + "sortDefault": "По умолчанию", + "sortSeverity": "По критичности", + "sortLatest": "Сначала новые", + "expandPage": "Развернуть страницу", + "collapsePage": "Свернуть страницу", "hostPagination": "Показано {{start}}–{{end}} из {{total}} групп по хостам", "taskPagination": "Показано {{start}}–{{end}} из {{total}} групп по задачам", "recordPagination": "Показано {{start}}–{{end}} из {{total}} записей", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 7c9d9e5f..23077e88 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -2852,6 +2852,17 @@ "errorGeneric": "操作失败,请稍后重试。" }, "vulnerabilityPage": { + "exportVisibleHosts": "导出右侧列表", + "tableDownload": "下载", + "pageAllHosts": "本页全部域名", + "hostSearch": "搜索全部域名…", + "domainAll": "本页该域名下全部主机", + "tableSeverity": "严重度", + "tableTitle": "漏洞名称", + "tableStatus": "状态", + "tableTask": "所属任务", + "tableDate": "发现时间", + "tableActions": "操作", "alertTitle": "机器人漏洞提醒", "alertDescription": "按严重级别将新发现的漏洞推送至当前账号绑定的机器人。", "alertHint": "发现符合级别的新漏洞后,通过已绑定机器人账号推送。", @@ -2902,6 +2913,14 @@ "noRecords": "暂无漏洞记录", "unknownHost": "未识别到主机", "groupPageCount": "{{count}} 条漏洞", + "pageFindings": "本页 {{count}} 条漏洞", + "groupPending": "待处理 {{count}}", + "sortLabel": "排序", + "sortDefault": "默认顺序", + "sortSeverity": "高危优先", + "sortLatest": "最新发现", + "expandPage": "展开本页", + "collapsePage": "收起本页", "hostPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个域名组", "taskPagination": "显示 {{start}}–{{end}} / 共 {{total}} 个任务组", "recordPagination": "显示 {{start}}–{{end}} / 共 {{total}} 条漏洞", diff --git a/web/static/js/vulnerability-host-view.test.cjs b/web/static/js/vulnerability-host-view.test.cjs new file mode 100644 index 00000000..95f7f444 --- /dev/null +++ b/web/static/js/vulnerability-host-view.test.cjs @@ -0,0 +1,38 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const vm = require('node:vm'); +const test = require('node:test'); + +test('domain export includes exactly the visible records from the loaded page', () => { + const rows = [ + { id: 'a', target_host: 'api.example.com', target_domain: 'example.com' }, + { id: 'b', target_host: 'www.example.com', target_domain: 'example.com' }, + { id: 'c', target_host: 'example.net', target_domain: 'example.net' }, + { id: 'unknown', target_host: '' }, + ]; + const downloads = []; + const context = vm.createContext({ + vulnerabilityHostRows: rows, + vulnerabilityHostSelection: '', + formatVulnerabilityAsMarkdown: item => item.id, + triggerTextDownload: (name, content) => downloads.push(content), + }); + const source = fs.readFileSync('web/static/js/vulnerability.js', 'utf8'); + vm.runInContext(source.slice( + source.indexOf('function getVisibleVulnerabilityHostItems()'), + source.indexOf('function renderVulnerabilityHostRiskDot(') + ), context); + + for (const [selection, expected] of [ + ['', ['a', 'b', 'c', 'unknown']], + ['host:api.example.com', ['a']], + ['domain:example.com', ['a', 'b']], + ['host:', ['unknown']], + ['host:missing.example.com', []], + ]) { + context.vulnerabilityHostSelection = selection; + downloads.length = 0; + context.exportVisibleVulnerabilityHosts(); + assert.deepEqual(downloads, expected.length ? [expected.join('\n\n---\n\n')] : []); + } +}); diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index d5053061..60aa3d9d 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -65,6 +65,10 @@ function restoreExpandedVulnerabilityDetails(expandedIds) { const icon = document.getElementById('expand-icon-' + id); if (!content || content.style.display !== 'none') return; content.style.display = 'block'; + const row = content.closest('.vulnerability-table-detail'); + if (row) row.hidden = false; + const trigger = document.getElementById('vulnerability-row-toggle-' + id); + if (trigger) trigger.setAttribute('aria-expanded', 'true'); if (icon) icon.style.transform = 'rotate(90deg)'; loadVulnerabilityRelatedFacts(id).catch(function (e) { console.warn(e); }); }); @@ -218,6 +222,8 @@ async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) { if (!vulnerabilityStatusMatchesFilter(newStatus)) { await removeVulnerabilityCard(vulnId); + } else { + await loadVulnerabilities(null, { preserveScroll: true, silent: true }); } } catch (error) { console.error('更新漏洞状态失败:', error); @@ -230,8 +236,8 @@ async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) { // 从localStorage读取每页显示数量,默认为20 const getVulnerabilityPageSize = () => { - const saved = localStorage.getItem('vulnerabilityPageSize'); - return saved ? parseInt(saved, 10) : 20; + const saved = Number(localStorage.getItem('vulnerabilityPageSize')); + return [10, 20, 50, 100].includes(saved) ? saved : 20; }; let currentVulnerabilityId = null; @@ -256,6 +262,13 @@ const VULNERABILITY_VIEWS = ['host', 'task', 'none']; const savedVulnerabilityView = localStorage.getItem('vulnerabilityListView'); let vulnerabilityView = VULNERABILITY_VIEWS.includes(savedVulnerabilityView) ? savedVulnerabilityView : 'host'; let vulnerabilityListRequest = 0; +let vulnerabilityStatsRequest = 0; +const savedVulnerabilitySort = localStorage.getItem('vulnerabilityListSort'); +let vulnerabilitySort = ['severity', 'latest'].includes(savedVulnerabilitySort) ? savedVulnerabilitySort : ''; +let vulnerabilityHostQuery = ''; +let vulnerabilityHostSelection = ''; +let vulnerabilityHostRows = []; +let vulnerabilityHostSearchTimer = null; const VULN_STAT_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info']; let vulnerabilityStatCardsBound = false; @@ -378,6 +391,7 @@ async function initVulnerabilityPage() { initVulnerabilityStatCards(); initVulnerabilityFilterPanel(); initVulnerabilityViewSwitch(); + document.getElementById('vulnerability-sort').value = vulnerabilitySort; syncVulnerabilityFiltersFromLocationHash(); await refreshVulnerabilityProjectFilter(); updateVulnerabilityFilterPanelState(); @@ -400,6 +414,8 @@ function initVulnerabilityViewSwitch() { const view = event.target.closest('button[data-vuln-view]')?.dataset.vulnView; if (!VULNERABILITY_VIEWS.includes(view) || view === vulnerabilityView) return; vulnerabilityView = view; + clearTimeout(vulnerabilityHostSearchTimer); + vulnerabilityHostSelection = ''; localStorage.setItem('vulnerabilityListView', view); updateSelection(); const scroll = getVulnerabilityScrollContainer(); @@ -1211,6 +1227,7 @@ function updateVulnerabilityStatStackedBar(bySeverity, total) { // 加载漏洞统计 async function loadVulnerabilityStats() { + const request = ++vulnerabilityStatsRequest; try { // 检查apiFetch是否可用 if (typeof apiFetch === 'undefined') { @@ -1228,8 +1245,10 @@ async function loadVulnerabilityStats() { } const stats = await response.json(); + if (request !== vulnerabilityStatsRequest) return; updateVulnerabilityStats(stats); } catch (error) { + if (request !== vulnerabilityStatsRequest) return; console.error('加载漏洞统计失败:', error); // 统计失败不影响列表显示,只重置统计为0 updateVulnerabilityStats(null); @@ -1296,6 +1315,7 @@ async function loadVulnerabilities(page = null, options = {}) { : new Map(); if (!silent) { listContainer.innerHTML = `
| ' + escapeHtml(vulnT('vulnerabilityPage.' + key)) + ' | ').join('')} +
|---|
${escapeHtml((vuln.description || '').slice(0, 160))}
+