Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1523 lines
46 KiB
JavaScript
1523 lines
46 KiB
JavaScript
import { setLang, tr, LOC, resolveLang, currentLang } from './i18n.js';
|
||
|
||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||
const $ = (selector) => document.querySelector(selector);
|
||
const $$ = (selector) => document.querySelectorAll(selector);
|
||
|
||
// Admin token for the routes that change state. `harpia serve` prints a link
|
||
// with `?token=`; it is kept for this tab only and dropped from the address bar.
|
||
const TOKEN_KEY = 'harpia.adminToken';
|
||
{
|
||
const params = new URLSearchParams(location.search);
|
||
if (params.has('token')) {
|
||
sessionStorage.setItem(TOKEN_KEY, params.get('token'));
|
||
params.delete('token');
|
||
const query = params.toString();
|
||
history.replaceState(null, '', location.pathname + (query ? `?${query}` : '') + location.hash);
|
||
}
|
||
}
|
||
|
||
// fetch() for writes: sends the admin token and, on 401, asks for it once and retries.
|
||
async function adminFetch(url, options = {}) {
|
||
const send = () => fetch(url, {
|
||
...options,
|
||
headers: { ...options.headers, Authorization: `Bearer ${sessionStorage.getItem(TOKEN_KEY) || ''}` },
|
||
});
|
||
let res = await send();
|
||
if (res.status === 401) {
|
||
const token = window.prompt(t('Token de administração (exibido no log do harpia serve ou definido em HARPIA_ADMIN_TOKEN):'));
|
||
if (token && token.trim()) {
|
||
sessionStorage.setItem(TOKEN_KEY, token.trim());
|
||
res = await send();
|
||
}
|
||
}
|
||
return res;
|
||
}
|
||
|
||
// DOM Elements
|
||
const connection = $('#connection');
|
||
const connectionText = $('#connectionText');
|
||
const versionEl = $('#version');
|
||
const feedsStatusEl = $('#feedsStatus');
|
||
const refreshBtn = $('#refreshBtn');
|
||
const viewTitle = $('#viewTitle');
|
||
const viewSub = $('#viewSub');
|
||
const lastUpdated = $('#lastUpdated');
|
||
const settingsBtn = $('#settingsBtn');
|
||
const settingsDlg = $('#settingsDlg');
|
||
const closeSettings = $('#closeSettings');
|
||
const doneSettings = $('#doneSettings');
|
||
const langSel = $('#langSel');
|
||
const themePick = $('#themePick');
|
||
|
||
// KPIs
|
||
const kpiHosts = $('#kpiHosts');
|
||
const kpiHostsSub = $('#kpiHostsSub');
|
||
const kpiPorts = $('#kpiPorts');
|
||
const kpiPortsSub = $('#kpiPortsSub');
|
||
const kpiCritical = $('#kpiCritical');
|
||
const kpiCriticalSub = $('#kpiCriticalSub');
|
||
const kpiFeeds = $('#kpiFeeds');
|
||
const kpiFeedsSub = $('#kpiFeedsSub');
|
||
|
||
// Overview Charts & Priority
|
||
const severityChart = $('#severityChart');
|
||
const severityTip = $('#severityTip');
|
||
const hostExposureChart = $('#hostExposureChart');
|
||
const hostExposureTip = $('#hostExposureTip');
|
||
const overviewFindings = $('#overviewFindings');
|
||
const seeAllFindingsBtn = $('#seeAllFindings');
|
||
|
||
// Hosts View
|
||
const hostCount = $('#hostCount');
|
||
const hostSearch = $('#hostSearch');
|
||
const hostStatusFilters = $('#hostStatusFilters');
|
||
const hostRows = $('#hostRows');
|
||
|
||
// Findings View
|
||
const findingsCount = $('#findingsCount');
|
||
const severityFilters = $('#severityFilters');
|
||
const findingsSort = $('#findingsSort');
|
||
const findingsSearch = $('#findingsSearch');
|
||
const findingsList = $('#findingsList');
|
||
|
||
// Groups View
|
||
const groupsCount = $('#groupsCount');
|
||
const groupsGrid = $('#groupsGrid');
|
||
const feedsSummary = $('#feedsSummary');
|
||
const btnNewGroup = $('#btnNewGroup');
|
||
|
||
// Group Modal
|
||
const groupDlg = $('#groupDlg');
|
||
const groupForm = $('#groupForm');
|
||
const groupDlgTitle = $('#groupDlgTitle');
|
||
const closeGroupDlg = $('#closeGroupDlg');
|
||
const cancelGroupDlg = $('#cancelGroupDlg');
|
||
const groupFormError = $('#groupFormError');
|
||
const groupName = $('#groupName');
|
||
const groupTargets = $('#groupTargets');
|
||
const groupExclude = $('#groupExclude');
|
||
const groupCron = $('#groupCron');
|
||
const groupProfile = $('#groupProfile');
|
||
const groupCriticality = $('#groupCriticality');
|
||
|
||
// Changes View
|
||
const changesCount = $('#changesCount');
|
||
const changesPeriodFilters = $('#changesPeriodFilters');
|
||
const changesSearch = $('#changesSearch');
|
||
const changesTimeline = $('#changesTimeline');
|
||
const btnExportChangesCsv = $('#btnExportChangesCsv');
|
||
|
||
// Application State
|
||
const state = {
|
||
view: 'overview',
|
||
health: null,
|
||
status: null,
|
||
hosts: [],
|
||
changes: [],
|
||
config: null,
|
||
lastUpdated: null,
|
||
pollTimer: null,
|
||
expandedHosts: new Set(),
|
||
expandedFindings: new Set(),
|
||
filters: {
|
||
hostSearch: '',
|
||
hostStatus: 'all',
|
||
findingSeverity: 'all',
|
||
findingSort: 'cvss-desc',
|
||
findingSearch: '',
|
||
changesPeriod: '24h',
|
||
changesSearch: '',
|
||
},
|
||
};
|
||
|
||
let editingGroupName = null;
|
||
|
||
const VIEW_META = {
|
||
overview: {
|
||
title: 'Visão geral',
|
||
sub: 'Auditoria contínua de superfície de ataque e identificação de vulnerabilidades',
|
||
},
|
||
hosts: {
|
||
title: 'Hosts e Superfície',
|
||
sub: 'Ativos identificados no escopo autorizado e portas abertas observadas',
|
||
},
|
||
findings: {
|
||
title: 'Inventário de Vulnerabilidades',
|
||
sub: 'Correlação de versões com feeds NVD, checagens de configuração e CISA KEV',
|
||
},
|
||
groups: {
|
||
title: 'Grupos e Agendamento',
|
||
sub: 'Alvos configurados, perfis de portas e cadência contínua',
|
||
},
|
||
changes: {
|
||
title: 'Mudanças na Superfície',
|
||
sub: 'Linha do tempo de novas portas, hosts sumidos e alterações observadas',
|
||
},
|
||
};
|
||
|
||
// Utilities
|
||
function t(key) {
|
||
return tr(key);
|
||
}
|
||
|
||
function el(tag, className, text) {
|
||
const node = document.createElement(tag);
|
||
if (className) node.className = className;
|
||
if (text !== undefined && text !== null) node.textContent = text;
|
||
return node;
|
||
}
|
||
|
||
function svgEl(tag, attributes = {}, text) {
|
||
const node = document.createElementNS(SVG_NS, tag);
|
||
for (const [key, value] of Object.entries(attributes)) {
|
||
node.setAttribute(key, String(value));
|
||
}
|
||
if (text !== undefined && text !== null) node.textContent = text;
|
||
return node;
|
||
}
|
||
|
||
function formatInt(value) {
|
||
return new Intl.NumberFormat(LOC(), { maximumFractionDigits: 0 }).format(value);
|
||
}
|
||
|
||
function formatScore(score) {
|
||
if (score === null || score === undefined) return '—';
|
||
return Number(score).toFixed(1);
|
||
}
|
||
|
||
function cvssSeverity(cvss) {
|
||
if (cvss === null || cvss === undefined) return 'info';
|
||
const score = Number(cvss);
|
||
if (score >= 9.0) return 'critical';
|
||
if (score >= 7.0) return 'high';
|
||
if (score >= 4.0) return 'medium';
|
||
if (score > 0) return 'low';
|
||
return 'info';
|
||
}
|
||
|
||
function severityLabel(sev) {
|
||
switch (sev) {
|
||
case 'critical': return t('Crítico');
|
||
case 'high': return t('Alto');
|
||
case 'medium': return t('Médio');
|
||
case 'low': return t('Baixo');
|
||
default: return t('Informativo');
|
||
}
|
||
}
|
||
|
||
function timeAgo(dateString) {
|
||
if (!dateString) return '—';
|
||
const date = new Date(dateString);
|
||
const diffSec = Math.floor((Date.now() - date.getTime()) / 1000);
|
||
if (isNaN(diffSec) || diffSec < 0) return dateString;
|
||
if (diffSec < 60) return `${diffSec}s atrás`;
|
||
const diffMin = Math.floor(diffSec / 60);
|
||
if (diffMin < 60) return `${diffMin}min atrás`;
|
||
const diffH = Math.floor(diffMin / 60);
|
||
if (diffH < 24) return `${diffH}h atrás`;
|
||
const diffD = Math.floor(diffH / 24);
|
||
return `${diffD}d atrás`;
|
||
}
|
||
|
||
function timeUntil(dateString) {
|
||
if (!dateString) return '—';
|
||
const date = new Date(dateString);
|
||
const diffSec = Math.floor((date.getTime() - Date.now()) / 1000);
|
||
if (isNaN(diffSec)) return dateString;
|
||
if (diffSec <= 0) return t('executando agora…');
|
||
if (diffSec < 60) return `em ${diffSec}s`;
|
||
const diffMin = Math.floor(diffSec / 60);
|
||
if (diffMin < 60) return `em ${diffMin}min`;
|
||
const diffH = Math.floor(diffMin / 60);
|
||
return `em ${diffH}h`;
|
||
}
|
||
|
||
// Flat list of all findings across all hosts and ports
|
||
function getAllFindings() {
|
||
const list = [];
|
||
for (const host of state.hosts) {
|
||
for (const port of host.ports || []) {
|
||
for (const finding of port.findings || []) {
|
||
list.push({
|
||
...finding,
|
||
hostIp: host.ip,
|
||
hostNetwork: host.network,
|
||
port: port.port,
|
||
protocol: port.protocol,
|
||
product: port.product,
|
||
version: port.version,
|
||
cpe: port.cpe,
|
||
uid: `${host.ip}:${port.port}:${finding.id}`,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
return list;
|
||
}
|
||
|
||
// Data Fetching
|
||
async function fetchData() {
|
||
try {
|
||
const period = state.filters.changesPeriod || '24h';
|
||
const [healthRes, statusRes, hostsRes, changesRes, configRes] = await Promise.all([
|
||
fetch('/api/health').catch(() => null),
|
||
fetch('/api/status').catch(() => null),
|
||
fetch('/api/hosts').catch(() => null),
|
||
fetch(`/api/changes?since=${encodeURIComponent(period)}`).catch(() => null),
|
||
fetch('/api/config').catch(() => null),
|
||
]);
|
||
|
||
if (!healthRes || !statusRes || !hostsRes) {
|
||
throw new Error('Falha ao comunicar com a API do Harpia');
|
||
}
|
||
|
||
state.health = await healthRes.json();
|
||
state.status = await statusRes.json();
|
||
state.hosts = await hostsRes.json();
|
||
state.changes = changesRes && changesRes.ok ? await changesRes.json() : [];
|
||
state.config = configRes && configRes.ok ? await configRes.json() : null;
|
||
|
||
state.lastUpdated = new Date();
|
||
connection.classList.remove('offline');
|
||
connectionText.textContent = t('Conectado');
|
||
if (state.health && state.health.version) {
|
||
versionEl.textContent = `Harpia v${state.health.version}`;
|
||
$('#versionPill').textContent = `v${state.health.version}`;
|
||
}
|
||
if (state.status) {
|
||
feedsStatusEl.textContent = `${formatInt(state.status.feeds_cve_count || 0)} CVEs`;
|
||
}
|
||
lastUpdated.textContent = state.lastUpdated.toLocaleTimeString(LOC());
|
||
|
||
render();
|
||
} catch (err) {
|
||
console.error('fetchData error:', err);
|
||
connection.classList.add('offline');
|
||
connectionText.textContent = t('Desconectado');
|
||
}
|
||
}
|
||
|
||
// Navigation
|
||
function switchView(target) {
|
||
if (target === 'settings') {
|
||
openSettingsDialog();
|
||
return;
|
||
}
|
||
if (!VIEW_META[target]) return;
|
||
state.view = target;
|
||
|
||
$$('.nav-item').forEach((item) => {
|
||
const isActive = item.dataset.target === target;
|
||
item.classList.toggle('active', isActive);
|
||
if (isActive) item.setAttribute('aria-current', 'page');
|
||
else item.removeAttribute('aria-current');
|
||
});
|
||
|
||
$$('.view').forEach((view) => {
|
||
view.classList.toggle('active', view.id === target);
|
||
view.hidden = view.id !== target;
|
||
});
|
||
|
||
const meta = VIEW_META[target];
|
||
viewTitle.textContent = t(meta.title);
|
||
viewSub.textContent = t(meta.sub);
|
||
|
||
render();
|
||
}
|
||
|
||
// Master Render
|
||
function render() {
|
||
renderOverview();
|
||
renderHosts();
|
||
renderFindings();
|
||
renderGroups();
|
||
renderChanges();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ OVERVIEW
|
||
function renderOverview() {
|
||
const allFindings = getAllFindings();
|
||
const activeHosts = state.hosts.filter((h) => h.status === 'ativo');
|
||
let openPortsCount = 0;
|
||
for (const h of state.hosts) {
|
||
openPortsCount += (h.ports || []).filter((p) => p.status === 'aberta').length;
|
||
}
|
||
|
||
const criticalFindings = allFindings.filter((f) => cvssSeverity(f.cvss) === 'critical' || f.kev);
|
||
|
||
kpiHosts.textContent = formatInt(activeHosts.length);
|
||
kpiHostsSub.textContent = `${state.hosts.length} ${t('descobertos em escopo')}`;
|
||
|
||
kpiPorts.textContent = formatInt(openPortsCount);
|
||
kpiPortsSub.textContent = t('serviços expostos');
|
||
|
||
kpiCritical.textContent = formatInt(criticalFindings.length);
|
||
const kevCount = allFindings.filter((f) => f.kev).length;
|
||
kpiCriticalSub.textContent = `${kevCount} ${t('no KEV')}`;
|
||
|
||
const cveCount = state.status ? state.status.feeds_cve_count || 0 : 0;
|
||
const kevFeedsCount = state.status ? state.status.feeds_kev_count || 0 : 0;
|
||
kpiFeeds.textContent = formatInt(cveCount);
|
||
kpiFeedsSub.textContent = `${kevFeedsCount} ${t('no KEV')}`;
|
||
|
||
renderSeverityChart(allFindings);
|
||
renderHostExposureChart();
|
||
renderOverviewFindings(allFindings);
|
||
}
|
||
|
||
// 1. Severity Distribution SVG Chart
|
||
function renderSeverityChart(allFindings) {
|
||
const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0 };
|
||
for (const f of allFindings) {
|
||
const sev = cvssSeverity(f.cvss);
|
||
counts[sev] = (counts[sev] || 0) + 1;
|
||
}
|
||
|
||
const total = allFindings.length;
|
||
if (total === 0) {
|
||
severityChart.setAttribute('viewBox', '0 0 680 220');
|
||
chartEmpty(severityChart, t('Nenhum achado para exibir no gráfico.'));
|
||
return;
|
||
}
|
||
|
||
const width = 680;
|
||
const rowHeight = 36;
|
||
const top = 16;
|
||
const labelWidth = 120;
|
||
const rightPad = 48;
|
||
const plotWidth = width - labelWidth - rightPad;
|
||
const rows = [
|
||
{ key: 'critical', label: t('Crítico (9.0+)'), count: counts.critical, color: 'critical' },
|
||
{ key: 'high', label: t('Alto (7.0-8.9)'), count: counts.high, color: 'high' },
|
||
{ key: 'medium', label: t('Médio (4.0-6.9)'), count: counts.medium, color: 'medium' },
|
||
{ key: 'low', label: t('Baixo (0.1-3.9)'), count: counts.low, color: 'low' },
|
||
{ key: 'info', label: t('Informativo'), count: counts.info, color: 'info' },
|
||
];
|
||
|
||
const maxVal = Math.max(...rows.map((r) => r.count), 1);
|
||
const height = top + rows.length * rowHeight + 24;
|
||
severityChart.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
||
severityChart.replaceChildren();
|
||
|
||
// Grid Lines
|
||
const axis = svgEl('g', { class: 'axis' });
|
||
for (const tick of [0, 0.25, 0.5, 0.75, 1]) {
|
||
const x = labelWidth + plotWidth * tick;
|
||
axis.append(
|
||
svgEl('line', {
|
||
x1: x,
|
||
x2: x,
|
||
y1: top - 4,
|
||
y2: height - 22,
|
||
class: tick === 0 ? 'axis-line strong' : 'axis-line',
|
||
}),
|
||
);
|
||
}
|
||
severityChart.append(axis);
|
||
|
||
// Bars
|
||
rows.forEach((row, index) => {
|
||
const y = top + index * rowHeight;
|
||
const barWidth = Math.max(2, (row.count / maxVal) * plotWidth);
|
||
|
||
const group = svgEl('g', {
|
||
class: 'bar-row',
|
||
tabindex: '0',
|
||
role: 'button',
|
||
'aria-label': `${row.label}: ${row.count}`,
|
||
});
|
||
|
||
group.append(
|
||
svgEl(
|
||
'text',
|
||
{ x: labelWidth - 10, y: y + 16, 'text-anchor': 'end', class: 'bar-label' },
|
||
row.label,
|
||
),
|
||
);
|
||
|
||
group.append(
|
||
svgEl('rect', {
|
||
x: labelWidth,
|
||
y: y + 2,
|
||
width: plotWidth,
|
||
height: 18,
|
||
class: 'bar-track',
|
||
}),
|
||
);
|
||
|
||
if (row.count > 0) {
|
||
group.append(
|
||
svgEl('rect', {
|
||
x: labelWidth,
|
||
y: y + 2,
|
||
width: barWidth,
|
||
height: 18,
|
||
class: `bar-fill ${row.color}`,
|
||
}),
|
||
);
|
||
}
|
||
|
||
group.append(
|
||
svgEl(
|
||
'text',
|
||
{
|
||
x: labelWidth + (row.count > 0 ? barWidth + 8 : 8),
|
||
y: y + 16,
|
||
class: 'bar-value',
|
||
},
|
||
formatInt(row.count),
|
||
),
|
||
);
|
||
|
||
group.addEventListener('mousemove', (e) => {
|
||
const pct = total > 0 ? ((row.count / total) * 100).toFixed(1) : '0';
|
||
fillTip(severityTip, row.label, [
|
||
`${formatInt(row.count)} ${t('achados')}`,
|
||
`${pct}% do total de vulnerabilidades`,
|
||
'Clique para filtrar os achados',
|
||
]);
|
||
positionTip(severityTip, e, severityChart.parentElement);
|
||
severityTip.hidden = false;
|
||
});
|
||
|
||
group.addEventListener('mouseleave', () => {
|
||
severityTip.hidden = true;
|
||
});
|
||
|
||
group.addEventListener('click', () => {
|
||
state.filters.findingSeverity = row.key;
|
||
switchView('findings');
|
||
});
|
||
|
||
severityChart.append(group);
|
||
});
|
||
}
|
||
|
||
// 2. Top Exposed Hosts SVG Chart
|
||
function renderHostExposureChart() {
|
||
const hostScores = state.hosts.map((h) => {
|
||
let maxCvss = 0;
|
||
let count = 0;
|
||
let hasKev = false;
|
||
for (const p of h.ports || []) {
|
||
for (const f of p.findings || []) {
|
||
count += 1;
|
||
if (f.cvss && f.cvss > maxCvss) maxCvss = f.cvss;
|
||
if (f.kev) hasKev = true;
|
||
}
|
||
}
|
||
return {
|
||
ip: h.ip,
|
||
network: h.network,
|
||
maxCvss,
|
||
count,
|
||
hasKev,
|
||
};
|
||
});
|
||
|
||
hostScores.sort((a, b) => b.maxCvss - a.maxCvss || b.count - a.count);
|
||
const topHosts = hostScores.slice(0, 6);
|
||
|
||
if (topHosts.length === 0 || topHosts.every((h) => h.count === 0 && h.maxCvss === 0)) {
|
||
hostExposureChart.setAttribute('viewBox', '0 0 520 220');
|
||
chartEmpty(hostExposureChart, t('Nenhum host com achados para exibir.'));
|
||
return;
|
||
}
|
||
|
||
const width = 520;
|
||
const rowHeight = 36;
|
||
const top = 16;
|
||
const labelWidth = 110;
|
||
const rightPad = 46;
|
||
const plotWidth = width - labelWidth - rightPad;
|
||
const height = top + topHosts.length * rowHeight + 24;
|
||
hostExposureChart.setAttribute('viewBox', `0 0 ${width} ${height}`);
|
||
hostExposureChart.replaceChildren();
|
||
|
||
// Grid
|
||
const axis = svgEl('g', { class: 'axis' });
|
||
for (const tick of [0, 2.5, 5.0, 7.5, 10.0]) {
|
||
const x = labelWidth + (tick / 10.0) * plotWidth;
|
||
axis.append(
|
||
svgEl('line', {
|
||
x1: x,
|
||
x2: x,
|
||
y1: top - 4,
|
||
y2: height - 22,
|
||
class: tick === 0 ? 'axis-line strong' : 'axis-line',
|
||
}),
|
||
);
|
||
axis.append(
|
||
svgEl('text', { x, y: height - 8, 'text-anchor': 'middle', class: 'axis-label' }, tick.toFixed(1)),
|
||
);
|
||
}
|
||
hostExposureChart.append(axis);
|
||
|
||
topHosts.forEach((host, index) => {
|
||
const y = top + index * rowHeight;
|
||
const barWidth = Math.max(3, (host.maxCvss / 10.0) * plotWidth);
|
||
const sev = cvssSeverity(host.maxCvss);
|
||
|
||
const group = svgEl('g', {
|
||
class: 'bar-row',
|
||
tabindex: '0',
|
||
role: 'button',
|
||
'aria-label': `${host.ip}: Max CVSS ${host.maxCvss}`,
|
||
});
|
||
|
||
group.append(
|
||
svgEl('text', { x: labelWidth - 10, y: y + 16, 'text-anchor': 'end', class: 'bar-label mono' }, host.ip),
|
||
);
|
||
|
||
group.append(
|
||
svgEl('rect', {
|
||
x: labelWidth,
|
||
y: y + 2,
|
||
width: plotWidth,
|
||
height: 18,
|
||
class: 'bar-track',
|
||
}),
|
||
);
|
||
|
||
group.append(
|
||
svgEl('rect', {
|
||
x: labelWidth,
|
||
y: y + 2,
|
||
width: barWidth,
|
||
height: 18,
|
||
class: `bar-fill ${sev}`,
|
||
}),
|
||
);
|
||
|
||
group.append(
|
||
svgEl(
|
||
'text',
|
||
{
|
||
x: labelWidth + barWidth + 8,
|
||
y: y + 16,
|
||
class: 'bar-value',
|
||
},
|
||
host.maxCvss > 0 ? host.maxCvss.toFixed(1) : '—',
|
||
),
|
||
);
|
||
|
||
group.addEventListener('mousemove', (e) => {
|
||
fillTip(hostExposureTip, host.ip, [
|
||
`Grupo: ${host.network}`,
|
||
`Maior CVSS: ${host.maxCvss > 0 ? host.maxCvss.toFixed(1) : '—'} (${severityLabel(sev)})`,
|
||
`${formatInt(host.count)} vulnerabilidade(s) observada(s)`,
|
||
host.hasKev ? 'Contém vulnerabilidade no CISA KEV!' : '',
|
||
'Clique para abrir na tabela de hosts',
|
||
]);
|
||
positionTip(hostExposureTip, e, hostExposureChart.parentElement);
|
||
hostExposureTip.hidden = false;
|
||
});
|
||
|
||
group.addEventListener('mouseleave', () => {
|
||
hostExposureTip.hidden = true;
|
||
});
|
||
|
||
group.addEventListener('click', () => {
|
||
state.filters.hostSearch = host.ip;
|
||
state.expandedHosts.add(host.ip);
|
||
switchView('hosts');
|
||
});
|
||
|
||
hostExposureChart.append(group);
|
||
});
|
||
}
|
||
|
||
// 3. Priority Findings List
|
||
function renderOverviewFindings(allFindings) {
|
||
overviewFindings.replaceChildren();
|
||
if (allFindings.length === 0) {
|
||
overviewFindings.append(el('p', 'empty', t('Nenhum achado de vulnerabilidade registrado ainda.')));
|
||
return;
|
||
}
|
||
|
||
// Sort by KEV first, then highest CVSS
|
||
const sorted = [...allFindings].sort((a, b) => {
|
||
if (a.kev !== b.kev) return a.kev ? -1 : 1;
|
||
return (b.cvss || 0) - (a.cvss || 0);
|
||
});
|
||
|
||
const topItems = sorted.slice(0, 5);
|
||
topItems.forEach((finding) => {
|
||
const sev = cvssSeverity(finding.cvss);
|
||
const item = el('div', `ov-item ${sev}`);
|
||
item.tabIndex = 0;
|
||
item.role = 'button';
|
||
|
||
const left = el('div');
|
||
const badge = el('span', `sev-badge ${sev}`);
|
||
badge.textContent = `${formatScore(finding.cvss)} ${severityLabel(sev)}`;
|
||
left.append(badge);
|
||
if (finding.kev) {
|
||
const kb = el('span', 'kev-badge', t('KEV ATIVO'));
|
||
kb.style.marginLeft = '6px';
|
||
left.append(kb);
|
||
}
|
||
|
||
const mid = el('div');
|
||
const title = el('strong', '', finding.id);
|
||
const desc = el('p', 'hint', finding.title || finding.description || '');
|
||
desc.style.margin = '2px 0 0';
|
||
desc.style.whiteSpace = 'nowrap';
|
||
desc.style.overflow = 'hidden';
|
||
desc.style.textOverflow = 'ellipsis';
|
||
mid.append(title, desc);
|
||
|
||
const right = el('div', 'mono', `${finding.hostIp}:${finding.port}`);
|
||
|
||
item.append(left, mid, right);
|
||
item.addEventListener('click', () => {
|
||
state.filters.findingSearch = finding.id;
|
||
state.expandedFindings.add(finding.uid);
|
||
switchView('findings');
|
||
});
|
||
|
||
overviewFindings.append(item);
|
||
});
|
||
}
|
||
|
||
function chartEmpty(svg, text) {
|
||
const viewBox = svg.getAttribute('viewBox') || '0 0 680 220';
|
||
const [, , width, height] = viewBox.split(' ').map(Number);
|
||
svg.replaceChildren();
|
||
const label = svgEl(
|
||
'text',
|
||
{
|
||
x: width / 2,
|
||
y: height / 2,
|
||
'text-anchor': 'middle',
|
||
class: 'chart-empty',
|
||
},
|
||
text,
|
||
);
|
||
svg.append(label);
|
||
}
|
||
|
||
function positionTip(tip, event, container) {
|
||
const rect = container.getBoundingClientRect();
|
||
const width = tip.offsetWidth || 220;
|
||
const height = tip.offsetHeight || 90;
|
||
let x = event.clientX - rect.left + 14;
|
||
let y = event.clientY - rect.top + 14;
|
||
if (x + width + 12 > rect.width) x = Math.max(8, event.clientX - rect.left - width - 14);
|
||
if (y + height + 12 > rect.height) y = Math.max(8, event.clientY - rect.top - height - 14);
|
||
tip.style.left = `${x}px`;
|
||
tip.style.top = `${y}px`;
|
||
}
|
||
|
||
function fillTip(tip, title, lines) {
|
||
tip.replaceChildren();
|
||
tip.append(el('strong', '', title));
|
||
for (const line of lines) {
|
||
if (line) tip.append(el('span', '', line));
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ HOSTS VIEW
|
||
function renderHosts() {
|
||
const q = state.filters.hostSearch.trim().toLowerCase();
|
||
const statusFilter = state.filters.hostStatus;
|
||
|
||
const filtered = state.hosts.filter((h) => {
|
||
if (statusFilter === 'ativo' && h.status !== 'ativo') return false;
|
||
if (statusFilter === 'with-vulns') {
|
||
const hasVuln = (h.ports || []).some((p) => (p.findings || []).length > 0);
|
||
if (!hasVuln) return false;
|
||
}
|
||
if (!q) return true;
|
||
return (
|
||
h.ip.toLowerCase().includes(q) ||
|
||
h.network.toLowerCase().includes(q) ||
|
||
(h.ports || []).some(
|
||
(p) =>
|
||
String(p.port).includes(q) ||
|
||
(p.product && p.product.toLowerCase().includes(q)) ||
|
||
(p.version && p.version.toLowerCase().includes(q)),
|
||
)
|
||
);
|
||
});
|
||
|
||
hostCount.textContent = `${filtered.length} de ${state.hosts.length} hosts`;
|
||
hostRows.replaceChildren();
|
||
|
||
if (state.hosts.length === 0) {
|
||
const row = document.createElement('tr');
|
||
const cell = el('td', 'empty', t('Nenhum host carregado.'));
|
||
cell.colSpan = 8;
|
||
row.append(cell);
|
||
hostRows.append(row);
|
||
return;
|
||
}
|
||
|
||
if (filtered.length === 0) {
|
||
const row = document.createElement('tr');
|
||
const cell = el('td', 'empty', t('Nenhum host corresponde aos filtros.'));
|
||
cell.colSpan = 8;
|
||
row.append(cell);
|
||
hostRows.append(row);
|
||
return;
|
||
}
|
||
|
||
filtered.forEach((host, index) => {
|
||
const isExpanded = state.expandedHosts.has(host.ip);
|
||
const row = document.createElement('tr');
|
||
row.className = `host-row${isExpanded ? ' open' : ''}`;
|
||
row.tabIndex = 0;
|
||
|
||
let maxCvss = 0;
|
||
let totalFindings = 0;
|
||
const openPorts = [];
|
||
for (const p of host.ports || []) {
|
||
if (p.status === 'aberta') openPorts.push(p.port);
|
||
for (const f of p.findings || []) {
|
||
totalFindings += 1;
|
||
if (f.cvss && f.cvss > maxCvss) maxCvss = f.cvss;
|
||
}
|
||
}
|
||
|
||
const rankCell = el('td', 'rank', formatInt(index + 1));
|
||
const ipCell = el('td');
|
||
ipCell.append(el('strong', 'mono host-name', host.ip));
|
||
|
||
const groupCell = el('td', '', host.network);
|
||
|
||
const statusCell = el('td');
|
||
const statusWrap = el(
|
||
'span',
|
||
`status-indicator ${host.status === 'ativo' ? 'active' : 'gone'}`,
|
||
);
|
||
statusWrap.append(el('span', 'sdot'), el('span', '', t(host.status)));
|
||
statusCell.append(statusWrap);
|
||
|
||
const portsCell = el('td');
|
||
if (openPorts.length > 0) {
|
||
const badges = openPorts.slice(0, 4).map((p) => el('span', 'tag-badge', `TCP/${p}`));
|
||
if (openPorts.length > 4) {
|
||
badges.push(el('span', 'mono', `+${openPorts.length - 4}`));
|
||
}
|
||
badges.forEach((b) => {
|
||
b.style.marginRight = '4px';
|
||
portsCell.append(b);
|
||
});
|
||
} else {
|
||
portsCell.textContent = '—';
|
||
}
|
||
|
||
const maxCvssCell = el('td');
|
||
if (maxCvss > 0) {
|
||
const sev = cvssSeverity(maxCvss);
|
||
const cvssBadge = el('span', `sev-badge ${sev}`, `${maxCvss.toFixed(1)} ${severityLabel(sev)}`);
|
||
maxCvssCell.append(cvssBadge);
|
||
} else {
|
||
maxCvssCell.textContent = '—';
|
||
}
|
||
|
||
const findingsCell = el('td', 'mono', formatInt(totalFindings));
|
||
const chevronCell = el('td', 'chevron-cell', isExpanded ? '⌄' : '›');
|
||
|
||
row.append(
|
||
rankCell,
|
||
ipCell,
|
||
groupCell,
|
||
statusCell,
|
||
portsCell,
|
||
maxCvssCell,
|
||
findingsCell,
|
||
chevronCell,
|
||
);
|
||
|
||
row.addEventListener('click', () => {
|
||
toggleHostExpansion(host.ip);
|
||
});
|
||
|
||
hostRows.append(row);
|
||
|
||
if (isExpanded) {
|
||
const detailRow = document.createElement('tr');
|
||
detailRow.className = 'host-detail-row';
|
||
const cell = document.createElement('td');
|
||
cell.colSpan = 8;
|
||
cell.append(renderHostDetail(host));
|
||
detailRow.append(cell);
|
||
hostRows.append(detailRow);
|
||
}
|
||
});
|
||
}
|
||
|
||
function toggleHostExpansion(ip) {
|
||
if (state.expandedHosts.has(ip)) state.expandedHosts.delete(ip);
|
||
else state.expandedHosts.add(ip);
|
||
renderHosts();
|
||
}
|
||
|
||
function renderHostDetail(host) {
|
||
const wrap = el('div', 'host-detail-wrap');
|
||
const portsGrid = el('div', 'ports-grid');
|
||
|
||
if (!host.ports || host.ports.length === 0) {
|
||
wrap.append(el('p', 'empty', t('Sem portas abertas detectadas.')));
|
||
return wrap;
|
||
}
|
||
|
||
host.ports.forEach((port) => {
|
||
const card = el('div', 'port-card');
|
||
const head = el('div', 'port-card-head');
|
||
head.append(
|
||
el('span', 'port-num', `${port.protocol.toUpperCase()}/${port.port}`),
|
||
el('span', `sev-badge ${port.status === 'aberta' ? 'low' : 'info'}`, t(port.status)),
|
||
);
|
||
card.append(head);
|
||
|
||
if (port.product || port.version) {
|
||
const prodText = `${port.product || 'Serviço desconhecido'} ${port.version || ''}`.trim();
|
||
card.append(el('div', 'port-product', prodText));
|
||
}
|
||
|
||
if (port.cpe) {
|
||
card.append(el('div', 'cpe-block', port.cpe));
|
||
}
|
||
|
||
const findingsList = el('div', 'port-findings-list');
|
||
const portFindings = port.findings || [];
|
||
if (portFindings.length > 0) {
|
||
card.append(el('strong', 'hint', `${portFindings.length} vulnerabilidade(s) nesta porta:`));
|
||
portFindings.slice(0, 8).forEach((f) => {
|
||
const item = el('div', 'port-finding-mini');
|
||
const left = el('span');
|
||
const sev = cvssSeverity(f.cvss);
|
||
left.append(el('strong', '', f.id), el('span', 'dim', ` · ${f.title || ''}`));
|
||
|
||
const right = el('span');
|
||
const badge = el('span', `sev-badge ${sev}`, formatScore(f.cvss));
|
||
right.append(badge);
|
||
if (f.kev) {
|
||
const kb = el('span', 'kev-badge', 'KEV');
|
||
kb.style.marginLeft = '4px';
|
||
right.append(kb);
|
||
}
|
||
|
||
item.append(left, right);
|
||
findingsList.append(item);
|
||
});
|
||
if (portFindings.length > 8) {
|
||
const more = el('button', 'btn small', `+${portFindings.length - 8} achados adicionais...`);
|
||
more.type = 'button';
|
||
more.addEventListener('click', () => {
|
||
state.filters.findingSearch = host.ip;
|
||
switchView('findings');
|
||
});
|
||
findingsList.append(more);
|
||
}
|
||
} else {
|
||
findingsList.append(el('p', 'hint', t('Sem achados nesta porta.')));
|
||
}
|
||
card.append(findingsList);
|
||
portsGrid.append(card);
|
||
});
|
||
|
||
wrap.append(portsGrid);
|
||
return wrap;
|
||
}
|
||
|
||
// ------------------------------------------------------------------ FINDINGS VIEW
|
||
function renderFindings() {
|
||
const allFindings = getAllFindings();
|
||
const q = state.filters.findingSearch.trim().toLowerCase();
|
||
const sevFilter = state.filters.findingSeverity;
|
||
const sort = state.filters.findingSort;
|
||
|
||
const filtered = allFindings.filter((f) => {
|
||
if (sevFilter === 'kev' && !f.kev) return false;
|
||
if (sevFilter !== 'all' && sevFilter !== 'kev') {
|
||
if (cvssSeverity(f.cvss) !== sevFilter) return false;
|
||
}
|
||
if (!q) return true;
|
||
return (
|
||
f.id.toLowerCase().includes(q) ||
|
||
(f.title && f.title.toLowerCase().includes(q)) ||
|
||
(f.description && f.description.toLowerCase().includes(q)) ||
|
||
f.hostIp.toLowerCase().includes(q) ||
|
||
(f.product && f.product.toLowerCase().includes(q))
|
||
);
|
||
});
|
||
|
||
// Sorting
|
||
filtered.sort((a, b) => {
|
||
if (sort === 'cvss-desc') return (b.cvss || 0) - (a.cvss || 0);
|
||
if (sort === 'cvss-asc') return (a.cvss || 0) - (b.cvss || 0);
|
||
if (sort === 'kev-first') {
|
||
if (a.kev !== b.kev) return a.kev ? -1 : 1;
|
||
return (b.cvss || 0) - (a.cvss || 0);
|
||
}
|
||
if (sort === 'id-asc') return a.id.localeCompare(b.id);
|
||
return 0;
|
||
});
|
||
|
||
findingsCount.textContent = `${filtered.length} de ${allFindings.length} achados`;
|
||
findingsList.replaceChildren();
|
||
|
||
if (filtered.length === 0) {
|
||
findingsList.append(
|
||
el('p', 'empty', t('Nenhum achado encontrado para os filtros selecionados.')),
|
||
);
|
||
return;
|
||
}
|
||
|
||
filtered.forEach((finding) => {
|
||
const isExpanded = state.expandedFindings.has(finding.uid);
|
||
const sev = cvssSeverity(finding.cvss);
|
||
const card = el('div', `alert-card ${sev}`);
|
||
|
||
const head = el('button', 'alert-head');
|
||
head.type = 'button';
|
||
head.setAttribute('aria-expanded', isExpanded ? 'true' : 'false');
|
||
|
||
const badge = el('span', `sev-badge ${sev}`, `${formatScore(finding.cvss)} ${severityLabel(sev)}`);
|
||
|
||
const main = el('div', 'alert-main');
|
||
const title = el('div', 'alert-title', `${finding.id}: ${finding.title || finding.description || ''}`);
|
||
const meta = el('div', 'alert-meta');
|
||
meta.append(
|
||
el('span', 'alert-target', `${finding.hostIp}:${finding.port}`),
|
||
el('span', 'dim', '·'),
|
||
el('span', '', `${finding.product || 'Serviço'} ${finding.version || ''}`.trim()),
|
||
);
|
||
if (finding.kev) {
|
||
meta.append(el('span', 'kev-badge', t('KEV ATIVO')));
|
||
}
|
||
if (finding.confianca) {
|
||
meta.append(el('span', 'conf-badge', finding.confianca.toUpperCase()));
|
||
}
|
||
main.append(title, meta);
|
||
|
||
const right = el('div', 'mono', `${finding.protocol.toUpperCase()}/${finding.port}`);
|
||
const chevron = el('div', 'chevron', isExpanded ? '⌄' : '›');
|
||
|
||
head.append(badge, main, right, chevron);
|
||
head.addEventListener('click', () => {
|
||
toggleFindingExpansion(finding.uid);
|
||
});
|
||
card.append(head);
|
||
|
||
if (isExpanded) {
|
||
const body = el('div', 'alert-body');
|
||
|
||
if (finding.description) {
|
||
body.append(el('p', '', finding.description));
|
||
}
|
||
|
||
// Metrics grid
|
||
const metrics = el('div', 'metrics');
|
||
const addMetric = (label, val) => {
|
||
if (!val) return;
|
||
const m = el('div', 'metric');
|
||
m.append(el('span', 'metric-label', label), el('span', 'metric-value', val));
|
||
metrics.append(m);
|
||
};
|
||
addMetric('Score CVSS', formatScore(finding.cvss));
|
||
addMetric('Host Alvo', finding.hostIp);
|
||
addMetric('Porta', `${finding.protocol.toUpperCase()}/${finding.port}`);
|
||
addMetric('Produto', finding.product);
|
||
addMetric('Versão', finding.version);
|
||
addMetric('Confiança', finding.confianca);
|
||
addMetric('Catálogo KEV', finding.kev ? 'Sim (Ativamente explorado)' : 'Não');
|
||
body.append(metrics);
|
||
|
||
if (finding.cpe) {
|
||
const cpeBox = el('div');
|
||
cpeBox.append(el('span', 'metric-label', 'CPE Normalizado: '));
|
||
cpeBox.append(el('span', 'cpe-block', finding.cpe));
|
||
body.append(cpeBox);
|
||
}
|
||
|
||
// Evidência Determinística
|
||
if (finding.evidencia && typeof finding.evidencia === 'object') {
|
||
const evHead = el('div', 'evidence-head');
|
||
evHead.append(el('h3', '', t('Evidência determinística')));
|
||
body.append(evHead);
|
||
|
||
const table = el('table', 'kv');
|
||
for (const [k, v] of Object.entries(finding.evidencia)) {
|
||
const tr = document.createElement('tr');
|
||
const th = el('th', '', k);
|
||
const td = el('td', '', typeof v === 'object' ? JSON.stringify(v) : String(v));
|
||
tr.append(th, td);
|
||
table.append(tr);
|
||
}
|
||
body.append(table);
|
||
}
|
||
|
||
card.append(body);
|
||
}
|
||
|
||
findingsList.append(card);
|
||
});
|
||
}
|
||
|
||
function toggleFindingExpansion(uid) {
|
||
if (state.expandedFindings.has(uid)) state.expandedFindings.delete(uid);
|
||
else state.expandedFindings.add(uid);
|
||
renderFindings();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ GROUPS VIEW
|
||
function renderGroups() {
|
||
groupsGrid.replaceChildren();
|
||
feedsSummary.replaceChildren();
|
||
|
||
const groups = state.status ? state.status.groups || [] : [];
|
||
groupsCount.textContent = `${groups.length} ${t('grupos configurados')}`;
|
||
|
||
if (groups.length === 0) {
|
||
groupsGrid.append(el('p', 'empty', t('Nenhum grupo configurado.')));
|
||
} else {
|
||
groups.forEach((g) => {
|
||
const card = el('div', 'group-card');
|
||
const head = el('div', 'group-card-head');
|
||
head.append(
|
||
el('span', 'group-name', g.group),
|
||
el('span', 'cron-tag', g.cron),
|
||
);
|
||
|
||
const configGroup = state.config && state.config.grupo
|
||
? state.config.grupo.find((cg) => cg.nome === g.group)
|
||
: null;
|
||
|
||
if (configGroup && configGroup.criticidade) {
|
||
head.append(el('span', 'group-card-badge', configGroup.criticidade));
|
||
}
|
||
card.append(head);
|
||
|
||
if (configGroup && configGroup.alvos && configGroup.alvos.length > 0) {
|
||
const targetsDiv = el('div', 'group-card-targets');
|
||
targetsDiv.textContent = configGroup.alvos.join(', ');
|
||
card.append(targetsDiv);
|
||
}
|
||
|
||
const details = el('div', 'hint');
|
||
details.append(
|
||
el('span', '', `${t('Perfil:')} `),
|
||
el('strong', 'tag-badge', g.profile),
|
||
);
|
||
card.append(details);
|
||
|
||
const next = el('div', 'group-next');
|
||
next.append(
|
||
el('span', '', t('Próxima execução:')),
|
||
el('strong', '', `${timeUntil(g.next_run)} (${g.next_run ? new Date(g.next_run).toLocaleTimeString(LOC()) : '—'})`),
|
||
);
|
||
card.append(next);
|
||
|
||
// Actions row
|
||
const actions = el('div', 'group-card-actions');
|
||
const editBtn = el('button', 'btn secondary small', t('Editar'));
|
||
editBtn.type = 'button';
|
||
editBtn.addEventListener('click', () => openEditGroupDialog(g.group));
|
||
|
||
const removeBtn = el('button', 'btn danger small', t('Remover'));
|
||
removeBtn.type = 'button';
|
||
removeBtn.addEventListener('click', () => deleteGroup(g.group));
|
||
|
||
actions.append(editBtn, removeBtn);
|
||
card.append(actions);
|
||
|
||
groupsGrid.append(card);
|
||
});
|
||
}
|
||
|
||
// Feeds summary
|
||
if (state.status) {
|
||
const tiles = [
|
||
{ label: t('Total de CVEs'), val: formatInt(state.status.feeds_cve_count || 0) },
|
||
{ label: t('Total no KEV'), val: formatInt(state.status.feeds_kev_count || 0) },
|
||
{ label: t('Lotes ingeridos'), val: formatInt(state.status.sweeps_ingested || 0) },
|
||
{
|
||
label: t('Último Sync'),
|
||
val: state.status.feeds_last_sync
|
||
? `${timeAgo(state.status.feeds_last_sync)} (${new Date(state.status.feeds_last_sync).toLocaleTimeString(LOC())})`
|
||
: t('não executado'),
|
||
},
|
||
];
|
||
tiles.forEach((item) => {
|
||
const tile = el('div', 'summary-tile');
|
||
tile.append(el('span', 'summary-label', item.label), el('strong', 'summary-value', item.val));
|
||
feedsSummary.append(tile);
|
||
});
|
||
}
|
||
}
|
||
|
||
function populateProfilesDropdown() {
|
||
groupProfile.replaceChildren();
|
||
const profiles = state.config && state.config.perfis ? Object.keys(state.config.perfis) : ['padrao'];
|
||
if (!profiles.includes('padrao')) {
|
||
profiles.unshift('padrao');
|
||
}
|
||
profiles.forEach((p) => {
|
||
const opt = document.createElement('option');
|
||
opt.value = p;
|
||
opt.textContent = p;
|
||
groupProfile.append(opt);
|
||
});
|
||
}
|
||
|
||
function openCreateGroupDialog() {
|
||
editingGroupName = null;
|
||
groupDlgTitle.textContent = t('Novo Grupo');
|
||
groupFormError.hidden = true;
|
||
groupFormError.textContent = '';
|
||
groupName.value = '';
|
||
groupName.disabled = false;
|
||
groupTargets.value = '';
|
||
groupExclude.value = '';
|
||
groupCron.value = '';
|
||
populateProfilesDropdown();
|
||
groupProfile.value = 'padrao';
|
||
groupCriticality.value = '';
|
||
groupDlg.showModal();
|
||
}
|
||
|
||
function openEditGroupDialog(name) {
|
||
const group = state.config && state.config.grupo
|
||
? state.config.grupo.find((g) => g.nome === name)
|
||
: null;
|
||
if (!group) return;
|
||
|
||
editingGroupName = name;
|
||
groupDlgTitle.textContent = `${t('Editar Grupo')}: ${name}`;
|
||
groupFormError.hidden = true;
|
||
groupFormError.textContent = '';
|
||
groupName.value = group.nome || '';
|
||
groupName.disabled = false;
|
||
groupTargets.value = (group.alvos || []).join('\n');
|
||
groupExclude.value = (group.excluir || []).join('\n');
|
||
groupCron.value = group.cron || '';
|
||
populateProfilesDropdown();
|
||
groupProfile.value = group.perfil || 'padrao';
|
||
groupCriticality.value = group.criticidade || '';
|
||
groupDlg.showModal();
|
||
}
|
||
|
||
async function handleGroupFormSubmit(e) {
|
||
e.preventDefault();
|
||
groupFormError.hidden = true;
|
||
groupFormError.textContent = '';
|
||
|
||
const name = groupName.value.trim();
|
||
if (!name) {
|
||
groupFormError.hidden = false;
|
||
groupFormError.textContent = t('Nome do grupo é obrigatório.');
|
||
return;
|
||
}
|
||
|
||
const targets = groupTargets.value
|
||
.split(/[\n,]+/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean);
|
||
|
||
if (targets.length === 0) {
|
||
groupFormError.hidden = false;
|
||
groupFormError.textContent = t('Pelo menos um alvo autorizado é obrigatório.');
|
||
return;
|
||
}
|
||
|
||
const exclude = groupExclude.value
|
||
.split(/[\n,]+/)
|
||
.map((s) => s.trim())
|
||
.filter(Boolean);
|
||
|
||
const payload = {
|
||
nome: name,
|
||
alvos: targets,
|
||
};
|
||
if (exclude.length > 0) payload.excluir = exclude;
|
||
if (groupCron.value.trim()) payload.cron = groupCron.value.trim();
|
||
if (groupProfile.value) payload.perfil = groupProfile.value;
|
||
if (groupCriticality.value) payload.criticidade = groupCriticality.value;
|
||
|
||
try {
|
||
let res;
|
||
if (editingGroupName) {
|
||
res = await adminFetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
||
method: 'PUT',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
} else {
|
||
res = await adminFetch('/api/config/groups', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
}
|
||
|
||
if (!res.ok) {
|
||
const errText = await res.text();
|
||
groupFormError.hidden = false;
|
||
groupFormError.textContent = errText || t('Erro ao salvar grupo');
|
||
return;
|
||
}
|
||
|
||
groupDlg.close();
|
||
await fetchData();
|
||
} catch (err) {
|
||
groupFormError.hidden = false;
|
||
groupFormError.textContent = err.message || t('Erro de rede ao salvar grupo');
|
||
}
|
||
}
|
||
|
||
async function deleteGroup(name) {
|
||
const confirmed = window.confirm(
|
||
`${t('Tem certeza que deseja remover o grupo')} "${name}"?`
|
||
);
|
||
if (!confirmed) return;
|
||
|
||
try {
|
||
const res = await adminFetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
||
method: 'DELETE',
|
||
});
|
||
if (!res.ok) {
|
||
const errText = await res.text();
|
||
alert(errText || t('Erro ao remover grupo'));
|
||
return;
|
||
}
|
||
await fetchData();
|
||
} catch (err) {
|
||
alert(err.message || t('Erro de rede ao remover grupo'));
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ CHANGES VIEW
|
||
function renderChanges() {
|
||
changesTimeline.replaceChildren();
|
||
const q = state.filters.changesSearch.trim().toLowerCase();
|
||
|
||
const filtered = state.changes.filter((c) => {
|
||
if (!q) return true;
|
||
return (
|
||
(c.asset_key && c.asset_key.toLowerCase().includes(q)) ||
|
||
(c.kind && c.kind.toLowerCase().includes(q)) ||
|
||
(c.group && c.group.toLowerCase().includes(q))
|
||
);
|
||
});
|
||
|
||
changesCount.textContent = `${filtered.length} ${t('eventos')}`;
|
||
|
||
if (filtered.length === 0) {
|
||
changesTimeline.append(
|
||
el('p', 'empty', t('Nenhum evento registrado no período selecionado.')),
|
||
);
|
||
return;
|
||
}
|
||
|
||
filtered.forEach((event) => {
|
||
const item = el('div', 'timeline-item');
|
||
const kind = event.kind || 'default';
|
||
|
||
const dot = el('div', `timeline-dot ${kind}`);
|
||
dot.textContent = eventKindSymbol(kind);
|
||
|
||
const info = el('div', 'timeline-info');
|
||
info.append(
|
||
el('div', 'timeline-title', eventKindLabel(kind)),
|
||
el('div', 'timeline-sub', `${event.asset_key || ''} · grupo ${event.group || ''}`),
|
||
);
|
||
|
||
const time = el('div', 'timeline-time', timeAgo(event.occurred_at));
|
||
|
||
item.append(dot, info, time);
|
||
changesTimeline.append(item);
|
||
});
|
||
}
|
||
|
||
function eventKindSymbol(kind) {
|
||
switch (kind) {
|
||
case 'host_new': return '+';
|
||
case 'port_opened': return '▲';
|
||
case 'service_changed': return '⟳';
|
||
case 'port_closed': return '▼';
|
||
case 'host_gone': return '×';
|
||
default: return '•';
|
||
}
|
||
}
|
||
|
||
function eventKindLabel(kind) {
|
||
switch (kind) {
|
||
case 'host_new': return t('Novo host descoberto');
|
||
case 'host_gone': return t('Host ausente/sumido');
|
||
case 'host_returned': return t('Host retornado');
|
||
case 'port_opened': return t('Nova porta aberta');
|
||
case 'port_closed': return t('Porta fechada');
|
||
case 'service_changed': return t('Serviço alterado');
|
||
default: return kind;
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ SETTINGS & THEME
|
||
function initSettings() {
|
||
const savedLang = localStorage.getItem('harpia-lang') || 'auto';
|
||
langSel.value = savedLang;
|
||
setLang(resolveLang(savedLang));
|
||
|
||
const savedTheme = localStorage.getItem('harpia-theme') || 'auto';
|
||
applyTheme(savedTheme);
|
||
|
||
langSel.addEventListener('change', () => {
|
||
const val = langSel.value;
|
||
localStorage.setItem('harpia-lang', val);
|
||
setLang(resolveLang(val));
|
||
render();
|
||
});
|
||
|
||
themePick.querySelectorAll('button').forEach((btn) => {
|
||
btn.addEventListener('click', () => {
|
||
const mode = btn.dataset.themePick;
|
||
localStorage.setItem('harpia-theme', mode);
|
||
applyTheme(mode);
|
||
});
|
||
});
|
||
|
||
settingsBtn.addEventListener('click', openSettingsDialog);
|
||
closeSettings.addEventListener('click', () => settingsDlg.close());
|
||
doneSettings.addEventListener('click', () => settingsDlg.close());
|
||
|
||
// Listen to language change to trigger re-render
|
||
document.addEventListener('harpia:lang', () => {
|
||
render();
|
||
});
|
||
}
|
||
|
||
function applyTheme(mode) {
|
||
themePick.querySelectorAll('button').forEach((b) => {
|
||
b.classList.toggle('active', b.dataset.themePick === mode);
|
||
});
|
||
if (mode === 'light') {
|
||
document.documentElement.setAttribute('data-theme', 'light');
|
||
} else if (mode === 'dark') {
|
||
document.documentElement.removeAttribute('data-theme');
|
||
} else {
|
||
// Auto
|
||
const prefersLight = window.matchMedia('(prefers-color-scheme: light)').matches;
|
||
if (prefersLight) document.documentElement.setAttribute('data-theme', 'light');
|
||
else document.documentElement.removeAttribute('data-theme');
|
||
}
|
||
}
|
||
|
||
function openSettingsDialog() {
|
||
settingsDlg.showModal();
|
||
}
|
||
|
||
// ------------------------------------------------------------------ EVENT LISTENERS
|
||
function initEvents() {
|
||
// Navigation
|
||
$$('.nav-item').forEach((item) => {
|
||
item.addEventListener('click', () => {
|
||
switchView(item.dataset.target);
|
||
});
|
||
});
|
||
|
||
// Topbar refresh
|
||
refreshBtn.addEventListener('click', () => {
|
||
refreshBtn.disabled = true;
|
||
fetchData().finally(() => {
|
||
refreshBtn.disabled = false;
|
||
});
|
||
});
|
||
|
||
seeAllFindingsBtn.addEventListener('click', () => {
|
||
state.filters.findingSeverity = 'all';
|
||
switchView('findings');
|
||
});
|
||
|
||
// Hosts View Filters
|
||
hostSearch.addEventListener('input', (e) => {
|
||
state.filters.hostSearch = e.target.value;
|
||
renderHosts();
|
||
});
|
||
|
||
hostStatusFilters.querySelectorAll('button').forEach((btn) => {
|
||
btn.addEventListener('click', () => {
|
||
hostStatusFilters.querySelectorAll('button').forEach((b) => b.classList.remove('active'));
|
||
btn.classList.add('active');
|
||
state.filters.hostStatus = btn.dataset.status;
|
||
renderHosts();
|
||
});
|
||
});
|
||
|
||
// Findings View Filters
|
||
findingsSearch.addEventListener('input', (e) => {
|
||
state.filters.findingSearch = e.target.value;
|
||
renderFindings();
|
||
});
|
||
|
||
findingsSort.addEventListener('change', (e) => {
|
||
state.filters.findingSort = e.target.value;
|
||
renderFindings();
|
||
});
|
||
|
||
severityFilters.querySelectorAll('button').forEach((btn) => {
|
||
btn.addEventListener('click', () => {
|
||
severityFilters.querySelectorAll('button').forEach((b) => b.classList.remove('active'));
|
||
btn.classList.add('active');
|
||
state.filters.findingSeverity = btn.dataset.severity;
|
||
renderFindings();
|
||
});
|
||
});
|
||
|
||
// Changes View Filters
|
||
changesSearch.addEventListener('input', (e) => {
|
||
state.filters.changesSearch = e.target.value;
|
||
renderChanges();
|
||
});
|
||
|
||
changesPeriodFilters.querySelectorAll('button').forEach((btn) => {
|
||
btn.addEventListener('click', () => {
|
||
changesPeriodFilters.querySelectorAll('button').forEach((b) => b.classList.remove('active'));
|
||
btn.classList.add('active');
|
||
state.filters.changesPeriod = btn.dataset.period;
|
||
if (btnExportChangesCsv) {
|
||
btnExportChangesCsv.href = `/api/export/changes.csv?since=${encodeURIComponent(btn.dataset.period)}`;
|
||
}
|
||
fetchData();
|
||
});
|
||
});
|
||
|
||
// Group Dialog
|
||
if (btnNewGroup) {
|
||
btnNewGroup.addEventListener('click', openCreateGroupDialog);
|
||
}
|
||
if (closeGroupDlg) {
|
||
closeGroupDlg.addEventListener('click', () => groupDlg.close());
|
||
}
|
||
if (cancelGroupDlg) {
|
||
cancelGroupDlg.addEventListener('click', () => groupDlg.close());
|
||
}
|
||
if (groupForm) {
|
||
groupForm.addEventListener('submit', handleGroupFormSubmit);
|
||
}
|
||
if (groupDlg) {
|
||
groupDlg.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Escape') groupDlg.close();
|
||
});
|
||
}
|
||
|
||
// Keyboard shortcut for settings: Escape to close dialog
|
||
settingsDlg.addEventListener('keydown', (e) => {
|
||
if (e.key === 'Escape') settingsDlg.close();
|
||
});
|
||
}
|
||
|
||
// ------------------------------------------------------------------ INITIALIZATION
|
||
function init() {
|
||
initSettings();
|
||
initEvents();
|
||
fetchData();
|
||
state.pollTimer = setInterval(fetchData, 10000);
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded', init);
|