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.loading'))}
`; + updateVulnerabilityGroupControls(); } try { @@ -1312,6 +1332,8 @@ async function loadVulnerabilities(page = null, options = {}) { const params = buildVulnerabilityFilterParams(); params.append('group_by', view); + if (vulnerabilitySort) params.append('sort', vulnerabilitySort); + if (view === 'host' && vulnerabilityHostQuery) params.append('host_q', vulnerabilityHostQuery); params.append('page', vulnerabilityPagination.currentPage.toString()); params.append('limit', vulnerabilityPagination.pageSize.toString()); @@ -1349,6 +1371,10 @@ async function loadVulnerabilities(page = null, options = {}) { renderVulnerabilities(vulnerabilities, { view, expandedIds: expandedIds || [], groupOpenStates }); renderVulnerabilityPagination(); + if (page !== null && !preserveScroll) { + const container = getVulnerabilityScrollContainer(); + if (container) container.scrollTop = 0; + } if (preserveScroll && scrollEl) { requestAnimationFrame(function () { @@ -1359,6 +1385,7 @@ async function loadVulnerabilities(page = null, options = {}) { if (request !== vulnerabilityListRequest) return; console.error('加载漏洞列表失败:', error); listContainer.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loadListFailed'))}: ${escapeHtml(error.message)}
`; + updateVulnerabilityGroupControls(); } } @@ -1366,12 +1393,17 @@ async function loadVulnerabilities(page = null, options = {}) { function renderVulnerabilities(vulnerabilities, renderOptions) { const opts = renderOptions && typeof renderOptions === 'object' ? renderOptions : {}; const listContainer = document.getElementById('vulnerabilities-list'); + if (opts.view === 'host') { + renderVulnerabilityHostBrowser(Array.isArray(vulnerabilities) ? vulnerabilities : [], opts); + return; + } if (!Array.isArray(vulnerabilities) || vulnerabilities.length === 0) { listContainer.innerHTML = '
暂无漏洞记录
'; if (typeof window.applyTranslations === 'function') { window.applyTranslations(listContainer); } + updateVulnerabilityGroupControls(); return; } @@ -1389,6 +1421,40 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { } if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer); restoreExpandedVulnerabilityDetails(expandedIds); + listContainer.querySelectorAll('.vulnerability-group').forEach(group => { + group.addEventListener('toggle', updateVulnerabilityGroupControls); + }); + updateVulnerabilityGroupControls(); +} + +function changeVulnerabilitySort(value) { + if (!['', 'severity', 'latest'].includes(value)) return; + vulnerabilitySort = value; + localStorage.setItem('vulnerabilityListSort', value); + loadVulnerabilities(1); +} + +function setVulnerabilityGroupsOpen(open) { + document.querySelectorAll('#vulnerabilities-list .vulnerability-group').forEach(group => { + group.open = open; + }); + updateVulnerabilityGroupControls(); +} + +function updateVulnerabilityGroupControls() { + const list = document.getElementById('vulnerabilities-list'); + const toolbar = document.getElementById('vulnerability-list-toolbar'); + if (!list || !toolbar) return; + const groups = Array.from(list.querySelectorAll('.vulnerability-group')); + const count = vulnerabilityView === 'host' && list.querySelector('.vulnerability-host-browser') + ? vulnerabilityHostRows.length + : list.querySelectorAll('.vulnerability-card, .vulnerability-table-item').length; + document.getElementById('vulnerability-page-summary').textContent = count + ? vulnT('vulnerabilityPage.pageFindings', { count }) : ''; + const controls = document.getElementById('vulnerability-group-controls'); + controls.hidden = vulnerabilityView !== 'task'; + document.getElementById('vulnerability-expand-groups').disabled = !groups.some(group => !group.open); + document.getElementById('vulnerability-collapse-groups').disabled = !groups.some(group => group.open); } function renderVulnerabilityGroups(vulnerabilities, opts) { @@ -1411,11 +1477,26 @@ function renderVulnerabilityGroups(vulnerabilities, opts) { const open = items.some(vuln => vulnerabilityFilters.id === vuln.id) || (opts.groupOpenStates?.get(key) ?? (index === 0 || items.some(vuln => expandedIds.has(vuln.id)))); const count = vulnT('vulnerabilityPage.groupPageCount', { count: items.length }); + const severities = {}; + let pending = 0; + for (const item of items) { + severities[item.severity] = (severities[item.severity] || 0) + 1; + if (!item.status || item.status === 'open' || item.status === 'confirmed') pending++; + } + const badges = VULN_STAT_SEVERITIES.filter(severity => severities[severity]).map(severity => + `${escapeHtml(vulnSeverityLabel(severity))} ${severities[severity]}` + ).join(''); + const tags = opts.view === 'task' && items[0].task_id + ? Array.from(new Set(items.map(item => (item.task_tag || '').trim()).filter(Boolean))).join(' · ') + : ''; return `
${escapeHtml(label)} ${escapeHtml(count)} + ${badges} + ${escapeHtml(vulnT('vulnerabilityPage.groupPending', { count: pending }))} + ${tags ? `${escapeHtml(tags)}` : ''}
${items.map(renderVulnerabilityCard).join('')}
@@ -1423,6 +1504,177 @@ function renderVulnerabilityGroups(vulnerabilities, opts) { }).join(''); } +function renderVulnerabilityHostBrowser(vulnerabilities, opts) { + const activeSearch = document.activeElement?.id === 'vulnerability-host-search'; + const caret = activeSearch ? document.activeElement.selectionStart : null; + vulnerabilityHostRows = vulnerabilities; + const domains = new Map(); + for (const vuln of vulnerabilities) { + const host = vuln.target_host || ''; + const domain = vuln.target_domain || host; + if (!domains.has(domain)) domains.set(domain, new Map()); + const hosts = domains.get(domain); + hosts.set(host, (hosts.get(host) || 0) + 1); + } + const button = (key, label, count, items = []) => ` + `; + const tree = Array.from(domains, ([domain, hosts]) => { + const count = Array.from(hosts.values()).reduce((sum, n) => sum + n, 0); + if (hosts.size === 1 && hosts.has(domain)) { + return button('host:' + domain, domain || vulnT('vulnerabilityPage.unknownHost'), count, + vulnerabilities.filter(vuln => (vuln.target_host || '') === domain)); + } + return `
+ ${escapeHtml(domain)} ${count} + ${button('domain:' + domain, vulnT('vulnerabilityPage.domainAll'), count)} + ${Array.from(hosts, ([host, n]) => button('host:' + host, host, n, + vulnerabilities.filter(vuln => (vuln.target_host || '') === host))).join('')} +
`; + }).join(''); + const list = document.getElementById('vulnerabilities-list'); + list.innerHTML = ` +
+ +
+
+

+ +
+
+
+ +
+
+
+
`; + const search = document.getElementById('vulnerability-host-search'); + search.addEventListener('input', () => { + vulnerabilityHostQuery = search.value.trim(); + clearTimeout(vulnerabilityHostSearchTimer); + // Invalidate an in-flight response as soon as the next query is typed. + vulnerabilityListRequest++; + vulnerabilityHostSearchTimer = setTimeout(() => { + vulnerabilityHostSelection = ''; + loadVulnerabilities(1, { silent: true }); + }, VULNERABILITY_FILTER_DEBOUNCE_MS); + }); + list.querySelector('.vulnerability-host-tree').addEventListener('click', event => { + const option = event.target.closest('button[data-host-key]'); + if (!option) return; + vulnerabilityHostSelection = option.dataset.hostKey; + renderVulnerabilityHostTable(); + }); + if (!Array.from(list.querySelectorAll('[data-host-key]')).some(el => el.dataset.hostKey === vulnerabilityHostSelection)) { + vulnerabilityHostSelection = ''; + } + renderVulnerabilityHostTable(opts.expandedIds); + if (activeSearch) { + search.focus({ preventScroll: true }); + search.setSelectionRange(caret, caret); + } +} + +function getVisibleVulnerabilityHostItems() { + const selection = vulnerabilityHostSelection; + return vulnerabilityHostRows.filter(vuln => !selection || + selection === 'host:' + (vuln.target_host || '') || + selection === 'domain:' + (vuln.target_domain || vuln.target_host || '')); +} + +function exportVisibleVulnerabilityHosts() { + const items = getVisibleVulnerabilityHostItems(); + if (!items.length) return; + const content = items.map(formatVulnerabilityAsMarkdown).join('\n\n---\n\n'); + triggerTextDownload('vulnerabilities-hosts-' + new Date().toISOString().slice(0, 10) + '.md', content); +} + +function renderVulnerabilityHostRiskDot(items) { + const highest = VULN_STAT_SEVERITIES.find(severity => items.some(item => item.severity === severity)); + return highest ? `` : ''; +} + +function renderVulnerabilityHostTable(expandedIds) { + const selection = vulnerabilityHostSelection; + const items = getVisibleVulnerabilityHostItems(); + document.querySelectorAll('#vulnerabilities-list [data-host-key]').forEach(option => { + option.setAttribute('aria-pressed', String(option.dataset.hostKey === selection)); + }); + const label = selection ? selection.slice(selection.indexOf(':') + 1) : vulnT('vulnerabilityPage.pageAllHosts'); + document.getElementById('vulnerability-host-selection').textContent = label || vulnT('vulnerabilityPage.unknownHost'); + document.getElementById('vulnerability-host-selection-count').textContent = + vulnT('vulnerabilityPage.groupPageCount', { count: items.length }); + const counts = {}; + let pending = 0; + for (const item of items) { + counts[item.severity] = (counts[item.severity] || 0) + 1; + if (!item.status || item.status === 'open' || item.status === 'confirmed') pending++; + } + document.getElementById('vulnerability-host-risk-summary').innerHTML = + VULN_STAT_SEVERITIES.filter(severity => counts[severity]).map(severity => + `${escapeHtml(vulnSeverityLabel(severity))} ${counts[severity]}` + ).join('') + `${escapeHtml(vulnT('vulnerabilityPage.groupPending', { count: pending }))}`; + document.getElementById('vulnerability-host-export').disabled = items.length === 0; + const container = document.getElementById('vulnerability-host-table'); + container.innerHTML = items.length ? `
+ + + ${['tableSeverity', 'tableTitle', 'detailTarget', 'tableStatus', 'tableTask', 'tableDate', 'tableActions'] + .map(key => '').join('')} + + ${items.map(renderVulnerabilityTableItem).join('')} +
' + escapeHtml(vulnT('vulnerabilityPage.' + key)) + '
` : `
${escapeHtml(vulnT('vulnerabilityPage.noRecords'))}
`; + initVulnerabilityStatusPickers(container); + initVulnerabilityProjectBindSelects(container); + if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(container); + const exact = items.find(vuln => vulnerabilityFilters.id === vuln.id); + restoreExpandedVulnerabilityDetails(exact ? [exact.id] : expandedIds); + updateVulnerabilityGroupControls(); +} + +function renderVulnerabilityTableItem(vuln) { + const id = escapeAttr(vuln.id); + const jsID = escapeJsStringAttr(vuln.id); + const task = vuln.task_tag || vuln.task_id || vulnT('vulnerabilityPage.viewNoTask'); + const created = new Date(vuln.created_at); + return ` + + ${escapeHtml(vulnSeverityLabel(vuln.severity))} + + +

${escapeHtml((vuln.description || '').slice(0, 160))}

+ + ${escapeHtml(vuln.target_host || vuln.target || '—')} + ${buildVulnerabilityStatusPicker(vuln)} + ${escapeHtml(task)} + ${escapeHtml(created.toLocaleString(vulnDateLocale(), { + month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' + }))} +
+ + + + +
+ + ${renderVulnerabilityDetailsContent(vuln)} + `; +} + function renderVulnerabilityCard(vuln) { const severityClass = `severity-${vuln.severity}`; const severityText = vulnSeverityLabel(vuln.severity); @@ -1477,7 +1729,14 @@ function renderVulnerabilityCard(vuln) { - + `; +} + +function renderVulnerabilityDetailsContent(vuln) { + return ` + - `; } @@ -1870,7 +2128,7 @@ function clearVulnerabilityFilters() { // 刷新漏洞 function refreshVulnerabilities() { loadVulnerabilityStats(); - loadVulnerabilities(); + loadVulnerabilities(null, { preserveScroll: true, silent: true }); } async function loadVulnerabilityAlertSubscription() { @@ -1961,6 +2219,11 @@ function toggleVulnerabilityDetails(id) { content.style.display = 'none'; icon.style.transform = 'rotate(0deg)'; } + const expanded = content.style.display !== 'none'; + const row = content.closest('.vulnerability-table-detail'); + if (row) row.hidden = !expanded; + const trigger = document.getElementById('vulnerability-row-toggle-' + id); + if (trigger) trigger.setAttribute('aria-expanded', String(expanded)); } /** 展开漏洞详情时加载关联项目事实 */ diff --git a/web/templates/index.html b/web/templates/index.html index 60142a43..f2110a85 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -39,7 +39,7 @@ } })(); - + @@ -2857,6 +2857,23 @@ +
+ +
+ +
+ + +
+
+
加载中...
@@ -7089,7 +7106,7 @@ - +