fix(vulnerabilities): prefer domains and unify task tree navigation

This commit is contained in:
Sycun 2026-11-13 16:47:17 +08:00
parent 76e9df9b0c
commit b77c8cda27
13 changed files with 238 additions and 179 deletions

View File

@ -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)

View File

@ -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<?", vulnerabilityTargetsVersion)
if err != nil {
return err
}
@ -97,7 +127,7 @@ func (db *DB) backfillVulnerabilityTargets() error {
return err
}
for id, raw := range targets {
if _, err := tx.Exec("UPDATE vulnerabilities SET targets_json=?,targets_version=1 WHERE id=?", raw, id); err != nil {
if _, err := tx.Exec("UPDATE vulnerabilities SET targets_json=?,targets_version=? WHERE id=?", raw, vulnerabilityTargetsVersion, id); err != nil {
return err
}
}

View File

@ -24,7 +24,7 @@ func TestVulnerabilityWorkspaceTargetsAndLegacyUpgrade(t *testing.T) {
}
}
count, err := db.CountVulnerabilityGroupsForAccess(VulnerabilityListFilter{}, RBACListAccess{}, "host")
if err != nil || count != 3 {
if err != nil || count != 2 {
t.Fatalf("host count: %d %v", count, err)
}
rows, err := db.ListVulnerabilitiesByGroupForAccess(2, 0, VulnerabilityListFilter{SummaryOnly: true}, RBACListAccess{}, "host", "")
@ -37,6 +37,36 @@ func TestVulnerabilityWorkspaceTargetsAndLegacyUpgrade(t *testing.T) {
}
}
func TestVulnerabilityDomainGroupsPreferNamesAndRepairStoredTargets(t *testing.T) {
db := newRBACTestDB(t)
raw := "https://vpn.example.com/login (真实 IP 190.104.230.105,Citrix Gateway 26.6.1.20,Keycloak 4.4.0.final,Ivanti Connect Secure 22.x,getFunction.php)"
v, err := db.CreateVulnerability(&Vulnerability{Title: "domain with infrastructure notes", Severity: "high", Target: raw})
if err != nil {
t.Fatal(err)
}
if len(v.Targets) != 2 || v.Targets[0].Host != "vpn.example.com" || !v.Targets[0].GroupHost || v.Targets[1].Host != "190.104.230.105" || v.Targets[1].GroupHost {
t.Fatalf("parsed targets: %+v", v.Targets)
}
if _, err := db.Exec(`UPDATE vulnerabilities SET targets_json='[{"host":"22.x"}]',targets_version=1 WHERE id=?`, v.ID); err != nil {
t.Fatal(err)
}
if err := db.backfillVulnerabilityTargets(); err != nil {
t.Fatal(err)
}
ip, err := db.CreateVulnerability(&Vulnerability{Title: "IP only", Severity: "high", Target: "192.0.2.5:8080"})
if err != nil {
t.Fatal(err)
}
rows, err := db.ListVulnerabilitiesByGroupForAccess(20, 0, VulnerabilityListFilter{}, RBACListAccess{}, "host", "")
if err != nil || len(rows) != 2 || rows[0].ID != v.ID || rows[1].ID != ip.ID {
t.Fatalf("domain-first groups: %+v %v", rows, err)
}
got, _ := db.GetVulnerability(v.ID)
if got.Target != raw || len(got.Targets) != 2 {
t.Fatalf("backfill changed raw target: %+v", got)
}
}
func TestVulnerabilityTargetParserIgnoresRelativeEndpoints(t *testing.T) {
if got := vulnerabilityTargetsJSON("GET /api/config.php HTTP/1.1"); got != "[]" {
t.Fatalf("relative endpoint parsed as host: %s", got)

View File

@ -169,6 +169,7 @@ func parseVulnerabilityListFilter(c *gin.Context) database.VulnerabilityListFilt
ID: c.Query("id"),
Search: q,
HostQuery: c.Query("host_q"),
TaskQuery: c.Query("task_q"),
CaseID: c.Query("case_id"),
ConversationID: c.Query("conversation_id"),
Severity: c.Query("severity"),

View File

@ -74,10 +74,11 @@ func TestListVulnerabilitiesGroupedViews(t *testing.T) {
page, total, pages int
ids, hosts []string
}{
{"group_by=host&page=1", 1, 5, 3, []string{"ipv6", "domain-new", "domain-old"}, []string{"2001:db8::1", "example.com", "example.com"}},
{"group_by=host&page=1", 1, 5, 3, []string{"domain-new", "domain-old", "domain-old"}, []string{"example.com", "example.com", "secondary.example.net"}},
{"group_by=host&page=4", 3, 5, 3, []string{"unknown"}, []string{""}},
{"group_by=task&page=1", 1, 3, 2, []string{"ipv6", "domain-new", "subdomain", "domain-old"}, nil},
{"group_by=task&page=2", 2, 3, 2, []string{"unknown"}, nil},
{"group_by=task&task_q=queue", 1, 1, 1, []string{"ipv6", "domain-new"}, nil},
{"group_by=none&page=1", 1, 5, 3, []string{"unknown", "ipv6"}, nil},
{"page=1", 1, 5, 3, []string{"unknown", "ipv6"}, nil},
} {

View File

@ -24,7 +24,6 @@
color: var(--text-secondary);
}
#vulnerability-distinct-count { font-weight: 600; color: var(--text-primary); }
#page-vulnerabilities .dashboard-stats {
grid-template-columns: repeat(6,minmax(0,1fr));
@ -107,8 +106,17 @@
#page-vulnerabilities .vulnerability-host-overview { min-height: 36px; margin-bottom: 12px; }
#page-vulnerabilities .vulnerability-host-results-heading h3 { font-size: 16px; font-weight: 600; }
#page-vulnerabilities .vulnerability-host-table { min-width: 880px; font-size: 13px; }
#page-vulnerabilities .vulnerability-host-table th { font-size: 12px; padding: 12px; }
#page-vulnerabilities .vulnerability-host-table th { width: auto; font-size: 12px; padding: 12px; }
#page-vulnerabilities .vulnerability-host-table td { padding: 16px 12px; }
#page-vulnerabilities .vulnerability-host-table .vulnerability-select-column { text-align: center; padding-inline: 8px; }
#page-vulnerabilities .vulnerability-select-column .vulnerability-select-record { margin: 0; vertical-align: middle; }
.vulnerability-col-select { width: 44px; }
.vulnerability-col-severity { width: 84px; }
.vulnerability-col-target { width: 19%; }
.vulnerability-col-status { width: 110px; }
.vulnerability-col-task { width: 13%; }
.vulnerability-col-date { width: 90px; }
.vulnerability-col-actions { width: 100px; }
#page-vulnerabilities .vulnerability-table-item:hover { background: color-mix(in srgb,var(--accent-color) 3%,var(--vuln-panel)); }
#page-vulnerabilities .vulnerability-row-toggle { font-size: 14px; line-height: 1.5; padding: 0; }
#page-vulnerabilities .vulnerability-table-title p { margin-top: 6px; font-size: 12px; }
@ -153,7 +161,7 @@
height: 100%;
margin: 0;
padding: 0;
border-radius: 16px 0 0 16px;
border-radius: 0;
background: var(--bg-primary);
box-shadow: -12px 0 48px rgba(15,23,42,.16);
display: flex;

View File

@ -2721,6 +2721,11 @@
"errorGeneric": "حدث خطأ ما. يُرجى المحاولة مرة أخرى."
},
"vulnerabilityPage": {
"taskSearch": "البحث في المهام أو قوائم الانتظار أو الوسوم…",
"allTasks": "جميع المهام",
"clearTaskSelection": "مسح مرشح المهام",
"taskQueueGroup": "قائمة المهام {{id}}",
"selectColumn": "تحديد",
"statReports": "تقارير الثغرات",
"history_retest_started": "تم إنشاء فرع إعادة الاختبار",
"retestSnapshot": "لقطة الأدلة عند إعادة الاختبار",
@ -2824,7 +2829,7 @@
"viewLabel": "عرض الثغرات",
"viewHost": "حسب المضيف",
"viewTask": "حسب المهمة",
"viewRaw": "السجلات الأصلية",
"viewRaw": "الثغرات الأصلية",
"viewTaskGroup": "المهمة {{id}}",
"viewNoTask": "لا توجد مهمة مرتبطة",
"batchExport": "تصدير جماعي",

View File

@ -2864,6 +2864,11 @@
"errorGeneric": "Something went wrong. Please try again."
},
"vulnerabilityPage": {
"taskSearch": "Search tasks, queues or tags…",
"allTasks": "All tasks",
"clearTaskSelection": "Clear task filter",
"taskQueueGroup": "Task queue {{id}}",
"selectColumn": "Select",
"statReports": "Reported findings",
"history_retest_started": "Retest branch created",
"retestSnapshot": "Evidence snapshot at retest",
@ -2967,7 +2972,7 @@
"viewLabel": "Vulnerability view",
"viewHost": "By host",
"viewTask": "By task",
"viewRaw": "Raw records",
"viewRaw": "Raw findings",
"viewTaskGroup": "Task {{id}}",
"viewNoTask": "No linked task",
"batchExport": "Batch export",

View File

@ -2877,6 +2877,11 @@
"errorGeneric": "Что-то пошло не так. Повторите попытку."
},
"vulnerabilityPage": {
"taskSearch": "Поиск задач, очередей или тегов…",
"allTasks": "Все задачи",
"clearTaskSelection": "Сбросить фильтр задач",
"taskQueueGroup": "Очередь {{id}}",
"selectColumn": "Выбор",
"statReports": "Отчёты об уязвимостях",
"history_retest_started": "Создана ветка проверки",
"retestSnapshot": "Снимок доказательств при проверке",
@ -2980,7 +2985,7 @@
"viewLabel": "Вид списка уязвимостей",
"viewHost": "По хостам",
"viewTask": "По задачам",
"viewRaw": "Исходные записи",
"viewRaw": "Исходные уязвимости",
"viewTaskGroup": "Задача {{id}}",
"viewNoTask": "Без связанной задачи",
"batchExport": "Пакетный экспорт",

View File

@ -2852,6 +2852,11 @@
"errorGeneric": "操作失败,请稍后重试。"
},
"vulnerabilityPage": {
"taskSearch": "搜索任务、队列或标签…",
"allTasks": "全部任务",
"clearTaskSelection": "清除任务筛选",
"taskQueueGroup": "任务队列 {{id}}",
"selectColumn": "选择",
"statReports": "上报记录",
"history_retest_started": "复测分支已创建",
"retestSnapshot": "复测时的证据快照",
@ -2955,7 +2960,7 @@
"viewLabel": "漏洞视图",
"viewHost": "按域名",
"viewTask": "按任务",
"viewRaw": "原始记录",
"viewRaw": "原始漏洞",
"viewTaskGroup": "任务 {{id}}",
"viewNoTask": "未关联任务",
"batchExport": "批量导出",

View File

@ -5,21 +5,22 @@ 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: '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')] : []);
}
});

