Add files via upload

This commit is contained in:
公明
2026-06-20 17:25:44 +08:00
committed by GitHub
parent 46f68cc1d4
commit 46a7d338a4
6 changed files with 1571 additions and 27 deletions
+555
View File
@@ -0,0 +1,555 @@
/**
* 项目事实图渲染(Cytoscape + ELK),供项目管理页使用。
* 节点采用 SVG 卡片背景(图标 + 多行文字),避免 Cytoscape 原生 label 定位问题。
*/
(function (global) {
'use strict';
let _cy = null;
let _graphData = null;
let _onNodeSelect = null;
let _onEdgeSelect = null;
const EDGE_COLORS = {
discovered_on: '#4F46E5',
leads_to: '#64748B',
enables: '#E11D48',
exploits: '#DC2626',
depends_on: '#0D9488',
contains: '#6366F1',
part_of: '#6366F1',
supports: '#94A3B8',
links_vuln: '#BE123C',
};
const CARD_PAD = 14;
const CARD_TEXT_PAD_RIGHT = 12;
const CARD_ICON = 36;
const CARD_ICON_GAP = 12;
const CARD_TEXT_X = CARD_PAD + CARD_ICON + CARD_ICON_GAP;
const CARD_MIN_W = 300;
const CARD_TARGET_W = 360;
const CARD_MIN_H = 88;
const CARD_MAX_H = 152;
const CARD_HEADER_FS = 11;
const CARD_HEADER_LH = 16;
const CARD_SUMMARY_FS = 13;
const CARD_SUMMARY_LH = 18;
const CARD_SECTION_GAP = 6;
const CARD_FONT =
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "PingFang SC", "Microsoft YaHei", sans-serif';
function nodeTheme(type) {
switch (type) {
case 'target':
return { typeLabel: '目标', typeEn: 'TARGET', accent: '#4F46E5', bgEnd: '#F5F3FF', icon: 'target' };
case 'finding':
return { typeLabel: '发现', typeEn: 'FINDING', accent: '#E11D48', bgEnd: '#FFF1F2', icon: 'vulnerability' };
case 'vulnerability':
return { typeLabel: '漏洞', typeEn: 'VULN', accent: '#BE123C', bgEnd: '#FFF1F2', icon: 'vulnerability' };
case 'auth':
return { typeLabel: '认证', typeEn: 'AUTH', accent: '#0D9488', bgEnd: '#F0FDFA', icon: 'default' };
case 'infra':
return { typeLabel: '基础设施', typeEn: 'INFRA', accent: '#64748B', bgEnd: '#F8FAFC', icon: 'default' };
case 'missing':
return { typeLabel: '缺失', typeEn: 'MISSING', accent: '#CBD5E1', bgEnd: '#F1F5F9', icon: 'default' };
default:
return { typeLabel: '备注', typeEn: 'NOTE', accent: '#94A3B8', bgEnd: '#F8FAFC', icon: 'default' };
}
}
function escapeXml(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function escapeHtml(str) {
return escapeXml(str);
}
function buildStatusBadge(confidence) {
const conf = (confidence || '').toLowerCase();
if (conf === 'tentative') return '待确认';
if (conf === 'deprecated') return '已废弃';
return '';
}
function buildHeaderText(theme, statusBadge) {
const line = (theme.typeEn || '') + ' · ' + (theme.typeLabel || '');
return statusBadge ? line + ' · ' + statusBadge : line;
}
function isWideChar(ch) {
const code = ch.codePointAt(0) || 0;
if (code >= 0x4e00 && code <= 0x9fff) return true;
if (code >= 0x3400 && code <= 0x4dbf) return true;
if (code >= 0xf900 && code <= 0xfaff) return true;
if (code >= 0xff00 && code <= 0xffef) return true;
return /[·:,。;!?【】()《》、「」]/.test(ch);
}
function charWidth(ch, fontSize, bold) {
const scale = bold ? 1.05 : 1;
if (ch === ' ') return fontSize * 0.3 * scale;
if (isWideChar(ch)) return fontSize * scale;
return fontSize * 0.58 * scale;
}
function lineWidth(text, fontSize, bold) {
let width = 0;
for (const ch of text) width += charWidth(ch, fontSize, bold);
return width;
}
function wrapTextLines(text, maxWidth, fontSize, maxLines, bold) {
const raw = String(text || '').replace(/\s+/g, ' ').trim();
if (!raw) return ['—'];
const safeWidth = Math.max(40, maxWidth - 4);
const chars = [...raw];
const lines = [];
let index = 0;
while (index < chars.length && lines.length < maxLines) {
let line = '';
let width = 0;
while (index < chars.length) {
const ch = chars[index];
const nextWidth = charWidth(ch, fontSize, bold);
if (line && width + nextWidth > safeWidth) break;
line += ch;
width += nextWidth;
index += 1;
if (width >= safeWidth) break;
}
if (line) lines.push(line);
}
if (index < chars.length && lines.length) {
let last = lines[lines.length - 1];
while (last.length > 1 && lineWidth(last + '…', fontSize, bold) > safeWidth) {
last = last.slice(0, -1);
}
lines[lines.length - 1] = last + '…';
}
return lines.length ? lines : ['—'];
}
function cardTextWidth(nodeWidth) {
return nodeWidth - CARD_TEXT_X - CARD_PAD - CARD_TEXT_PAD_RIGHT;
}
function computeNodeLayout(type, summary, statusBadge, theme) {
const width = type === 'target' ? CARD_TARGET_W : CARD_MIN_W;
const textW = cardTextWidth(width);
const t = theme || nodeTheme(type);
const headerLines = wrapTextLines(buildHeaderText(t, statusBadge), textW, CARD_HEADER_FS, 2, true);
const summaryLines = wrapTextLines(summary, textW, CARD_SUMMARY_FS, 4, true);
const height = Math.min(
CARD_MAX_H,
Math.max(
CARD_MIN_H,
CARD_PAD +
headerLines.length * CARD_HEADER_LH +
CARD_SECTION_GAP +
summaryLines.length * CARD_SUMMARY_LH +
CARD_PAD,
),
);
return {
width,
height,
headerLines,
summaryLines,
searchLabel: headerLines.join(' ') + '\n' + summaryLines.join(' '),
};
}
function svgIconGroup(kind, color, x, y) {
const scale = (CARD_ICON / 24).toFixed(3);
if (kind === 'target') {
return (
`<g transform="translate(${x}, ${y}) scale(${scale})">` +
`<circle cx="12" cy="12" r="6" fill="none" stroke="${color}" stroke-width="2"/>` +
`<circle cx="12" cy="12" r="2.5" fill="${color}"/></g>`
);
}
if (kind === 'vulnerability') {
return (
`<g transform="translate(${x}, ${y}) scale(${scale})">` +
`<path d="M12 3l9 16H3z" fill="none" stroke="${color}" stroke-width="2"/>` +
`<line x1="12" y1="9" x2="12" y2="13" stroke="${color}" stroke-width="2"/>` +
`<circle cx="12" cy="16" r="1" fill="${color}"/></g>`
);
}
return (
`<g transform="translate(${x}, ${y}) scale(${scale})">` +
`<circle cx="12" cy="12" r="5" fill="${color}" opacity="0.85"/></g>`
);
}
function buildNodeCardSvgUrl(theme, layout, confidence) {
const { width, height, headerLines, summaryLines } = layout;
const accent = theme.accent;
const bgEnd = theme.bgEnd;
const conf = (confidence || '').toLowerCase();
const isTentative = conf === 'tentative';
const isDeprecated = conf === 'deprecated';
const iconX = CARD_PAD;
const iconY = (height - CARD_ICON) / 2;
const headerY = CARD_PAD + CARD_HEADER_FS;
const summaryY = CARD_PAD + headerLines.length * CARD_HEADER_LH + CARD_SECTION_GAP + CARD_SUMMARY_FS;
const stroke = isTentative
? `stroke="${accent}" stroke-width="1.5" stroke-dasharray="8 5" stroke-opacity="0.9"`
: `stroke="${accent}" stroke-width="1.5" stroke-opacity="0.72"`;
const headerSvg = headerLines
.map(
(line, i) =>
`<text x="${CARD_TEXT_X}" y="${headerY + i * CARD_HEADER_LH}" font-size="${CARD_HEADER_FS}" font-weight="700" fill="${accent}" fill-opacity="0.88" font-family='${CARD_FONT}'>${escapeXml(line)}</text>`,
)
.join('');
const summarySvg = summaryLines
.map(
(line, i) =>
`<text x="${CARD_TEXT_X}" y="${summaryY + i * CARD_SUMMARY_LH}" font-size="${CARD_SUMMARY_FS}" font-weight="600" fill="#0f172a" font-family='${CARD_FONT}'>${escapeXml(line)}</text>`,
)
.join('');
const textClipW = width - CARD_TEXT_X - CARD_PAD - 2;
const textClipH = height - CARD_PAD * 2 + 4;
const svg =
`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
`<defs><linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">` +
`<stop offset="0%" stop-color="#FFFFFF"/><stop offset="100%" stop-color="${bgEnd}"/></linearGradient>` +
`<clipPath id="textClip"><rect x="${CARD_TEXT_X}" y="${CARD_PAD - 2}" width="${textClipW}" height="${textClipH}"/></clipPath></defs>` +
`<g${isDeprecated ? ' opacity="0.55"' : ''}>` +
`<rect x="0.75" y="0.75" width="${width - 1.5}" height="${height - 1.5}" rx="12" fill="url(#bg)" ${stroke}/>` +
svgIconGroup(theme.icon, accent, iconX, iconY) +
`<g clip-path="url(#textClip)">${headerSvg}${summarySvg}</g>` +
`</g></svg>`;
try {
return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
} catch (e) {
return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);
}
}
function destroy() {
if (_cy) {
_cy.destroy();
_cy = null;
}
_graphData = null;
}
function centerGraph() {
if (!_cy) return;
try {
_cy.fit(undefined, 56);
if (_cy.zoom() < 0.65) {
_cy.zoom(0.65);
_cy.center();
}
} catch (e) {
console.warn('centerGraph', e);
}
}
function applyElkLayout(validEdges, isComplex) {
const layoutOptions = {
name: 'breadthfirst',
directed: true,
spacingFactor: isComplex ? 3.0 : 2.5,
padding: 40,
};
const elkInstance = typeof ELK !== 'undefined' ? new ELK() : null;
if (!elkInstance) {
const layout = _cy.layout(layoutOptions);
layout.one('layoutstop', () => setTimeout(centerGraph, 100));
layout.run();
return;
}
const nodeGap = isComplex ? 45 : 60;
const layerGap = isComplex ? 70 : 95;
const elkGraph = {
id: 'root',
layoutOptions: {
'elk.algorithm': 'layered',
'elk.direction': 'DOWN',
'elk.spacing.nodeNode': String(nodeGap),
'elk.layered.spacing.nodeNodeBetweenLayers': String(layerGap),
'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
},
children: (_graphData.nodes || []).map((node) => {
const n = _cy ? _cy.getElementById(node.id) : null;
const w = n.length ? n.data('nodeWidth') : node.type === 'target' ? CARD_TARGET_W : CARD_MIN_W;
const h = n.length ? n.data('nodeHeight') : CARD_MIN_H;
return { id: node.id, width: w, height: h };
}),
edges: validEdges.map((edge) => ({
id: edge.id,
sources: [edge.source],
targets: [edge.target],
})),
};
elkInstance
.layout(elkGraph)
.then((laidOut) => {
(laidOut.children || []).forEach((elkNode) => {
const cyNode = _cy.getElementById(elkNode.id);
if (cyNode.length && elkNode.x != null) {
cyNode.position({
x: elkNode.x + (elkNode.width || 0) / 2,
y: elkNode.y + (elkNode.height || 0) / 2,
});
}
});
setTimeout(centerGraph, 120);
})
.catch(() => {
const layout = _cy.layout(layoutOptions);
layout.one('layoutstop', () => setTimeout(centerGraph, 100));
layout.run();
});
}
function render(container, graphData, options) {
if (!container || typeof cytoscape === 'undefined') {
if (container) {
container.innerHTML = '<div class="error-message">Cytoscape 未加载</div>';
}
return null;
}
destroy();
_graphData = graphData || { nodes: [], edges: [] };
_onNodeSelect = options && options.onNodeSelect;
_onEdgeSelect = options && options.onEdgeSelect;
const nodes = _graphData.nodes || [];
const edges = _graphData.edges || [];
if (!nodes.length) {
const title = (options && options.emptyTitle) || '';
const hint = (options && options.emptyText) || '暂无事实关系';
const steps = (options && options.emptySteps) || [];
const actionLabel = options && options.emptyActionLabel;
const stepsHtml = steps.length
? '<ol class="project-fact-graph-empty-steps">' +
steps.map((s) => '<li>' + escapeHtml(String(s)) + '</li>').join('') +
'</ol>'
: '';
const actionHtml =
actionLabel && options.onEmptyAction
? '<button type="button" class="btn-primary btn-small project-fact-graph-empty-cta">' +
escapeHtml(actionLabel) +
'</button>'
: '';
container.innerHTML =
'<div class="project-fact-graph-empty">' +
'<div class="project-fact-graph-empty-icon" aria-hidden="true">' +
'<svg width="48" height="48" viewBox="0 0 24 24" fill="none"><circle cx="6" cy="6" r="2.5" fill="#4F46E5" opacity="0.9"/><circle cx="18" cy="6" r="2.5" fill="#E11D48" opacity="0.9"/><circle cx="12" cy="18" r="2.5" fill="#0D9488" opacity="0.9"/>' +
'<path d="M8 7l4 9M16 7l-4 9M8 7h8" stroke="#CBD5E1" stroke-width="1.5" stroke-linecap="round"/></svg>' +
'</div>' +
(title ? '<h4 class="project-fact-graph-empty-title">' + escapeHtml(title) + '</h4>' : '') +
'<p class="project-fact-graph-empty-hint">' + escapeHtml(hint) + '</p>' +
stepsHtml +
actionHtml +
'</div>';
const cta = container.querySelector('.project-fact-graph-empty-cta');
if (cta && typeof options.onEmptyAction === 'function') {
cta.addEventListener('click', options.onEmptyAction);
}
return null;
}
container.innerHTML = '';
const isComplex = nodes.length > 15 || edges.length > 25;
const elements = [];
const nodeIds = new Set();
nodes.forEach((node) => {
nodeIds.add(node.id);
const theme = nodeTheme(node.type || node.category || 'note');
const label = node.label || node.fact_key || node.id;
const statusBadge = buildStatusBadge(node.confidence);
const layout = computeNodeLayout(node.type || node.category || 'note', label, statusBadge, theme);
elements.push({
data: {
id: node.id,
label: layout.searchLabel,
factKey: node.fact_key || node.id,
type: node.type || 'note',
typeLabel: theme.typeLabel,
typeEn: theme.typeEn,
accentColor: theme.accent,
statusBadge: statusBadge,
confidence: node.confidence || '',
nodeWidth: layout.width,
nodeHeight: layout.height,
cardSvgUrl: buildNodeCardSvgUrl(theme, layout, node.confidence),
},
});
});
const validEdges = [];
edges.forEach((edge, idx) => {
if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) return;
const id = edge.id || 'e-' + idx;
validEdges.push({ ...edge, id });
elements.push({
data: {
id,
source: edge.source,
target: edge.target,
type: edge.type || 'leads_to',
confidence: edge.confidence || 'confirmed',
},
});
});
_cy = cytoscape({
container,
elements,
style: [
{
selector: 'node',
style: {
label: '',
width: (ele) => ele.data('nodeWidth') || CARD_MIN_W,
height: (ele) => ele.data('nodeHeight') || CARD_MIN_H,
shape: 'round-rectangle',
'background-color': '#ffffff',
'background-image': (ele) => ele.data('cardSvgUrl') || 'none',
'background-width': (ele) => (ele.data('nodeWidth') || CARD_MIN_W) + 'px',
'background-height': (ele) => (ele.data('nodeHeight') || CARD_MIN_H) + 'px',
'background-position-x': '50%',
'background-position-y': '50%',
'background-fit': 'none',
'border-width': 0,
'background-opacity': 1,
},
},
{
selector: 'edge',
style: {
width: 2.2,
'line-color': (ele) => EDGE_COLORS[ele.data('type')] || '#CBD5E1',
'target-arrow-color': (ele) => EDGE_COLORS[ele.data('type')] || '#CBD5E1',
'target-arrow-shape': 'triangle',
'curve-style': 'bezier',
opacity: (ele) => (ele.data('confidence') === 'tentative' ? 0.55 : 0.9),
'line-style': (ele) => (ele.data('confidence') === 'tentative' ? 'dashed' : 'solid'),
},
},
{
selector: 'edge:selected',
style: {
width: 3.5,
opacity: 1,
'line-color': '#4F46E5',
'target-arrow-color': '#4F46E5',
},
},
{
selector: 'node:selected',
style: {
'border-width': 3,
'border-color': '#4F46E5',
'border-opacity': 1,
},
},
],
minZoom: 0.35,
maxZoom: 3,
});
_cy.on('tap', 'node', (evt) => {
const d = evt.target.data();
const key = d.factKey || d.id;
if (_connectMode && _connectPick) {
_connectPick(key);
return;
}
if (typeof _onNodeSelect === 'function') {
_onNodeSelect(key, d);
}
});
_cy.on('tap', 'edge', (evt) => {
if (_connectMode && _connectPick) return;
const d = evt.target.data();
if (typeof _onEdgeSelect === 'function') {
_onEdgeSelect(d.id, d);
}
});
_cy.on('tap', (evt) => {
if (evt.target === _cy) {
clearEdgeSelection();
}
});
applyElkLayout(validEdges, isComplex);
return _cy;
}
function filterBySearch(query) {
if (!_cy) return;
const q = (query || '').trim().toLowerCase();
_cy.nodes().forEach((n) => {
if (!q) {
n.style('opacity', 1);
return;
}
const text = (
(n.data('label') || '') +
' ' +
(n.data('factKey') || '') +
' ' +
(n.data('typeLabel') || '')
).toLowerCase();
n.style('opacity', text.includes(q) ? 1 : 0.15);
});
_cy.edges().forEach((e) => {
e.style('opacity', q ? 0.12 : 0.9);
});
}
let _connectMode = false;
let _connectPick = null;
function selectEdge(edgeId) {
if (!_cy || !edgeId) return;
_cy.elements().unselect();
const edge = _cy.getElementById(edgeId);
if (edge.length) edge.select();
}
function clearEdgeSelection() {
if (!_cy) return;
_cy.elements().unselect();
}
function setConnectMode(enabled, onPick) {
_connectMode = !!enabled;
_connectPick = typeof onPick === 'function' ? onPick : null;
if (_cy) {
_cy.userPanningEnabled(!_connectMode);
}
}
global.ProjectFactGraph = {
render,
destroy,
center: centerGraph,
filterBySearch,
setConnectMode,
selectEdge,
clearEdgeSelection,
};
})(typeof window !== 'undefined' ? window : globalThis);
+317 -5
View File
@@ -64,6 +64,8 @@ Host: ...
## 关联
- related_vulnerability_id: <可选>
- 依赖事实: <fact_key,如 auth/session_cookie>
- 结构化出边(自动同步):
- discovered_on: target/primary_domain
## 备注与不确定性
<待验证假设、环境差异、绕过尝试记录>`;
@@ -730,20 +732,280 @@ async function selectProject(id) {
function switchProjectTab(tab) {
currentProjectTab = tab;
['facts', 'conversations', 'vulns', 'settings'].forEach((t) => {
['facts', 'graph', 'conversations', 'vulns', 'settings'].forEach((t) => {
const btn = document.getElementById(`project-tab-${t}`);
const panel = document.getElementById(`project-panel-${t}`);
if (btn) btn.classList.toggle('is-active', t === tab);
if (panel) panel.hidden = t !== tab;
});
if (tab === 'facts') loadProjectFacts();
if (tab === 'graph') loadProjectFactGraph();
if (tab === 'conversations') loadProjectConversations();
if (tab === 'vulns') loadProjectVulnerabilities();
}
let _selectedGraphFactKey = null;
let _selectedGraphEdgeId = null;
let _currentGraphData = null;
let _graphConnectMode = false;
let _graphConnectSource = null;
function toggleProjectFactGraphConnectMode() {
_graphConnectMode = !_graphConnectMode;
_graphConnectSource = null;
const btn = document.getElementById('project-graph-connect-btn');
if (btn) {
btn.classList.toggle('is-active', _graphConnectMode);
btn.textContent = _graphConnectMode ? tp('projects.graphConnectActive') : tp('projects.graphConnect');
btn.classList.toggle('projects-graph-action-btn--connect-active', _graphConnectMode);
}
if (typeof ProjectFactGraph !== 'undefined') {
ProjectFactGraph.setConnectMode(_graphConnectMode, handleGraphConnectNodePick);
}
}
async function handleGraphConnectNodePick(factKey) {
if (!factKey || String(factKey).startsWith('vuln:')) return;
if (!_graphConnectSource) {
_graphConnectSource = factKey;
if (typeof showNotification === 'function') {
showNotification(tpFmt('projects.graphConnectPickTarget', `已选源节点 ${factKey},请点击目标节点`, { source: factKey }), 'info');
}
return;
}
if (_graphConnectSource === factKey) return;
const edgeType = window.prompt(tp('projects.graphEdgeTypePrompt'), 'leads_to');
if (!edgeType) {
_graphConnectSource = null;
return;
}
const res = await apiFetch(`/api/projects/${currentProjectId}/fact-edges`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
source_fact_key: _graphConnectSource,
target_fact_key: factKey,
edge_type: edgeType.trim(),
}),
});
_graphConnectSource = null;
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return alert(err.error || tp('projects.graphConnectFailed'));
}
if (typeof showNotification === 'function') showNotification(tp('projects.graphConnectSuccess'), 'success');
loadProjectFactGraph();
loadProjectFacts();
}
function formatOutgoingLinksForModal(links) {
if (!links || !links.length) return '';
return links
.map((e) => `${e.edge_type || e.type}: ${e.target_fact_key || e.to}`)
.join('\n');
}
async function loadProjectFactGraph() {
const container = document.getElementById('project-fact-graph-container');
const statsEl = document.getElementById('project-fact-graph-stats');
if (!container || !currentProjectId) return;
container.innerHTML = `<div class="loading-spinner">${escapeHtml(tp('common.loading'))}</div>`;
closeProjectFactGraphSidebar();
const view = document.getElementById('project-graph-view')?.value || 'path';
const hideDeprecated = document.getElementById('project-facts-filter-hide-deprecated')?.checked !== false;
const params = new URLSearchParams({ view });
if (!hideDeprecated) params.set('exclude_deprecated', '0');
try {
const res = await apiFetch(`/api/projects/${currentProjectId}/fact-graph?${params}`);
if (!res.ok) throw new Error(tp('common.loadFailed'));
const data = await res.json();
_currentGraphData = data;
if (typeof ProjectFactGraph !== 'undefined') {
ProjectFactGraph.render(container, data, {
emptyText: tp('projects.graphEmpty'),
emptyTitle: tp('projects.graphEmptyTitle'),
emptySteps: [
tp('projects.graphEmptyStep1'),
tp('projects.graphEmptyStep2'),
tp('projects.graphEmptyStep3'),
],
emptyActionLabel: tp('projects.graphEmptyCta'),
onEmptyAction: () => showAddFactModal(),
onNodeSelect: (factKey) => showProjectFactGraphNode(factKey, _currentGraphData),
onEdgeSelect: (edgeId) => showProjectFactGraphEdge(edgeId, _currentGraphData),
});
}
const nodeCount = (data.nodes || []).length;
const edgeCount = (data.edges || []).length;
if (statsEl) {
statsEl.innerHTML =
`<span class="projects-graph-stat-badge"><strong>${nodeCount}</strong> ${escapeHtml(tp('projects.graphStatsNodes'))}</span>` +
`<span class="projects-graph-stat-badge"><strong>${edgeCount}</strong> ${escapeHtml(tp('projects.graphStatsEdges'))}</span>`;
}
} catch (e) {
container.innerHTML = `<div class="error-message">${escapeHtml(e.message || tp('common.loadFailed'))}</div>`;
if (statsEl) statsEl.textContent = '';
}
}
function filterProjectFactGraph() {
const q = document.getElementById('project-graph-search')?.value || '';
if (typeof ProjectFactGraph !== 'undefined') {
ProjectFactGraph.filterBySearch(q);
}
}
function centerProjectFactGraph() {
if (typeof ProjectFactGraph !== 'undefined') ProjectFactGraph.center();
}
function closeProjectFactGraphSidebar() {
_selectedGraphFactKey = null;
_selectedGraphEdgeId = null;
if (typeof ProjectFactGraph !== 'undefined') ProjectFactGraph.clearEdgeSelection();
const sidebar = document.getElementById('project-fact-graph-sidebar');
if (sidebar) sidebar.hidden = true;
}
function isSyntheticGraphEdge(edge) {
if (!edge) return true;
const id = String(edge.id || '');
const type = String(edge.type || '');
return id.startsWith('vuln-link:') || type === 'links_vuln';
}
function getGraphEdgesForFact(factKey, graphData) {
if (!factKey || !graphData?.edges) return [];
return graphData.edges.filter((e) => e.source === factKey || e.target === factKey);
}
function renderGraphEdgesListHtml(factKey, graphData, selectedEdgeId) {
const edges = getGraphEdgesForFact(factKey, graphData);
if (!edges.length) {
return `<p class="project-fact-graph-edges-empty">${escapeHtml(tp('projects.graphEdgesEmpty'))}</p>`;
}
return edges
.map((e) => {
const isOut = e.source === factKey;
const dirLabel = isOut ? tp('projects.graphEdgeOutgoing') : tp('projects.graphEdgeIncoming');
const other = isOut ? e.target : e.source;
const arrow = isOut ? '→' : '←';
const selected = e.id === selectedEdgeId ? ' is-selected' : '';
const synthetic = isSyntheticGraphEdge(e);
const deleteBtn = synthetic
? `<span class="project-fact-graph-edge-synthetic" title="${escapeHtml(tp('projects.graphEdgeSynthetic'))}">—</span>`
: `<button type="button" class="project-fact-graph-edge-delete" data-edge-id="${escapeHtml(e.id)}" onclick="event.stopPropagation(); deleteProjectFactEdge(this.dataset.edgeId)" title="${escapeHtml(tp('projects.graphDeleteEdge'))}">×</button>`;
return `<div class="project-fact-graph-edge-item${selected}" data-edge-id="${escapeHtml(e.id)}" onclick="focusProjectFactGraphEdge(${JSON.stringify(e.id)})">
<span class="project-fact-graph-edge-dir">${escapeHtml(dirLabel)}</span>
<span class="project-fact-graph-edge-type">${escapeHtml(e.type || '')}</span>
<span class="project-fact-graph-edge-arrow">${arrow}</span>
<span class="project-fact-graph-edge-peer" title="${escapeHtml(other)}">${escapeHtml(other)}</span>
${deleteBtn}
</div>`;
})
.join('');
}
function renderProjectFactGraphEdges(factKey, graphData, selectedEdgeId) {
const wrap = document.getElementById('project-fact-graph-edges-wrap');
const list = document.getElementById('project-fact-graph-edges-list');
if (!wrap || !list) return;
const edges = getGraphEdgesForFact(factKey, graphData);
wrap.hidden = false;
list.innerHTML = renderGraphEdgesListHtml(factKey, graphData, selectedEdgeId);
if (selectedEdgeId) {
const selectedEl = list.querySelector('[data-edge-id="' + String(selectedEdgeId).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]');
if (selectedEl) selectedEl.scrollIntoView({ block: 'nearest' });
}
if (!edges.length) wrap.hidden = false;
}
function showProjectFactGraphNode(factKey, graphData, selectedEdgeId) {
if (!factKey || String(factKey).startsWith('vuln:')) {
closeProjectFactGraphSidebar();
return;
}
_selectedGraphFactKey = factKey;
_selectedGraphEdgeId = selectedEdgeId || null;
const node = (graphData?.nodes || []).find((n) => n.fact_key === factKey || n.id === factKey);
const sidebar = document.getElementById('project-fact-graph-sidebar');
const titleEl = document.getElementById('project-fact-graph-node-title');
const metaEl = document.getElementById('project-fact-graph-node-meta');
const categoryEl = document.getElementById('project-fact-graph-node-category');
if (!sidebar || !titleEl || !metaEl) return;
titleEl.textContent = factKey;
if (categoryEl) {
const cat = node?.category || node?.type || '';
categoryEl.textContent = cat;
categoryEl.hidden = !cat;
categoryEl.className = 'project-fact-graph-node-category project-fact-graph-node-category--' + (cat || 'note');
}
const conf = node?.confidence || '';
const label = node?.label || '';
if (label || conf) {
const parts = [];
if (label) {
parts.push(`<span class="project-fact-graph-node-summary">${escapeHtml(label)}</span>`);
}
if (conf) {
parts.push(formatConfidenceBadge(conf));
}
metaEl.innerHTML = parts.join('');
} else {
metaEl.textContent = '';
}
renderProjectFactGraphEdges(factKey, graphData, _selectedGraphEdgeId);
if (_selectedGraphEdgeId && typeof ProjectFactGraph !== 'undefined') {
ProjectFactGraph.selectEdge(_selectedGraphEdgeId);
} else if (typeof ProjectFactGraph !== 'undefined') {
ProjectFactGraph.clearEdgeSelection();
}
sidebar.hidden = false;
}
function showProjectFactGraphEdge(edgeId, graphData) {
const edge = (graphData?.edges || []).find((e) => e.id === edgeId);
if (!edge) return;
const anchorKey = edge.source && !String(edge.source).startsWith('vuln:') ? edge.source : edge.target;
showProjectFactGraphNode(anchorKey, graphData, edgeId);
}
function focusProjectFactGraphEdge(edgeId) {
if (!edgeId || !_currentGraphData) return;
showProjectFactGraphEdge(edgeId, _currentGraphData);
}
async function deleteProjectFactEdge(edgeId) {
if (!edgeId || !currentProjectId) return;
const edge = (_currentGraphData?.edges || []).find((e) => e.id === edgeId);
if (isSyntheticGraphEdge(edge)) return;
if (!confirm(tp('projects.confirmDeleteGraphEdge'))) return;
const res = await apiFetch(`/api/projects/${currentProjectId}/fact-edges/${encodeURIComponent(edgeId)}`, {
method: 'DELETE',
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return alert(err.error || tp('projects.graphEdgeDeleteFailed'));
}
if (typeof showNotification === 'function') showNotification(tp('projects.graphEdgeDeleteSuccess'), 'success');
const keepKey = _selectedGraphFactKey;
await loadProjectFactGraph();
if (keepKey) showProjectFactGraphNode(keepKey, _currentGraphData);
loadProjectFacts();
}
function openSelectedGraphFactDetail() {
if (_selectedGraphFactKey) viewProjectFactBody(_selectedGraphFactKey);
}
function editSelectedGraphFact() {
if (_selectedGraphFactKey) showEditFactModal(_selectedGraphFactKey);
}
function buildProjectFactsQueryParams() {
const params = new URLSearchParams();
params.set('limit', '200');
params.set('include_link_counts', 'true');
const search = document.getElementById('project-facts-search')?.value?.trim();
const category = document.getElementById('project-facts-filter-category')?.value?.trim();
const confidence = document.getElementById('project-facts-filter-confidence')?.value?.trim();
@@ -768,11 +1030,11 @@ function debouncedLoadProjectFacts() {
async function loadProjectFacts() {
const tbody = document.getElementById('project-facts-tbody');
if (!tbody || !currentProjectId) return;
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="7">${escapeHtml(tp('common.loading'))}</td></tr>`;
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="8">${escapeHtml(tp('common.loading'))}</td></tr>`;
const qs = buildProjectFactsQueryParams().toString();
const res = await apiFetch(`/api/projects/${currentProjectId}/facts?${qs}`);
if (!res.ok) {
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="7">${escapeHtml(tp('common.loadFailed'))}</td></tr>`;
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="8">${escapeHtml(tp('common.loadFailed'))}</td></tr>`;
return;
}
const facts = await res.json();
@@ -782,7 +1044,7 @@ async function loadProjectFacts() {
document.getElementById('project-facts-filter-category')?.value ||
document.getElementById('project-facts-filter-confidence')?.value ||
document.getElementById('project-facts-filter-sparse')?.checked;
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="7">${
tbody.innerHTML = `<tr class="is-empty-row"><td colspan="8">${
hasFilter ? tp('projects.noMatchingFacts') : tp('projects.noFacts')
}</td></tr>`;
refreshProjectHeaderStats();
@@ -797,10 +1059,16 @@ async function loadProjectFacts() {
const pinBadge = f.pinned
? `<span class="projects-list-item-badge" title="${escapeHtml(tp('projects.pinned'))}">${escapeHtml(tp('projects.pinned'))}</span>`
: '';
const lc = f.link_counts || {};
const linkBadge =
lc.outgoing || lc.incoming
? `<span class="projects-fact-link-badge" title="${escapeHtml(tp('projects.linkCountsTitle'))}">↑${lc.outgoing || 0}${lc.incoming || 0}</span>`
: '<span class="projects-fact-link-badge projects-fact-link-badge--empty">—</span>';
return `<tr>
<td class="cell-fact-key"><code class="projects-fact-key-chip" title="${keyEsc}">${keyEsc}</code>${pinBadge}${vulnLink}</td>
<td class="cell-fact-category">${formatCategoryBadge(f.category)}</td>
<td class="cell-summary" title="${escapeHtml(f.summary)}">${escapeHtml(f.summary)}</td>
<td class="cell-fact-links">${linkBadge}</td>
<td>${formatFactBodyBadge(f)}</td>
<td>${formatConfidenceBadge(f.confidence)}</td>
<td>${formatProjectTime(f.updated_at, f.created_at)}</td>
@@ -849,6 +1117,7 @@ async function loadProjectConversations() {
<td class="col-actions">
<div class="projects-table-actions">
<button type="button" class="projects-action-btn projects-action-btn--view" data-conv-id="${idEsc}" onclick="openProjectConversation(this.dataset.convId)">${escapeHtml(tp('projects.open'))}</button>
<button type="button" class="projects-action-btn" data-conv-id="${idEsc}" onclick="promoteConversationAttackChain(this.dataset.convId)" title="${escapeHtml(tp('projects.promoteAttackChainTitle'))}">${escapeHtml(tp('projects.promoteAttackChain'))}</button>
<button type="button" class="projects-action-btn projects-action-btn--mute" data-conv-id="${idEsc}" onclick="unbindConversationFromProject(this.dataset.convId)" title="${escapeHtml(tp('projects.unbindProjectTitle'))}">${escapeHtml(tp('projects.unbind'))}</button>
</div>
</td>
@@ -869,6 +1138,32 @@ function openProjectConversation(conversationId) {
}, 200);
}
async function promoteConversationAttackChain(conversationId) {
if (!currentProjectId || !conversationId) return;
if (!confirm(tp('projects.confirmPromoteAttackChain'))) return;
const res = await apiFetch(
`/api/projects/${currentProjectId}/promote-attack-chain/${encodeURIComponent(conversationId)}`,
{ method: 'POST' },
);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
return alert(err.error || tp('projects.promoteAttackChainFailed'));
}
const data = await res.json();
if (typeof showNotification === 'function') {
showNotification(
tpFmt(
'projects.promoteAttackChainSuccess',
`已沉淀 ${data.facts_created || 0} 新 / ${data.facts_updated || 0} 更新 / ${data.edges_created || 0}`,
data,
),
'success',
);
}
loadProjectFacts();
if (currentProjectTab === 'graph') loadProjectFactGraph();
}
async function unbindConversationFromProject(conversationId) {
if (!conversationId || !confirm(tp('projects.confirmUnbindConversation'))) return;
const res = await apiFetch(`/api/conversations/${encodeURIComponent(conversationId)}/project`, {
@@ -1509,6 +1804,8 @@ function resetFactModalForm() {
if (pinEl) pinEl.checked = false;
const rel = document.getElementById('fact-modal-related-vuln');
if (rel) rel.value = '';
const linksEl = document.getElementById('fact-modal-links');
if (linksEl) linksEl.value = '';
updateFactFormHints();
}
@@ -1540,6 +1837,8 @@ function fillFactModalForm(f) {
}
const rel = document.getElementById('fact-modal-related-vuln');
if (rel) rel.value = f.related_vulnerability_id || '';
const linksEl = document.getElementById('fact-modal-links');
if (linksEl) linksEl.value = formatOutgoingLinksForModal(f.outgoing_links);
const pinEl = document.getElementById('fact-modal-pinned');
if (pinEl) pinEl.checked = !!f.pinned;
updateFactFormHints();
@@ -1556,7 +1855,7 @@ async function showEditFactModal(factKey) {
resetFactModalForm();
openProjectsOverlay('fact-modal', { focus: false });
const res = await apiFetch(
`/api/projects/${currentProjectId}/facts?fact_key=${encodeURIComponent(factKey)}`,
`/api/projects/${currentProjectId}/facts?fact_key=${encodeURIComponent(factKey)}&include_links=true`,
);
if (!res.ok) {
closeFactModal();
@@ -1594,6 +1893,7 @@ async function saveFactModal() {
confidence: document.getElementById('fact-modal-confidence').value,
pinned: !!document.getElementById('fact-modal-pinned')?.checked,
related_vulnerability_id: document.getElementById('fact-modal-related-vuln')?.value?.trim() || '',
links_text: document.getElementById('fact-modal-links')?.value || '',
};
const editId = window._factModalEditId;
const res = editId
@@ -1613,12 +1913,14 @@ async function saveFactModal() {
}
closeFactModal();
loadProjectFacts();
if (currentProjectTab === 'graph') loadProjectFactGraph();
}
async function deleteProjectFact(id) {
if (!confirm(tp('projects.confirmDeleteFact'))) return;
await apiFetch(`/api/projects/${currentProjectId}/facts/${id}`, { method: 'DELETE' });
loadProjectFacts();
if (currentProjectTab === 'graph') loadProjectFactGraph();
}
function parseProjectDate(t) {
@@ -1974,5 +2276,15 @@ window.viewFactsForVulnerability = viewFactsForVulnerability;
window.openProjectConversation = openProjectConversation;
window.unbindConversationFromProject = unbindConversationFromProject;
window.loadProjectConversations = loadProjectConversations;
window.loadProjectFactGraph = loadProjectFactGraph;
window.filterProjectFactGraph = filterProjectFactGraph;
window.centerProjectFactGraph = centerProjectFactGraph;
window.closeProjectFactGraphSidebar = closeProjectFactGraphSidebar;
window.openSelectedGraphFactDetail = openSelectedGraphFactDetail;
window.editSelectedGraphFact = editSelectedGraphFact;
window.promoteConversationAttackChain = promoteConversationAttackChain;
window.deleteProjectFactEdge = deleteProjectFactEdge;
window.focusProjectFactGraphEdge = focusProjectFactGraphEdge;
window.toggleProjectFactGraphConnectMode = toggleProjectFactGraphConnectMode;
window.rebuildProjectNameMap = rebuildProjectNameMap;
window.projectNameById = projectNameById;