Files
CyberStrikeAI/web/static/js/vulnerability-workspace.js
T

220 lines
14 KiB
JavaScript

// Vulnerability selection, review and evidence workspace.
let vulnerabilityWorkspaceRows = new Map();
let vulnerabilityWorkspaceSelected = new Set();
let vulnerabilityMergeCaseID = '';
let vulnerabilityMergeIDs = [];
let vulnerabilityMergeBusy = false;
let vulnerabilityInspectorID = '';
let vulnerabilityInspectorRequest = 0;
function setVulnerabilityWorkspaceRows(rows) {
vulnerabilityWorkspaceRows = new Map(rows.map(row => [row.id, row]));
vulnerabilityWorkspaceSelected = new Set(Array.from(vulnerabilityWorkspaceSelected).filter(id =>
vulnerabilityWorkspaceRows.has(id) && !vulnerabilityWorkspaceRows.get(id).case_id));
updateVulnerabilityWorkspaceSelection();
}
function vulnerabilitySelectionInput(vuln) {
return `<input class="vulnerability-select-record" type="checkbox"
data-select-vulnerability="${escapeAttr(vuln.id)}"
aria-label="${escapeAttr(vulnT('vulnerabilityPage.selectRecord', {title:vuln.title}))}"
${vuln.case_id ? 'disabled' : ''} ${vulnerabilityWorkspaceSelected.has(vuln.id) ? 'checked' : ''}
data-require-permission="vulnerability:write"
onclick="event.stopPropagation()" onchange="selectVulnerabilityRecord(this.dataset.selectVulnerability,this.checked)">`;
}
function selectVulnerabilityRecord(id, checked) {
if (checked) vulnerabilityWorkspaceSelected.add(id);
else vulnerabilityWorkspaceSelected.delete(id);
updateVulnerabilityWorkspaceSelection();
}
function updateVulnerabilityWorkspaceSelection() {
const button = document.getElementById('vulnerability-merge-selected');
if (!button) return;
const count = vulnerabilityWorkspaceSelected.size;
button.disabled = count < 2;
button.textContent = count
? vulnT('vulnerabilityPage.mergeCount', {count})
: vulnT('vulnerabilityPage.mergeSelected');
document.querySelectorAll('[data-select-vulnerability]').forEach(input => {
input.checked = vulnerabilityWorkspaceSelected.has(input.dataset.selectVulnerability);
});
}
function openVulnerabilityMergeDialog(caseID = '') {
if (vulnerabilityMergeBusy) return;
vulnerabilityMergeCaseID = caseID;
vulnerabilityMergeIDs = Array.from(vulnerabilityWorkspaceSelected);
if (!caseID && vulnerabilityMergeIDs.length < 2) return;
const rows = vulnerabilityMergeIDs.map(id => vulnerabilityWorkspaceRows.get(id));
document.getElementById('vulnerability-merge-title').textContent =
vulnT(caseID ? 'vulnerabilityPage.splitCase' : 'vulnerabilityPage.mergeSelected');
document.getElementById('vulnerability-merge-description').textContent =
vulnT(caseID ? 'vulnerabilityPage.splitHint' : 'vulnerabilityPage.mergeHint', {count:rows.length});
document.getElementById('vulnerability-merge-name-label').hidden = Boolean(caseID);
const name = document.getElementById('vulnerability-merge-name');
name.required = !caseID;
name.value = rows[0]?.title || '';
document.getElementById('vulnerability-merge-reason').value = '';
document.getElementById('vulnerability-merge-error').textContent = '';
openAppModal('vulnerability-merge-modal');
}
async function saveVulnerabilityMerge() {
if (vulnerabilityMergeBusy) return;
const title = document.getElementById('vulnerability-merge-name').value.trim();
const reason = document.getElementById('vulnerability-merge-reason').value.trim();
if (!reason || (!vulnerabilityMergeCaseID && !title)) return;
const button = document.getElementById('vulnerability-merge-save');
vulnerabilityMergeBusy = true;
button.disabled = true;
try {
const url = vulnerabilityMergeCaseID
? '/api/vulnerabilities/cases/' + encodeURIComponent(vulnerabilityMergeCaseID) + '/split'
: '/api/vulnerabilities/cases';
const response = await apiFetch(url, {
method:'POST', headers:{'Content-Type':'application/json'},
body:JSON.stringify({ids:vulnerabilityMergeIDs,title,reason})
});
const data = await response.json();
if (!response.ok) throw new Error(data.error || vulnT('vulnerabilityPage.saveFailed'));
vulnerabilityWorkspaceSelected.clear();
closeAppModal('vulnerability-merge-modal');
closeAppModal('vulnerability-inspector');
refreshVulnerabilities();
} catch(error) {
document.getElementById('vulnerability-merge-error').textContent = error.message;
} finally {
vulnerabilityMergeBusy = false;
button.disabled = false;
}
}
function switchVulnerabilityInspectorTab(tab) {
const root = document.getElementById('vulnerability-inspector-body');
root.querySelectorAll('[data-inspector-tab]').forEach(button => {
button.setAttribute('aria-pressed', String(button.dataset.inspectorTab === tab));
});
root.querySelectorAll('[data-inspector-panel]').forEach(panel => {
panel.hidden = panel.dataset.inspectorPanel !== tab;
});
}
async function openVulnerabilityInspector(id) {
vulnerabilityInspectorID = id;
const request = ++vulnerabilityInspectorRequest;
const title = document.getElementById('vulnerability-inspector-title');
const body = document.getElementById('vulnerability-inspector-body');
title.textContent = vulnerabilityWorkspaceRows.get(id)?.title || vulnT('vulnerabilityPage.inspectorTitle');
body.innerHTML = `<div class="loading-spinner">${escapeHtml(vulnT('vulnerabilityPage.loading'))}</div>`;
openAppModal('vulnerability-inspector');
document.querySelector('#vulnerability-inspector .modal-close').focus();
try {
const response = await apiFetch('/api/vulnerabilities/' + encodeURIComponent(id) + '/context');
if (!response.ok) throw new Error(vulnT('vulnerabilityPage.fetchFailed'));
const context = await response.json();
if (request !== vulnerabilityInspectorRequest) return;
const v = context.vulnerability;
title.textContent = v.title;
title.title = v.title;
const jsID = escapeJsStringAttr(v.id);
const targets = (v.targets || []).map(target => `
<li><div class="vulnerability-target-heading"><strong title="${escapeAttr(target.host)}">${escapeHtml(target.host)}</strong>
<button type="button" class="btn-ghost" data-target="${escapeAttr(target.raw)}" onclick="vulnerabilityCopyEncoded(event,encodeURIComponent(this.dataset.target))">${escapeHtml(vulnT('common.copy'))}</button></div>
<code tabindex="0" title="${escapeAttr(target.raw)}">${escapeHtml(target.raw)}</code>
</li>`).join('');
const history = (context.history || []).map(event => `
<li class="vulnerability-timeline-event">
<div><strong>${escapeHtml(vulnT('vulnerabilityPage.history_' + event.kind))}</strong>
<time>${escapeHtml(new Date(event.created_at).toLocaleString(vulnDateLocale()))}</time></div>
${event.status ? `<span class="severity-badge">${escapeHtml(vulnStatusLabel(event.status))}</span>` : ''}
<p>${escapeHtml(event.evidence || '')}</p>
${event.snapshot ? `<details class="vulnerability-evidence-snapshot"><summary>${escapeHtml(vulnT('vulnerabilityPage.retestSnapshot'))}</summary>
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailReproductionSteps'),event.snapshot.reproduction_steps)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailEvidence'),event.snapshot.evidence,{code:true})}</details>` : ''}
${event.conversation_id ? `<button type="button" class="btn-ghost" onclick="openVulnerabilityConversation(${escapeJsStringAttr(event.conversation_id)})">${escapeHtml(vulnT('vulnerabilityPage.openRetestChat'))}</button>` : ''}
</li>`).join('');
const members = (context.members || []).map(member => `
<button type="button" class="vulnerability-member-link" onclick="openVulnerabilityInspector(${escapeJsStringAttr(member.id)})">
<span>${escapeHtml(member.title)}</span><span>${escapeHtml(vulnStatusLabel(member.status))}</span>
</button>`).join('');
const assets = (context.assets || []).map(asset =>
`<li><strong>${escapeHtml(asset.host)}</strong><code>${escapeHtml(asset.id)}${asset.port ? ' · ' + asset.port : ''}</code></li>`).join('');
body.innerHTML = `
<div class="vulnerability-inspector-meta">
<span class="severity-badge severity-${escapeAttr(v.severity)}">${escapeHtml(vulnSeverityLabel(v.severity))}</span>
${buildVulnerabilityStatusPicker(v)}
<span>${escapeHtml(v.type || '')}</span>
<span>${escapeHtml(vulnT('vulnerabilityMd.labelCreated'))}: ${renderVulnerabilityTimestamp(v.created_at)}</span>
<span>${escapeHtml(vulnT('vulnerabilityMd.labelUpdated'))}: ${renderVulnerabilityTimestamp(v.updated_at)}</span>
</div>
<div class="vulnerability-inspector-actions">
<button class="btn-primary" data-require-permission="vulnerability:write" onclick="openVulnerabilityRetest(${jsID})" ${v.conversation_id ? '' : 'disabled'}>${escapeHtml(vulnT('vulnerabilityRetest.button'))}</button>
<button class="btn-secondary" data-require-permission="vulnerability:write" onclick="editVulnerability(${jsID})">${escapeHtml(vulnT('common.edit'))}</button>
<button class="btn-secondary" onclick="openVulnerabilityDownload(${jsID},event)">${escapeHtml(vulnT('vulnerabilityPage.tableDownload'))}</button>
<button class="btn-secondary btn-delete" data-require-permission="vulnerability:delete" onclick="deleteVulnerability(${jsID})">${escapeHtml(vulnT('common.delete'))}</button>
</div>
<div class="vulnerability-inspector-tabs" role="group">
${['overview','evidence','history'].map(tab => `<button type="button" data-inspector-tab="${tab}" aria-pressed="${tab==='overview'}" onclick="switchVulnerabilityInspectorTab('${tab}')">${escapeHtml(vulnT('vulnerabilityPage.inspector_' + tab))}</button>`).join('')}
</div>
<section data-inspector-panel="overview">
<p class="vulnerability-inspector-description">${escapeHtml(v.description || '')}</p>
${vulnDetailProjectField(v)}
${vulnDetailField(vulnT('vulnerabilityPage.detailVulnId'),v.id,true)}
${vulnDetailConversationField(v.conversation_id)}
${v.task_id ? vulnDetailField(vulnT('vulnerabilityPage.detailTaskId'),v.task_id,true) : ''}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailImpact'),v.impact)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRecommendation'),v.recommendation)}
<h3>${escapeHtml(vulnT('vulnerabilityPage.affectedTargets'))}</h3>
<ul class="vulnerability-target-list">${targets || '<li>'+escapeHtml(v.target || vulnT('vulnerabilityPage.unknownHost'))+'</li>'}</ul>
${assets ? `<h3>${escapeHtml(vulnT('vulnerabilityPage.linkedAssets'))}</h3><ul class="vulnerability-target-list">${assets}</ul>` : ''}
${members ? `<section class="vulnerability-case-members"><h3>${escapeHtml(v.case_title)}</h3>${members}
<button class="btn-secondary" data-require-permission="vulnerability:write" onclick="openVulnerabilityMergeDialog(${escapeJsStringAttr(v.case_id)})">${escapeHtml(vulnT('vulnerabilityPage.splitCase'))}</button></section>` : ''}
<div class="vulnerability-related-facts" id="vuln-related-facts-${escapeAttr(v.id)}" data-project-id="${escapeAttr(v.project_id || '')}" data-vuln-id="${escapeAttr(v.id)}" hidden></div>
</section>
<section data-inspector-panel="evidence" hidden>
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailPreconditions'),v.preconditions)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailReproductionSteps'),v.reproduction_steps)}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailEvidence'),v.evidence,{code:true})}
${vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestNotes'),v.retest_notes)}
</section>
<section data-inspector-panel="history" hidden>
<ol class="vulnerability-timeline">${history || '<li>'+escapeHtml(vulnT('vulnerabilityPage.noHistory'))+'</li>'}</ol>
${v.retest_log ? vulnNarrativeSection(vulnT('vulnerabilityPage.detailRetestLog'),v.retest_log,{code:true}) : ''}
</section>`;
initVulnerabilityStatusPickers(body);
initVulnerabilityProjectBindSelects(body);
if (typeof rbacAfterDynamicRender === 'function') rbacAfterDynamicRender(body);
loadVulnerabilityRelatedFacts(v.id).catch(console.warn);
} catch(error) {
if (request === vulnerabilityInspectorRequest) body.innerHTML = `<div class="error-message">${escapeHtml(error.message)}</div>`;
}
}
function refreshVulnerabilityInspector(id) {
if (vulnerabilityInspectorID === id && isAppModalOpen('vulnerability-inspector')) openVulnerabilityInspector(id);
}
['vulnerability-inspector','vulnerability-merge-modal'].forEach(id => {
const dialog = document.getElementById(id);
if (!dialog) return;
if (id === 'vulnerability-inspector') {
dialog.addEventListener('click', event => {
if (event.target === dialog) closeAppModal(id);
});
}
dialog.addEventListener('keydown', event => {
if (event.key === 'Escape' && !vulnerabilityMergeBusy) {
closeAppModal(id);
event.stopPropagation();
}
if (event.key !== 'Tab') return;
const controls = Array.from(dialog.querySelectorAll('button,input,textarea,select,[tabindex="0"]'))
.filter(el => !el.disabled && el.getClientRects().length);
const first = controls[0], last = controls[controls.length-1];
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); }
});
});