feat(vulnerabilities): group findings by target host

This commit is contained in:
Sycun 2026-11-13 14:45:28 +08:00
parent 14c5422901
commit 72042749e3
10 changed files with 332 additions and 165 deletions

View File

@ -9,7 +9,7 @@ import (
"sync"
"time"
_ "github.com/mattn/go-sqlite3"
"github.com/mattn/go-sqlite3"
"go.uber.org/zap"
)
@ -128,9 +128,17 @@ func (db *DB) runPassiveCheckpoint(trigger string) {
db.logger.Debug("SQLite PASSIVE checkpoint 完成(成功)", fields...)
}
func init() {
sql.Register("cyberstrike-sqlite3", &sqlite3.SQLiteDriver{
ConnectHook: func(conn *sqlite3.SQLiteConn) error {
return conn.RegisterFunc("vulnerability_target_host", vulnerabilityTargetHost, true)
},
})
}
// NewDB 创建数据库连接
func NewDB(dbPath string, logger *zap.Logger) (*DB, error) {
db, err := sql.Open("sqlite3", sqliteOpenDSN(dbPath))
db, err := sql.Open("cyberstrike-sqlite3", sqliteOpenDSN(dbPath))
if err != nil {
return nil, fmt.Errorf("打开数据库失败: %w", err)
}

View File

@ -3,11 +3,14 @@ package database
import (
"database/sql"
"fmt"
"net/netip"
"net/url"
"strings"
"time"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/net/idna"
)
// VulnerabilityListFilter 列表/统计/导出共用的筛选条件
@ -143,6 +146,7 @@ type Vulnerability struct {
Status string `json:"status"` // open, confirmed, fixed, false_positive, ignored
Type string `json:"type"`
Target string `json:"target"`
TargetHost *string `json:"target_host,omitempty"`
Preconditions string `json:"preconditions"`
ReproSteps string `json:"reproduction_steps"`
Evidence string `json:"evidence"`
@ -234,6 +238,49 @@ 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)
}
func vulnerabilityTargetHost(target string) string {
target = strings.TrimSpace(target)
if ip, err := netip.ParseAddr(target); err == nil {
return ip.String()
}
scheme, _, hasScheme := strings.Cut(target, "://")
explicitURL := strings.HasPrefix(target, "//") || (hasScheme && !strings.ContainsAny(scheme, "/?#"))
if !explicitURL {
target = "//" + target
}
parsed, err := url.Parse(target)
if err != nil || parsed.Host == "" {
return ""
}
host := parsed.Hostname()
if ip, err := netip.ParseAddr(host); err == nil {
return ip.String()
}
host, err = idna.Lookup.ToASCII(host)
host = strings.ToLower(strings.TrimSuffix(host, "."))
if err != nil || !validAssetDomain(host) {
return ""
}
// A relative endpoint such as "api/login" does not identify a host.
if !explicitURL && parsed.Port() == "" && host != "localhost" && !strings.Contains(host, ".") {
return ""
}
return host
}
func (db *DB) listVulnerabilitiesForAccess(limit, offset int, filter VulnerabilityListFilter, access RBACListAccess, byHost bool) ([]*Vulnerability, error) {
hostExpr, order := "NULL", "created_at DESC"
if byHost {
hostExpr = "vulnerability_target_host(target)"
order = "target_host = '', target_host, created_at DESC, id"
}
query := `
SELECT id, COALESCE(conversation_id,''), COALESCE(project_id,''), title, description, severity, status, conversation_tag, task_tag,
vulnerability_type, target,
@ -241,7 +288,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili
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,
created_at, updated_at
created_at, updated_at, ` + hostExpr + ` AS target_host
FROM vulnerabilities
WHERE 1=1
`
@ -249,7 +296,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili
query, args = filter.appendWhere(query, args)
query, args = appendVulnerabilityAccessFilter(query, args, access)
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
query += " ORDER BY " + order + " LIMIT ? OFFSET ?"
args = append(args, limit, offset)
rows, err := db.Query(query, args...)
@ -266,7 +313,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili
&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.CreatedAt, &vuln.UpdatedAt,
&vuln.CreatedAt, &vuln.UpdatedAt, &vuln.TargetHost,
)
if err != nil {
db.logger.Warn("扫描漏洞记录失败", zap.Error(err))
@ -275,7 +322,7 @@ func (db *DB) ListVulnerabilitiesForAccess(limit, offset int, filter Vulnerabili
vulnerabilities = append(vulnerabilities, &vuln)
}
return vulnerabilities, nil
return vulnerabilities, rows.Err()
}
// CountVulnerabilities 统计漏洞总数(支持筛选条件)

