From b77c8cda278889710582ab1a9a40baea64018fc5 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:47:17 +0800 Subject: [PATCH] fix(vulnerabilities): prefer domains and unify task tree navigation --- internal/database/vulnerability.go | 34 ++- internal/database/vulnerability_workspace.go | 52 +++- .../database/vulnerability_workspace_test.go | 32 ++- internal/handler/vulnerability.go | 1 + internal/handler/vulnerability_group_test.go | 3 +- web/static/css/vulnerability-workspace.css | 14 +- web/static/i18n/ar-SA.json | 7 +- web/static/i18n/en-US.json | 7 +- web/static/i18n/ru-RU.json | 7 +- web/static/i18n/zh-CN.json | 7 +- .../js/vulnerability-host-view.test.cjs | 17 +- web/static/js/vulnerability.js | 223 +++++++----------- web/templates/index.html | 13 +- 13 files changed, 238 insertions(+), 179 deletions(-) diff --git a/internal/database/vulnerability.go b/internal/database/vulnerability.go index 657c6b61..45cdee27 100644 --- a/internal/database/vulnerability.go +++ b/internal/database/vulnerability.go @@ -20,6 +20,7 @@ type VulnerabilityListFilter struct { ID string Search string // 关键词模糊匹配(标题、描述、类型、目标等) HostQuery string + TaskQuery string CaseID string SummaryOnly bool ConversationID string @@ -52,6 +53,14 @@ func (f VulnerabilityListFilter) appendWhere(query string, args []interface{}) ( query += " AND case_id=?" args = append(args, f.CaseID) } + if q := strings.TrimSpace(f.TaskQuery); q != "" { + query += ` AND (COALESCE(task_tag,'') LIKE ? ESCAPE '\' OR EXISTS ( + SELECT 1 FROM batch_tasks bt LEFT JOIN batch_task_queues bq ON bq.id=bt.queue_id + WHERE bt.conversation_id=vulnerabilities.conversation_id + AND (bt.id LIKE ? ESCAPE '\' OR bt.queue_id LIKE ? ESCAPE '\' OR COALESCE(bq.title,'') LIKE ? ESCAPE '\')))` + pattern := escapeVulnerabilityLikePattern(q) + args = append(args, pattern, pattern, pattern, pattern) + } if f.ID != "" { query += " AND vulnerabilities.id = ?" args = append(args, f.ID) @@ -153,6 +162,7 @@ type Vulnerability struct { TaskTag string `json:"task_tag,omitempty"` TaskID string `json:"task_id,omitempty"` TaskQueueID string `json:"task_queue_id,omitempty"` + TaskQueueTitle string `json:"task_queue_title,omitempty"` Title string `json:"title"` Description string `json:"description"` Severity string `json:"severity"` // critical, high, medium, low, info @@ -201,7 +211,7 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { id, conversation_id, project_id, conversation_tag, task_tag, title, description, severity, status, vulnerability_type, target, preconditions, reproduction_steps, evidence, impact, recommendation, retest_notes, created_at, updated_at, targets_json, targets_version - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1) + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ` _, err := db.Exec( @@ -209,7 +219,7 @@ func (db *DB) CreateVulnerability(vuln *Vulnerability) (*Vulnerability, error) { vuln.ID, nullIfEmpty(vuln.ConversationID), nullIfEmpty(vuln.ProjectID), vuln.ConversationTag, vuln.TaskTag, vuln.Title, vuln.Description, vuln.Severity, vuln.Status, vuln.Type, vuln.Target, vuln.Preconditions, vuln.ReproSteps, vuln.Evidence, vuln.Impact, vuln.Recommendation, vuln.RetestNotes, - vuln.CreatedAt, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), + vuln.CreatedAt, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), vulnerabilityTargetsVersion, ) if err != nil { return nil, fmt.Errorf("创建漏洞失败: %w", err) @@ -317,10 +327,12 @@ const vulnerabilitySeverityRankExpr = `CASE severity func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAccess, groupBy string) (string, []interface{}) { var key string join := "" + isIP := "0" switch groupBy { case "host": key = "COALESCE(json_extract(jt.value,'$.host'),'')" - join = " LEFT JOIN json_each(targets_json) jt ON 1=1" + join = " LEFT JOIN json_each(targets_json) jt ON json_extract(jt.value,'$.group_host')=1" + isIP = "COALESCE(json_extract(jt.value,'$.kind')='ip',0)" case "case": key = "CASE WHEN case_id IS NOT NULL THEN 'case:' || case_id ELSE 'row:' || vulnerabilities.id END" case "task": @@ -331,7 +343,7 @@ func vulnerabilityGroupQuery(filter VulnerabilityListFilter, access RBACListAcce default: return "", nil } - query := "SELECT DISTINCT vulnerabilities.id, created_at, " + vulnerabilitySeverityRankExpr + " AS severity_rank, " + + query := "SELECT DISTINCT vulnerabilities.id, created_at, " + isIP + " AS group_is_ip, " + vulnerabilitySeverityRankExpr + " AS severity_rank, " + key + " AS group_key FROM vulnerabilities" + join + " WHERE 1=1" query, args := filter.appendWhere(query, nil) if groupBy == "host" && strings.TrimSpace(filter.HostQuery) != "" { @@ -355,6 +367,9 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln hostExpr, order := "NULL", "created_at DESC" itemOrder := "created_at DESC, id" groupOrder := "group_key = '', group_key" + if groupBy == "host" { + groupOrder = "group_key = '', group_is_ip, group_key" + } switch sortBy { case "severity": itemOrder = vulnerabilitySeverityRankExpr + ", created_at DESC, id" @@ -367,12 +382,12 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln if groupQuery != "" { prefix = `WITH scoped AS (` + groupQuery + `), page_groups AS ( - SELECT group_key, MIN(severity_rank) AS group_severity, MAX(created_at) AS group_latest + SELECT group_key, MIN(group_is_ip) AS group_is_ip, 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, page_groups.group_severity, page_groups.group_latest + SELECT scoped.id, scoped.group_key, page_groups.group_is_ip, page_groups.group_severity, page_groups.group_latest FROM scoped JOIN page_groups USING (group_key) )` args = append(args, limit, offset) @@ -397,6 +412,7 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln ` + details + `, ` + vulnerabilityTaskIDExpr + ` 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, + COALESCE((SELECT bq.title FROM batch_tasks bt JOIN batch_task_queues bq ON bq.id=bt.queue_id WHERE bt.conversation_id=vulnerabilities.conversation_id ORDER BY bt.id LIMIT 1),''), created_at, updated_at, ` + hostExpr + ` AS target_host, targets_json, COALESCE(case_id,''), COALESCE((SELECT title FROM vulnerability_cases vc WHERE vc.id=vulnerabilities.case_id),'') FROM vulnerabilities` + join + ` @@ -426,7 +442,7 @@ func (db *DB) ListVulnerabilitiesByGroupForAccess(limit, offset int, filter Vuln &vuln.ID, &vuln.ConversationID, &vuln.ProjectID, &vuln.Title, &vuln.Description, &vuln.Severity, &vuln.Status, &vuln.ConversationTag, &vuln.TaskTag, &vuln.Type, &vuln.Target, &vuln.Preconditions, &vuln.ReproSteps, &vuln.Evidence, &vuln.Impact, &vuln.Recommendation, &vuln.RetestNotes, - &vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, + &vuln.RetestLog, &vuln.TaskID, &vuln.TaskQueueID, &vuln.TaskQueueTitle, &vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost, &targets, &vuln.CaseID, &vuln.CaseTitle, ) if err != nil { @@ -481,7 +497,7 @@ func (db *DB) UpdateVulnerability(id string, vuln *Vulnerability) error { UPDATE vulnerabilities SET project_id = ?, conversation_tag = ?, task_tag = ?, title = ?, description = ?, severity = ?, status = ?, vulnerability_type = ?, target = ?, preconditions = ?, reproduction_steps = ?, evidence = ?, impact = ?, - recommendation = ?, retest_notes = ?, updated_at = ?, targets_json = ?, targets_version=1 + recommendation = ?, retest_notes = ?, updated_at = ?, targets_json = ?, targets_version=? WHERE id = ? ` @@ -497,7 +513,7 @@ func (db *DB) UpdateVulnerability(id string, vuln *Vulnerability) error { query, nullIfEmpty(vuln.ProjectID), vuln.ConversationTag, vuln.TaskTag, vuln.Title, vuln.Description, vuln.Severity, vuln.Status, vuln.Type, vuln.Target, vuln.Preconditions, vuln.ReproSteps, vuln.Evidence, vuln.Impact, - vuln.Recommendation, vuln.RetestNotes, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), id, + vuln.Recommendation, vuln.RetestNotes, vuln.UpdatedAt, vulnerabilityTargetsJSON(vuln.Target), vulnerabilityTargetsVersion, id, ) if err != nil { return fmt.Errorf("更新漏洞失败: %w", err) diff --git a/internal/database/vulnerability_workspace.go b/internal/database/vulnerability_workspace.go index c48e7a8a..1286288c 100644 --- a/internal/database/vulnerability_workspace.go +++ b/internal/database/vulnerability_workspace.go @@ -16,15 +16,21 @@ import ( ) type VulnerabilityTarget struct { - Raw string `json:"raw"` - Host string `json:"host"` - Domain string `json:"domain"` - Scheme string `json:"scheme,omitempty"` - Port string `json:"port,omitempty"` - Path string `json:"path,omitempty"` + Raw string `json:"raw"` + Host string `json:"host"` + Domain string `json:"domain"` + Scheme string `json:"scheme,omitempty"` + Port string `json:"port,omitempty"` + Path string `json:"path,omitempty"` + Kind string `json:"kind"` + GroupHost bool `json:"group_host"` } +const vulnerabilityTargetsVersion = 2 + var vulnerabilityTargetPattern = regexp.MustCompile(`(?i)(?:[a-z][a-z0-9+.-]*://|//)[^\s<>"',;,;、()]+|(?:\[[0-9a-f:]+\]|(?:[\p{L}\p{N}][\p{L}\p{N}.-]*\.)+[\p{L}\p{N}-]+|localhost)(?::[0-9]+)?(?:/[^\s<>"',;,;、()]*)?`) +var vulnerabilityVersionContext = regexp.MustCompile(`(?i)(?:版本(?:号)?|version|ver|Citrix Gateway|NetScaler(?: ADC)?|Keycloak|Ivanti Connect Secure|nginx|Apache|OpenSSL|Tomcat)\s*[:=]?\s*$`) +var vulnerabilityVersionToken = regexp.MustCompile(`(?i)^\d+(?:\.\d+)*\.(?:x|final|release|snapshot|alpha\d*|beta\d*|rc\d*)$`) func vulnerabilityTargetsJSON(raw string) string { targets := []VulnerabilityTarget{} @@ -43,11 +49,25 @@ func vulnerabilityTargetsJSON(raw string) string { if host == "" { continue } - if _, err := netip.ParseAddr(host); err != nil && strings.Trim(host, "0123456789.") == "" { + _, ipErr := netip.ParseAddr(host) + explicitHost := strings.Contains(candidate, "://") || strings.HasPrefix(candidate, "//") + if !explicitHost && vulnerabilityVersionToken.MatchString(host) { continue } - target := VulnerabilityTarget{Raw: candidate, Host: host, Domain: host} - if _, err := netip.ParseAddr(host); err != nil { + if ipErr == nil && !explicitHost && vulnerabilityVersionContext.MatchString(raw[:match[0]]) { + continue + } + if ipErr != nil && !explicitHost { + _, icann := publicsuffix.PublicSuffix(host) + localHost := host == "localhost" || strings.HasSuffix(host, ".test") || strings.HasSuffix(host, ".local") || strings.HasSuffix(host, ".internal") || strings.HasSuffix(host, ".lan") + if !icann && !localHost { + continue + } + } + target := VulnerabilityTarget{Raw: candidate, Host: host, Domain: host, Kind: "domain"} + if ipErr == nil { + target.Kind = "ip" + } else { if domain, err := publicsuffix.EffectiveTLDPlusOne(host); err == nil { target.Domain = domain } @@ -68,6 +88,16 @@ func vulnerabilityTargetsJSON(raw string) string { seen[key] = true targets = append(targets, target) } + hasDomain := false + for _, target := range targets { + if target.Kind == "domain" { + hasDomain = true + break + } + } + for i := range targets { + targets[i].GroupHost = targets[i].Kind == "domain" || !hasDomain + } data, _ := json.Marshal(targets) return string(data) } @@ -78,7 +108,7 @@ func (db *DB) backfillVulnerabilityTargets() error { return err } defer tx.Rollback() - rows, err := tx.Query("SELECT id, COALESCE(target,'') FROM vulnerabilities WHERE targets_version=0") + rows, err := tx.Query("SELECT id, COALESCE(target,'') FROM vulnerabilities WHERE targets_version { 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: 'a', target_host: 'api.example.com', target_domain: 'example.com', task_id:'task-a', task_queue_id:'queue' }, + { id: 'b', target_host: 'www.example.com', target_domain: 'example.com', task_id:'task-b', task_queue_id:'queue' }, { id: 'c', target_host: 'example.net', target_domain: 'example.net' }, { id: 'unknown', target_host: '' }, ]; const downloads = []; const context = vm.createContext({ - vulnerabilityHostRows: rows, - vulnerabilityHostSelection: '', + vulnerabilityBrowserRows: rows, + vulnerabilityBrowserSelection: '', + vulnerabilityView: 'host', 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 getVisibleVulnerabilityBrowserItems()'), source.indexOf('function renderVulnerabilityHostRiskDot(') ), context); @@ -29,10 +30,12 @@ test('domain export includes exactly the visible records from the loaded page', ['domain:example.com', ['a', 'b']], ['host:', ['unknown']], ['host:missing.example.com', []], + ['task:task-a',['a']], + ['queue:queue',['a','b']], ]) { - context.vulnerabilityHostSelection = selection; + context.vulnerabilityBrowserSelection = selection; downloads.length = 0; - context.exportVisibleVulnerabilityHosts(); + context.exportVisibleVulnerabilityBrowser(); 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 e28c1649..94bd9653 100644 --- a/web/static/js/vulnerability.js +++ b/web/static/js/vulnerability.js @@ -259,16 +259,18 @@ let vulnerabilityPagination = { total: 0, totalPages: 1 }; -const VULNERABILITY_VIEWS = ['host', 'task', 'case', 'none']; +const VULNERABILITY_VIEWS = ['host', 'task', 'none']; const savedVulnerabilityView = localStorage.getItem('vulnerabilityListView'); -let vulnerabilityView = VULNERABILITY_VIEWS.includes(savedVulnerabilityView) ? savedVulnerabilityView : 'host'; +let vulnerabilityView = savedVulnerabilityView === 'case' ? 'none' + : 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 vulnerabilityTaskQuery = ''; +let vulnerabilityBrowserSelection = ''; +let vulnerabilityBrowserRows = []; let vulnerabilityHostSearchTimer = null; const VULN_STAT_SEVERITIES = ['critical', 'high', 'medium', 'low', 'info']; @@ -416,7 +418,7 @@ function initVulnerabilityViewSwitch() { if (!VULNERABILITY_VIEWS.includes(view) || view === vulnerabilityView) return; vulnerabilityView = view; clearTimeout(vulnerabilityHostSearchTimer); - vulnerabilityHostSelection = ''; + vulnerabilityBrowserSelection = ''; localStorage.setItem('vulnerabilityListView', view); updateSelection(); const scroll = getVulnerabilityScrollContainer(); @@ -1275,8 +1277,6 @@ function updateVulnerabilityStats(stats) { totalEl.textContent = String(total); totalEl.classList.toggle('is-zero', total === 0); } - const distinctEl = document.getElementById('vulnerability-distinct-count'); - if (distinctEl) distinctEl.textContent = vulnT('vulnerabilityPage.distinctCount', { count: stats.distinct ?? total }); VULN_STAT_SEVERITIES.forEach(function (sev) { const count = bySeverity[sev] || 0; @@ -1313,15 +1313,12 @@ async function loadVulnerabilities(page = null, options = {}) { } const listContainer = document.getElementById('vulnerabilities-list'); - const groupOpenStates = preserveScroll - ? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-group'), group => [group.dataset.groupKey, group.open])) - : new Map(); const hostOpenStates = preserveScroll ? new Map(Array.from(listContainer.querySelectorAll('.vulnerability-domain-branch'), branch => [branch.dataset.domain, branch.open])) : new Map(); if (!silent) { listContainer.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loading'))}
`; - updateVulnerabilityGroupControls(); + updateVulnerabilityListSummary(); } try { @@ -1341,6 +1338,7 @@ async function loadVulnerabilities(page = null, options = {}) { params.append('summary', 'true'); if (vulnerabilitySort) params.append('sort', vulnerabilitySort); if (view === 'host' && vulnerabilityHostQuery) params.append('host_q', vulnerabilityHostQuery); + if (view === 'task' && vulnerabilityTaskQuery) params.append('task_q', vulnerabilityTaskQuery); params.append('page', vulnerabilityPagination.currentPage.toString()); params.append('limit', vulnerabilityPagination.pageSize.toString()); @@ -1377,7 +1375,7 @@ async function loadVulnerabilities(page = null, options = {}) { } renderVulnerabilities(vulnerabilities, { - view, expandedIds: expandedIds || [], groupOpenStates, hostOpenStates, + view, expandedIds: expandedIds || [], hostOpenStates, preserveHostSelection: preserveScroll }); renderVulnerabilityPagination(); @@ -1395,7 +1393,7 @@ async function loadVulnerabilities(page = null, options = {}) { if (request !== vulnerabilityListRequest) return; console.error('加载漏洞列表失败:', error); listContainer.innerHTML = `
${escapeHtml(vulnT('vulnerabilityPage.loadListFailed'))}: ${escapeHtml(error.message)}
`; - updateVulnerabilityGroupControls(); + updateVulnerabilityListSummary(); } } @@ -1404,8 +1402,8 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { const opts = renderOptions && typeof renderOptions === 'object' ? renderOptions : {}; const listContainer = document.getElementById('vulnerabilities-list'); if (typeof setVulnerabilityWorkspaceRows === 'function') setVulnerabilityWorkspaceRows(vulnerabilities || []); - if (opts.view === 'host') { - renderVulnerabilityHostBrowser(Array.isArray(vulnerabilities) ? vulnerabilities : [], opts); + if (opts.view === 'host' || opts.view === 'task') { + renderVulnerabilityBrowser(Array.isArray(vulnerabilities) ? vulnerabilities : [], opts); return; } @@ -1414,7 +1412,7 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { if (typeof window.applyTranslations === 'function') { window.applyTranslations(listContainer); } - updateVulnerabilityGroupControls(); + updateVulnerabilityListSummary(); return; } @@ -1422,9 +1420,7 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { ? vulnerabilities[0].id : null; const expandedIds = exactMatch ? [exactMatch] : opts.expandedIds; - listContainer.innerHTML = opts.view === 'none' - ? vulnerabilities.map(renderVulnerabilityCard).join('') - : renderVulnerabilityGroups(vulnerabilities, { ...opts, expandedIds }); + listContainer.innerHTML = vulnerabilities.map(renderVulnerabilityCard).join(''); initVulnerabilityStatusPickers(listContainer); initVulnerabilityProjectBindSelects(listContainer); if (typeof window.applyTranslations === 'function') { @@ -1436,10 +1432,7 @@ function renderVulnerabilities(vulnerabilities, renderOptions) { } else { restoreExpandedVulnerabilityDetails(expandedIds); } - listContainer.querySelectorAll('.vulnerability-group').forEach(group => { - group.addEventListener('toggle', updateVulnerabilityGroupControls); - }); - updateVulnerabilityGroupControls(); + updateVulnerabilityListSummary(); } function changeVulnerabilitySort(value) { @@ -1449,118 +1442,68 @@ function changeVulnerabilitySort(value) { loadVulnerabilities(1); } -function setVulnerabilityGroupsOpen(open) { - document.querySelectorAll('#vulnerabilities-list .vulnerability-group').forEach(group => { - group.open = open; - }); - updateVulnerabilityGroupControls(); -} - -function updateVulnerabilityGroupControls() { +function updateVulnerabilityListSummary() { 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') - ? new Set(vulnerabilityHostRows.map(vuln => vuln.id)).size + const count = ['host','task'].includes(vulnerabilityView) && list.querySelector('.vulnerability-host-browser') + ? new Set(vulnerabilityBrowserRows.map(vuln => vuln.id)).size : 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 = !['task','case'].includes(vulnerabilityView); - 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) { - 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'); - } else if (opts.view === 'case') { - key = vuln.case_id ? 'case:' + vuln.case_id : 'row:' + vuln.id; - label = vuln.case_title || vuln.title; - } - 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 }); - 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)}` : ''} - -
- ${opts.view === 'case' && items[0].case_id ? `` : ''} - ${items.map(renderVulnerabilityCard).join('')} -
-
- `; - }).join(''); -} - -function renderVulnerabilityHostBrowser(vulnerabilities, opts) { +function renderVulnerabilityBrowser(vulnerabilities, opts) { const activeSearch = document.activeElement?.id === 'vulnerability-host-search'; const caret = activeSearch ? document.activeElement.selectionStart : null; - vulnerabilityHostRows = vulnerabilities; - const domains = new Map(); + vulnerabilityBrowserRows = vulnerabilities; + const isTask = opts.view === 'task'; + const groups = 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); + let rootKey = 'domain:' + domain, rootLabel = domain; + let key = 'host:' + host, label = host || vulnT('vulnerabilityPage.unknownHost'); + let flat = host === domain; + if (isTask) { + const tag = (vuln.task_tag || '').replace(/^ +| +$/g, ''); + key = vuln.task_id ? 'task:' + vuln.task_id : 'tag:' + tag; + label = vuln.task_id ? vulnT('vulnerabilityPage.viewTaskGroup', {id:vuln.task_id}) : tag || vulnT('vulnerabilityPage.viewNoTask'); + rootKey = vuln.task_queue_id ? 'queue:' + vuln.task_queue_id : key; + rootLabel = vuln.task_queue_title || (vuln.task_queue_id + ? vulnT('vulnerabilityPage.taskQueueGroup', {id:vuln.task_queue_id}) : label); + flat = !vuln.task_queue_id; + } + if (!groups.has(rootKey)) groups.set(rootKey, {label:rootLabel, children:new Map(), items:[], flat}); + const group = groups.get(rootKey); + group.flat = group.flat && flat; + group.items.push(vuln); + if (!group.children.has(key)) group.children.set(key, {label, items:[]}); + group.children.get(key).items.push(vuln); } const button = (key, label, count, items = []) => ` `; - const tree = Array.from(domains, ([domain, hosts]) => { - const count = new Set(vulnerabilities.filter(vuln => (vuln.target_domain || vuln.target_host || '') === domain).map(vuln => vuln.id)).size; - if (hosts.size === 1 && hosts.has(domain)) { - return button('host:' + domain, domain || vulnT('vulnerabilityPage.unknownHost'), count, - vulnerabilities.filter(vuln => (vuln.target_host || '') === domain)); + const tree = Array.from(groups, ([rootKey, group]) => { + const count = new Set(group.items.map(vuln => vuln.id)).size; + if (group.flat && group.children.size === 1) { + const [key,child] = group.children.entries().next().value; + return button(key, child.label, count, child.items); } - const open = opts.hostOpenStates?.get(domain) ?? true; - return `
- ${count} - ${Array.from(hosts, ([host, n]) => button('host:' + host, host, n, - vulnerabilities.filter(vuln => (vuln.target_host || '') === host))).join('')} + const open = opts.hostOpenStates?.get(rootKey) ?? true; + return `
+ ${count} + ${Array.from(group.children, ([key, child]) => button(key, child.label, child.items.length, child.items)).join('')}
`; }).join(''); const list = document.getElementById('vulnerabilities-list'); list.innerHTML = `
-
`; const search = document.getElementById('vulnerability-host-search'); search.addEventListener('input', () => { - vulnerabilityHostQuery = search.value.trim(); + if (isTask) vulnerabilityTaskQuery = search.value.trim(); + else vulnerabilityHostQuery = search.value.trim(); clearTimeout(vulnerabilityHostSearchTimer); // Invalidate an in-flight response as soon as the next query is typed. vulnerabilityListRequest++; vulnerabilityHostSearchTimer = setTimeout(() => { - vulnerabilityHostSelection = ''; + vulnerabilityBrowserSelection = ''; loadVulnerabilities(1, { silent: true }); }, VULNERABILITY_FILTER_DEBOUNCE_MS); }); @@ -1596,30 +1540,33 @@ function renderVulnerabilityHostBrowser(vulnerabilities, opts) { const option = event.target.closest('button[data-host-key]'); if (!option) return; event.preventDefault(); - vulnerabilityHostSelection = option.dataset.hostKey; - renderVulnerabilityHostTable(); + vulnerabilityBrowserSelection = option.dataset.hostKey; + renderVulnerabilityBrowserTable(); }); if (!opts.preserveHostSelection && - !Array.from(list.querySelectorAll('[data-host-key]')).some(el => el.dataset.hostKey === vulnerabilityHostSelection)) { - vulnerabilityHostSelection = ''; + !Array.from(list.querySelectorAll('[data-host-key]')).some(el => el.dataset.hostKey === vulnerabilityBrowserSelection)) { + vulnerabilityBrowserSelection = ''; } - renderVulnerabilityHostTable(opts.expandedIds); + renderVulnerabilityBrowserTable(opts.expandedIds); if (activeSearch) { search.focus({ preventScroll: true }); search.setSelectionRange(caret, caret); } } -function getVisibleVulnerabilityHostItems() { - const selection = vulnerabilityHostSelection; - const items = vulnerabilityHostRows.filter(vuln => !selection || +function getVisibleVulnerabilityBrowserItems() { + const selection = vulnerabilityBrowserSelection; + const items = vulnerabilityBrowserRows.filter(vuln => !selection || selection === 'host:' + (vuln.target_host || '') || - selection === 'domain:' + (vuln.target_domain || vuln.target_host || '')); + selection === 'domain:' + (vuln.target_domain || vuln.target_host || '') || + (vuln.task_id && selection === 'task:' + vuln.task_id) || + (vuln.task_queue_id && selection === 'queue:' + vuln.task_queue_id) || + (!vuln.task_id && selection === 'tag:' + (vuln.task_tag || '').replace(/^ +| +$/g, ''))); return Array.from(new Map(items.map(vuln => [vuln.id,vuln])).values()); } -async function exportVisibleVulnerabilityHosts() { - const items = getVisibleVulnerabilityHostItems(); +async function exportVisibleVulnerabilityBrowser() { + const items = getVisibleVulnerabilityBrowserItems(); if (!items.length) return; try { const full = []; @@ -1630,7 +1577,7 @@ async function exportVisibleVulnerabilityHosts() { full.push(await response.json()); } const content = full.map(formatVulnerabilityAsMarkdown).join('\n\n---\n\n'); - triggerTextDownload('vulnerabilities-hosts-' + new Date().toISOString().slice(0, 10) + '.md', content); + triggerTextDownload('vulnerabilities-' + vulnerabilityView + '-' + new Date().toISOString().slice(0, 10) + '.md', content); } catch(error) { alert(error.message); } } @@ -1639,13 +1586,15 @@ function renderVulnerabilityHostRiskDot(items) { return highest ? `` : ''; } -function renderVulnerabilityHostTable(expandedIds) { - const selection = vulnerabilityHostSelection; - const items = getVisibleVulnerabilityHostItems(); +function renderVulnerabilityBrowserTable(expandedIds) { + const selection = vulnerabilityBrowserSelection; + const items = getVisibleVulnerabilityBrowserItems(); 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.allHosts'); + const selectedOption = Array.from(document.querySelectorAll('#vulnerabilities-list [data-host-key]')).find(option => option.dataset.hostKey === selection); + const label = selection ? (selectedOption?.querySelector('[title]')?.title || selectedOption?.title || selection.slice(selection.indexOf(':') + 1)) + : vulnT(vulnerabilityView === 'task' ? 'vulnerabilityPage.allTasks' : 'vulnerabilityPage.allHosts'); const heading = document.getElementById('vulnerability-host-selection'); heading.textContent = label || vulnT('vulnerabilityPage.unknownHost'); heading.title = heading.textContent; @@ -1666,7 +1615,13 @@ function renderVulnerabilityHostTable(expandedIds) { const container = document.getElementById('vulnerability-host-table'); container.innerHTML = items.length ? `
+ + + + + + ${['tableSeverity', 'tableTitle', 'detailTarget', 'tableStatus', 'tableTask', 'tableDate', 'tableActions'] .map(key => '').join('')} @@ -1678,7 +1633,7 @@ function renderVulnerabilityHostTable(expandedIds) { const exact = items.find(vuln => vulnerabilityFilters.id === vuln.id); if (exact?.summary_only && typeof openVulnerabilityInspector === 'function') openVulnerabilityInspector(exact.id); else restoreExpandedVulnerabilityDetails(exact ? [exact.id] : expandedIds); - updateVulnerabilityGroupControls(); + updateVulnerabilityListSummary(); } function renderVulnerabilityTableItem(vuln) { @@ -1689,7 +1644,8 @@ function renderVulnerabilityTableItem(vuln) { const created = new Date(vuln.created_at); return ` - + + - ${vuln.summary_only ? '' : ``} + ${vuln.summary_only ? '' : ``} `; } @@ -1820,7 +1776,6 @@ function renderVulnerabilityPagination() { const paginationLabel = { host: 'vulnerabilityPage.hostPagination', task: 'vulnerabilityPage.taskPagination', - case: 'vulnerabilityPage.casePagination', none: 'vulnerabilityPage.recordPagination' }[vulnerabilityView]; diff --git a/web/templates/index.html b/web/templates/index.html index 9b3fcf59..838d9e19 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -48,7 +48,7 @@ - + @@ -2702,8 +2702,7 @@ aria-label="漏洞视图" data-i18n="vulnerabilityPage.viewLabel" data-i18n-attr="aria-label"> - - +
@@ -2718,7 +2717,6 @@
资产、上报与处置进展 -
最新发现 -
- - -
+
@@ -7136,7 +7131,7 @@ - +
${escapeHtml(vulnT('vulnerabilityPage.selectColumn'))}' + escapeHtml(vulnT('vulnerabilityPage.' + key)) + '
${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}${escapeHtml(vulnSeverityLabel(vuln.severity))}${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}${escapeHtml(vulnSeverityLabel(vuln.severity))}