From 2c4364ad47e33560e5d4ba2844a320c4b48c4351 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:04:06 +0800 Subject: [PATCH] feat(vulnerabilities): add host, task, and raw list views --- internal/database/vulnerability.go | 21 +++-- internal/handler/vulnerability.go | 14 +-- internal/handler/vulnerability_group_test.go | 33 +++++-- web/static/css/style.css | 61 ++++++++++-- web/static/i18n/ar-SA.json | 8 +- web/static/i18n/en-US.json | 8 +- web/static/i18n/ru-RU.json | 8 +- web/static/i18n/zh-CN.json | 8 +- web/static/js/vulnerability.js | 97 ++++++++++++++------ web/templates/index.html | 14 ++- 10 files changed, 206 insertions(+), 66 deletions(-) diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index eae814e7..1acd99cb 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -239,11 +239,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.listVulnerabilitiesForAccess(limit, offset, filter, access, false) -} - -func (db *DB) ListVulnerabilitiesByHostForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess) ([]*Vulnerability, error) { - return db.listVulnerabilitiesForAccess(limit, offset, filter, access, true) + return db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, "") } func vulnerabilityTargetHost(target string) string { @@ -292,19 +288,26 @@ func vulnerabilityTargetHost(target string) string { return host } -func (db *DB) listVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, byHost bool) ([]*Vulnerability, error) { +func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, groupBy string) ([]*Vulnerability, error) { hostExpr, order := "NULL", "created_at DESC" - if byHost { + switch groupBy { + case "host": hostExpr = "vulnerability_target_host(target)" order = "target_host = '', target_host, created_at DESC, id" + case "task": + order = `task_id = '', task_id, + CASE WHEN task_id = '' THEN NULLIF(TRIM(task_tag), '') END ASC NULLS LAST, + created_at DESC, id` + case "none": + order = "created_at DESC, id" } query := ` SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, conversation_tag, task_tag, vulnerability_type, target, COALESCE(preconditions,''), COALESCE(reproduction_steps,''), COALESCE(evidence,''), impact, recommendation, COALESCE(retest_notes,''), COALESCE(retest_log,''), - COALESCE((SELECT bt.id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id LIMIT 1), '') AS task_id, - COALESCE((SELECT bt.queue_id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id LIMIT 1), '') AS task_queue_id, + COALESCE((SELECT bt.id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '') AS task_id, + COALESCE((SELECT bt.queue_id FROM batch_tasks bt WHERE bt.conversation_id = vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1), '') AS task_queue_id, created_at, updated_at, ` + hostExpr + ` AS target_host FROM vulnerabilities WHERE 1=1 diff --git a/internal/handler/vulnerability.go b/internal/handler/vulnerability.go index 7b211ff7..fb580b2b 100644 --- a/internal/handler/vulnerability.go +++ b/internal/handler/vulnerability.go @@ -184,7 +184,7 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { pageStr := c.Query("page") filter := parseVulnerabilityListFilter(c) access := vulnerabilityAccessFromContext(c) - byHost := c.Query("group_by") == "host" + groupBy := c.Query("group_by") limit, _ := strconv.Atoi(limitStr) if limit <= 0 || limit > 100 { @@ -224,15 +224,11 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) { page = (offset / limit) + 1 } - list := h.db.ListVulnerabilitiesForAccess - if byHost { - list = h.db.ListVulnerabilitiesByHostForAccess - if page > totalPages { - page = totalPages - offset = (page - 1) * limit - } + if (groupBy == "host" || groupBy == "task" || groupBy == "none") && page > totalPages { + page = totalPages + offset = (page - 1) * limit } - vulnerabilities, err := list(limit, offset, filter, access) + vulnerabilities, err := h.db.ListVulnerabilitiesByGroupForAccess(limit, offset, filter, access, groupBy) 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 6b64082e..f34c423b 100644 --- a/internal/handler/vulnerability_group_test.go +++ b/internal/handler/vulnerability_group_test.go @@ -13,25 +13,38 @@ import ( "go.uber.org/zap" ) -func TestListVulnerabilitiesGroupedByHost(t *testing.T) { +func TestListVulnerabilitiesGroupedViews(t *testing.T) { db, err := database.NewDB(filepath.Join(t.TempDir(), "grouped.db"), zap.NewNop()) if err != nil { t.Fatal(err) } defer db.Close() + linked, err := db.CreateConversation("linked task", database.ConversationCreateMeta{}) + if err != nil { + t.Fatal(err) + } + if err := db.CreateBatchQueue("queue", "queue", "", "eino_single", "manual", "", nil, "", 1, + []map[string]interface{}{{"id": "task", "message": "task"}}); err != nil { + t.Fatal(err) + } + if err := db.UpdateBatchTaskStatus("queue", "task", "completed", linked.ID, "", ""); err != nil { + t.Fatal(err) + } + for i, item := range []struct { - id, target, severity string + id, target, severity, taskTag, conversationID string }{ - {"domain-old", "HTTPS://Example.COM.:443/login?keyword=%ZZ (旧接口);https://secondary.example.net/", "high"}, - {"domain-new", "example.com:8443(受影响的服务)", "high"}, - {"subdomain", "https://sub.example.com(旧记录)", "high"}, - {"ipv6", "https://[2001:0DB8::1]:8080/", "high"}, - {"unknown", "/api/login", "high"}, - {"filtered", "https://other.example.com/", "low"}, + {"domain-old", "HTTPS://Example.COM.:443/login?keyword=%ZZ (旧接口);https://secondary.example.net/", "high", "a", ""}, + {"domain-new", "example.com:8443(受影响的服务)", "high", "", linked.ID}, + {"subdomain", "https://sub.example.com(旧记录)", "high", "a", ""}, + {"ipv6", "https://[2001:0DB8::1]:8080/", "high", "b", linked.ID}, + {"unknown", "/api/login", "high", "", ""}, + {"filtered", "https://other.example.com/", "low", "", ""}, } { _, err := db.CreateVulnerability(&database.Vulnerability{ ID: item.id, Target: item.target, Title: item.id, Severity: item.severity, + TaskTag: item.taskTag, ConversationID: item.conversationID, CreatedAt: time.Unix(int64(i+1), 0), }) if err != nil { @@ -64,6 +77,10 @@ func TestListVulnerabilitiesGroupedByHost(t *testing.T) { {"group_by=host&page=1", 1, []string{"ipv6", "domain-new"}, []string{"2001:db8::1", "example.com"}}, {"group_by=host&page=2", 2, []string{"domain-old", "subdomain"}, []string{"example.com", "sub.example.com"}}, {"group_by=host&page=4", 3, []string{"unknown"}, []string{""}}, + {"group_by=task&page=1", 1, []string{"ipv6", "domain-new"}, nil}, + {"group_by=task&page=2", 2, []string{"subdomain", "domain-old"}, nil}, + {"group_by=task&page=3", 3, []string{"unknown"}, nil}, + {"group_by=none&page=1", 1, []string{"unknown", "ipv6"}, nil}, {"page=1", 1, []string{"unknown", "ipv6"}, nil}, } { t.Run(tc.query, func(t *testing.T) { diff --git a/web/static/css/style.css b/web/static/css/style.css index 163e1f1e..bf59ecab 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -27456,37 +27456,86 @@ tr.mcp-stats-tool-row[data-tool-name]:focus-visible { margin-bottom: 0; } -.vulnerability-host-group { +#page-vulnerabilities > .page-header, +.vulnerability-header-start { + flex-wrap: wrap; + gap: 12px; +} + +.vulnerability-header-start { + display: flex; + align-items: center; + min-width: 0; +} + +.vulnerability-view-switch { + display: flex; + flex-wrap: wrap; + gap: 2px; + padding: 3px; + border: 1px solid var(--border-color); + border-radius: 8px; + background: var(--bg-secondary); +} + +.vulnerability-view-switch button { + border: 0; + border-radius: 5px; + background: transparent; + color: var(--text-secondary); + padding: 5px 10px; + font: inherit; + font-size: 0.8125rem; + cursor: pointer; +} + +.vulnerability-view-switch button:hover { + color: var(--text-primary); +} + +.vulnerability-view-switch button[aria-pressed="true"] { + background: var(--bg-primary); + color: var(--text-primary); + font-weight: 600; + box-shadow: var(--shadow-sm); +} + +.vulnerability-view-switch button:focus-visible { + outline: 2px solid var(--accent-color); + outline-offset: -2px; +} + +.vulnerability-group { min-width: 0; border: 1px solid var(--border-color); border-radius: 8px; background: var(--bg-secondary); } -.vulnerability-host-group > summary { +.vulnerability-group > summary { padding: 12px 16px; cursor: pointer; overflow-wrap: anywhere; } -.vulnerability-host-group > summary:focus-visible { +.vulnerability-group > summary:focus-visible { outline: 2px solid var(--accent-color); outline-offset: -2px; border-radius: 8px; } -.vulnerability-host-name { +.vulnerability-group-name { margin-inline-start: 6px; font-weight: 600; } -.vulnerability-host-count { +.vulnerability-group-count { margin-inline-start: 8px; color: var(--text-muted); font-size: 0.8125rem; } -.vulnerability-host-cards { +.vulnerability-group-cards { display: grid; gap: 10px; padding: 0 12px 12px; diff --git a/web/static/i18n/ar-SA.json b/web/static/i18n/ar-SA.json index 101b4600..5d4de63e 100644 --- a/web/static/i18n/ar-SA.json +++ b/web/static/i18n/ar-SA.json @@ -2770,7 +2770,13 @@ "loadListFailed": "فشل التحميل", "noRecords": "لا توجد سجلات ثغرات", "unknownHost": "مضيف غير معروف", - "hostPageCount": "{{count}} في هذه الصفحة", + "groupPageCount": "{{count}} في هذه الصفحة", + "viewLabel": "عرض الثغرات", + "viewHost": "حسب المضيف", + "viewTask": "حسب المهمة", + "viewRaw": "السجلات الأصلية", + "viewTaskGroup": "المهمة {{id}}", + "viewNoTask": "لا توجد مهمة مرتبطة", "batchExport": "تصدير جماعي", "batchDelete": "حذف جماعي", "batchDeleteNoResults": "لا توجد ثغرات تطابق عوامل التصفية الحالية لحذفها", diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 80f44786..506855bc 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -2913,7 +2913,13 @@ "loadListFailed": "Failed to load", "noRecords": "No vulnerability records", "unknownHost": "Unknown host", - "hostPageCount": "{{count}} on this page", + "groupPageCount": "{{count}} on this page", + "viewLabel": "Vulnerability view", + "viewHost": "By host", + "viewTask": "By task", + "viewRaw": "Raw records", + "viewTaskGroup": "Task {{id}}", + "viewNoTask": "No linked task", "batchExport": "Batch export", "batchDelete": "Batch delete", "batchDeleteNoResults": "No vulnerabilities match the current filters to delete", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 66297f83..36021303 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -2926,7 +2926,13 @@ "loadListFailed": "Не удалось загрузить", "noRecords": "Нет записей об уязвимостях", "unknownHost": "Неизвестный хост", - "hostPageCount": "На этой странице: {{count}}", + "groupPageCount": "На этой странице: {{count}}", + "viewLabel": "Вид списка уязвимостей", + "viewHost": "По хостам", + "viewTask": "По задачам", + "viewRaw": "Исходные записи", + "viewTaskGroup": "Задача {{id}}", + "viewNoTask": "Без связанной задачи", "batchExport": "Пакетный экспорт", "batchDelete": "Пакетное удаление", "batchDeleteNoResults": "Нет уязвимостей по текущим фильтрам для удаления", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 9de8313c..b1eadc22 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -2901,7 +2901,13 @@ "loadListFailed": "加载失败", "noRecords": "暂无漏洞记录", "unknownHost": "未识别到主机", - "hostPageCount": "本页 {{count}} 条", + "groupPageCount": "本页 {{count}} 条", + "viewLabel": "漏洞视图", + "viewHost": "按域名", + "viewTask": "按任务", + "viewRaw": "原始记录", + "viewTaskGroup": "任务 {{id}}", + "viewNoTask": "未关联任务", "batchExport": "批量导出", "batchDelete": "批量删除", "batchDeleteNoResults": "当前筛选条件下没有可删除的漏洞", diff --git a/web/static/js/vulnerability.js b/web/static/js/vulnerability.js index fa22dfde..d24bd38a 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -252,6 +252,10 @@ let vulnerabilityPagination = { total: 0, totalPages: 1 }; +const VULNERABILITY_VIEWS = ['host', 'task', 'none']; +const savedVulnerabilityView = localStorage.getItem('vulnerabilityListView'); +let vulnerabilityView = VULNERABILITY_VIEWS.includes(savedVulnerabilityView) ? savedVulnerabilityView : 'host'; +let vulnerabilityListRequest = 0; const VULN_STAT_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info']; let vulnerabilityStatCardsBound = false; @@ -373,6 +377,7 @@ async function initVulnerabilityPage() { vulnerabilityPagination.pageSize = getVulnerabilityPageSize(); initVulnerabilityStatCards(); initVulnerabilityFilterPanel(); + initVulnerabilityViewSwitch(); syncVulnerabilityFiltersFromLocationHash(); await refreshVulnerabilityProjectFilter(); updateVulnerabilityFilterPanelState(); @@ -382,6 +387,27 @@ async function initVulnerabilityPage() { loadVulnerabilities(); } +function initVulnerabilityViewSwitch() { + const control = document.getElementById('vulnerability-view-switch'); + if (!control || control.dataset.bound) return; + control.dataset.bound = 'true'; + const buttons = control.querySelectorAll('button[data-vuln-view]'); + const updateSelection = () => buttons.forEach(button => { + button.setAttribute('aria-pressed', String(button.dataset.vulnView === vulnerabilityView)); + }); + updateSelection(); + control.addEventListener('click', event => { + const view = event.target.closest('button[data-vuln-view]')?.dataset.vulnView; + if (!VULNERABILITY_VIEWS.includes(view) || view === vulnerabilityView) return; + vulnerabilityView = view; + localStorage.setItem('vulnerabilityListView', view); + updateSelection(); + const scroll = getVulnerabilityScrollContainer(); + if (scroll) scroll.scrollTop = 0; + loadVulnerabilities(1); + }); +} + function initVulnerabilityStatCards() { if (vulnerabilityStatCardsBound) { syncVulnerabilityStatCardActiveState(); @@ -1251,6 +1277,8 @@ function updateVulnerabilityStats(stats) { // 加载漏洞列表 async function loadVulnerabilities(page = null, options = {}) { + const request = ++vulnerabilityListRequest; + const view = vulnerabilityView; const opts = options && typeof options === 'object' ? options : {}; const preserveScroll = !!opts.preserveScroll; const silent = !!opts.silent; @@ -1264,7 +1292,7 @@ async function loadVulnerabilities(page = null, options = {}) { const listContainer = document.getElementById('vulnerabilities-list'); const groupOpenStates = preserveScroll - ? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-host-group'), group => [group.dataset.host, group.open])) + ? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-group'), group => [group.dataset.groupKey, group.open])) : new Map(); if (!silent) { listContainer.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loading'))}
`; @@ -1283,7 +1311,7 @@ async function loadVulnerabilities(page = null, options = {}) { } const params = buildVulnerabilityFilterParams(); - params.append('group_by', 'host'); + params.append('group_by', view); params.append('page', vulnerabilityPagination.currentPage.toString()); params.append('limit', vulnerabilityPagination.pageSize.toString()); @@ -1295,6 +1323,7 @@ async function loadVulnerabilities(page = null, options = {}) { } const data = await response.json(); + if (request !== vulnerabilityListRequest) return; // 判断响应格式:新格式(有total字段)还是旧格式(直接是数组) let vulnerabilities; @@ -1318,15 +1347,16 @@ async function loadVulnerabilities(page = null, options = {}) { console.error('未知的响应格式:', data); } - renderVulnerabilities(vulnerabilities, { expandedIds: expandedIds || [], groupOpenStates }); + renderVulnerabilities(vulnerabilities, { view, expandedIds: expandedIds || [], groupOpenStates }); renderVulnerabilityPagination(); if (preserveScroll && scrollEl) { requestAnimationFrame(function () { - scrollEl.scrollTop = scrollTop; + if (request === vulnerabilityListRequest) scrollEl.scrollTop = scrollTop; }); } } catch (error) { + if (request !== vulnerabilityListRequest) return; console.error('加载漏洞列表失败:', error); listContainer.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loadListFailed'))}: ${escapeHtml(error.message)}
`; } @@ -1345,39 +1375,52 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { return; } - const groups = new Map(); - for (const vuln of vulnerabilities) { - const host = vuln.target_host || ''; - if (!groups.has(host)) groups.set(host, []); - groups.get(host).push(vuln); - } const exactMatch = vulnerabilities.length === 1 && vulnerabilityFilters.id === vulnerabilities[0].id ? vulnerabilities[0].id : null; - const expandedIds = new Set(opts.expandedIds); - listContainer.innerHTML = Array.from(groups, ([host, items], index) => { - const open = exactMatch || (opts.groupOpenStates?.get(host) ?? - (index === 0 || items.some(vuln => expandedIds.has(vuln.id)))); - const label = host || vulnT('vulnerabilityPage.unknownHost'); - const count = vulnT('vulnerabilityPage.hostPageCount', { count: items.length }); - return ` -
- - ${escapeHtml(label)} - ${escapeHtml(count)} - -
${items.map(renderVulnerabilityCard).join('')}
-
- `; - }).join(''); + const expandedIds = exactMatch ? [exactMatch] : opts.expandedIds; + listContainer.innerHTML = opts.view === 'none' + ? vulnerabilities.map(renderVulnerabilityCard).join('') + : renderVulnerabilityGroups(vulnerabilities, { ...opts, expandedIds }); initVulnerabilityStatusPickers(listContainer); initVulnerabilityProjectBindSelects(listContainer); if (typeof window.applyTranslations === 'function') { window.applyTranslations(listContainer); } if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer); + restoreExpandedVulnerabilityDetails(expandedIds); +} - restoreExpandedVulnerabilityDetails(exactMatch ? [exactMatch] : opts.expandedIds); +function renderVulnerabilityGroups(vulnerabilities, opts) { + const groups = new Map(); + for (const vuln of vulnerabilities) { + let key = vuln.target_host || ''; + let label = key || vulnT('vulnerabilityPage.unknownHost'); + if (opts.view === 'task') { + const taskTag = (vuln.task_tag || '').replace(/^ +| +$/g, ''); + key = vuln.task_id ? 'id:' + vuln.task_id : 'tag:' + taskTag; + label = vuln.task_id + ? vulnT('vulnerabilityPage.viewTaskGroup', { id: vuln.task_id }) + : taskTag || vulnT('vulnerabilityPage.viewNoTask'); + } + if (!groups.has(key)) groups.set(key, { label, items: [] }); + groups.get(key).items.push(vuln); + } + const expandedIds = new Set(opts.expandedIds); + return Array.from(groups, ([key, { label, items }], index) => { + 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 }); + return ` +
+ + ${escapeHtml(label)} + ${escapeHtml(count)} + +
${items.map(renderVulnerabilityCard).join('')}
+
+ `; + }).join(''); } function renderVulnerabilityCard(vuln) { diff --git a/web/templates/index.html b/web/templates/index.html index 47298b9f..adf088c5 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -39,7 +39,7 @@ } })(); - + @@ -2695,7 +2695,15 @@