View File

@ -184,8 +184,12 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
pageStr := c.Query("page")
filter := parseVulnerabilityListFilter(c)
access := vulnerabilityAccessFromContext(c)
byHost := c.Query("group_by") == "host"
limit, _ := strconv.Atoi(limitStr)
if limit <= 0 || limit > 100 {
limit = 20
}
offset, _ := strconv.Atoi(offsetStr)
page := 1
@ -197,9 +201,6 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
}
}
if limit <= 0 || limit > 100 {
limit = 20
}
if offset < 0 {
offset = 0
}
@ -212,14 +213,6 @@ func (h *VulnerabilityHandler) ListVulnerabilities(c *gin.Context) {
total = 0
}
// 获取漏洞列表
vulnerabilities, err := h.db.ListVulnerabilitiesForAccess(limit, offset, filter, access)
if err != nil {
h.logger.Error("获取漏洞列表失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// 计算总页数
totalPages := (total + limit - 1) / limit
if totalPages == 0 {
@ -231,6 +224,21 @@ 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
}
}
vulnerabilities, err := list(limit, offset, filter, access)
if err != nil {
h.logger.Error("获取漏洞列表失败", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
response := ListVulnerabilitiesResponse{
Vulnerabilities: vulnerabilities,
Total: total,

View File

@ -0,0 +1,88 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"time"
"cyberstrike-ai/internal/database"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestListVulnerabilitiesGroupedByHost(t *testing.T) {
db, err := database.NewDB(filepath.Join(t.TempDir(), "grouped.db"), zap.NewNop())
if err != nil {
t.Fatal(err)
}
defer db.Close()
for i, item := range []struct {
id, target, severity string
}{
{"domain-old", "HTTPS://Example.COM.:443/login", "high"},
{"domain-new", "example.com:8443/api", "high"},
{"subdomain", "https://sub.example.com/api", "high"},
{"ipv6", "https://[2001:0DB8::1]:8080/", "high"},
{"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,
CreatedAt: time.Unix(int64(i+1), 0),
})
if err != nil {
t.Fatal(err)
}
}
h := NewVulnerabilityHandler(db, zap.NewNop())
fetch := func(query string) ListVulnerabilitiesResponse {
t.Helper()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/api/vulnerabilities?severity=high&limit=2&"+query, nil)
h.ListVulnerabilities(c)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
var result ListVulnerabilitiesResponse
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
return result
}
for _, tc := range []struct {
query string
page int
ids, hosts []string
}{
{"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{""}},
{"page=1", 1, []string{"unknown", "ipv6"}, nil},
} {
t.Run(tc.query, func(t *testing.T) {
result := fetch(tc.query)
if result.Total != 5 || result.TotalPages != 3 || result.Page != tc.page || len(result.Vulnerabilities) != len(tc.ids) {
t.Fatalf("unexpected pagination: %+v", result)
}
for i, v := range result.Vulnerabilities {
if v.ID != tc.ids[i] {
t.Fatalf("record %d = %q, want %q", i, v.ID, tc.ids[i])
}
if tc.hosts == nil {
if v.TargetHost != nil {
t.Fatalf("ordinary listing returned target_host for %q", v.ID)
}
} else if v.TargetHost == nil || *v.TargetHost != tc.hosts[i] {
t.Fatalf("target_host for %q = %v, want %q", v.ID, v.TargetHost, tc.hosts[i])
}
}
})
}
}

View File

@ -27456,6 +27456,42 @@ tr.mcp-stats-tool-row[data-tool-name]:focus-visible {
margin-bottom: 0;
}
.vulnerability-host-group {
min-width: 0;
border: 1px solid var(--border-color);
border-radius: 8px;
background: var(--bg-secondary);
}
.vulnerability-host-group > summary {
padding: 12px 16px;
cursor: pointer;
overflow-wrap: anywhere;
}
.vulnerability-host-group > summary:focus-visible {
outline: 2px solid var(--accent-color);
outline-offset: -2px;
border-radius: 8px;
}
.vulnerability-host-name {
margin-inline-start: 6px;
font-weight: 600;
}
.vulnerability-host-count {
margin-inline-start: 8px;
color: var(--text-muted);
font-size: 0.8125rem;
}
.vulnerability-host-cards {
display: grid;
gap: 10px;
padding: 0 12px 12px;
}
.vulnerability-card {
background: var(--bg-primary);
border: 1px solid var(--border-color);

View File

@ -2769,6 +2769,8 @@
"loading": "جارٍ التحميل...",
"loadListFailed": "فشل التحميل",
"noRecords": "لا توجد سجلات ثغرات",
"unknownHost": "مضيف غير معروف",
"hostPageCount": "{{count}} في هذه الصفحة",
"batchExport": "تصدير جماعي",
"batchDelete": "حذف جماعي",
"batchDeleteNoResults": "لا توجد ثغرات تطابق عوامل التصفية الحالية لحذفها",

View File

@ -2912,6 +2912,8 @@
"loading": "Loading...",
"loadListFailed": "Failed to load",
"noRecords": "No vulnerability records",
"unknownHost": "Unknown host",
"hostPageCount": "{{count}} on this page",
"batchExport": "Batch export",
"batchDelete": "Batch delete",
"batchDeleteNoResults": "No vulnerabilities match the current filters to delete",

View File

@ -2925,6 +2925,8 @@
"loading": "Загрузка...",
"loadListFailed": "Не удалось загрузить",
"noRecords": "Нет записей об уязвимостях",
"unknownHost": "Неизвестный хост",
"hostPageCount": "На этой странице: {{count}}",
"batchExport": "Пакетный экспорт",
"batchDelete": "Пакетное удаление",
"batchDeleteNoResults": "Нет уязвимостей по текущим фильтрам для удаления",

View File

@ -2900,6 +2900,8 @@
"loading": "加载中...",
"loadListFailed": "加载失败",
"noRecords": "暂无漏洞记录",
"unknownHost": "未识别到主机",
"hostPageCount": "本页 {{count}} 条",
"batchExport": "批量导出",
"batchDelete": "批量删除",
"batchDeleteNoResults": "当前筛选条件下没有可删除的漏洞",

View File

@ -187,40 +187,13 @@ function vulnerabilityStatusMatchesFilter(status) {
return !filterStatus || filterStatus === status;
}
function removeVulnerabilityCard(vulnId, options) {
const opts = options || {};
const card = document.getElementById('vulnerability-card-' + vulnId) ||
document.querySelector('.vulnerability-card[data-vuln-id="' + vulnId + '"]');
if (!card) return;
const nextCard = card.nextElementSibling;
card.classList.add('vulnerability-card--removing');
setTimeout(function () {
card.remove();
if (opts.decrementTotal !== false) {
vulnerabilityPagination.total = Math.max(0, (vulnerabilityPagination.total || 0) - 1);
vulnerabilityPagination.totalPages = Math.max(
1,
Math.ceil(vulnerabilityPagination.total / vulnerabilityPagination.pageSize)
);
renderVulnerabilityPagination();
}
const list = document.getElementById('vulnerabilities-list');
const remaining = list ? list.querySelectorAll('.vulnerability-card').length : 0;
if (remaining === 0) {
if (vulnerabilityPagination.currentPage > 1) {
vulnerabilityPagination.currentPage--;
}
loadVulnerabilities();
return;
}
if (opts.focusNext !== false && nextCard && nextCard.classList.contains('vulnerability-card')) {
nextCard.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}
}, VULNERABILITY_REMOVE_ANIM_MS);
async function removeVulnerabilityCard(vulnId) {
const card = document.getElementById('vulnerability-card-' + vulnId);
if (card) {
card.classList.add('vulnerability-card--removing');
await new Promise(resolve => setTimeout(resolve, VULNERABILITY_REMOVE_ANIM_MS));
}
await loadVulnerabilities(null, { preserveScroll: true, silent: true });
}
async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) {
@ -244,7 +217,7 @@ async function changeVulnerabilityStatus(vulnId, newStatus, pickerEl) {
loadVulnerabilityStats();
if (!vulnerabilityStatusMatchesFilter(newStatus)) {
removeVulnerabilityCard(vulnId, { decrementTotal: true, focusNext: true });
await removeVulnerabilityCard(vulnId);
}
} catch (error) {
console.error('更新漏洞状态失败:', error);
@ -1290,6 +1263,9 @@ 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();
if (!silent) {
listContainer.innerHTML = `<div class="loading-spinner">${escapeHtml(vulnT('vulnerabilityPage.loading'))}</div>`;
}
@ -1307,6 +1283,7 @@ async function loadVulnerabilities(page = null, options = {}) {
}
const params = buildVulnerabilityFilterParams();
params.append('group_by', 'host');
params.append('page', vulnerabilityPagination.currentPage.toString());
params.append('limit', vulnerabilityPagination.pageSize.toString());
@ -1341,7 +1318,7 @@ async function loadVulnerabilities(page = null, options = {}) {
console.error('未知的响应格式:', data);
}
renderVulnerabilities(vulnerabilities, { expandedIds: expandedIds || [] });
renderVulnerabilities(vulnerabilities, { expandedIds: expandedIds || [], groupOpenStates });
renderVulnerabilityPagination();
if (preserveScroll && scrollEl) {
@ -1360,16 +1337,7 @@ function renderVulnerabilities(vulnerabilities, renderOptions) {
const opts = renderOptions && typeof renderOptions === 'object' ? renderOptions : {};
const listContainer = document.getElementById('vulnerabilities-list');
// 处理空值情况(使用 data-i18n 以便语言切换时自动更新)
if (!vulnerabilities || !Array.isArray(vulnerabilities)) {
listContainer.innerHTML = '<div class="empty-state" data-i18n="vulnerabilityPage.noRecords">暂无漏洞记录</div>';
if (typeof window.applyTranslations === 'function') {
window.applyTranslations(listContainer);
}
return;
}
if (vulnerabilities.length === 0) {
if (!Array.isArray(vulnerabilities) || vulnerabilities.length === 0) {
listContainer.innerHTML = '<div class="empty-state" data-i18n="vulnerabilityPage.noRecords">暂无漏洞记录</div>';
if (typeof window.applyTranslations === 'function') {
window.applyTranslations(listContainer);
@ -1377,89 +1345,31 @@ function renderVulnerabilities(vulnerabilities, renderOptions) {
return;
}
const html = vulnerabilities.map(vuln => {
const severityClass = `severity-${vuln.severity}`;
const severityText = vulnSeverityLabel(vuln.severity);
const createdDate = new Date(vuln.created_at).toLocaleString(vulnDateLocale());
const projectLabel = vuln.project_id
? escapeHtml(typeof getProjectName === 'function' ? getProjectName(vuln.project_id) : vuln.project_id)
: escapeHtml(vulnT('vulnerabilityPage.projectUnbound'));
const projectBadge = vuln.project_id
? `<span class="vulnerability-project-badge" title="${escapeAttr(vuln.project_id)}">${escapeHtml(vulnT('vulnerabilityPage.detailProject'))}: ${projectLabel}</span>`
: `<span class="vulnerability-project-badge vulnerability-project-badge--unbound">${escapeHtml(vulnT('vulnerabilityPage.projectUnbound'))}</span>`;
const dlTitle = escapeHtml(vulnT('vulnerabilityDownload.download'));
const editTitle = escapeHtml(vulnT('common.edit'));
const deleteTitle = escapeHtml(vulnT('common.delete'));
const vulnIdJs = escapeJsStringAttr(vuln.id);
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 `
<div class="vulnerability-card ${severityClass}" id="vulnerability-card-${escapeAttr(vuln.id)}" data-vuln-id="${escapeAttr(vuln.id)}">
<div class="vulnerability-header" onclick="toggleVulnerabilityDetails(${vulnIdJs})" style="cursor: pointer;">
<div class="vulnerability-title-section">
<div style="display: flex; align-items: center; gap: 8px;">
<svg class="vulnerability-expand-icon" id="expand-icon-${escapeAttr(vuln.id)}" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="transition: transform 0.2s ease; flex-shrink: 0;">
<path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<h3 class="vulnerability-title">${escapeHtml(vuln.title)}</h3>
</div>
<div class="vulnerability-meta">
<span class="severity-badge ${severityClass}">${severityText}</span>
${buildVulnerabilityStatusPicker(vuln)}
${projectBadge}
<span class="vulnerability-date">${createdDate}</span>
</div>
</div>
<div class="vulnerability-actions" onclick="event.stopPropagation();">
<button type="button" class="btn-ghost" data-require-permission="vulnerability:write" onclick="openVulnerabilityRetest(${vulnIdJs})" ${vuln.conversation_id ? '' : 'disabled'}>${escapeHtml(vulnT('vulnerabilityRetest.button'))}</button>
<button class="btn-ghost" type="button" onclick="openVulnerabilityDownload(${vulnIdJs}, event)" title="${dlTitle}" aria-label="${dlTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="7 10 12 15 17 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
<button class="btn-ghost" onclick="editVulnerability(${vulnIdJs})" title="${editTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
<button class="btn-ghost" data-require-permission="vulnerability:delete" onclick="deleteVulnerability(${vulnIdJs})" title="${deleteTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
</div>
</div>
<div class="vulnerability-content" id="content-${vuln.id}" style="display: none;">
${vuln.description ? `<div class="vulnerability-description">${escapeHtml(vuln.description)}</div>` : ''}
<div class="vulnerability-details">
${vulnDetailField(vulnT('vulnerabilityPage.detailVulnId'), vuln.id, true)}
${vulnDetailProjectField(vuln)}
${vuln.type ? vulnDetailField(vulnT('vulnerabilityPage.detailType'), vuln.type, false) : ''}
${vuln.target ? vulnDetailField(vulnT('vulnerabilityPage.detailTarget'), vuln.target, false) : ''}
${vulnDetailConversationField(vuln.conversation_id)}
${vuln.task_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskId'), vuln.task_id, true) : ''}
${vuln.task_queue_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskQueueId'), vuln.task_queue_id, true) : ''}
${vuln.conversation_tag ? vulnDetailField(vulnT('vulnerabilityPage.detailConversationTag'), vuln.conversation_tag, false) : ''}
${vuln.task_tag ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskTag'), vuln.task_tag, false) : ''}
</div>
<div class="vulnerability-repro">
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailPreconditions'), vuln.preconditions)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailReproductionSteps'), vuln.reproduction_steps)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailEvidence'), vuln.evidence, { code: true })}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailImpact'), vuln.impact)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRecommendation'), vuln.recommendation)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestNotes'), vuln.retest_notes)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestLog'), vuln.retest_log, { code: true })}
</div>
<div class="vulnerability-related-facts" id="vuln-related-facts-${escapeAttr(vuln.id)}" data-project-id="${escapeAttr(vuln.project_id || '')}" data-vuln-id="${escapeAttr(vuln.id)}" hidden></div>
</div>
</div>
<details class="vulnerability-host-group" data-host="${escapeAttr(host)}"${open ? ' open' : ''}>
<summary>
<span class="vulnerability-host-name">${escapeHtml(label)}</span>
<span class="vulnerability-host-count">${escapeHtml(count)}</span>
</summary>
<div class="vulnerability-host-cards">${items.map(renderVulnerabilityCard).join('')}</div>
</details>
`;
}).join('');
listContainer.innerHTML = html;
initVulnerabilityStatusPickers(listContainer);
initVulnerabilityProjectBindSelects(listContainer);
if (typeof window.applyTranslations === 'function') {
@ -1467,14 +1377,89 @@ function renderVulnerabilities(vulnerabilities, renderOptions) {
}
if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(listContainer);
restoreExpandedVulnerabilityDetails(opts.expandedIds);
restoreExpandedVulnerabilityDetails(exactMatch ? [exactMatch] : opts.expandedIds);
}
// 如果通过漏洞ID筛选且只返回一条记录,自动展开详情(提升“点击查看”的用户体验)
if (vulnerabilities.length === 1 && vulnerabilityFilters.id && vulnerabilityFilters.id === vulnerabilities[0].id) {
setTimeout(() => {
toggleVulnerabilityDetails(vulnerabilities[0].id);
}, 300);
}
function renderVulnerabilityCard(vuln) {
const severityClass = `severity-${vuln.severity}`;
const severityText = vulnSeverityLabel(vuln.severity);
const createdDate = new Date(vuln.created_at).toLocaleString(vulnDateLocale());
const projectLabel = vuln.project_id
? escapeHtml(typeof getProjectName === 'function' ? getProjectName(vuln.project_id) : vuln.project_id)
: escapeHtml(vulnT('vulnerabilityPage.projectUnbound'));
const projectBadge = vuln.project_id
? `<span class="vulnerability-project-badge" title="${escapeAttr(vuln.project_id)}">${escapeHtml(vulnT('vulnerabilityPage.detailProject'))}: ${projectLabel}</span>`
: `<span class="vulnerability-project-badge vulnerability-project-badge--unbound">${escapeHtml(vulnT('vulnerabilityPage.projectUnbound'))}</span>`;
const dlTitle = escapeHtml(vulnT('vulnerabilityDownload.download'));
const editTitle = escapeHtml(vulnT('common.edit'));
const deleteTitle = escapeHtml(vulnT('common.delete'));
const vulnIdJs = escapeJsStringAttr(vuln.id);
return `
<div class="vulnerability-card ${severityClass}" id="vulnerability-card-${escapeAttr(vuln.id)}" data-vuln-id="${escapeAttr(vuln.id)}">
<div class="vulnerability-header" onclick="toggleVulnerabilityDetails(${vulnIdJs})" style="cursor: pointer;">
<div class="vulnerability-title-section">
<div style="display: flex; align-items: center; gap: 8px;">
<svg class="vulnerability-expand-icon" id="expand-icon-${escapeAttr(vuln.id)}" width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="transition: transform 0.2s ease; flex-shrink: 0;">
<path d="M9 18l6-6-6-6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<h3 class="vulnerability-title">${escapeHtml(vuln.title)}</h3>
</div>
<div class="vulnerability-meta">
<span class="severity-badge ${severityClass}">${severityText}</span>
${buildVulnerabilityStatusPicker(vuln)}
${projectBadge}
<span class="vulnerability-date">${createdDate}</span>
</div>
</div>
<div class="vulnerability-actions" onclick="event.stopPropagation();">
<button type="button" class="btn-ghost" data-require-permission="vulnerability:write" onclick="openVulnerabilityRetest(${vulnIdJs})" ${vuln.conversation_id ? '' : 'disabled'}>${escapeHtml(vulnT('vulnerabilityRetest.button'))}</button>
<button class="btn-ghost" type="button" onclick="openVulnerabilityDownload(${vulnIdJs}, event)" title="${dlTitle}" aria-label="${dlTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<polyline points="7 10 12 15 17 10" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<line x1="12" y1="15" x2="12" y2="3" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
<button class="btn-ghost" onclick="editVulnerability(${vulnIdJs})" title="${editTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
<button class="btn-ghost" data-require-permission="vulnerability:delete" onclick="deleteVulnerability(${vulnIdJs})" title="${deleteTitle}">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
</button>
</div>
</div>
<div class="vulnerability-content" id="content-${vuln.id}" style="display: none;">
${vuln.description ? `<div class="vulnerability-description">${escapeHtml(vuln.description)}</div>` : ''}
<div class="vulnerability-details">
${vulnDetailField(vulnT('vulnerabilityPage.detailVulnId'), vuln.id, true)}
${vulnDetailProjectField(vuln)}
${vuln.type ? vulnDetailField(vulnT('vulnerabilityPage.detailType'), vuln.type, false) : ''}
${vuln.target ? vulnDetailField(vulnT('vulnerabilityPage.detailTarget'), vuln.target, false) : ''}
${vulnDetailConversationField(vuln.conversation_id)}
${vuln.task_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskId'), vuln.task_id, true) : ''}
${vuln.task_queue_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskQueueId'), vuln.task_queue_id, true) : ''}
${vuln.conversation_tag ? vulnDetailField(vulnT('vulnerabilityPage.detailConversationTag'), vuln.conversation_tag, false) : ''}
${vuln.task_tag ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskTag'), vuln.task_tag, false) : ''}
</div>
<div class="vulnerability-repro">
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailPreconditions'), vuln.preconditions)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailReproductionSteps'), vuln.reproduction_steps)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailEvidence'), vuln.evidence, { code: true })}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailImpact'), vuln.impact)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRecommendation'), vuln.recommendation)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestNotes'), vuln.retest_notes)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestLog'), vuln.retest_log, { code: true })}
</div>
<div class="vulnerability-related-facts" id="vuln-related-facts-${escapeAttr(vuln.id)}" data-project-id="${escapeAttr(vuln.project_id || '')}" data-vuln-id="${escapeAttr(vuln.id)}" hidden></div>
</div>
</div>
`;
}
// 渲染分页控件
@ -1759,7 +1744,7 @@ async function saveVulnerability() {
const newStatus = (updated && updated.status) || data.status;
if (!vulnerabilityStatusMatchesFilter(newStatus)) {
removeVulnerabilityCard(editedId, { decrementTotal: true, focusNext: true });
await removeVulnerabilityCard(editedId);
return;
}
@ -1784,20 +1769,7 @@ async function deleteVulnerability(id) {
if (!response.ok) throw new Error(vulnT('vulnerabilityPage.deleteFailed'));
loadVulnerabilityStats();
const card = document.getElementById('vulnerability-card-' + id) ||
document.querySelector('.vulnerability-card[data-vuln-id="' + id + '"]');
if (card) {
removeVulnerabilityCard(id, { decrementTotal: true, focusNext: true });
return;
}
if (vulnerabilityPagination.currentPage > 1 && vulnerabilityPagination.total > 0) {
const itemsOnCurrentPage = vulnerabilityPagination.total - (vulnerabilityPagination.currentPage - 1) * vulnerabilityPagination.pageSize;
if (itemsOnCurrentPage <= 1) {
vulnerabilityPagination.currentPage--;
}
}
await loadVulnerabilities(null, { preserveScroll: true });
await removeVulnerabilityCard(id);
} catch (error) {
console.error('删除漏洞失败:', error);
alert(vulnT('vulnerabilityPage.deleteFailed') + ': ' + error.message);