View File

@ -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 = `<div class="loading-spinner">${escapeHtml(vulnT('vulnerabilityPage.loading'))}</div>`;
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 = `<div class="error-message">${escapeHtml(vulnT('vulnerabilityPage.loadListFailed'))}: ${escapeHtml(error.message)}</div>`;
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 =>
`<span class="severity-badge severity-${severity}">${escapeHtml(vulnSeverityLabel(severity))} ${severities[severity]}</span>`
).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 `
<details class="vulnerability-group" data-group-key="${escapeAttr(key)}"${open ? ' open' : ''}>
<summary>
<span class="vulnerability-group-name">${escapeHtml(label)}</span>
<span class="vulnerability-group-count">${escapeHtml(count)}</span>
<span class="vulnerability-group-risk">${badges}</span>
<span class="vulnerability-group-pending">${escapeHtml(vulnT('vulnerabilityPage.groupPending', { count: pending }))}</span>
${tags ? `<span class="vulnerability-group-tags">${escapeHtml(tags)}</span>` : ''}
</summary>
<div class="vulnerability-group-cards">
${opts.view === 'case' && items[0].case_id ? `<button class="btn-secondary vulnerability-case-split" data-require-permission="vulnerability:write" onclick="openVulnerabilityMergeDialog(${escapeJsStringAttr(items[0].case_id)})">${escapeHtml(vulnT('vulnerabilityPage.splitCase'))}</button>` : ''}
${items.map(renderVulnerabilityCard).join('')}
</div>
</details>
`;
}).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 = []) => `
<button type="button" class="vulnerability-host-option" data-host-key="${escapeAttr(key)}" aria-pressed="false">
<span class="vulnerability-host-option-name" title="${escapeAttr(label)}">${renderVulnerabilityHostRiskDot(items)}${escapeHtml(label)}</span><span class="vulnerability-host-number">${count}</span>
</button>`;
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 `<details class="vulnerability-domain-branch" data-domain="${escapeAttr(domain)}"${open ? ' open' : ''}>
<summary><button type="button" class="vulnerability-domain-label" data-host-key="domain:${escapeAttr(domain)}" title="${escapeAttr(domain)}" aria-pressed="false">${escapeHtml(domain)}</button><span class="vulnerability-host-number">${count}</span></summary>
${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 `<details class="vulnerability-domain-branch" data-domain="${escapeAttr(rootKey)}"${open ? ' open' : ''}>
<summary><button type="button" class="vulnerability-domain-label" data-host-key="${escapeAttr(rootKey)}" title="${escapeAttr(group.label)}" aria-pressed="false">${escapeHtml(group.label)}</button><span class="vulnerability-host-number">${count}</span></summary>
${Array.from(group.children, ([key, child]) => button(key, child.label, child.items.length, child.items)).join('')}
</details>`;
}).join('');
const list = document.getElementById('vulnerabilities-list');
list.innerHTML = `
<div class="vulnerability-host-browser">
<aside class="vulnerability-host-sidebar" aria-label="${escapeAttr(vulnT('vulnerabilityPage.viewHost'))}">
<aside class="vulnerability-host-sidebar" aria-label="${escapeAttr(vulnT(isTask ? 'vulnerabilityPage.viewTask' : 'vulnerabilityPage.viewHost'))}">
<input id="vulnerability-host-search" type="search"
aria-label="${escapeAttr(vulnT('vulnerabilityPage.hostSearch'))}"
placeholder="${escapeAttr(vulnT('vulnerabilityPage.hostSearch'))}" value="${escapeAttr(vulnerabilityHostQuery)}">
aria-label="${escapeAttr(vulnT(isTask ? 'vulnerabilityPage.taskSearch' : 'vulnerabilityPage.hostSearch'))}"
placeholder="${escapeAttr(vulnT(isTask ? 'vulnerabilityPage.taskSearch' : 'vulnerabilityPage.hostSearch'))}" value="${escapeAttr(isTask ? vulnerabilityTaskQuery : vulnerabilityHostQuery)}">
<nav class="vulnerability-host-tree">
${tree}
</nav>
@ -1569,26 +1512,27 @@ function renderVulnerabilityHostBrowser(vulnerabilities, opts) {
<div class="vulnerability-host-results-heading">
<h3 id="vulnerability-host-selection"></h3>
<div class="vulnerability-host-heading-actions">
<button type="button" id="vulnerability-host-clear" class="btn-ghost" onclick="vulnerabilityHostSelection='';renderVulnerabilityHostTable()" hidden>${escapeHtml(vulnT('vulnerabilityPage.clearHostSelection'))}</button>
<button type="button" id="vulnerability-host-clear" class="btn-ghost" onclick="vulnerabilityBrowserSelection='';renderVulnerabilityBrowserTable()" hidden>${escapeHtml(vulnT(isTask ? 'vulnerabilityPage.clearTaskSelection' : 'vulnerabilityPage.clearHostSelection'))}</button>
<span id="vulnerability-host-selection-count"></span>
</div>
</div>
<div class="vulnerability-host-overview">
<div id="vulnerability-host-risk-summary"></div>
<button type="button" class="btn-secondary" id="vulnerability-host-export"
onclick="exportVisibleVulnerabilityHosts()" data-require-permission="vulnerability:read">${escapeHtml(vulnT('vulnerabilityPage.exportVisibleHosts'))}</button>
onclick="exportVisibleVulnerabilityBrowser()" data-require-permission="vulnerability:read">${escapeHtml(vulnT('vulnerabilityPage.exportVisibleHosts'))}</button>
</div>
<div id="vulnerability-host-table"></div>
</section>
</div>`;
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 ? `<span class="vulnerability-host-risk-dot severity-${highest}" title="${escapeAttr(vulnSeverityLabel(highest))}"></span>` : '';
}
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 ? `<div class="vulnerability-table-scroll">
<table class="vulnerability-host-table">
<colgroup>
<col class="vulnerability-col-select"><col class="vulnerability-col-severity"><col>
<col class="vulnerability-col-target"><col class="vulnerability-col-status">
<col class="vulnerability-col-task"><col class="vulnerability-col-date"><col class="vulnerability-col-actions">
</colgroup>
<thead><tr>
<th scope="col" class="vulnerability-select-column">${escapeHtml(vulnT('vulnerabilityPage.selectColumn'))}</th>
${['tableSeverity', 'tableTitle', 'detailTarget', 'tableStatus', 'tableTask', 'tableDate', 'tableActions']
.map(key => '<th scope="col">' + escapeHtml(vulnT('vulnerabilityPage.' + key)) + '</th>').join('')}
</tr></thead>
@ -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 `<tbody class="vulnerability-table-item" id="vulnerability-card-${id}" data-vuln-id="${id}">
<tr>
<td>${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}<span class="severity-badge severity-${escapeAttr(vuln.severity)}">${escapeHtml(vulnSeverityLabel(vuln.severity))}</span></td>
<td class="vulnerability-select-column">${typeof vulnerabilitySelectionInput === 'function' ? vulnerabilitySelectionInput(vuln) : ''}</td>
<td><span class="severity-badge severity-${escapeAttr(vuln.severity)}">${escapeHtml(vulnSeverityLabel(vuln.severity))}</span></td>
<td class="vulnerability-table-title">
<button type="button" id="vulnerability-row-toggle-${id}" class="vulnerability-row-toggle"
aria-expanded="false" aria-controls="content-${id}" onclick="${vuln.summary_only ? 'openVulnerabilityInspector' : 'toggleVulnerabilityDetails'}(${jsID})">
@ -1716,7 +1672,7 @@ function renderVulnerabilityTableItem(vuln) {
<button type="button" class="btn-ghost" data-require-permission="vulnerability:delete" onclick="deleteVulnerability(${jsID})">${escapeHtml(vulnT('common.delete'))}</button>
</div></td>
</tr>
${vuln.summary_only ? '' : `<tr class="vulnerability-table-detail" hidden><td colspan="7">${renderVulnerabilityDetailsContent(vuln)}</td></tr>`}
${vuln.summary_only ? '' : `<tr class="vulnerability-table-detail" hidden><td colspan="8">${renderVulnerabilityDetailsContent(vuln)}</td></tr>`}
</tbody>`;
}
@ -1820,7 +1776,6 @@ function renderVulnerabilityPagination() {
const paginationLabel = {
host: 'vulnerabilityPage.hostPagination',
task: 'vulnerabilityPage.taskPagination',
case: 'vulnerabilityPage.casePagination',
none: 'vulnerabilityPage.recordPagination'
}[vulnerabilityView];

View File

@ -48,7 +48,7 @@
<link rel="stylesheet" href="/static/vendor/xterm.css">
<!-- 移动端样式层:全部规则限定在 767.98px 以下,桌面端零影响 -->
<link rel="stylesheet" href="/static/css/mobile.css?v=20261015-project-table-3">
<link rel="stylesheet" href="/static/css/vulnerability-workspace.css?v=20261113-long-targets">
<link rel="stylesheet" href="/static/css/vulnerability-workspace.css?v=20261113-tree-views">
<script src="/static/js/router.js?v=20261011-token-settings"></script>
</head>
<body>
@ -2702,8 +2702,7 @@
aria-label="漏洞视图" data-i18n="vulnerabilityPage.viewLabel" data-i18n-attr="aria-label">
<button type="button" data-vuln-view="host" aria-pressed="true" data-i18n="vulnerabilityPage.viewHost">按域名</button>
<button type="button" data-vuln-view="task" aria-pressed="false" data-i18n="vulnerabilityPage.viewTask">按任务</button>
<button type="button" data-vuln-view="case" aria-pressed="false" data-i18n="vulnerabilityPage.viewCases">独立漏洞</button>
<button type="button" data-vuln-view="none" aria-pressed="false" data-i18n="vulnerabilityPage.viewRaw">原始记录</button>
<button type="button" data-vuln-view="none" aria-pressed="false" data-i18n="vulnerabilityPage.viewRaw">原始漏洞</button>
</div>
</div>
<div class="page-header-actions">
@ -2718,7 +2717,6 @@
<div class="vulnerability-dashboard" id="vulnerability-dashboard">
<div class="vulnerability-workspace-caption">
<span data-i18n="vulnerabilityPage.workspaceSubtitle">资产、上报与处置进展</span>
<span id="vulnerability-distinct-count"></span>
</div>
<div class="dashboard-stats" id="vulnerability-stat-cards" role="group" aria-label="漏洞严重度统计">
<div class="stat-card stat-card-total is-clickable is-active" data-severity="" role="button" tabindex="0"
@ -2875,10 +2873,7 @@
<option value="latest" data-i18n="vulnerabilityPage.sortLatest">最新发现</option>
</select>
</label>
<div id="vulnerability-group-controls" class="vulnerability-group-controls">
<button type="button" id="vulnerability-expand-groups" class="btn-secondary" onclick="setVulnerabilityGroupsOpen(true)" data-i18n="vulnerabilityPage.expandPage">展开本页</button>
<button type="button" id="vulnerability-collapse-groups" class="btn-secondary" onclick="setVulnerabilityGroupsOpen(false)" data-i18n="vulnerabilityPage.collapsePage">收起本页</button>
</div>
</div>
</div>
<div id="vulnerabilities-list" class="vulnerabilities-list">
@ -7136,7 +7131,7 @@
<script src="/static/js/skills.js?v=20261103-personal-integration"></script>
<script src="/static/js/fact-graph.js"></script>
<script src="/static/js/projects.js?v=20260819-1-pagination-20261027"></script>
<script src="/static/js/vulnerability.js?v=20261113-domain-labels"></script>
<script src="/static/js/vulnerability.js?v=20261113-tree-views"></script>
<script src="/static/js/vulnerability-workspace.js?v=20261113-long-targets"></script>
<script src="/static/js/vulnerability-download.js?v=20261030-2"></script>
<script src="/static/js/webshell.js?v=20261011-token-usage-tool-title"></script>