feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped

New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 22:39:33 -03:00
1 parent b7462c14fa
commit 2ebda1e4d7
79 files changed
+9091 -171

No files matched your search

+400 -60
View File
@@ -28,6 +28,19 @@
* pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00"
* Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice
* Urutau.toast(msg) short confirmation toast
* Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby,
* popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }.
* Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat.<category>,
* help.metric.<name> (requests, malicious, unique_ips, attacks_per_hour_24h, moving_avg_7d_per_hour, trend,
* active_attackers_24h/_1h, new_attackers, returning_rate, sessions_per_day, exposure_rate, exploits_refused_pct,
* ban_coverage, blocklist_coverage, blocklist_leak, mttb, visitors, pages, bytes, latency, bots) and
* help.term.<term> (session, stage.recon|probe|exploit|access|banned, campaign, family, mitre, net_type, cadence,
* score, level, fcrdns, exposure, blocklist, peer, hub, client_type, status_class, attack_profile).
* Pass the key WITHOUT the "help." prefix: Urutau.help(el, 'metric.mttb'). Metric cards accept {help:'metric.x'},
* panels accept {help:'term.x'}. Category names: t('cat.<c>') is the long name, t('cat.short.<c>') the short one.
* Groups: registerPage({..., group:'monitor|investigate|analyze|operate|reports'}); known ids are placed by the built-in
* order, unknown ids go to the end of their group (default group: analyze).
* Page scripts load from /pages.json ({"pages":[{"name":"geo","css":true}]}): add your name there when you create <name>.js.
* Urutau.registerI18n({ en: {...}, 'pt-BR': {...} }) merge keys (existing keys win)
* Urutau.t(key, vars?) vars: a number (fills {n}) or an object ({name: ...})
* Urutau.api(path, params) -> Promise<json> GET with query params; 401 goes to
@@ -45,6 +58,16 @@
* function handlers, any other attribute as a string. SVG tags work.
* Urutau.css(name) reads a design token, e.g. css('accent') or css('--cat-exploit')
* Urutau.setSliceNote(text) optional extra words appended to the slice sentence
* Urutau.charts: own SVG chart library (no dependencies, CSP-safe, theme tokens, ResizeObserver,
* every chart also renders a visually hidden <table> for screen readers, and an empty
* state when there is nothing to draw). Every function returns a DOM node; append it.
* donut(data[{key,label,value}], {title, colors:['--viz-3',...], centerLabel, format})
* radar(axes[{key,label}], series[{label,values[]}], {max, format, colors, title})
* stackedArea(series[{key,label,values[]}], stepSeconds, {start (unix), colors, title})
* bars(rows[{key,label,value,color?:'--token',parts?:[{label,value,color?}]}], {horizontal=true, stacked, format, colors, title})
* heatmap(matrix[row][col], xLabels[], yLabels[], {format, title}) cells use --seq-1..5
* sparkline(values[]) gauge(value, max, thresholds[{at,tone:'ok|warn|danger|info'}], {label, format})
* colors are CSS token names ("--viz-1"); the default palette is --viz-1..8 in order.
* Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline } shared primitives
* (the same ones the core pages use; see their definitions below)
*
@@ -357,6 +380,7 @@
var acts = opts.actions ? [].concat(opts.actions) : null;
var head = h('div', 'panel-h', h('h2', null, opts.title), acts ? h('div', 'acts', acts) : null);
var body = h('div', 'panel-b', kids);
if (opts.help) help(head.firstChild, opts.help);
var variant = pick(['list', 'chart', 'map'], opts.variant, '');
var foot = opts.footer ? h('div', 'panel-f', opts.footer) : null;
var node = h('section', 'panel' + (variant ? ' card-' + variant : '') + (opts.cls ? ' ' + opts.cls : ''), head, opts.hint ? h('p', 'hint', opts.hint) : null, body, foot);
@@ -384,11 +408,13 @@
var arrow = o.delta === 0 ? '\u25A0' : up ? '\u25B2' : '\u25BC';
dl = h('p', 'cm-delta' + (big && o.delta !== 0 ? (good ? ' good' : ' bad') : ''), arrow + ' ' + nfFor({ maximumFractionDigits: 0 }, 'd0').format(Math.abs(o.delta)) + '%');
}
var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), h('p', 'cm-label', label), h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark));
var lab = h('p', 'cm-label', label);
if (o.help) help(lab, o.help);
var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), lab, h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark));
if (o.hint) n.title = o.hint;
return n;
}
function stat(label, value, sub, tone, hint) { return metric(label, value, { sub: sub, tone: tone, hint: hint }); }
function stat(label, value, sub, tone, hint, helpKey) { return metric(label, value, { sub: sub, tone: tone, hint: hint, help: helpKey }); }
function lead(title, body, tone) {
var tn = pick(['ok', 'danger', 'neutral'], tone, 'ok');
return h('section', 'lead tone-' + tn, h('div', null, h('h2', null, title), body ? h('p', null, body) : null), h('span', 'pulse', ''));
@@ -402,7 +428,47 @@
function showSkeleton(box, n, cls) { clear(box); for (var i = 0; i < n; i++) box.appendChild(h('div', cls || 'skeleton')); }
function badge(text, tone) { var tn = pick(KNOWN_TONES, tone, 'neutral'); return h('span', 'badge' + (tn === 'neutral' ? '' : ' tone-' + tn), text); }
function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return badge(t('level.' + l), LEVEL_TONE[l]); }
function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'); return h('span', 'cat c-' + k, label || t('cat.' + k)); }
function catShort(c) { var k = pick(KNOWN_CATS, c, 'ok'); return t('cat.short.' + k); }
function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'), n = h('span', 'cat c-' + k, label || catShort(k)); n.title = t('cat.' + k); return n; }
// ---------------------------------------------------------------- help and glossary
// help.cat.<cat>, help.metric.<name>, help.term.<term> (+ ".do" = what to do) live in the central dictionary
var glossary = {
has: function (key) { var k = 'help.' + key; return t(k) !== k; },
get: function (key) { var k = 'help.' + key, tx = t(k); if (tx === k) return null; var dk = k + '.do', d = t(dk); return { text: tx, action: d === dk ? '' : d }; }
};
var helpPop = null, helpBtn = null, helpPinned = false;
function ensureHelpPop() {
if (!helpPop) { helpPop = h('div', 'help-pop'); helpPop.id = 'help-pop'; helpPop.setAttribute('role', 'tooltip'); helpPop.hidden = true; document.body.appendChild(helpPop); }
return helpPop;
}
function hideHelp() { if (helpPop) helpPop.hidden = true; helpBtn = null; helpPinned = false; }
function showHelp(btn, key) {
var g = glossary.get(key), pop = ensureHelpPop();
if (!g) return;
clear(pop);
pop.appendChild(h('p', 'help-t', g.text));
if (g.action) pop.appendChild(h('p', 'help-do', h('strong', null, t('help.do') + ': '), g.action));
pop.hidden = false; helpBtn = btn;
var r = btn.getBoundingClientRect(), w = pop.offsetWidth, ph = pop.offsetHeight;
var left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8)), top = r.bottom + 6;
if (top + ph > window.innerHeight - 8) top = Math.max(8, r.top - ph - 6);
pop.style.left = left + 'px'; pop.style.top = top + 'px';
}
// append an accessible "?" to a node: focusable, aria-describedby, popover with short text + what to do
function help(node, key) {
if (!node || !glossary.has(key)) return null;
var b = el('button', { type: 'button', class: 'help-btn', 'aria-label': t('help.label'), 'aria-describedby': 'help-pop' }, '?');
ensureHelpPop();
b.addEventListener('mouseenter', function () { if (!helpPinned) showHelp(b, key); });
b.addEventListener('focus', function () { if (!helpPinned) showHelp(b, key); });
b.addEventListener('mouseleave', function () { if (!helpPinned) hideHelp(); });
b.addEventListener('blur', function () { if (!helpPinned) hideHelp(); });
b.addEventListener('click', function (e) { e.stopPropagation(); if (helpBtn === b && helpPinned) hideHelp(); else { showHelp(b, key); helpPinned = true; } });
node.appendChild(b);
return b;
}
// ranked list with a proportional bar; rows: [{key, n, label?}]
function bars(rows, opts) {
@@ -628,6 +694,8 @@
});
th.appendChild(b);
} else th.textContent = colLabel(x.k);
var hk = { score: 'term.score', level: 'term.level', cats: 'term.categories', origin: 'term.net_type' }[x.k];
if (hk) help(th, hk);
tr.appendChild(th);
});
thead.appendChild(tr);
@@ -665,7 +733,7 @@
var chips = h('span');
var kinds = Object.keys(x.counts || {}).filter(function (k) { return k !== 'ok' && k !== 'ssh-ok' && KNOWN_CATS.indexOf(k) >= 0; })
.sort(function (a, b) { return x.counts[b] - x.counts[a]; });
kinds.slice(0, 2).forEach(function (k) { chips.appendChild(h('span', 'chip', t('cat.' + k) + ' ' + nf(x.counts[k]))); });
kinds.slice(0, 2).forEach(function (k) { { var cp = h('span', 'chip', catShort(k) + ' ' + nf(x.counts[k])); cp.title = t('cat.' + k); chips.appendChild(cp); } });
if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2)));
cell('cats', chips); break;
}
@@ -822,7 +890,7 @@
bar.appendChild(fill);
[[1, 'drawer.cut.susp'], [5, 'drawer.cut.host']].forEach(function (c) { var tk = h('b', 'tick'); tk.style.left = c[0] + '%'; tk.title = t(c[1]); bar.appendChild(tk); });
var verdict = h('section', 'ip-verdict lv-' + pick(KNOWN_LEVELS, level, 'low'),
h('div', 'iv-top', levelBadge(level), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000')), bar,
h('div', 'iv-top', (function () { var w = h('span', 'iv-lv', levelBadge(level)); help(w, 'term.level'); return w; })(), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000'), (function () { var w = h('span', 'iv-h'); help(w, 'term.score'); return w; })()), bar,
h('p', 'note iv-cuts', t('drawer.cuts')),
origin ? h('p', 'iv-origin', origin) : null,
first && last ? h('p', 'note', t('drawer.active', { v: spanText(last - first) }) + ' \u00b7 ' + t('detail.last') + ': ' + ago(last)) : null);
@@ -836,7 +904,7 @@
var days = typeof tm.active_days === 'number' ? nf(tm.active_days) : '\u2014';
var nbans = (d.bans && d.bans.length) || (d.jails || []).length;
box.appendChild(h('div', 'drawer-metrics',
metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans') })));
metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans'), help: 'cat.ban' })));
var tstep = (d.timeline && d.timeline.step) || 3600, all = numbersOf(d.timeline), keep = Math.round(7 * 86400 / tstep), vals = all.slice(-keep);
if (vals.length > 1 && Math.max.apply(null, vals) > 0) {
var t0 = ((d.timeline && d.timeline.start) || 0) + (all.length - vals.length) * tstep;
@@ -845,10 +913,11 @@
if (Array.isArray(d.techniques) && d.techniques.length) {
var chips = h('div', 'chip-group');
d.techniques.slice(0, 8).forEach(function (x) { chips.appendChild(h('span', 'chip-mitre', (x.id ? x.id + ' ' : '') + (x.name || '') + (x.n ? ' \u00d7' + nf(x.n) : ''))); });
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.techniques')), chips));
var th3 = h('h3', null, t('drawer.techniques')); help(th3, 'term.mitre');
box.appendChild(h('section', 'drawer-sec', th3, chips));
}
var kinds = Object.keys(d.counts || {}).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0 && c !== 'ok' && c !== 'ssh-ok'; });
if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.categories')), cc)); }
if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); var ch3 = h('h3', null, t('drawer.categories')); help(ch3, 'term.categories'); box.appendChild(h('section', 'drawer-sec', ch3, cc)); }
if (Array.isArray(v.reasons) && v.reasons.length) {
var ul = h('ul'); v.reasons.slice(0, 3).forEach(function (r) { ul.appendChild(h('li', null, reasonText(r))); });
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.reasons')), ul));
@@ -874,8 +943,203 @@
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
}
// ---------------------------------------------------------------- charts library (own SVG, no dependencies)
var VIZ = ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-6', '--viz-7', '--viz-8'];
function vizColor(i, colors) { return 'var(' + ((colors && colors[i % colors.length]) || VIZ[i % VIZ.length]) + ')'; }
// run fn(width) now and whenever the box is resized
function watch(node, fn) {
if (!window.ResizeObserver) { fn(node.clientWidth || 320); return; }
var last = 0;
new ResizeObserver(function (es) { var w = Math.round(es[0].contentRect.width); if (w > 0 && w !== last) { last = w; fn(w); } }).observe(node);
}
// screen-reader alternative: a real table with the same numbers
function srTable(caption, head, rows) {
return h('table', 'sr-only', h('caption', null, caption || ''), h('thead', null, h('tr', null, head.map(function (x) { return el('th', { scope: 'col' }, x); }))),
h('tbody', null, rows.map(function (r) { return h('tr', null, r.map(function (c) { return h('td', null, String(c)); })); })));
}
function sumOf(a) { var s = 0; a.forEach(function (x) { s += x; }); return s; }
function legendList(items, colors, fmt, onHover) {
var ul = h('ul', 'vz-legend');
items.forEach(function (d, i) {
var li = h('li', null, h('span', 'sw'), h('span', 'vz-l', d.label), h('span', 'vz-v num', fmt(d)));
li.firstChild.style.background = vizColor(i, colors);
if (onHover) { li.addEventListener('mouseenter', function () { onHover(i); }); li.addEventListener('mouseleave', function () { onHover(-1); }); }
ul.appendChild(li);
});
return ul;
}
// donut(data [{key,label,value}], {title, colors:[token], centerLabel, format})
function donut(data, o) {
o = o || {};
data = (data || []).filter(function (x) { return x && x.value > 0; });
var total = sumOf(data.map(function (x) { return x.value; })), fmt = o.format || nf;
if (!total) return empty(t('charts.empty'));
var R = 70, C = 2 * Math.PI * R, acc = 0, segs = [];
var svg = svgEl('svg', { viewBox: '0 0 200 200', 'class': 'vz-donut', role: 'img', 'aria-label': o.title || '' });
var cv = svgEl('text', { x: 100, y: 102, 'text-anchor': 'middle', 'class': 'vz-c-v' }), cl = svgEl('text', { x: 100, y: 124, 'text-anchor': 'middle', 'class': 'vz-c-l' });
function center(i) {
if (i < 0) { cv.textContent = fmt(total); cl.textContent = o.centerLabel || t('charts.total'); return; }
cv.textContent = pct(data[i].value, total); cl.textContent = data[i].label;
}
data.forEach(function (d, i) {
var len = d.value / total * C, vis = Math.max(0.5, len - (data.length > 1 ? 1.5 : 0));
var c = svgEl('circle', { cx: 100, cy: 100, r: R, fill: 'none', 'stroke-width': 26, 'stroke-dasharray': vis + ' ' + (C - vis), 'stroke-dashoffset': -acc, transform: 'rotate(-90 100 100)', 'class': 'vz-seg', tabindex: 0, 'aria-label': d.label + ': ' + fmt(d.value) + ' (' + pct(d.value, total) + ')' });
c.style.stroke = vizColor(i, o.colors);
c.addEventListener('mouseenter', function () { center(i); }); c.addEventListener('focus', function () { center(i); });
c.addEventListener('mouseleave', function () { center(-1); }); c.addEventListener('blur', function () { center(-1); });
segs.push(c); svg.appendChild(c); acc += len;
});
svg.appendChild(cv); svg.appendChild(cl); center(-1);
var legend = legendList(data, o.colors, function (d) { return fmt(d.value) + ' · ' + pct(d.value, total); }, function (i) { center(i); segs.forEach(function (s, k) { s.classList.toggle('dim', i >= 0 && k !== i); }); });
return h('div', 'vz vz-donut-wrap', h('div', 'vz-donut-svg', svg), legend, srTable(o.title, [t('charts.item'), t('charts.value')], data.map(function (d) { return [d.label, fmt(d.value) + ' (' + pct(d.value, total) + ')']; })));
}
// radar(axes [{key,label}], series [{label, values[]}], {max, format, colors})
function radar(axes, series, o) {
o = o || {};
var n = axes.length;
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
var mx = o.max || Math.max.apply(null, [0].concat.apply([], series.map(function (s) { return s.values; })));
if (n < 3 || !series.length || !(mx > 0)) return empty(t('charts.empty'));
var fmt = o.format || nf, W = 360, H = 290, cx = 180, cy = 145, R = 82;
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, 'class': 'vz-radar', role: 'img', 'aria-label': o.title || '' });
function pt(i, f) { var a = -Math.PI / 2 + i * 2 * Math.PI / n; return [cx + Math.cos(a) * R * f, cy + Math.sin(a) * R * f, Math.cos(a), Math.sin(a)]; }
[.25, .5, .75, 1].forEach(function (f) {
svg.appendChild(svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, f); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-ring' }));
});
var rl = svgEl('text', { x: cx + 4, y: cy - R + 12, 'class': 'axis' }); rl.textContent = fmt(mx); svg.appendChild(rl);
axes.forEach(function (a, i) {
var p = pt(i, 1), q = pt(i, 1.14);
svg.appendChild(svgEl('line', { x1: cx, y1: cy, x2: p[0], y2: p[1], 'class': 'gridline' }));
var tx = svgEl('text', { x: q[0], y: q[1] + 4, 'text-anchor': q[2] > .3 ? 'start' : q[2] < -.3 ? 'end' : 'middle', 'class': 'vz-axl' });
tx.textContent = a.label; svg.appendChild(tx);
});
series.forEach(function (s, k) {
var col = vizColor(k, o.colors);
var poly = svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-rs' });
poly.style.stroke = col; poly.style.fill = col; svg.appendChild(poly);
axes.forEach(function (a, i) {
var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)), c = svgEl('circle', { cx: p[0], cy: p[1], r: 3, 'class': 'vz-dot', tabindex: 0, 'aria-label': s.label + ', ' + a.label + ': ' + fmt(s.values[i] || 0) });
c.style.fill = col; var ti = svgEl('title', {}); ti.textContent = s.label + ' · ' + a.label + ': ' + fmt(s.values[i] || 0); c.appendChild(ti); svg.appendChild(c);
});
});
var legend = legendList(series.map(function (s) { return { label: s.label }; }), o.colors, function () { return ''; });
return h('div', 'vz vz-radar-wrap', svg, legend, srTable(o.title, [t('charts.item')].concat(series.map(function (s) { return s.label; })), axes.map(function (a, i) { return [a.label].concat(series.map(function (s) { return fmt(s.values[i] || 0); })); })));
}
// stackedArea(series [{key,label,values[]}], step seconds, {start, colors, title})
function stackedArea(series, step, o) {
o = o || {};
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
var n = series.length ? series[0].values.length : 0, tot = [], mx = 0, i;
if (n < 2) return empty(t('charts.empty'));
for (i = 0; i < n; i++) { var v = 0; series.forEach(function (s) { v += s.values[i] || 0; }); tot.push(v); if (v > mx) mx = v; }
var wrap = h('div', 'chart-wrap vz-area'), box = h('div', 'vz');
var colors = o.colors;
function draw(Wpx) {
clear(wrap);
var W = Math.max(280, Wpx), H = 220, L = 40, R = 6, Tp = 8, B = 22, top = niceMax(mx), ph = H - Tp - B, dx = (W - L - R) / (n - 1);
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), k;
for (k = 0; k <= 4; k++) {
var y = Tp + ph - ph * k / 4;
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
var lb = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); lb.textContent = top >= 10000 ? nfCompact(Math.round(top * k / 4)) : nf(Math.round(top * k / 4)); svg.appendChild(lb);
}
var nt = W < 520 ? 3 : 5, longSpan = step * n > 2 * 86400;
for (k = 0; k < nt; k++) {
var ix = Math.round((n - 1) * k / (nt - 1)), xl = svgEl('text', { x: L + dx * ix, y: H - 6, 'text-anchor': k === 0 ? 'start' : k === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
xl.textContent = tickLabel((o.start || 0) + ix * step, longSpan); svg.appendChild(xl);
}
var base = []; for (i = 0; i < n; i++) base.push(0);
series.forEach(function (s, si) {
var up = [], down = [];
for (i = 0; i < n; i++) { var lo = base[i], hi = lo + (s.values[i] || 0); up.push((L + dx * i).toFixed(1) + ',' + (Tp + ph - hi / top * ph).toFixed(1)); down.unshift((L + dx * i).toFixed(1) + ',' + (Tp + ph - lo / top * ph).toFixed(1)); base[i] = hi; }
var p = svgEl('polygon', { points: up.concat(down).join(' '), 'class': 'vz-area-s' }); p.style.fill = vizColor(si, colors); svg.appendChild(p);
});
var tip = h('div', 'tip'); tip.hidden = true;
var guide = svgEl('line', { y1: Tp, y2: Tp + ph, 'class': 'vz-guide' }); guide.style.display = 'none'; svg.appendChild(guide);
var hit = svgEl('rect', { x: L, y: Tp, width: W - L - R, height: ph, fill: 'transparent' });
function at(ev) {
var r = svg.getBoundingClientRect(), px = (ev.clientX - r.left) * W / r.width, ix = Math.max(0, Math.min(n - 1, Math.round((px - L) / dx)));
clear(tip); tip.appendChild(h('strong', null, new Date(((o.start || 0) + ix * step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
series.forEach(function (s) { tip.appendChild(h('div', null, h('span', null, s.label), h('span', 'num', nf(s.values[ix] || 0)))); });
tip.hidden = false; tip.style.left = Math.max(0, Math.min(L + dx * ix + 12, W - 170)) + 'px'; tip.style.top = '4px';
guide.setAttribute('x1', L + dx * ix); guide.setAttribute('x2', L + dx * ix); guide.style.display = '';
}
hit.addEventListener('mousemove', at); hit.addEventListener('click', at);
hit.addEventListener('mouseleave', function () { tip.hidden = true; guide.style.display = 'none'; });
svg.appendChild(hit); wrap.appendChild(svg); wrap.appendChild(tip);
}
box.appendChild(wrap);
box.appendChild(legendList(series.map(function (s) { return { label: s.label }; }), colors, function (d, j) { return ''; }));
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], series.map(function (s) { return [s.label, nf(sumOf(s.values))]; })));
watch(wrap, draw);
return box;
}
// bars(rows [{key,label,value,color?,parts?:[{label,value,color?}]}], {horizontal (default true), stacked, format, colors})
function barChart(rows, o) {
o = o || {};
rows = (rows || []).filter(function (r) { return r; });
var fmt = o.format || nf, hor = o.horizontal !== false;
function rowTotal(r) { return r.parts ? sumOf(r.parts.map(function (p) { return p.value; })) : r.value; }
var mx = Math.max.apply(null, [0].concat(rows.map(rowTotal)));
if (!mx) return empty(t('charts.empty'));
var box = h('div', 'vz vz-bars' + (hor ? '' : ' vz-cols'));
rows.forEach(function (r, i) {
var tot = rowTotal(r), track = h('div', 'vz-track');
var parts = r.parts && o.stacked !== false ? r.parts : [{ label: r.label, value: r.value, color: r.color }];
parts.forEach(function (p, j) {
var seg = h('i'); seg.style[hor ? 'width' : 'height'] = Math.max(p.value ? 1 : 0, p.value / mx * 100) + '%';
seg.style.background = p.color ? 'var(' + p.color + ')' : vizColor(r.parts ? j : (r.color ? 0 : i), r.color ? [r.color] : o.colors);
seg.title = p.label + ': ' + fmt(p.value); track.appendChild(seg);
});
box.appendChild(h('div', 'vz-row', h('span', 'vz-l', r.label), track, h('span', 'vz-v num', fmt(tot))));
});
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], rows.map(function (r) { return [r.label, fmt(rowTotal(r))]; })));
return box;
}
// heatmap(matrix [row][col] numbers, xLabels, yLabels, {format, title}); cell colour from --seq-1..5
function heatmap(matrix, xl, yl, o) {
o = o || {};
var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
if (!mx) return empty(t('charts.empty'));
var fmt = o.format || nf, wrap = h('div', 'vz vz-heat');
function draw(Wpx) {
clear(wrap);
var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22;
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw);
matrix.forEach(function (row, y) {
var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt);
row.forEach(function (v, x) {
var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0;
var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
});
});
for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
wrap.appendChild(svg);
}
var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); })));
watch(wrap, draw);
return box;
}
// gauge(value, max, thresholds [{at, tone: ok|warn|danger|info}], {label, format})
function gauge(value, max, thr, o) {
o = o || {};
max = max > 0 ? max : 1;
var fmt = o.format || nf, v = Math.max(0, Math.min(max, Number(value) || 0));
thr = thr && thr.length ? thr : [{ at: 0, tone: 'ok' }, { at: max * .5, tone: 'warn' }, { at: max * .8, tone: 'danger' }];
var tone = 'ok'; thr.forEach(function (x) { if (v >= x.at) tone = pick(['ok', 'warn', 'danger', 'info'], x.tone, 'ok'); });
var d = 'M20 100 A80 80 0 0 1 180 100';
var svg = svgEl('svg', { viewBox: '0 0 200 120', 'class': 'vz-gauge', role: 'img', 'aria-label': (o.label || '') + ' ' + fmt(v) + ' / ' + fmt(max) });
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-bg' }));
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-fg tone-' + tone, 'stroke-dasharray': (v / max * 100) + ' 100' }));
var tv = svgEl('text', { x: 100, y: 92, 'text-anchor': 'middle', 'class': 'vz-c-v' }); tv.textContent = fmt(v); svg.appendChild(tv);
var lo = svgEl('text', { x: 20, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); lo.textContent = '0'; svg.appendChild(lo);
var hi = svgEl('text', { x: 180, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); hi.textContent = fmt(max); svg.appendChild(hi);
return h('div', 'vz vz-gauge-wrap', svg, o.label ? h('div', 'vz-c-l', o.label) : null);
}
var charts = { donut: donut, radar: radar, stackedArea: stackedArea, bars: barChart, heatmap: heatmap, sparkline: sparkline, gauge: gauge };
// ---------------------------------------------------------------- page registry
var ORDER = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources'];
var pages = {};
var current = null; // { page, el }
function registerPage(p) {
@@ -883,9 +1147,27 @@
pages[p.id] = p;
if (booted) { renderNav(); route(); }
}
// rail groups; ids not listed go to the end of their group (page.group, else Analyze)
var GROUPS = [
['monitor', ['overview', 'live', 'slo']],
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search']],
['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']],
['operate', ['defense', 'sources', 'integrity']],
['reports', ['reports']]
];
function groupOf(p) {
if (p.group) for (var i = 0; i < GROUPS.length; i++) if (GROUPS[i][0] === p.group) return p.group;
for (var j = 0; j < GROUPS.length; j++) if (GROUPS[j][1].indexOf(p.id) >= 0) return GROUPS[j][0];
return 'analyze';
}
function orderedPages() {
var ids = Object.keys(pages);
return ORDER.filter(function (id) { return pages[id]; }).concat(ids.filter(function (id) { return ORDER.indexOf(id) < 0; }).sort()).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; });
var visible = Object.keys(pages).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; }), out = [];
GROUPS.forEach(function (g) {
var mine = visible.filter(function (p) { return groupOf(p) === g[0]; });
g[1].forEach(function (id) { mine.filter(function (p) { return p.id === id; }).forEach(function (p) { out.push(p); }); });
mine.filter(function (p) { return g[1].indexOf(p.id) < 0; }).sort(function (a, b) { return a.id < b.id ? -1 : 1; }).forEach(function (p) { out.push(p); });
});
return out;
}
function sp(n, node) { node.classList.add('span-' + n); return node; }
function grid12() { return h('div', 'grid-12'); }
@@ -937,7 +1219,7 @@
function bucketNote(step) { return step ? t('timeline.bucket', { n: nf(Math.max(1, Math.round(step / 60))) }) : ''; }
function timelinePanel() {
var wrap = h('div', 'chart-wrap'), legend = h('div', 'legend'), note = h('span', 'note bucket-note');
var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true }, wrap, legend);
var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true, help: 'metric.attacks_per_hour_24h' }, wrap, legend);
var data = null;
function renderLegend() {
clear(legend);
@@ -945,7 +1227,9 @@
var b = el('button', { type: 'button', 'aria-pressed': state.hidden[c] ? 'false' : 'true' }, h('span', 'sw b-' + c), h('span', null, t('cat.' + c)));
b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); draw(); });
legend.appendChild(b);
b.title = t('cat.' + c);
});
help(legend, 'term.categories');
legend.appendChild(note);
}
function draw() {
@@ -1003,7 +1287,7 @@
clear(box);
keys.forEach(function (k) {
var x = m[k];
box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x) }));
box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x), help: 'metric.' + k }));
});
return true;
}
@@ -1012,12 +1296,12 @@
var T = s.totals, hosts = s.hosts || [], on = hosts.filter(function (x) { return x.online; }).length;
var range = rangeLower();
clear(box);
box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range })));
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral'));
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans')));
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range })));
box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.requests'));
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral', null, 'metric.malicious'));
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral', null, 'term.level'));
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral', null, 'term.level'));
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'), 'neutral', null, 'cat.ban'));
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.unique_ips'));
}
function overviewLead(s) {
var T = s.totals;
@@ -1043,17 +1327,19 @@
}
// ---------------------------------------------------------------- page: overview
var RADAR_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe'];
var pOverview = corePage({
id: 'overview', icon: ICONS.overview, titleKey: 'nav.overview',
build: function (root) {
var v = {}, g = grid12();
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
v.timeline = timelinePanel();
v.radar = panel({ title: t('ov.radar'), hint: t('ov.radar.hint'), loading: true, help: 'term.attack_profile' });
v.countries = panel({ title: t('ov.countries'), hint: t('ov.countries.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/geo' }, t('ov.all')) });
v.topips = panel({ title: t('ov.topips'), hint: t('ov.topips.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/ips' }, t('ov.all')) });
v.feedList = feedList(30);
v.feed = panel({ title: t('ov.feed'), hint: t('ov.feed.hint'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline.node));
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(8, v.timeline.node)); g.appendChild(sp(4, v.radar));
g.appendChild(sp(4, v.countries)); g.appendChild(sp(4, v.topips)); g.appendChild(sp(4, v.feed));
root.appendChild(g);
v.offResize = onResize(function () { v.timeline.draw(); });
@@ -1061,9 +1347,21 @@
v.feedList.render();
return v;
},
load: function (c) { return getSummary(c).then(function (s) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m }); }); }); },
load: function (c) {
return getSummary(c).then(function (s) {
var hosts = (s.hosts || []).filter(function (x) { return x.online !== false; }).slice(0, 4);
var rq = c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range };
var jobs = hosts.length > 1 ? hosts.map(function (x) { return api('/api/v1/summary', Object.assign({ host: x.name }, rq)).then(function (r) { return { label: x.name, s: r }; }, function () { return null; }); }) : [Promise.resolve({ label: (hosts[0] && hosts[0].name) || t('host.all'), s: s })];
return Promise.all(jobs).then(function (rs) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m, radar: rs.filter(Boolean) }); }); });
});
},
render: function (v, s) {
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel'); v.lead.appendChild(overviewLead(s));
ready(v.radar); clear(v.radar.body);
v.radar.body.appendChild(charts.radar(RADAR_CATS.map(function (c) { return { key: c, label: catShort(c) }; }), (s.radar || []).map(function (r) {
var vals = RADAR_CATS.map(function (c) { var n = 0; ((r.s.timeline.series || {})[c] || []).forEach(function (x) { n += x; }); return n; }), tot = sumOf(vals) || 1;
return { label: r.label, values: vals.map(function (x) { return Math.round(x / tot * 1000) / 10; }) };
}), { title: t('ov.radar'), format: function (x) { return nf(x) + '%' } }));
kpiRow(s, v.kpis, s.metrics, 'overview');
v.timeline.set(s);
clear(v.countries.body); v.countries.body.appendChild(bars(s.countries, { label: function (r) { return countryLabel(r.key); } }));
@@ -1097,13 +1395,13 @@
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); v.mon = sp(12, h('p', 'note'));
v.timeline = timelinePanel();
v.mapbox = mapBox();
v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true }, v.mapbox);
v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true, help: 'term.categories' }, v.mapbox);
v.tbl = ipTable(false);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score', actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node);
v.feedList = feedList(100);
v.feed = panel({ title: t('feed.title'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true });
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true });
v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true, help: 'cat.scanner' }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true, help: 'metric.requests' });
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true, help: 'term.family' }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true, help: 'cat.ssh-fail' });
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(v.mon); g.appendChild(sp(12, v.timeline.node)); g.appendChild(sp(8, v.map)); g.appendChild(sp(4, v.feed));
g.appendChild(sp(12, v.ips));
[v.paths, v.domains, v.uas, v.users].forEach(function (x) { g.appendChild(sp(3, x)); });
@@ -1149,24 +1447,31 @@
sel.value = state.domain;
if (sel.value !== state.domain) sel.value = 'all';
}
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
var pTraffic = corePage({
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
build: function (root) {
var v = {}, g = grid12();
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
v.wrap = h('div', 'chart-wrap'); v.note = h('span', 'note bucket-note');
v.legend = h('div', 'legend', h('span', 'li', h('span', 'sw b-treq'), t('traffic.requests')), h('span', 'li', h('span', 'sw b-tpages'), t('traffic.pages')), v.note);
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.timeline.hint'), variant: 'chart', loading: true }, v.wrap, v.legend);
v.wrap = h('div'); v.note = h('span', 'note bucket-note');
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.area.hint'), variant: 'chart', loading: true, help: 'metric.pages' }, v.wrap, h('div', 'legend', v.note));
v.mapbox = mapBox();
v.map = panel({ title: t('map.visitors'), hint: t('map.visitors.hint'), variant: 'map', loading: true }, v.mapbox);
var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['browsers', 'traffic.browsers'], ['oses', 'traffic.oses'], ['devices', 'traffic.devices'], ['bots', 'traffic.bots'], ['status', 'traffic.status']];
var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['bots', 'traffic.bots']];
ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]), variant: 'list', loading: true }); });
v.client = panel({ title: t('traffic.client'), hint: t('traffic.client.hint'), loading: true, help: 'term.client_type' });
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
['pages', 'refs', 'cities', 'browsers', 'oses', 'devices'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(sp(6, v.bots)); g.appendChild(sp(6, v.status)); g.appendChild(v.privacy);
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(v.privacy);
root.appendChild(g);
v.offResize = onResize(function () { if (v.data) drawTraffic(v, v.data); });
return v;
},
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
@@ -1179,31 +1484,35 @@
? lead(t('tr.lead.some', { n: nf(d.visitors), p: nf(d.pages) }), t('tr.lead.body', { r: nf(d.requests), b: nf(d.bots), a: nf(Math.round(d.p50_ms)), c: nf(Math.round(d.p95_ms)) }), 'ok')
: lead(t('tr.lead.none'), t('tr.lead.noneBody'), 'neutral'));
clear(v.kpis);
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests')));
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) })));
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors')));
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms', t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) })));
ready(v.timeline); ready(v.map);
drawTraffic(v, d);
var rg = rangeLower();
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'), 'neutral', null, 'metric.requests'));
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }), 'neutral', null, 'metric.pages'));
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'), 'neutral', null, 'metric.visitors'));
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.bytes'));
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms), 'ms \u00b7 ' + t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.latency'));
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }), 'neutral', null, 'metric.bots'));
// time series: page views and the rest of the requests
var tl = d.timeline, pg = tl.pages || [], other = (tl.req || []).map(function (x, i) { return Math.max(0, x - (pg[i] || 0)); });
ready(v.timeline); clear(v.wrap);
v.note.textContent = bucketNote(tl.step);
v.wrap.appendChild(charts.stackedArea([{ key: 'pages', label: t('traffic.pages'), values: pg }, { key: 'other', label: t('traffic.otherReq'), values: other }], tl.step, { start: tl.start, colors: ['--accent', '--viz-8'], title: t('traffic.timeline') }));
ready(v.map);
renderMap(v.mapbox, d.countries, true, t('map.visitors'));
function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); }
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false);
fill('browsers', d.browsers, false); fill('oses', d.oses, false);
fill('devices', (d.devices || []).map(function (x) { return { key: t('device.' + pick(['desktop', 'mobile', 'tablet', 'bot', 'tool'], x.key, 'unknown')), n: x.n }; }), false);
fill('bots', d.bot_names, false);
fill('status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true);
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); fill('bots', d.bot_names, false);
// client type: devices as reported, plus bots when the devices list has no bot entry
var dev = (d.devices || []).map(function (x) { return { k: pick(CLIENT_ORDER, x.key, 'misc'), n: x.n }; });
dev.sort(function (a, b) { return CLIENT_ORDER.indexOf(a.k) - CLIENT_ORDER.indexOf(b.k); });
function donutOf(box, data, colors, title) { ready(box); clear(box.body); box.body.appendChild(charts.donut(data, { title: title, colors: colors })); }
donutOf(v.client, dev.map(function (x) { return { key: x.k, label: t('device.' + x.k), value: x.n }; }), dev.map(function (x) { return CLIENT_COLORS[x.k]; }), t('traffic.client'));
donutOf(v.browsers, (d.browsers || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.browsers'));
donutOf(v.oses, (d.oses || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.oses'));
var cls = ['2xx', '3xx', '4xx', '5xx'];
ready(v.status); clear(v.status.body);
v.status.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (d.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
},
dispose: function (v) { v.offResize(); }
dispose: function () { }
});
function drawTraffic(v, d) {
var tl = d.timeline;
v.note.textContent = bucketNote(tl.step);
chart(v.wrap, { start: tl.start, step: tl.step, stacked: false, aria: t('traffic.timeline'), layers: [
{ cls: 'b-treq', label: t('traffic.requests'), vals: tl.req }, { cls: 'b-tpages', label: t('traffic.pages'), vals: tl.pages }
] });
}
// ---------------------------------------------------------------- page: ips
var pIPs = corePage({
@@ -1213,7 +1522,7 @@
v.lead = sp(12, h('div'));
v.tbl = ipTable(true);
v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); });
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score' }, v.tbl.node);
g.appendChild(v.lead); g.appendChild(sp(12, v.ips)); root.appendChild(g);
return v;
},
@@ -1242,7 +1551,7 @@
var copy = el('button', { type: 'button', class: 'btn primary' }, t('blocklist.copy'));
var dlTxt = el('a', { class: 'btn', href: '/api/v1/blocklist.txt' }, t('blocklist.download'));
var dlJson = el('a', { class: 'btn', href: '/api/v1/blocklist.json' }, t('blocklist.downloadJson'));
var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help') },
var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help'), help: 'term.blocklist' },
h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg);
var timer = 0, alive = true;
function query(extra) {
@@ -1294,11 +1603,11 @@
var v = {}, g = grid12();
v.lead = sp(12, h('div'));
v.hostsBox = h('div', 'hosts');
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint') }, v.hostsBox);
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox);
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
v.tbody = h('tbody');
v.srcEmpty = h('div');
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint') }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty);
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint'), help: 'term.integrity_gap' }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty);
v.geoBox = h('div');
v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox);
v.bl = blocklistPanel();
@@ -1504,8 +1813,10 @@
function renderNav() {
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
clear(nav); clear(bar); clear(more);
var lastGroup = null;
list.forEach(function (p) {
var label = t(p.titleKey);
var label = t(p.titleKey), gr = groupOf(p);
if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; }
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label));
if (cur === p.id) a.setAttribute('aria-current', 'page');
nav.appendChild(a);
@@ -1522,7 +1833,10 @@
if (rest.some(function (p) { return p.id === cur; })) mb.setAttribute('aria-current', 'page');
mb.addEventListener('click', function () { setMore(more.hidden); });
bar.appendChild(mb);
var rg = null;
rest.forEach(function (p) {
var g2 = groupOf(p);
if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; }
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
if (cur === p.id) a.setAttribute('aria-current', 'page');
more.appendChild(a);
@@ -1639,7 +1953,7 @@
});
$('#scrim').addEventListener('click', closeDetail);
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { closeDetail(); setMore(false); closeRangePicker(true); return; }
if (e.key === 'Escape') { hideHelp(); closeDetail(); setMore(false); closeRangePicker(true); return; }
var box = $('#detail');
if (e.key === 'Tab' && !box.hidden) {
var f = Array.prototype.slice.call(box.querySelectorAll('button, a[href], [tabindex="0"]'));
@@ -1660,6 +1974,7 @@
var more = $('#more');
if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false);
if (rp.open && !$('#range-picker').contains(e.target)) closeRangePicker(false);
if (helpPinned) hideHelp();
});
window.addEventListener('hashchange', route);
window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage);
@@ -1680,8 +1995,33 @@
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
charts: charts, help: help, glossary: glossary,
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline }
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0);
// page scripts are listed in /pages.json ({"pages":[{"name":"geo","css":true}, ...]}); only files that exist
// are listed, so nothing 404s. Each name loads /<name>.js (and /<name>.css) in order, then the app boots.
var DEFAULT_PAGES = [{ name: 'geo', css: true }, { name: 'live', css: true }, { name: 'ip', css: true }, { name: 'replay', css: true }];
function loadScript(src) {
return new Promise(function (ok) {
var sc = document.createElement('script');
sc.src = src; sc.async = false;
sc.onload = ok; sc.onerror = function () { console.warn('page script failed: ' + src); ok(); };
document.head.appendChild(sc);
});
}
function loadPages() {
return fetch('/pages.json', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }, function () { return null; }).then(function (m) {
var list = m && Array.isArray(m.pages) ? m.pages : DEFAULT_PAGES, chain = Promise.resolve();
list.forEach(function (p) {
var name = p && String(p.name || '');
if (!/^[a-z][a-z0-9-]*$/.test(name)) return;
if (p.css) { var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/' + name + '.css'; document.head.appendChild(l); }
chain = chain.then(function () { return loadScript('/' + name + '.js'); });
});
return chain;
});
}
function start() { loadPages().then(boot, boot); }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else setTimeout(start, 0);
})();
+38
View File
@@ -0,0 +1,38 @@
/* Urutau - CAMPAIGNS page. Selectors prefixed cp-. */
.cp { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
.cp-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr)); gap: 12px; }
.cp-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-raised); }
.cp-card.cp-wide { background: var(--surface-panel); }
.cp-card header { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 10px; align-items: baseline; }
.cp-id { font-weight: 650; color: var(--accent); text-decoration: none; }
.cp-win { font-size: .75rem; color: var(--ink-muted); }
.cp-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.cp-st { display: flex; flex-direction: column; min-width: 0; }
.cp-st b { font-size: 1.125rem; color: var(--heading, var(--ink)); }
.cp-sk { font-size: .6875rem; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-muted); }
.cp-sig { margin: 0; display: flex; flex-direction: column; gap: 3px; min-width: 0; }
.cp-chips { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; }
.cp-chip { max-width: 100%; padding: 1px 8px; border: 1px solid var(--line); border-radius: 999px; background: var(--accent-soft); font-size: .75rem; font-family: var(--font-mono, monospace); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.cp-more { font-family: inherit; color: var(--ink-muted); }
.cp-card footer { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; }
.cp-card footer .btn { min-height: 34px; }
.cp-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; }
.cp-back { align-self: flex-start; }
.cp-gwrap { overflow: hidden; }
.cp-gantt { width: 100%; height: auto; display: block; }
.cp-gl { stroke: var(--line); stroke-width: 1; }
.cp-gt { fill: var(--ink-muted); font-size: 11px; font-family: var(--font-mono, monospace); }
.cp-bar { fill: var(--accent); }
.cp-b-recon { fill: var(--info); } .cp-b-probe { fill: var(--warn); } .cp-b-exploit { fill: var(--danger); }
.cp-b-access { fill: #c026d3; } .cp-b-banned { fill: var(--ink-faint); }
.cp-badge { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; }
.cp-s-recon { background: var(--info); } .cp-s-probe { background: var(--warn); } .cp-s-exploit { background: var(--danger); }
.cp-s-access { background: #c026d3; } .cp-s-banned { background: var(--ink-faint); }
.cp-matrix { display: grid; grid-template-columns: repeat(calc(var(--n) + 1), minmax(0, 1fr)); gap: 2px; max-width: 640px; }
.cp-mh { font-size: .625rem; font-family: var(--font-mono, monospace); color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; align-self: center; }
.cp-mc { display: flex; align-items: center; justify-content: center; aspect-ratio: 1; min-height: 20px; border-radius: 3px; font-size: .625rem; color: var(--ink); background: var(--surface-sunken); }
.cp-lv1 { background: color-mix(in srgb, var(--accent) 22%, var(--surface-sunken)); }
.cp-lv2 { background: color-mix(in srgb, var(--accent) 42%, var(--surface-sunken)); }
.cp-lv3 { background: color-mix(in srgb, var(--accent) 65%, var(--surface-sunken)); }
.cp-lv4 { background: var(--accent); color: var(--on-accent); }
@media (max-width: 640px) { .cp-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+263
View File
@@ -0,0 +1,263 @@
/* Urutau - CAMPAIGNS page: sets of addresses doing the same thing. List (cards, activity
Gantt, similarity matrix) at #/campaigns and detail at #/campaigns/<id>.
Data: /api/v1/campaigns and /api/v1/campaigns/{id}. Hostile data: textContent only. */
(function () {
'use strict';
var NS = 'http://www.w3.org/2000/svg';
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="5" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="M11 7.5L6 15.5M13 7.5l5 8M7.5 18h9"/></svg>';
var ID_OK = /^[A-Za-z0-9_-]{1,64}$/;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
var t = U.t, nf = U.fmt.num;
function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); }
U.registerI18n({
en: {
'cp.title': 'Campaigns',
'cp.lead.one': '{n} campaign groups {k} IPs',
'cp.lead.other': '{n} campaigns group {k} IPs',
'cp.lead.body': 'Addresses that asked for the same things {range}.',
'cp.lead.empty': 'No campaign in this slice',
'cp.lead.emptyBody': 'No set of at least three addresses behaved alike {range}.',
'cp.detail.lead': 'Campaign {id} groups {k} IPs',
'cp.cards': 'Campaigns',
'cp.ips': 'IPs',
'cp.asns': 'ASNs',
'cp.ccs': 'Countries',
'cp.sessions': 'Sessions',
'cp.window': 'Window',
'cp.techs': 'Techniques',
'cp.sig': 'Signature',
'cp.tool': 'Tool',
'cp.open': 'Open',
'cp.gantt': 'Activity',
'cp.gantt.hint': 'When each campaign was active.',
'cp.matrix': 'Similarity',
'cp.matrix.hint': 'Share of addresses two campaigns have in common.',
'cp.members': 'Members',
'cp.timeline': 'Timeline',
'cp.timeline.hint': 'Sessions of each member.',
'cp.replay': 'Replay campaign',
'cp.back': 'All campaigns',
'cp.c.ip': 'Address',
'cp.c.first': 'First seen',
'cp.c.last': 'Last seen',
'cp.c.stage': 'Stage',
'cp.c.sessions': 'Sessions',
'cp.truncated': 'The study was cut short; the list may be incomplete.',
'cp.err': 'Could not load the campaigns.',
'cp.retry': 'Try again',
'cp.unknown': 'Campaign not found',
'cp.unknownBody': 'It is not in this slice. Widen the period or go back to the list.',
'cp.stage.recon': 'Recon',
'cp.stage.probe': 'Probe',
'cp.stage.exploit': 'Exploit',
'cp.stage.access': 'Access',
'cp.stage.banned': 'Banned',
'cp.more': '+{n} more'
},
'pt-BR': {
'cp.title': 'Campanhas',
'cp.lead.one': '{n} campanha agrupa {k} IPs',
'cp.lead.other': '{n} campanhas agrupam {k} IPs',
'cp.lead.body': 'Endereços que pediram as mesmas coisas {range}.',
'cp.lead.empty': 'Nenhuma campanha neste recorte',
'cp.lead.emptyBody': 'Nenhum conjunto de três ou mais endereços agiu igual {range}.',
'cp.detail.lead': 'A campanha {id} agrupa {k} IPs',
'cp.cards': 'Campanhas',
'cp.ips': 'IPs',
'cp.asns': 'ASNs',
'cp.ccs': 'Países',
'cp.sessions': 'Sessões',
'cp.window': 'Janela',
'cp.techs': 'Técnicas',
'cp.sig': 'Assinatura',
'cp.tool': 'Ferramenta',
'cp.open': 'Abrir',
'cp.gantt': 'Atividade',
'cp.gantt.hint': 'Quando cada campanha esteve ativa.',
'cp.matrix': 'Semelhança',
'cp.matrix.hint': 'Fração de endereços que duas campanhas têm em comum.',
'cp.members': 'Membros',
'cp.timeline': 'Linha do tempo',
'cp.timeline.hint': 'Sessões de cada membro.',
'cp.replay': 'Reproduzir campanha',
'cp.back': 'Todas as campanhas',
'cp.c.ip': 'Endereço',
'cp.c.first': 'Primeira vez',
'cp.c.last': 'Última vez',
'cp.c.stage': 'Estágio',
'cp.c.sessions': 'Sessões',
'cp.truncated': 'O estudo foi interrompido; a lista pode estar incompleta.',
'cp.err': 'Não foi possível carregar as campanhas.',
'cp.retry': 'Tentar de novo',
'cp.unknown': 'Campanha não encontrada',
'cp.unknownBody': 'Ela não está neste recorte. Amplie o período ou volte à lista.',
'cp.stage.recon': 'Reconhecimento',
'cp.stage.probe': 'Sondagem',
'cp.stage.exploit': 'Exploração',
'cp.stage.access': 'Acesso',
'cp.stage.banned': 'Banido',
'cp.more': '+{n} mais'
}
});
function sec(v) { var n = Date.parse(v); return isFinite(n) ? Math.floor(n / 1000) : 0; }
function iso(s) { return new Date(s * 1000).toISOString(); }
function stg(s) { return STAGES.indexOf(s) >= 0 ? s : 'recon'; }
function short(id) { return String(id).slice(0, 12); }
function replayHref(c) {
return '#/replay?campaign=' + encodeURIComponent(c.id) + '&from=' + encodeURIComponent(iso(sec(c.first) - 300)) + '&to=' + encodeURIComponent(iso(sec(c.last) + 300));
}
function ipLink(ip) { return h('a', { class: 'mono cp-ip', href: '#/ip/' + encodeURIComponent(ip), text: ip }); }
function chips(list, max) {
var box = h('span', 'cp-chips');
(list || []).slice(0, max).forEach(function (x) { box.appendChild(h('span', { class: 'cp-chip', text: x })); });
if ((list || []).length > max) box.appendChild(h('span', { class: 'cp-chip cp-more', text: t('cp.more', { n: list.length - max }) }));
return box;
}
function svg(tag, a) { var n = document.createElementNS(NS, tag); Object.keys(a || {}).forEach(function (k) { n.setAttribute(k, String(a[k])); }); return n; }
// rows: [{label, segs: [{a, b, cls}]}], span: [min, max]; one SVG, rows 22 px high
function gantt(rows, a, b, aria) {
var W = 720, L = 130, R = 8, RH = 22, H = rows.length * RH + 22, span = Math.max(1, b - a);
var s = svg('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': aria, class: 'cp-gantt' });
rows.forEach(function (r, i) {
var y = i * RH;
s.appendChild(svg('line', { x1: L, x2: W - R, y1: y + RH - 1, y2: y + RH - 1, class: 'cp-gl' }));
var lab = svg('text', { x: 0, y: y + 15, class: 'cp-gt' }); lab.textContent = r.label.length > 18 ? r.label.slice(0, 17) + '…' : r.label; s.appendChild(lab);
r.segs.forEach(function (g) {
var x = L + (g.a - a) / span * (W - L - R), w = Math.max(3, (g.b - g.a) / span * (W - L - R));
var rc = svg('rect', { x: x, y: y + 4, width: w, height: RH - 9, rx: 3, class: g.cls || 'cp-bar' });
var ti = svg('title'); ti.textContent = U.fmt.date(g.a) + ' → ' + U.fmt.date(g.b); rc.appendChild(ti);
s.appendChild(rc);
});
});
[0, 1].forEach(function (k) {
var x = svg('text', { x: k ? W - R : L, y: H - 6, 'text-anchor': k ? 'end' : 'start', class: 'cp-gt' }); x.textContent = U.fmt.date(k ? b : a); s.appendChild(x);
});
return h('div', 'cp-gwrap', s);
}
function jaccard(x, y) {
var m = {}, i = 0; x.forEach(function (v) { m[v] = 1; });
y.forEach(function (v) { if (m[v]) i++; });
var u = x.length + y.length - i; return u ? i / u : 0;
}
function matrix(cs) {
var list = cs.slice(0, 10), box = h('div', 'cp-matrix');
box.style.setProperty('--n', String(list.length));
box.appendChild(h('span', 'cp-mc'));
list.forEach(function (c) { box.appendChild(h('span', { class: 'cp-mh', text: short(c.id) })); });
list.forEach(function (a) {
box.appendChild(h('span', { class: 'cp-mh', text: short(a.id) }));
list.forEach(function (b) {
var j = jaccard(a.ips || [], b.ips || []), lv = j >= .8 ? 4 : j >= .5 ? 3 : j >= .25 ? 2 : j > 0 ? 1 : 0;
box.appendChild(h('span', { class: 'cp-mc cp-lv' + lv, title: short(a.id) + ' / ' + short(b.id) + ': ' + Math.round(j * 100) + '%', text: j > 0 ? String(Math.round(j * 100)) : '' }));
});
});
return box;
}
function stat(k, v) { return h('div', 'cp-st', h('span', { class: 'cp-sk', text: k }), h('b', { class: 'num', text: v })); }
var inst = null;
function Page(root, ctx) {
var self = this, seq = 0, alive = true, data = null, key = '';
this.ctx = ctx;
var wrap = h('div', 'cp');
root.appendChild(wrap);
function id() { var s = self.ctx.params && self.ctx.params.segments || []; return s[0] || ''; }
function load() {
var my = ++seq, cid = id(), path = cid ? '/api/v1/campaigns/' + encodeURIComponent(cid) : '/api/v1/campaigns';
if (cid && !ID_OK.test(cid)) { data = { missing: true }; paint(); return; }
U.api(path, Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) {
if (!alive || my !== seq) return; data = d; key = cid; paint();
}).catch(function (e) {
if (!alive || my !== seq) return;
if (e && e.status === 404 && cid) { data = { missing: true }; key = cid; paint(); return; }
if (data) return;
var b = h('button', { type: 'button', class: 'btn', text: t('cp.retry') });
b.addEventListener('click', load);
wrap.textContent = '';
wrap.appendChild(h('div', 'state-error', h('strong', { text: t('cp.err') }), b));
});
}
function paint() {
wrap.textContent = '';
if (!data) return;
if (id()) return detail();
var cs = data.campaigns || [], range = U.rangeLabel({ inline: true });
wrap.appendChild(cs.length ? U.ui.lead(U.pl('cp.lead', cs.length, { n: nf(data.total || cs.length), k: nf(data.ips_n || 0) }), t('cp.lead.body', { range: range }), 'danger')
: U.ui.lead(t('cp.lead.empty'), t('cp.lead.emptyBody', { range: range }), 'neutral'));
if (data.truncated) wrap.appendChild(h('p', { class: 'note', text: t('cp.truncated') }));
if (!cs.length) return;
var grid = h('div', 'cp-cards');
cs.slice(0, 60).forEach(function (c) {
var sg = c.signature || {};
grid.appendChild(h('article', 'cp-card',
h('header', null, h('a', { class: 'cp-id mono', href: '#/campaigns/' + encodeURIComponent(c.id), text: short(c.id) }),
h('span', { class: 'cp-win', text: U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)) })),
h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))),
h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 3)),
sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null,
(c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 4)) : null,
(c.ccs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.ccs') }), chips((c.ccs || []).map(function (x) { return (U.fmt.flag(x) + ' ' + x).trim(); }), 6)) : null,
h('footer', null, h('a', { class: 'btn', href: '#/campaigns/' + encodeURIComponent(c.id), text: t('cp.open') }),
h('a', { class: 'btn', href: replayHref(c), text: t('cp.replay') }))));
});
wrap.appendChild(U.ui.panel({ title: t('cp.cards'), help: 'term.campaign' }, grid));
var top = cs.slice(0, 15), mn = Infinity, mx = 0;
top.forEach(function (c) { mn = Math.min(mn, sec(c.first)); mx = Math.max(mx, sec(c.last)); });
wrap.appendChild(U.ui.panel({ title: t('cp.gantt'), hint: t('cp.gantt.hint') },
gantt(top.map(function (c) { return { label: short(c.id), segs: [{ a: sec(c.first), b: sec(c.last) }] }; }), mn, Math.max(mx, mn + 1), t('cp.gantt'))));
if (cs.length > 1) wrap.appendChild(U.ui.panel({ title: t('cp.matrix'), help: 'term.campaign', hint: t('cp.matrix.hint') }, matrix(cs)));
}
function detail() {
wrap.appendChild(h('a', { class: 'btn cp-back', href: U.href('campaigns'), text: '← ' + t('cp.back') }));
if (data.missing || !data.campaign) { wrap.appendChild(U.ui.empty(t('cp.unknown'), t('cp.unknownBody'))); return; }
var c = data.campaign, sg = c.signature || {};
wrap.appendChild(U.ui.lead(t('cp.detail.lead', { id: short(c.id), k: nf(c.ips_n || 0) }), U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)), 'danger'));
var head = h('div', 'cp-card cp-wide',
h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))),
h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 5)),
sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null,
(c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 8)) : null,
h('footer', null, h('a', { class: 'btn primary', href: replayHref(c), text: t('cp.replay') })));
wrap.appendChild(head);
var ms = data.members || [], tb = h('tbody');
ms.forEach(function (m) {
function td(l, k) { return h('td', { 'data-label': l }, k); }
tb.appendChild(h('tr', 'row', td(t('cp.c.ip'), ipLink(m.ip)),
td(t('cp.c.first'), h('span', { text: m.first ? U.fmt.date(m.first) : '' })), td(t('cp.c.last'), h('span', { text: m.last ? U.fmt.date(m.last) : '' })),
td(t('cp.c.stage'), m.stage ? h('span', { class: 'cp-badge cp-s-' + stg(m.stage), text: t('cp.stage.' + stg(m.stage)) }) : h('span')),
td(t('cp.c.sessions'), h('span', { class: 'num', text: (m.sessions || []).length ? nf(m.sessions.length) : '\u2013' }))));
});
var th = h('tr'); ['ip', 'first', 'last', 'stage', 'sessions'].forEach(function (k) { th.appendChild(h('th', { text: t('cp.c.' + k) })); });
wrap.appendChild(U.ui.panel({ title: t('cp.members') + ' (' + nf(ms.length) + ')' }, h('table', 'stack', h('thead', null, th), tb)));
var rows = [], mn = Infinity, mx = 0;
ms.slice(0, 40).forEach(function (m) {
var segs = (m.sessions || []).map(function (s) { var a = sec(s.start), b = sec(s.end); mn = Math.min(mn, a); mx = Math.max(mx, b); return { a: a, b: b, cls: 'cp-bar cp-b-' + stg(s.stage) }; });
if (segs.length) rows.push({ label: m.ip, segs: segs });
});
if (rows.length) wrap.appendChild(U.ui.panel({ title: t('cp.timeline'), hint: t('cp.timeline.hint') }, gantt(rows, mn, Math.max(mx, mn + 1), t('cp.timeline'))));
}
this.update = function (c) {
var lang = self.ctx.lang, prev = key; self.ctx = c;
if (lang !== c.lang && data) paint();
if (id() !== prev) data = null;
load();
};
this.refresh = function () { load(); };
this.destroy = function () { alive = false; seq++; root.textContent = ''; };
load();
}
U.registerPage({
id: 'campaigns', group: 'investigate', icon: ICON, titleKey: 'cp.title',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); },
update: function (ctx) { if (inst) inst.update(ctx); },
refresh: function () { if (inst) inst.refresh(); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
return true;
}
if (!boot()) document.addEventListener('DOMContentLoaded', boot);
})();
+20
View File
@@ -0,0 +1,20 @@
/* Concentration page */
.an-chart { min-width: 0; }
.an-svg { display: block; width: 100%; height: auto; max-width: 100%; overflow: visible; }
.an-svg .an-grid { stroke: var(--line); stroke-width: 1; }
.an-svg .an-guide { stroke: var(--warn); stroke-width: 1; stroke-dasharray: 4 4; }
.an-svg .an-line { fill: none; stroke: var(--accent); stroke-width: 2.25; stroke-linejoin: round; stroke-linecap: round; }
.an-svg .an-fill { fill: var(--accent); fill-opacity: .14; stroke: none; }
.an-svg .an-dot { fill: var(--accent); stroke: var(--surface-panel); stroke-width: 1.5; }
.an-svg .an-tick { fill: var(--ink-muted); font-size: 11px; }
.an-svg .an-strong { fill: var(--ink); font-weight: 600; }
.an-kpis { display: flex; flex-wrap: wrap; gap: var(--s-5); margin: 0 0 var(--s-3); }
.an-kpi { display: grid; }
.an-kpi-v { font: 600 1.5rem var(--font-display); font-variant-numeric: tabular-nums; color: var(--heading); }
.an-kpi-l { color: var(--ink-muted); font-size: .8125rem; }
.an-scroll { max-height: 420px; overflow: auto; }
.an-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.an-table th, .an-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; }
.an-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.an-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.an-table .an-key { overflow-wrap: anywhere; word-break: break-all; }
+208
View File
@@ -0,0 +1,208 @@
/* Urutau - CONCENTRACAO page: do a few sources generate most of the attacks?
Pareto curve with a dimension selector (IP, ASN, country, path, domain),
Gini coefficient, top 10 share and a donut of the top 5 against the rest.
Data: /api/v1/concentration. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var DIMS = ['ip', 'asn', 'country', 'path', 'domain'];
U.registerI18n({
en: {
'an.co.title': 'Concentration',
'an.co.lead': 'The top 10 {dim} generate {pct} of the attacks',
'an.co.lead.body': 'Gini {gini} across {distinct} distinct values, {n} malicious events {range}.',
'an.co.lead.empty': 'No malicious events to measure',
'an.co.lead.empty.body': 'Nothing was recorded {range}.',
'an.co.dim': 'Group by',
'an.co.dim.ip': 'IP',
'an.co.dim.asn': 'ASN',
'an.co.dim.country': 'country',
'an.co.dim.path': 'path',
'an.co.dim.domain': 'domain',
'an.co.curve': 'Pareto curve',
'an.co.curve.hint': 'Share of all events held by the top N, ranked from the heaviest.',
'an.co.x': 'Rank',
'an.co.y': 'Cumulative share',
'an.co.gini': 'Gini',
'an.co.top10': 'Top 10',
'an.co.donut': 'Top 5 and the rest',
'an.co.donut.hint': 'How the five heaviest compare with everything else.',
'an.co.rest': 'others',
'an.co.list': 'Ranking',
'an.co.list.hint': 'Up to the 200 heaviest, with the cumulative share.',
'an.co.total': 'events',
'an.co.off': 'The event registry is off',
'an.co.off.d': 'This analysis reads the event registry, which is not enabled on this instance.',
'an.co.err': 'Could not load this analysis.',
'an.co.retry': 'Try again'
},
'pt-BR': {
'an.co.title': 'Concentração',
'an.co.lead': 'Os 10 maiores por {dim} geram {pct} dos ataques',
'an.co.lead.body': 'Gini {gini} em {distinct} valores distintos, {n} eventos maliciosos {range}.',
'an.co.lead.empty': 'Sem eventos maliciosos para medir',
'an.co.lead.empty.body': 'Nada foi registrado {range}.',
'an.co.dim': 'Agrupar por',
'an.co.dim.ip': 'IP',
'an.co.dim.asn': 'ASN',
'an.co.dim.country': 'país',
'an.co.dim.path': 'caminho',
'an.co.dim.domain': 'domínio',
'an.co.curve': 'Curva de Pareto',
'an.co.curve.hint': 'Parcela de todos os eventos nas N primeiras posições, do mais pesado ao mais leve.',
'an.co.x': 'Posição',
'an.co.y': 'Parcela acumulada',
'an.co.gini': 'Gini',
'an.co.top10': 'Top 10',
'an.co.donut': 'Top 5 e o resto',
'an.co.donut.hint': 'Como os cinco mais pesados se comparam com todo o resto.',
'an.co.rest': 'outros',
'an.co.list': 'Ranking',
'an.co.list.hint': 'Até os 200 mais pesados, com a parcela acumulada.',
'an.co.total': 'eventos',
'an.co.off': 'O registro de eventos está desligado',
'an.co.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.',
'an.co.err': 'Não foi possível carregar esta análise.',
'an.co.retry': 'Tentar de novo'
}
});
function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function s(tag, attrs, kids) { var n = el(tag, attrs); (kids || []).forEach(function (k) { n.appendChild(k); }); return n; }
function itemLabel(dim, it) {
if (dim === 'country') return it.key ? U.fmt.flag(it.key) + ' ' + U.fmt.country(it.key) : it.key;
if (dim === 'asn' && it.label) return it.key + ' ' + it.label;
return it.key;
}
// Pareto line: x is the rank, y the cumulative share (0..100)
function pareto(items) {
var W = 640, H = 280, L = 44, R = 12, T = 12, B = 34, w = W - L - R, h = H - T - B, n = items.length;
var svg = s('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'an-svg', role: 'img', 'aria-label': t('an.co.curve'), preserveAspectRatio: 'xMidYMid meet' });
function X(i) { return L + (n <= 1 ? 0 : i / (n - 1)) * w; }
function Y(v) { return T + (1 - v / 100) * h; }
[0, 25, 50, 75, 100].forEach(function (v) {
svg.appendChild(el('line', { class: 'an-grid', x1: L, x2: W - R, y1: Y(v), y2: Y(v) }));
svg.appendChild(el('text', { class: 'an-tick', x: L - 6, y: Y(v) + 4, 'text-anchor': 'end' }, v + '%'));
});
[0, 0.5, 1].forEach(function (f) {
var i = Math.round(f * (n - 1));
svg.appendChild(el('text', { class: 'an-tick', x: X(i), y: H - 16, 'text-anchor': f === 0 ? 'start' : f === 1 ? 'end' : 'middle' }, String(i + 1)));
});
svg.appendChild(el('text', { class: 'an-tick', x: L + w / 2, y: H - 2, 'text-anchor': 'middle' }, t('an.co.x')));
svg.appendChild(el('line', { class: 'an-guide', x1: L, x2: W - R, y1: Y(80), y2: Y(80) }));
var pts = items.map(function (it, i) { return X(i).toFixed(1) + ',' + Y(it.cum_pct).toFixed(1); });
if (n > 0) {
svg.appendChild(el('polygon', { class: 'an-fill', points: X(0).toFixed(1) + ',' + Y(0) + ' ' + pts.join(' ') + ' ' + X(n - 1).toFixed(1) + ',' + Y(0) }));
svg.appendChild(el('polyline', { class: 'an-line', points: pts.join(' ') }));
items.forEach(function (it, i) {
if (n > 40 && i % Math.ceil(n / 40) && i !== n - 1) return;
svg.appendChild(el('circle', { class: 'an-dot', cx: X(i), cy: Y(it.cum_pct), r: 3 }, el('title', null, '#' + (i + 1) + ' ' + it.key + ': ' + it.cum_pct + '%')));
});
}
return el('div', { class: 'an-chart' }, svg);
}
var inst = null, dimSaved = 'ip';
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx, dim = dimSaved;
var grid = el('div', { class: 'grid-12 an-page' });
var lead = el('div', { class: 'span-12' });
var chips = el('div', { class: 'chip-group', role: 'group', 'aria-label': t('an.co.dim') });
var btns = {};
DIMS.forEach(function (d) {
var b = el('button', { type: 'button', class: 'chip-btn', 'aria-pressed': d === dim ? 'true' : 'false' }, t('an.co.dim.' + d));
b.addEventListener('click', function () {
if (dim === d) return;
dim = dimSaved = d; data = null;
DIMS.forEach(function (x) { btns[x].setAttribute('aria-pressed', x === d ? 'true' : 'false'); });
load();
});
btns[d] = b; chips.appendChild(b);
});
var curve = U.ui.panel({ title: t('an.co.curve'), hint: t('an.co.curve.hint'), variant: 'chart', loading: true, actions: chips });
tip(curve, 'term.pareto');
var donut = U.ui.panel({ title: t('an.co.donut'), hint: t('an.co.donut.hint'), loading: true });
var list = U.ui.panel({ title: t('an.co.list'), hint: t('an.co.list.hint'), loading: true });
var kpis = el('div', { class: 'an-kpis' });
grid.appendChild(lead);
grid.appendChild(curve); curve.classList.add('span-8');
grid.appendChild(donut); donut.classList.add('span-4');
grid.appendChild(list); list.classList.add('span-12');
root.appendChild(grid);
function paint() {
clear(lead); [curve, donut, list].forEach(function (p) { clear(p.body); });
if (!data) return;
if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.co.off'), t('an.co.off.d'))); return; }
var d = data, range = U.rangeLabel({ inline: true }), dname = t('an.co.dim.' + d.dim);
if (!d.total) {
lead.appendChild(U.ui.lead(t('an.co.lead.empty'), t('an.co.lead.empty.body', { range: range }), 'neutral'));
curve.body.appendChild(U.ui.empty(t('charts.empty')));
donut.body.appendChild(U.ui.empty(t('charts.empty')));
list.body.appendChild(U.ui.empty(t('charts.empty')));
return;
}
lead.appendChild(U.ui.lead(t('an.co.lead', { dim: dname, pct: U.fmt.pct(d.top10_pct / 100) }),
t('an.co.lead.body', { gini: d.gini.toFixed(2), distinct: U.fmt.num(d.distinct), n: U.fmt.num(d.total), range: range }), 'neutral'));
kpis = el('div', { class: 'an-kpis' },
el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, d.gini.toFixed(2)), el('span', { class: 'an-kpi-l' }, t('an.co.gini'), ' ', (function () { var w = el('span'); U.help && U.help(w, 'term.gini'); return w; })())),
el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, U.fmt.pct(d.top10_pct / 100)), el('span', { class: 'an-kpi-l' }, t('an.co.top10'))));
curve.body.appendChild(kpis);
curve.body.appendChild(pareto(d.items));
var top5 = d.items.slice(0, 5), used = 0;
var rows = top5.map(function (it) { used += it.n; return { key: it.key, label: itemLabel(d.dim, it), value: it.n }; });
if (d.total > used) rows.push({ key: '_rest', label: t('an.co.rest'), value: d.total - used });
donut.body.appendChild(U.charts.donut(rows, { title: t('an.co.donut'), centerLabel: t('an.co.total'), colors: ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-8'] }));
var tbl = el('table', { class: 'an-table' });
tbl.appendChild(el('thead', null, el('tr', null, el('th', null, '#'), el('th', null, t('an.co.dim.' + d.dim)), el('th', { class: 'num' }, t('an.co.total')), el('th', { class: 'num' }, t('an.co.y')))));
var tb = el('tbody');
d.items.forEach(function (it, i) {
var cell = el('td', { class: 'an-key mono' });
if (d.dim === 'ip') {
var a = el('a', { href: '#/ip/' + encodeURIComponent(it.key) }, it.key);
cell.appendChild(a);
} else cell.textContent = itemLabel(d.dim, it);
tb.appendChild(el('tr', null, el('td', { class: 'num' }, String(i + 1)), cell, el('td', { class: 'num' }, U.fmt.num(it.n)), el('td', { class: 'num' }, it.cum_pct.toFixed(1) + '%')));
});
tbl.appendChild(tb);
list.body.appendChild(el('div', { class: 'an-scroll' }, tbl));
}
function load() {
var my = ++seq;
var p = Object.assign({ dim: dim }, U.rangeParams());
if (c.host && c.host !== 'all') p.host = c.host;
U.api('/api/v1/concentration', p).then(function (r) {
if (!alive || my !== seq) return;
data = r; paint();
}, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('an.co.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.co.err')), b));
});
}
load();
return {
root: root, lang: ctx.lang,
update: function (cx) { c = cx; load(); },
destroy: function () { alive = false; seq++; clear(root); }
};
}
U.registerPage({
id: 'concentration', group: 'analyze', titleKey: 'an.co.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 20V4"/><path d="M4 20h16"/><path d="M4 6c6 0 9 4 16 4"/></svg>',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); },
update: function (ctx) {
ctx = ctx || {};
if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx);
},
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+5
View File
@@ -0,0 +1,5 @@
/* Defense page */
.df-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.df-kpis .card-metric { min-width: 0; }
.df-sum { padding: 0 0 8px; }
.df-bl { color: var(--ink-muted); font-size: .875rem; margin: 4px 0 12px; overflow-wrap: anywhere; }
+201
View File
@@ -0,0 +1,201 @@
/* Urutau - DEFENSE page: is fail2ban acting? Bans over time per jail, time to
ban, blocklist coverage, leak and the SSH users tried. Data:
/api/v1/defense. Log data is hostile: dynamic text goes through textContent
only. */
(function () {
'use strict';
var MAX_BUCKETS = 400;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'df.title': 'Defense',
'df.lead.some': 'fail2ban applied {n} bans {range}',
'df.lead.sub.ok': '{a} bans are active. Few attackers kept arriving after being banned.',
'df.lead.sub.leak': '{a} bans are active, but {l} attackers kept arriving after a ban or listing.',
'df.lead.none': 'fail2ban did not ban anyone {range}',
'df.lead.none.sub': 'No ban events in this window. If attacks were seen, check that the fail2ban log is being read.',
'df.kpi.active': 'Active bans',
'df.kpi.active.sub': '{n} bans in the window',
'df.kpi.ttb': 'Time to ban',
'df.kpi.ttb.sub': 'median per attack episode; 90% within {p}',
'df.kpi.ttb.none': 'no data',
'df.kpi.cov': 'Blocklist coverage',
'df.kpi.cov.sub': '{n} addresses listed',
'df.kpi.leak': 'Leak',
'df.kpi.leak.sub': '{n} events after the ban',
'df.bans': 'Bans per jail over time',
'df.jails': 'Bans by jail',
'df.jails.center': 'bans',
'df.users': 'SSH users tried',
'df.users.hint': 'Names attackers tried to log in with. Red: a real account of yours.',
'df.users.none': 'No SSH failures in this window.',
'df.ssh.sum': '{f} failures from {s} sources; {o} successful logins after failures.',
'df.cov': 'Blocklist coverage',
'df.cov.hint': 'Share of the attackers of the window that are in the blocklist.',
'df.cov.label': 'of attackers listed',
'df.bl.size': '{n} addresses ({v4} IPv4, {v6} IPv6 /64)',
'df.bl.updated': 'last change {t}',
'df.bl.download': 'Download blocklist',
'df.error': 'Could not load the defense data.',
'df.disabled': 'The event registry is off',
'df.disabled.sub': 'Defense is computed from the event registry; enable it to see this page.',
'df.partial': 'Partial result: the study hit its time or size limit.',
'df.admin': 'your account'
},
'pt-BR': {
'df.title': 'Defesa',
'df.lead.some': 'O fail2ban aplicou {n} bans {range}',
'df.lead.sub.ok': '{a} bans estão ativos. Poucos atacantes continuaram chegando depois do ban.',
'df.lead.sub.leak': '{a} bans estão ativos, mas {l} atacantes continuaram chegando depois de um ban ou da listagem.',
'df.lead.none': 'O fail2ban não baniu ninguém {range}',
'df.lead.none.sub': 'Nenhum evento de ban nesta janela. Se houve ataques, confira se o log do fail2ban está sendo lido.',
'df.kpi.active': 'Bans ativos',
'df.kpi.active.sub': '{n} bans na janela',
'df.kpi.ttb': 'Tempo até o ban',
'df.kpi.ttb.sub': 'mediana por episódio de ataque; 90% em até {p}',
'df.kpi.ttb.none': 'sem dados',
'df.kpi.cov': 'Cobertura da blocklist',
'df.kpi.cov.sub': '{n} endereços listados',
'df.kpi.leak': 'Vazamento',
'df.kpi.leak.sub': '{n} eventos depois do ban',
'df.bans': 'Bans por jail ao longo do tempo',
'df.jails': 'Bans por jail',
'df.jails.center': 'bans',
'df.users': 'Usuários SSH tentados',
'df.users.hint': 'Nomes com que os atacantes tentaram entrar. Vermelho: uma conta real sua.',
'df.users.none': 'Nenhuma falha de SSH nesta janela.',
'df.ssh.sum': '{f} falhas de {s} origens; {o} logins bem-sucedidos depois de falhas.',
'df.cov': 'Cobertura da blocklist',
'df.cov.hint': 'Parcela dos atacantes da janela que está na blocklist.',
'df.cov.label': 'dos atacantes listados',
'df.bl.size': '{n} endereços ({v4} IPv4, {v6} IPv6 /64)',
'df.bl.updated': 'última alteração {t}',
'df.bl.download': 'Baixar a blocklist',
'df.error': 'Não foi possível carregar os dados de defesa.',
'df.disabled': 'O registro de eventos está desligado',
'df.disabled.sub': 'A defesa é calculada a partir do registro de eventos; ative-o para ver esta página.',
'df.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.',
'df.admin': 'sua conta'
}
});
var el = U.el, t = U.t, nf = U.fmt.num;
var root = null, seq = 0, alive = false, ctx = null, data = null;
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function dur(s) {
s = Math.round(s);
if (s < 60) return s + ' s';
if (s < 3600) return Math.round(s / 60) + ' min';
if (s < 86400) return (s / 3600).toFixed(s < 36000 ? 1 : 0).replace(/\.0$/, '') + ' h';
return (s / 86400).toFixed(1).replace(/\.0$/, '') + ' d';
}
function pctTxt(v) { return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; }
function series(d) {
var step = d.step || 3600, from = d.from || 0;
var end = Math.max(ctx && ctx.to ? ctx.to : Math.floor(Date.now() / 1000), 0);
(d.bans || []).forEach(function (b) { if (b.t > end) end = b.t; });
var n = Math.min(MAX_BUCKETS, Math.floor((end - from) / step) + 1);
if (n < 2) n = 2;
var start = from;
if (Math.floor((end - from) / step) + 1 > MAX_BUCKETS) start = Math.floor(end / step) * step - (MAX_BUCKETS - 1) * step;
var jails = {}, order = [];
(d.by_jail || []).forEach(function (j) { jails[j.jail] = new Array(n).fill(0); order.push(j.jail); });
(d.bans || []).forEach(function (b) {
var i = Math.round((b.t - start) / step);
if (i < 0 || i >= n) return;
if (!jails[b.jail]) { jails[b.jail] = new Array(n).fill(0); order.push(b.jail); }
jails[b.jail][i] += b.n;
});
return { step: step, start: start, list: order.map(function (j) { return { key: j, label: j, values: jails[j] }; }) };
}
function paint() {
if (!root) return;
clear(root);
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
if (!data.enabled) { root.appendChild(U.ui.empty(t('df.disabled'), t('df.disabled.sub'))); return; }
var d = data, range = U.rangeLabel({ inline: true }), leak = d.leak || { ips: 0, events: 0 };
var bl = d.blocklist || {}, ssh = d.ssh || { users: [] }, ttb = d.ttb || {};
if (d.bans_total > 0) {
var bad = leak.ips > 0 && leak.ips * 4 > d.bans_total;
root.appendChild(U.ui.lead(t('df.lead.some', { n: nf(d.bans_total), range: range }),
leak.ips > 0 ? t('df.lead.sub.leak', { a: nf(d.bans_active), l: nf(leak.ips) }) : t('df.lead.sub.ok', { a: nf(d.bans_active) }), bad ? 'danger' : 'ok'));
} else {
root.appendChild(U.ui.lead(t('df.lead.none', { range: range }), t('df.lead.none.sub'), 'danger'));
}
if (d.truncated) root.appendChild(el('p', { class: 'hint' }, t('df.partial')));
var kp = el('div', { class: 'grid-12 df-kpis' });
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
k(U.ui.metric(t('df.kpi.active'), nf(d.bans_active), { sub: t('df.kpi.active.sub', { n: nf(d.bans_total) }) }));
k(U.ui.metric(t('df.kpi.ttb'), ttb.n ? dur(ttb.median_s) : t('df.kpi.ttb.none'), ttb.n ? { sub: t('df.kpi.ttb.sub', { p: dur(ttb.p90_s) }) } : {}));
var cov = bl.coverage_pct || 0;
k(U.ui.metric(t('df.kpi.cov'), pctTxt(cov), { sub: t('df.kpi.cov.sub', { n: nf(bl.size || 0) }), tone: cov >= 70 ? 'ok' : cov >= 40 ? 'warn' : 'danger' }));
k(U.ui.metric(t('df.kpi.leak'), nf(leak.ips), { sub: t('df.kpi.leak.sub', { n: nf(leak.events) }), tone: leak.ips ? 'warn' : 'ok' }));
root.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
var sr = series(d);
var ap = U.ui.panel({ title: t('df.bans'), cls: 'span-8' });
if (U.charts && U.charts.stackedArea && sr.list.length) ap.body.appendChild(U.charts.stackedArea(sr.list, sr.step, { start: sr.start, title: t('df.bans') }));
else ap.body.appendChild(U.ui.empty(t('df.lead.none', { range: range })));
grid.appendChild(ap);
var jp = U.ui.panel({ title: t('df.jails'), cls: 'span-4' });
var jd = (d.by_jail || []).filter(function (j) { return j.total > 0; }).map(function (j) { return { key: j.jail, label: j.jail, value: j.total }; });
if (U.charts && U.charts.donut) jp.body.appendChild(U.charts.donut(jd, { title: t('df.jails'), centerLabel: t('df.jails.center'), format: nf }));
grid.appendChild(jp);
var up = U.ui.panel({ title: t('df.users'), hint: t('df.users.hint'), cls: 'span-8' });
var users = ssh.users || [];
if (!users.length) up.body.appendChild(U.ui.empty(t('df.users.none')));
else {
up.body.appendChild(el('p', { class: 'hint df-sum' }, t('df.ssh.sum', { f: nf(ssh.fails), s: nf(ssh.sources), o: nf(ssh.ok_after_fail) })));
var rows = users.slice(0, 15).map(function (u) {
var lit = u.user === 'admin' || u.user === 'root';
return { key: u.user, label: u.admin ? u.user + ' (' + t('df.admin') + ')' : u.user, value: u.n, color: u.admin ? '--danger' : lit ? '--warn' : '--viz-1' };
});
if (U.charts && U.charts.bars) up.body.appendChild(U.charts.bars(rows, { title: t('df.users'), format: nf }));
}
grid.appendChild(up);
var gp = U.ui.panel({ title: t('df.cov'), hint: t('df.cov.hint'), cls: 'span-4' });
if (U.charts && U.charts.gauge) gp.body.appendChild(U.charts.gauge(Math.round(cov), 100, [{ at: 0, tone: 'danger' }, { at: 40, tone: 'warn' }, { at: 70, tone: 'ok' }], { label: t('df.cov.label'), format: function (v) { return v + '%'; } }));
gp.body.appendChild(el('p', { class: 'df-bl' }, t('df.bl.size', { n: nf(bl.size || 0), v4: nf(bl.v4 || 0), v6: nf(bl.v6 || 0) }) + (bl.updated ? ' · ' + t('df.bl.updated', { t: U.fmt.ago(bl.updated) }) : '')));
gp.body.appendChild(el('a', { class: 'btn', href: '/api/v1/blocklist.txt?download=1&range=7d', download: 'urutau-blocklist.txt' }, t('df.bl.download')));
grid.appendChild(gp);
root.appendChild(grid);
}
function load() {
var my = ++seq;
U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(root);
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.error'))));
});
}
U.registerPage({
id: 'defense', group: 'operate', titleKey: 'df.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+10
View File
@@ -0,0 +1,10 @@
/* Errors page */
.hl-scroll { max-height: 420px; overflow: auto; }
.hl-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.hl-table th, .hl-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; }
.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.hl-page .panel { min-width: 0; }
@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } }
.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); }
.hl-help { display: inline-flex; align-items: center; gap: 4px; }
+146
View File
@@ -0,0 +1,146 @@
/* Urutau - page ERRORS ("where do the errors come from"): splits every 4xx/5xx into
frustrated attacks, proxy trouble, real application errors, bots and client mistakes.
Data: /api/v1/errors. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var ORDER = ['app', 'proxy', 'blocked', 'attack', 'bot', 'client_broken', 'client_auth', 'client_other'];
var COLOR = { app: '--danger', proxy: '--warn', blocked: '--info', attack: '--cat-exploit', bot: '--viz-6', client_broken: '--viz-2', client_auth: '--viz-4', client_other: '--ink-muted' };
U.registerI18n({
en: {
'hl.er.title': 'Where errors come from',
'hl.er.lead': '{n} errors; {atk} frustrated attacks, {app} real application errors',
'hl.er.lead.body': 'Of {req} requests {range}, {proxy} of the errors are proxy trouble and {bot} come from crawlers. Server error rate (application + proxy over legitimate requests, client cancellations excluded): {rate}. Data from this instance ({inst}) only.',
'hl.er.lead.empty': 'No errors recorded',
'hl.er.lead.empty.body': 'No 4xx or 5xx answers {range}, or the log has no origin fields yet.',
'hl.cls.app': 'Application', 'hl.cls.proxy': 'Proxy / network', 'hl.cls.blocked': 'Blocked by rule', 'hl.cls.attack': 'Attack',
'hl.cls.bot': 'Crawlers', 'hl.cls.client_broken': 'Broken links', 'hl.cls.client_auth': 'Authentication', 'hl.cls.client_other': 'Other client errors',
'hl.er.donut': 'Error classes', 'hl.er.donut.hint': 'Application and proxy errors are yours to fix; attacks and blocks mean the defences worked.',
'hl.er.total': 'errors',
'hl.er.time': 'Errors over time', 'hl.er.time.hint': 'Hourly, stacked by class.',
'hl.er.heat': 'Application errors by service and hour', 'hl.er.heat.hint': 'Only answers the backend itself failed (5xx from the origin).',
'hl.er.broken': 'Broken links', 'hl.er.broken.hint': 'Pages that answered 404 to a visitor who clicked a link. Fix the link or add a redirect.',
'hl.er.routes': 'Routes with the most errors', 'hl.er.routes.hint': 'Method and path (ids folded), by service and class.',
'hl.er.col.path': 'Missing path', 'hl.er.col.ref': 'Came from', 'hl.er.col.n': 'Hits', 'hl.er.col.last': 'Last',
'hl.er.col.svc': 'Service', 'hl.er.col.route': 'Route', 'hl.er.col.class': 'Class',
'hl.er.err': 'Could not load the error breakdown.', 'hl.er.retry': 'Try again',
'hl.er.empty': 'Nothing to show for this range.'
},
'pt-BR': {
'hl.er.title': 'De onde vêm os erros',
'hl.er.lead': '{n} erros; {atk} ataques frustrados, {app} erros reais de aplicação',
'hl.er.lead.body': 'De {req} requisições {range}, {proxy} dos erros são problema de proxy e {bot} vêm de rastreadores. Taxa de erro do servidor (aplicação + proxy sobre as requisições legítimas, sem cancelamentos do cliente): {rate}. Dados só desta instância ({inst}).',
'hl.er.lead.empty': 'Nenhum erro registrado',
'hl.er.lead.empty.body': 'Nenhuma resposta 4xx ou 5xx {range}, ou o log ainda não tem os campos de origem.',
'hl.cls.app': 'Aplicação', 'hl.cls.proxy': 'Proxy / rede', 'hl.cls.blocked': 'Bloqueado por regra', 'hl.cls.attack': 'Ataque',
'hl.cls.bot': 'Rastreadores', 'hl.cls.client_broken': 'Links quebrados', 'hl.cls.client_auth': 'Autenticação', 'hl.cls.client_other': 'Outros erros do cliente',
'hl.er.donut': 'Classes de erro', 'hl.er.donut.hint': 'Erros de aplicação e de proxy são seus para corrigir; ataques e bloqueios mostram que a defesa funcionou.',
'hl.er.total': 'erros',
'hl.er.time': 'Erros no tempo', 'hl.er.time.hint': 'Por hora, empilhados por classe.',
'hl.er.heat': 'Erros de aplicação por serviço e hora', 'hl.er.heat.hint': 'Só respostas em que o próprio backend falhou (5xx da origem).',
'hl.er.broken': 'Links quebrados', 'hl.er.broken.hint': 'Páginas que deram 404 para quem clicou num link. Corrija o link ou crie um redirecionamento.',
'hl.er.routes': 'Rotas com mais erros', 'hl.er.routes.hint': 'Método e caminho (ids agrupados), por serviço e classe.',
'hl.er.col.path': 'Caminho ausente', 'hl.er.col.ref': 'Veio de', 'hl.er.col.n': 'Acessos', 'hl.er.col.last': 'Último',
'hl.er.col.svc': 'Serviço', 'hl.er.col.route': 'Rota', 'hl.er.col.class': 'Classe',
'hl.er.err': 'Não foi possível carregar o detalhamento dos erros.', 'hl.er.retry': 'Tentar de novo',
'hl.er.empty': 'Nada para mostrar neste período.'
}
});
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function pctOf(a, b) { return b > 0 ? U.fmt.pct(a / b) : '0%'; }
function table(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function clock(ts) { return U.fmt.clock ? U.fmt.clock(ts) : String(ts); }
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 hl-page' });
var lead = el('div', { class: 'span-12' });
var pd = U.ui.panel({ title: t('hl.er.donut'), hint: t('hl.er.donut.hint'), loading: true, cls: 'span-4' });
var pt = U.ui.panel({ title: t('hl.er.time'), hint: t('hl.er.time.hint'), variant: 'chart', loading: true, cls: 'span-8' });
var ph = U.ui.panel({ title: t('hl.er.heat'), hint: t('hl.er.heat.hint'), variant: 'chart', loading: true, cls: 'span-12' });
var pb = U.ui.panel({ title: t('hl.er.broken'), hint: t('hl.er.broken.hint'), variant: 'list', loading: true, cls: 'span-6' });
var pr = U.ui.panel({ title: t('hl.er.routes'), hint: t('hl.er.routes.hint'), variant: 'list', loading: true, cls: 'span-6' });
[lead, pd, pt, ph, pb, pr].forEach(function (n) { grid.appendChild(n); });
root.appendChild(grid);
function chart(fn, args, host) {
if (U.charts && U.charts[fn]) host.appendChild(U.charts[fn].apply(null, args));
else host.appendChild(U.ui.empty(t('hl.er.empty')));
}
function paint() {
clear(lead); [pd, pt, ph, pb, pr].forEach(function (p) { clear(p.body); });
if (!data) return;
var d = data, cl = d.classes || {}, range = U.rangeLabel({ inline: true });
if (!d.errors) {
lead.appendChild(U.ui.lead(t('hl.er.lead.empty'), t('hl.er.lead.empty.body', { range: range }), 'neutral'));
[pd, pt, ph, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.er.empty'))); });
return;
}
lead.appendChild(U.ui.lead(t('hl.er.lead', { n: U.fmt.num(d.errors), atk: pctOf(cl.attack, d.errors), app: pctOf(cl.app, d.errors) }),
t('hl.er.lead.body', { req: U.fmt.num(d.requests), range: range, proxy: pctOf(cl.proxy, d.errors), bot: pctOf(cl.bot, d.errors), rate: U.fmt.pct(d.app_error_rate || 0), inst: d.instance || '' }),
(cl.app || 0) > (cl.attack || 0) ? 'warn' : 'neutral'));
var main = ['app', 'proxy', 'blocked', 'attack', 'bot'].map(function (k) { return { key: k, label: t('hl.cls.' + k), value: cl[k] || 0 }; });
main.push({ key: 'client', label: t('hl.cls.client_other'), value: cl.client || 0 });
chart('donut', [main, { title: t('hl.er.donut'), centerLabel: t('hl.er.total') }], pd.body);
if (U.help && U.glossary) {
var lis = pd.body.querySelectorAll('.vz-legend li');
['app', 'proxy', 'blocked', 'attack', 'bot', 'client'].forEach(function (k, i) {
if (lis[i] && U.glossary.has('term.error_class.' + k)) U.help(lis[i], 'term.error_class.' + k);
});
}
var series = ORDER.map(function (k) { return { key: k, label: t('hl.cls.' + k), values: (d.timeline.series[k] || []) }; });
chart('stackedArea', [series, d.timeline.step, { start: d.timeline.start, title: t('hl.er.time') }], pt.body);
var hm = d.heatmap || {};
if ((hm.svcs || []).length && (hm.hours || []).length) {
var xl = hm.hours.map(function (h) { return new Date(h * 1000).getHours() + 'h'; });
var seen = {}, yl = hm.svcs.map(function (n) {
var b = String(n).split('.')[0].slice(0, 8) || n; seen[b] = (seen[b] || 0) + 1;
return seen[b] > 1 ? b + seen[b] : b;
});
chart('heatmap', [hm.err, xl, yl, { title: t('hl.er.heat') }], ph.body);
} else ph.body.appendChild(U.ui.empty(t('hl.er.empty')));
var br = d.broken || [];
if (U.help && U.glossary && U.glossary.has('term.broken_link')) U.help(pb.querySelector('h2'), 'term.broken_link');
if (br.length) pb.body.appendChild(table([{ label: t('hl.er.col.path'), cls: 'mono' }, { label: t('hl.er.col.ref'), cls: 'mono' }, { label: t('hl.er.col.n'), cls: 'num' }, { label: t('hl.er.col.last') }],
br.map(function (b) { return [b.path, b.ref, U.fmt.num(b.n), b.last ? U.fmt.ago(b.last) : '']; })));
else pb.body.appendChild(U.ui.empty(t('hl.er.empty')));
var tr = d.top_routes || [];
if (tr.length) pr.body.appendChild(table([{ label: t('hl.er.col.svc') }, { label: t('hl.er.col.route'), cls: 'mono' }, { label: t('hl.er.col.class') }, { label: t('hl.er.col.n'), cls: 'num' }],
tr.map(function (r) { return [r.svc, r.route, (/^(app|proxy|blocked|attack|bot)$/.test(r.class) ? t('hl.cls.' + r.class) : t('hl.cls.client_other')), U.fmt.num(r.n)]; })));
else pr.body.appendChild(U.ui.empty(t('hl.er.empty')));
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.host && c.host !== 'all') p.host = c.host;
if (c.domain && c.domain !== 'all') p.host = c.domain;
U.api('/api/v1/errors', p).then(function (r) { if (alive && my === seq) { data = r; paint(); } }, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('hl.er.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.er.err')), b));
});
}
load();
return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } };
}
U.registerPage({
id: 'errors', group: 'analyze', titleKey: 'hl.er.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l9 16H3z"/><path d="M12 10v4"/><path d="M12 17h.01"/></svg>',
mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+9
View File
@@ -0,0 +1,9 @@
/* Evolution page (shared helpers .an-* live here: this file loads with the page set) */
.an-page .an-muted { color: var(--ink-muted); margin: 0; }
.an-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
.an-list li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 4px 0; border-bottom: 1px solid var(--line); min-width: 0; }
.an-list li:last-child { border-bottom: 0; }
.an-list .an-k, .an-list a { overflow-wrap: anywhere; min-width: 0; }
.an-list .an-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); white-space: nowrap; }
.an-list .an-bad { color: var(--danger); }
.an-list .an-good { color: var(--ok); }
+158
View File
@@ -0,0 +1,158 @@
/* Urutau - EVOLUCAO page: are we getting better or worse? Daily stacked area by
attack family, weekday x hour heatmap, families that appeared or vanished and
the change against the previous period. Data: /api/v1/evolution. Log data is
hostile: every string goes through textContent (Urutau.el). */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
U.registerI18n({
en: {
'an.ev.title': 'Evolution',
'an.ev.lead.better': 'Getting better: {pct} fewer attacks',
'an.ev.lead.worse': 'Getting worse: {pct} more attacks',
'an.ev.lead.same': 'Holding steady against the previous period',
'an.ev.lead.none': 'No previous period to compare',
'an.ev.lead.body': '{n} malicious events {range}, against {prev} in the period before.',
'an.ev.area': 'Attacks per day, by family',
'an.ev.area.hint': 'The seven busiest families; the rest are grouped as "other".',
'an.ev.heat': 'When do they come? (UTC)',
'an.ev.heat.hint': 'Malicious events by weekday and hour of the day.',
'an.ev.new': 'Appeared',
'an.ev.new.hint': 'Families seen now that did not exist in the previous period.',
'an.ev.gone': 'Vanished',
'an.ev.gone.hint': 'Families of the previous period that did not come back.',
'an.ev.none': 'None',
'an.ev.nocmp': 'There is no previous period with events to compare against.',
'an.ev.other': 'other',
'an.ev.off': 'The event registry is off',
'an.ev.off.d': 'This analysis reads the event registry, which is not enabled on this instance.',
'an.ev.err': 'Could not load this analysis.',
'an.ev.retry': 'Try again'
},
'pt-BR': {
'an.ev.title': 'Evolução',
'an.ev.lead.better': 'Melhorando: {pct} menos ataques',
'an.ev.lead.worse': 'Piorando: {pct} mais ataques',
'an.ev.lead.same': 'Estável em relação ao período anterior',
'an.ev.lead.none': 'Sem período anterior para comparar',
'an.ev.lead.body': '{n} eventos maliciosos {range}, contra {prev} no período anterior.',
'an.ev.area': 'Ataques por dia, por família',
'an.ev.area.hint': 'As sete famílias mais ativas; as demais ficam em "outras".',
'an.ev.heat': 'Quando eles vêm? (UTC)',
'an.ev.heat.hint': 'Eventos maliciosos por dia da semana e hora do dia.',
'an.ev.new': 'Surgiram',
'an.ev.new.hint': 'Famílias vistas agora que não existiam no período anterior.',
'an.ev.gone': 'Sumiram',
'an.ev.gone.hint': 'Famílias do período anterior que não voltaram.',
'an.ev.none': 'Nenhuma',
'an.ev.nocmp': 'Não há período anterior com eventos para comparar.',
'an.ev.other': 'outras',
'an.ev.off': 'O registro de eventos está desligado',
'an.ev.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.',
'an.ev.err': 'Não foi possível carregar esta análise.',
'an.ev.retry': 'Tentar de novo'
}
});
function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function params(ctx) {
var p = Object.assign({}, U.rangeParams());
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
return p;
}
function famList(rows, tone) {
if (!rows || !rows.length) return el('p', { class: 'an-muted' }, t('an.ev.none'));
var ul = el('ul', { class: 'an-list' });
rows.slice(0, 10).forEach(function (r) {
ul.appendChild(el('li', null, el('span', { class: 'an-k mono' }, r.fam), el('span', { class: 'an-n an-' + tone }, U.fmt.num(r.n))));
});
return ul;
}
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, lang = ctx.lang, c = ctx;
var grid = el('div', { class: 'grid-12 an-page' });
var lead = el('div', { class: 'span-12' });
var area = U.ui.panel({ title: t('an.ev.area'), hint: t('an.ev.area.hint'), variant: 'chart', loading: true });
var heat = U.ui.panel({ title: t('an.ev.heat'), hint: t('an.ev.heat.hint'), loading: true });
var nw = U.ui.panel({ title: t('an.ev.new'), hint: t('an.ev.new.hint'), loading: true });
var gone = U.ui.panel({ title: t('an.ev.gone'), hint: t('an.ev.gone.hint'), loading: true });
tip(area, 'metric.attacks_per_hour_24h');
[lead, area, heat, nw, gone].forEach(function (n, i) { grid.appendChild(n); if (i) n.classList.add(i === 1 ? 'span-12' : i === 2 ? 'span-12' : 'span-6'); });
root.appendChild(grid);
function paint() {
clear(lead); [area, heat, nw, gone].forEach(function (p) { clear(p.body); });
if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.ev.off'), t('an.ev.off.d'))); return; }
var d = data, pct = d.delta_pct, title, tone = 'neutral';
if (pct === null || pct === undefined) title = t('an.ev.lead.none');
else if (Math.abs(pct) < 5) title = t('an.ev.lead.same');
else if (pct < 0) { title = t('an.ev.lead.better', { pct: Math.abs(Math.round(pct)) + '%' }); tone = 'ok'; }
else { title = t('an.ev.lead.worse', { pct: Math.round(pct) + '%' }); tone = 'danger'; }
lead.appendChild(U.ui.lead(title, t('an.ev.lead.body', { n: U.fmt.num(d.total), range: U.rangeLabel({ inline: true }), prev: U.fmt.num(d.prev) }), tone));
// area: top 7 families + other
var tot = {};
d.days.forEach(function (x) { Object.keys(x.by_fam || {}).forEach(function (f) { tot[f] = (tot[f] || 0) + x.by_fam[f]; }); });
var top = Object.keys(tot).filter(function (f) { return f !== 'other'; }).sort(function (a, b) { return tot[b] - tot[a]; }).slice(0, 7);
var series = top.map(function (f) { return { key: f, label: f, values: d.days.map(function (x) { return (x.by_fam || {})[f] || 0; }) }; });
var rest = d.days.map(function (x) {
var s = 0; Object.keys(x.by_fam || {}).forEach(function (f) { if (top.indexOf(f) < 0) s += x.by_fam[f]; }); return s;
});
if (rest.some(function (v) { return v > 0; })) series.push({ key: 'other', label: t('an.ev.other'), values: rest });
var start = d.days.length ? Date.parse(d.days[0].d + 'T00:00:00Z') / 1000 : 0;
if (series.length && d.days.length >= 3) area.body.appendChild(U.charts.stackedArea(series, 86400, { start: start, title: t('an.ev.area') }));
else area.body.appendChild(U.ui.empty(t('charts.empty')));
// heatmap, Monday first
var order = [1, 2, 3, 4, 5, 6, 0], fmt = new Intl.DateTimeFormat(c.lang || undefined, { weekday: 'short', timeZone: 'UTC' });
var labels = order.map(function (w) { return fmt.format(new Date(Date.UTC(2023, 0, 1 + w))); });
var hours = []; for (var h = 0; h < 24; h++) hours.push(h % 3 === 0 ? String(h) : '');
heat.body.appendChild(U.charts.heatmap(order.map(function (w) { return d.hour_dow[w] || []; }), hours, labels, { title: t('an.ev.heat') }));
if (pct === null || pct === undefined) {
nw.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp')));
gone.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp')));
} else {
nw.body.appendChild(famList(d.new_families, 'bad'));
gone.body.appendChild(famList(d.gone_families, 'good'));
}
}
function load() {
var my = ++seq;
U.api('/api/v1/evolution', params(c)).then(function (r) {
if (!alive || my !== seq) return;
data = r; paint();
}, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('an.ev.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.ev.err')), b));
});
}
load();
return {
root: root,
lang: lang,
update: function (cx) { c = cx; load(); },
destroy: function () { alive = false; seq++; clear(root); }
};
}
U.registerPage({
id: 'evolution', group: 'analyze', titleKey: 'an.ev.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 17l5-5 4 4 8-9"/><path d="M15 7h5v5"/></svg>',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); },
update: function (ctx) {
ctx = ctx || {};
if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx);
},
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+380 -20
View File
@@ -240,14 +240,14 @@ window.URUTAU_I18N = {
'state.error': 'error',
'state.disabled': 'disabled',
'cat.ok': 'ok',
'cat.notfound': 'not found',
'cat.scanner': 'scanner',
'cat.exploit': 'exploit',
'cat.bruteforce': 'brute force',
'cat.ssh-fail': 'ssh fail',
'cat.ssh-probe': 'ssh probe',
'cat.ssh-ok': 'ssh login',
'cat.ban': 'ban',
'cat.notfound': 'Nonexistent page (404)',
'cat.scanner': 'Vulnerability scan',
'cat.exploit': 'Exploit attempt',
'cat.bruteforce': 'Brute force (login)',
'cat.ssh-fail': 'Failed SSH login',
'cat.ssh-probe': 'SSH probe',
'cat.ssh-ok': 'Successful SSH login',
'cat.ban': 'Banned (fail2ban)',
'feed.unban': 'unban',
'ago.now': 'now',
'ago.s': '{n}s ago',
@@ -269,7 +269,6 @@ window.URUTAU_I18N = {
'traffic.domain': 'Domain',
'traffic.allDomains': 'All domains',
'traffic.timeline': 'Requests and page views',
'traffic.timeline.hint': 'Requests answered per time bucket; the darker bar is the share counted as page views.',
'traffic.requests': 'Requests',
'traffic.pages': 'Page views',
'traffic.visitors': 'Visitors',
@@ -281,7 +280,6 @@ window.URUTAU_I18N = {
'traffic.cities': 'Cities',
'traffic.browsers': 'Browsers',
'traffic.oses': 'Operating systems',
'traffic.devices': 'Devices',
'traffic.status': 'Status codes',
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
'traffic.sub.visitors': 'distinct, hash per day',
@@ -299,6 +297,188 @@ window.URUTAU_I18N = {
'device.bot': 'bot',
'device.tool': 'tool',
'device.unknown': 'unknown',
'charts.empty': 'Nothing to chart in this slice.',
'charts.total': 'Total',
'charts.item': 'Item',
'charts.value': 'Value',
'nav.group.monitor': 'Monitor',
'nav.group.investigate': 'Investigate',
'nav.group.analyze': 'Analyze',
'nav.group.operate': 'Operate',
'nav.group.reports': 'Reports',
'traffic.client': 'Client type',
'traffic.client.hint': 'Share of visitors by kind of client, from the user agent.',
'traffic.otherReq': 'Other requests',
'traffic.status.2xx': '2xx success',
'traffic.status.3xx': '3xx redirect',
'traffic.status.4xx': '4xx client error',
'traffic.status.5xx': '5xx server error',
'traffic.browsers.hint': 'Browser family of the visitors.',
'traffic.oses.hint': 'Operating system of the visitors.',
'traffic.status.hint': 'Answers by HTTP status class.',
'traffic.area.hint': 'Requests per time bucket, split into page views and other requests (assets, APIs, bots).',
'device.misc': 'other',
'ov.radar': 'Attack profile',
'ov.radar.hint': 'Share of each attack category among the attacks of each host.',
'help.label': 'Explain',
'help.do': 'What to do',
'cat.short.ok': 'ok',
'cat.short.notfound': '404',
'cat.short.scanner': 'scan',
'cat.short.exploit': 'exploit',
'cat.short.bruteforce': 'brute force',
'cat.short.ssh-fail': 'SSH fail',
'cat.short.ssh-probe': 'SSH probe',
'cat.short.ssh-ok': 'SSH login',
'cat.short.ban': 'ban',
'help.cat.ok': 'A normal request that was answered successfully (2xx/3xx).',
'help.cat.ok.do': 'Nothing to do. These are your regular visitors.',
'help.cat.notfound': 'The visitor asked for an address that does not exist on the site. Almost always a robot guessing paths such as /.env or /wp-admin; it got nothing. Many 404s from one IP means scanning.',
'help.cat.notfound.do': 'Ignore isolated cases. If one IP keeps doing it, check whether it is already banned or listed on the blocklist.',
'help.cat.scanner': 'Automated probing for known weak spots (admin panels, backup files, old plugins). It looks for doors, it does not break them.',
'help.cat.scanner.do': 'Make sure the probed software is not exposed or outdated. Block repeat offenders.',
'help.cat.exploit': 'A request carrying an attack payload (path traversal, injection, known CVE). It tries to break in.',
'help.cat.exploit.do': 'Check whether the answer was refused (4xx/5xx). If it was answered 2xx, treat it as an incident and review the application.',
'help.cat.bruteforce': 'Repeated login attempts guessing passwords on a web form.',
'help.cat.bruteforce.do': 'Enforce strong passwords and rate limits; block the IP.',
'help.cat.ssh-fail': 'A failed SSH login: wrong user, wrong password or wrong key.',
'help.cat.ssh-fail.do': 'Disable password login, keep fail2ban active and review accounts with many failures.',
'help.cat.ssh-probe': 'A connection to the SSH port that never tried to log in (banner grab, protocol or key exchange scan).',
'help.cat.ssh-probe.do': 'Usually harmless alone; look for the same IP also failing logins.',
'help.cat.ssh-ok': 'A successful SSH login.',
'help.cat.ssh-ok.do': 'If the user or the origin is unexpected, check the account at once.',
'help.cat.ban': 'fail2ban banned the address after repeated abuse (or lifted a ban).',
'help.cat.ban.do': 'Nothing to do; the ban is automatic. Check the blocklist if the same IP returns.',
'help.metric.requests': 'All requests answered by the monitored servers in the slice, including assets and bots.',
'help.metric.requests.do': 'Compare with malicious events to see how much of the traffic is hostile.',
'help.metric.malicious': 'Events classified as an attack: scanning, exploits, brute force, SSH failures and probes.',
'help.metric.malicious.do': 'A sudden rise means a campaign; open Threats to see which category.',
'help.metric.unique_ips': 'Different IP addresses seen in the slice.',
'help.metric.unique_ips.do': 'Many new addresses with the same behavior suggest a distributed campaign.',
'help.metric.attacks_per_hour_24h': 'Average number of attack events per hour over the last 24 hours, with the change against the 24 hours before.',
'help.metric.attacks_per_hour_24h.do': 'Above your normal baseline? Check Threats for the dominant category.',
'help.metric.moving_avg_7d_per_hour': 'Attacks per hour averaged over 7 days: your usual background noise.',
'help.metric.moving_avg_7d_per_hour.do': 'Use it as the baseline; only deviations from it deserve attention.',
'help.metric.trend': 'How the attack rate moves compared with the previous period (rising, steady, falling).',
'help.metric.trend.do': 'A rising trend with new attackers is the pattern of a fresh campaign.',
'help.metric.active_attackers_24h': 'Distinct attacking IPs active in the last 24 hours.',
'help.metric.active_attackers_24h.do': 'If it keeps growing, review the blocklist coverage.',
'help.metric.active_attackers_1h': 'Distinct attacking IPs active in the last hour.',
'help.metric.active_attackers_1h.do': 'A spike here is the earliest sign of a new wave.',
'help.metric.new_attackers': 'Attacking IPs seen for the first time in this period.',
'help.metric.new_attackers.do': 'Many new IPs in a short time point to rotating infrastructure.',
'help.metric.returning_rate': 'Share of attackers that had already been seen before.',
'help.metric.returning_rate.do': 'High values mean persistent attackers: banning them pays off.',
'help.metric.sessions_per_day': 'Average attack sessions per day. A session groups one IP’s requests separated by short pauses.',
'help.metric.sessions_per_day.do': 'Compare with active attackers to see whether each one is persistent.',
'help.metric.exposure_rate': 'Share of attacks answered with success (2xx) on a sensitive path. This is the only number that shows real exposure.',
'help.metric.exposure_rate.do': 'Anything above 0% needs a look: open the IP page and the exposure section.',
'help.metric.exploits_refused_pct': 'Share of exploit attempts that the server refused (4xx/5xx).',
'help.metric.exploits_refused_pct.do': 'Close to 100% is healthy. Lower means some payloads got through.',
'help.metric.ban_coverage': 'Share of attacking IPs that fail2ban has banned.',
'help.metric.ban_coverage.do': 'Low coverage means attackers are not being stopped: check jails and thresholds.',
'help.metric.blocklist_coverage': 'Share of hostile IPs that are present on the exported blocklist.',
'help.metric.blocklist_coverage.do': 'Import the blocklist into your firewall to close the gap.',
'help.metric.blocklist_leak': 'Hostile IPs that were on the blocklist and still got through.',
'help.metric.blocklist_leak.do': 'Check that the firewall really applies the list.',
'help.metric.mttb': 'Mean time to ban: how long an attacker acts before fail2ban bans it (median).',
'help.metric.mttb.do': 'High values mean the ban rules are too slow.',
'help.metric.visitors': 'Distinct visitors, counted with a daily rotating hash. No IP is stored.',
'help.metric.visitors.do': 'Compare with page views to estimate engagement.',
'help.metric.pages': 'Page views: successful answers to real page requests, without assets, bots or tools.',
'help.metric.pages.do': 'A big gap to requests is normal: images, scripts and APIs are not pages.',
'help.metric.bytes': 'Total data sent to clients.',
'help.metric.bytes.do': 'A jump without more page views can mean downloads or scraping.',
'help.metric.latency': 'Response time: p50 is the typical request, p95 is the slowest 5%.',
'help.metric.latency.do': 'A high p95 with a normal p50 points to a few slow endpoints.',
'help.metric.bots': 'Requests made by search and AI crawlers.',
'help.metric.bots.do': 'Unwanted crawlers can be limited in robots.txt or at the proxy.',
'help.term.session': 'A burst of requests from one IP separated from the next by a long pause. It turns a flood of log lines into a few readable episodes.',
'help.term.session.do': 'Open an IP to see its sessions in order.',
'help.term.stage.recon': 'Reconnaissance: the attacker maps what exists (404s, probing).',
'help.term.stage.recon.do': 'Low risk by itself.',
'help.term.stage.probe': 'Probing: it tests specific weak points.',
'help.term.stage.probe.do': 'Watch whether it moves on to exploitation.',
'help.term.stage.exploit': 'Exploitation: it sends attack payloads.',
'help.term.stage.exploit.do': 'Check whether they were refused.',
'help.term.stage.access': 'Access: it got a successful answer or logged in.',
'help.term.stage.access.do': 'Treat as an incident and review the system.',
'help.term.stage.banned': 'Banned: fail2ban stopped it.',
'help.term.stage.banned.do': 'Confirm it does not come back from another address.',
'help.term.campaign': 'Several IPs acting alike (same tools, same targets, same time): probably one operator.',
'help.term.campaign.do': 'Block the whole network range, not just one IP.',
'help.term.family': 'A group of similar requests, such as WordPress, version control files or SQL injection.',
'help.term.family.do': 'Use it to see what the attackers are after.',
'help.term.mitre': 'A standard name for an attack technique, from the MITRE ATT&CK catalogue (for example T1110 Brute Force).',
'help.term.mitre.do': 'Use the code to search for mitigations.',
'help.term.net_type': 'The kind of network that owns the address: hosting, residential, mobile, university, VPN.',
'help.term.net_type.do': 'Hosting and VPN origins are rarely real customers.',
'help.term.cadence': 'How regular the time between requests is. Machines are regular; people are not.',
'help.term.cadence.do': 'Very regular cadence confirms automation.',
'help.term.score': 'A number from 0 to 1000 that adds up the evidence against an IP. Suspicious from 10, hostile from 50 (a strong rule can also make it hostile).',
'help.term.score.do': 'Sort by score to decide what to block first.',
'help.term.level': 'The verdict derived from the score: low, suspicious or hostile.',
'help.term.level.do': 'Hostile IPs are the candidates for the blocklist.',
'help.term.fcrdns': 'Forward-confirmed reverse DNS: the IP’s name resolves back to the same IP. Real search engines pass; impostors do not.',
'help.term.fcrdns.do': 'A bot claiming to be Google without FCrDNS is fake.',
'help.term.exposure': 'A sensitive path (such as /.env) that answered successfully to an attacker. Real exposure, not just an attempt.',
'help.term.exposure.do': 'Remove or protect the resource and rotate any secret in it.',
'help.term.blocklist': 'The list of hostile IPs ready to import into a firewall. Only addresses with strong evidence are included.',
'help.term.blocklist.do': 'Export it as text or JSON and load it into your firewall or fail2ban.',
'help.term.peer': 'Another Urutau instance that shares its data with this one.',
'help.term.peer.do': 'If a peer is offline, its numbers are missing from the totals.',
'help.term.hub': 'The instance that gathers the data of its peers into one view.',
'help.term.hub.do': 'Open the hub to see all servers together.',
'help.term.client_type': 'The kind of client behind each request: desktop, mobile, tablet, bot, tool or unknown, from its user agent.',
'help.term.client_type.do': 'A large share of tools or unknown clients is worth checking.',
'help.term.status_class': 'HTTP answers grouped by first digit: 2xx success, 3xx redirect, 4xx client error, 5xx server error.',
'help.term.status_class.do': '5xx means a problem on your side; many 4xx is usually scanning.',
'help.term.attack_profile': 'The share of each attack category among all attacks of a host. Different shapes mean different kinds of pressure.',
'help.term.attack_profile.do': 'A host with a very different shape is being targeted differently.',
'help.term.categories': 'Attack categories: 404 = a page that does not exist (usually a robot guessing paths); scan = automated search for weak spots; brute force = password guessing on a login form; exploit = a request carrying an attack payload; SSH fail = a wrong SSH login; SSH probe = a connection to the SSH port with no login attempt; ban = fail2ban blocked the address.',
'help.term.categories.do': 'Hover or focus the category names in the legend for the detail of each one.',
'help.term.apdex': 'Apdex: a 0 to 1 satisfaction score from response times. Fast answers count fully, tolerable ones count half, slow ones count zero.',
'help.term.apdex.do': 'Below 0.85 means users feel slowness: look at the slowest endpoints.',
'help.term.slo': 'Service level objective: the target you promise, for example 99.9% of requests answered without a server error.',
'help.term.slo.do': 'Compare the real number with the target; the gap is the error budget.',
'help.term.error_budget': 'How many failures the SLO still allows in the period. When it reaches zero, the target is broken.',
'help.term.error_budget.do': 'If the budget burns fast, pause risky changes and fix the cause first.',
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
'help.term.error_class.app.do': 'These are yours to fix: read the application logs.',
'help.term.error_class.proxy': 'Errors produced by the reverse proxy itself (bad gateway, timeout, no backend).',
'help.term.error_class.proxy.do': 'Check whether the backend is up and the proxy limits are right.',
'help.term.error_class.blocked': 'Requests refused on purpose by a rule (403, firewall or ban).',
'help.term.error_class.blocked.do': 'Usually healthy. Check only if real users are being blocked.',
'help.term.error_class.attack': 'Errors caused by attack traffic (probing for pages that do not exist, exploit attempts).',
'help.term.error_class.attack.do': 'Not a service problem. Do not count it against the SLO.',
'help.term.error_class.bot': 'Errors triggered by crawlers and automated clients that are not attacks.',
'help.term.error_class.bot.do': 'Fix broken links they find or limit them in robots.txt.',
'help.term.error_class.client': 'Errors caused by real visitors (a mistyped address, an expired link).',
'help.term.error_class.client.do': 'If frequent for one page, there may be a broken link.',
'help.term.error_class.unknown': 'Errors that could not be assigned to a cause.',
'help.term.error_class.unknown.do': 'Look at the examples to decide where they belong.',
'help.term.broken_link': 'An address that real visitors request and that answers 404. Usually a link that points to a page that was moved or removed.',
'help.term.broken_link.do': 'Fix the link or add a redirect to the new address.',
'help.term.gini': 'Gini index: how concentrated the attacks are, from 0 (spread evenly) to 1 (a few sources do almost everything).',
'help.term.gini.do': 'A high value means blocking a few addresses removes most of the noise.',
'help.term.pareto': 'Pareto curve: the share of all attacks produced by the top sources (the 80/20 view).',
'help.term.pareto.do': 'See how few IPs explain most of the attacks and block those first.',
'help.term.kaplan_meier': 'Survival curve (Kaplan-Meier): the share of attackers still active after a given time. It shows how long they persist.',
'help.term.kaplan_meier.do': 'A curve that stays high means persistent attackers: tighten the ban rules.',
'help.term.recidivism': 'The share of banned addresses that came back after the ban ended.',
'help.term.recidivism.do': 'High recidivism suggests longer bans or a permanent blocklist.',
'help.term.mitre_tactic': 'A tactic is the goal of an attacker in the MITRE ATT&CK catalogue (reconnaissance, initial access, credential access...). Techniques are the ways to reach it.',
'help.term.mitre_tactic.do': 'Use tactics to see which stage of an attack you are mostly seeing.',
'help.term.ttb': 'Time to ban: how long an attacker acted before being banned.',
'help.term.ttb.do': 'Long times mean the ban rules react too late.',
'help.term.leak': 'A leak is a request from an address that was already banned or blocklisted and still got an answer.',
'help.term.leak.do': 'Check that the firewall applies the blocklist at the right place.',
'help.term.integrity_gap': 'A period where the logs have a hole: no lines were read, so events may be missing.',
'help.term.integrity_gap.do': 'Check the log source and whether the file was rotated or the service stopped.',
'help.term.nonhuman': 'Non-human clients: bots, crawlers, tools and scripts, recognised by their user agent or behavior.',
'help.term.nonhuman.do': 'Not counted as visitors. Limit unwanted ones in robots.txt or at the proxy.',
'help.term.visit': 'A legitimate visit, shown anonymously on the live map: a real visitor, with no IP or identity stored.',
'help.term.visit.do': 'Nothing to do; it only shows where your audience comes from.',
'login.token': 'Access token',
'login.submit': 'Sign in',
'login.err.bad': 'Invalid token.',
@@ -532,14 +712,14 @@ window.URUTAU_I18N = {
'state.error': 'erro',
'state.disabled': 'desativada',
'cat.ok': 'ok',
'cat.notfound': 'não encontrado',
'cat.scanner': 'scanner',
'cat.exploit': 'exploit',
'cat.bruteforce': 'força bruta',
'cat.ssh-fail': 'falha ssh',
'cat.ssh-probe': 'sondagem ssh',
'cat.ssh-ok': 'login ssh',
'cat.ban': 'ban',
'cat.notfound': 'Página inexistente (404)',
'cat.scanner': 'Varredura de vulnerabilidades',
'cat.exploit': 'Tentativa de exploração',
'cat.bruteforce': 'Força bruta (login)',
'cat.ssh-fail': 'Login SSH falho',
'cat.ssh-probe': 'Sondagem SSH',
'cat.ssh-ok': 'Login SSH bem-sucedido',
'cat.ban': 'Banido (fail2ban)',
'feed.unban': 'desbanido',
'ago.now': 'agora',
'ago.s': 'há {n}s',
@@ -561,7 +741,6 @@ window.URUTAU_I18N = {
'traffic.domain': 'Domínio',
'traffic.allDomains': 'Todos os domínios',
'traffic.timeline': 'Requisições e páginas vistas',
'traffic.timeline.hint': 'Requisições atendidas por intervalo; a barra mais escura é a parcela contada como página vista.',
'traffic.requests': 'Requisições',
'traffic.pages': 'Páginas vistas',
'traffic.visitors': 'Visitantes',
@@ -573,7 +752,6 @@ window.URUTAU_I18N = {
'traffic.cities': 'Cidades',
'traffic.browsers': 'Navegadores',
'traffic.oses': 'Sistemas operacionais',
'traffic.devices': 'Dispositivos',
'traffic.status': 'Códigos de status',
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
'traffic.sub.visitors': 'distintos, hash diário',
@@ -591,6 +769,188 @@ window.URUTAU_I18N = {
'device.bot': 'bot',
'device.tool': 'ferramenta',
'device.unknown': 'desconhecido',
'charts.empty': 'Nada a exibir neste recorte.',
'charts.total': 'Total',
'charts.item': 'Item',
'charts.value': 'Valor',
'nav.group.monitor': 'Monitorar',
'nav.group.investigate': 'Investigar',
'nav.group.analyze': 'Analisar',
'nav.group.operate': 'Operar',
'nav.group.reports': 'Relatórios',
'traffic.client': 'Tipo de cliente',
'traffic.client.hint': 'Parcela dos visitantes por tipo de cliente, a partir do user-agent.',
'traffic.otherReq': 'Outras requisições',
'traffic.status.2xx': '2xx sucesso',
'traffic.status.3xx': '3xx redirecionamento',
'traffic.status.4xx': '4xx erro do cliente',
'traffic.status.5xx': '5xx erro do servidor',
'traffic.browsers.hint': 'Família de navegador dos visitantes.',
'traffic.oses.hint': 'Sistema operacional dos visitantes.',
'traffic.status.hint': 'Respostas por classe de status HTTP.',
'traffic.area.hint': 'Requisições por intervalo, divididas em páginas vistas e outras requisições (arquivos, APIs, robôs).',
'device.misc': 'outros',
'ov.radar': 'Perfil de ataque',
'ov.radar.hint': 'Parcela de cada categoria de ataque entre os ataques de cada host.',
'help.label': 'Explicar',
'help.do': 'O que fazer',
'cat.short.ok': 'ok',
'cat.short.notfound': '404',
'cat.short.scanner': 'varredura',
'cat.short.exploit': 'exploração',
'cat.short.bruteforce': 'força bruta',
'cat.short.ssh-fail': 'SSH falho',
'cat.short.ssh-probe': 'sondagem SSH',
'cat.short.ssh-ok': 'login SSH',
'cat.short.ban': 'ban',
'help.cat.ok': 'Um acesso normal que foi atendido com sucesso (2xx/3xx).',
'help.cat.ok.do': 'Nada a fazer. São os seus visitantes comuns.',
'help.cat.notfound': 'O visitante pediu um endereço que não existe no site. Quase sempre é um robô chutando caminhos como /.env ou /wp-admin; ele não obteve nada. Muitos 404 de um mesmo IP = varredura.',
'help.cat.notfound.do': 'Ignore casos isolados. Se um IP insiste, confira se já está banido ou na lista de bloqueio.',
'help.cat.scanner': 'Sondagem automática atrás de pontos fracos conhecidos (painéis, backups, plugins antigos). Procura portas, não as arromba.',
'help.cat.scanner.do': 'Confirme que o software sondado não está exposto nem desatualizado. Bloqueie reincidentes.',
'help.cat.exploit': 'Requisição com carga de ataque (travessia de caminho, injeção, CVE conhecida). Tenta invadir.',
'help.cat.exploit.do': 'Veja se a resposta foi recusada (4xx/5xx). Se foi 2xx, trate como incidente e revise a aplicação.',
'help.cat.bruteforce': 'Tentativas repetidas de login adivinhando senhas em um formulário web.',
'help.cat.bruteforce.do': 'Exija senhas fortes e limite de tentativas; bloqueie o IP.',
'help.cat.ssh-fail': 'Um login SSH que falhou: usuário, senha ou chave errados.',
'help.cat.ssh-fail.do': 'Desative login por senha, mantenha o fail2ban ativo e revise contas com muitas falhas.',
'help.cat.ssh-probe': 'Uma conexão à porta SSH que nunca tentou entrar (leitura de banner, varredura de protocolo ou troca de chaves).',
'help.cat.ssh-probe.do': 'Sozinha costuma ser inofensiva; veja se o mesmo IP também falha logins.',
'help.cat.ssh-ok': 'Um login SSH bem-sucedido.',
'help.cat.ssh-ok.do': 'Se o usuário ou a origem forem inesperados, verifique a conta imediatamente.',
'help.cat.ban': 'O fail2ban baniu o endereço após abusos repetidos (ou retirou o ban).',
'help.cat.ban.do': 'Nada a fazer; o ban é automático. Veja a lista de bloqueio se o mesmo IP voltar.',
'help.metric.requests': 'Todas as requisições atendidas pelos servidores monitorados no recorte, incluindo arquivos estáticos e robôs.',
'help.metric.requests.do': 'Compare com os eventos maliciosos para ver quanto do tráfego é hostil.',
'help.metric.malicious': 'Eventos classificados como ataque: varredura, exploração, força bruta, falhas e sondagens SSH.',
'help.metric.malicious.do': 'Uma alta repentina indica campanha; abra Ameaças para ver a categoria.',
'help.metric.unique_ips': 'Endereços IP diferentes vistos no recorte.',
'help.metric.unique_ips.do': 'Muitos endereços novos com o mesmo comportamento sugerem campanha distribuída.',
'help.metric.attacks_per_hour_24h': 'Média de eventos de ataque por hora nas últimas 24 horas, com a variação frente às 24 horas anteriores.',
'help.metric.attacks_per_hour_24h.do': 'Acima do seu normal? Veja em Ameaças qual categoria domina.',
'help.metric.moving_avg_7d_per_hour': 'Ataques por hora médios em 7 dias: o seu ruído de fundo habitual.',
'help.metric.moving_avg_7d_per_hour.do': 'Use como linha de base; só desvios dela merecem atenção.',
'help.metric.trend': 'Como a taxa de ataques se move frente ao período anterior (subindo, estável, caindo).',
'help.metric.trend.do': 'Tendência de alta com atacantes novos é o padrão de uma campanha recente.',
'help.metric.active_attackers_24h': 'IPs atacantes distintos ativos nas últimas 24 horas.',
'help.metric.active_attackers_24h.do': 'Se continuar crescendo, revise a cobertura da lista de bloqueio.',
'help.metric.active_attackers_1h': 'IPs atacantes distintos ativos na última hora.',
'help.metric.active_attackers_1h.do': 'Um pico aqui é o primeiro sinal de uma nova onda.',
'help.metric.new_attackers': 'IPs atacantes vistos pela primeira vez neste período.',
'help.metric.new_attackers.do': 'Muitos IPs novos em pouco tempo apontam para infraestrutura rotativa.',
'help.metric.returning_rate': 'Parcela dos atacantes que já tinham sido vistos antes.',
'help.metric.returning_rate.do': 'Valores altos indicam atacantes persistentes: banir compensa.',
'help.metric.sessions_per_day': 'Média de sessões de ataque por dia. Uma sessão agrupa as requisições de um IP separadas por pausas curtas.',
'help.metric.sessions_per_day.do': 'Compare com os atacantes ativos para ver se cada um é persistente.',
'help.metric.exposure_rate': 'Parcela dos ataques respondidos com sucesso (2xx) em um caminho sensível. É o único número que mostra exposição real.',
'help.metric.exposure_rate.do': 'Qualquer valor acima de 0% merece análise: abra a página do IP e a seção de exposição.',
'help.metric.exploits_refused_pct': 'Parcela das tentativas de exploração que o servidor recusou (4xx/5xx).',
'help.metric.exploits_refused_pct.do': 'Perto de 100% é saudável. Menos indica que alguma carga passou.',
'help.metric.ban_coverage': 'Parcela dos IPs atacantes que o fail2ban baniu.',
'help.metric.ban_coverage.do': 'Cobertura baixa significa atacantes não contidos: revise as jails e os limites.',
'help.metric.blocklist_coverage': 'Parcela dos IPs hostis que estão na lista de bloqueio exportada.',
'help.metric.blocklist_coverage.do': 'Importe a lista no firewall para fechar a diferença.',
'help.metric.blocklist_leak': 'IPs hostis que estavam na lista de bloqueio e ainda assim passaram.',
'help.metric.blocklist_leak.do': 'Verifique se o firewall realmente aplica a lista.',
'help.metric.mttb': 'Tempo médio até o ban: quanto o atacante age antes de ser banido (mediana).',
'help.metric.mttb.do': 'Valores altos indicam regras de ban lentas demais.',
'help.metric.visitors': 'Visitantes distintos, contados com um hash diário rotativo. Nenhum IP é guardado.',
'help.metric.visitors.do': 'Compare com as páginas vistas para estimar o engajamento.',
'help.metric.pages': 'Páginas vistas: respostas bem-sucedidas a pedidos de página reais, sem arquivos estáticos, robôs ou ferramentas.',
'help.metric.pages.do': 'Uma grande diferença para as requisições é normal: imagens, scripts e APIs não são páginas.',
'help.metric.bytes': 'Total de dados enviados aos clientes.',
'help.metric.bytes.do': 'Um salto sem mais páginas vistas pode indicar downloads ou raspagem.',
'help.metric.latency': 'Tempo de resposta: p50 é o pedido típico, p95 é o dos 5% mais lentos.',
'help.metric.latency.do': 'p95 alto com p50 normal aponta para poucos endpoints lentos.',
'help.metric.bots': 'Requisições feitas por robôs de busca e de IA.',
'help.metric.bots.do': 'Robôs indesejados podem ser limitados no robots.txt ou no proxy.',
'help.term.session': 'Uma rajada de requisições de um IP separada da próxima por uma pausa longa. Transforma milhares de linhas em poucos episódios legíveis.',
'help.term.session.do': 'Abra um IP para ver as sessões em ordem.',
'help.term.stage.recon': 'Reconhecimento: o atacante mapeia o que existe (404, sondagem).',
'help.term.stage.recon.do': 'Risco baixo isoladamente.',
'help.term.stage.probe': 'Sondagem: testa pontos fracos específicos.',
'help.term.stage.probe.do': 'Acompanhe se avança para a exploração.',
'help.term.stage.exploit': 'Exploração: envia cargas de ataque.',
'help.term.stage.exploit.do': 'Verifique se foram recusadas.',
'help.term.stage.access': 'Acesso: obteve resposta de sucesso ou entrou.',
'help.term.stage.access.do': 'Trate como incidente e revise o sistema.',
'help.term.stage.banned': 'Banido: o fail2ban o conteve.',
'help.term.stage.banned.do': 'Confirme que não volta por outro endereço.',
'help.term.campaign': 'Vários IPs agindo de forma parecida (mesmas ferramentas, alvos e horários): provavelmente um único operador.',
'help.term.campaign.do': 'Bloqueie a faixa de rede inteira, não só um IP.',
'help.term.family': 'Um grupo de requisições parecidas, como WordPress, arquivos de controle de versão ou injeção de SQL.',
'help.term.family.do': 'Use para ver o que os atacantes procuram.',
'help.term.mitre': 'Nome padronizado de uma técnica de ataque, do catálogo MITRE ATT&CK (por exemplo T1110 Força bruta).',
'help.term.mitre.do': 'Use o código para buscar mitigações.',
'help.term.net_type': 'O tipo de rede dona do endereço: hospedagem, residencial, móvel, universidade, VPN.',
'help.term.net_type.do': 'Origens de hospedagem e VPN raramente são clientes reais.',
'help.term.cadence': 'Quão regular é o intervalo entre as requisições. Máquinas são regulares; pessoas não.',
'help.term.cadence.do': 'Cadência muito regular confirma automação.',
'help.term.score': 'Número de 0 a 1000 que soma as evidências contra um IP. Suspeito a partir de 10, hostil a partir de 50 (uma regra forte também pode torná-lo hostil).',
'help.term.score.do': 'Ordene por pontuação para decidir o que bloquear primeiro.',
'help.term.level': 'O veredito derivado da pontuação: baixo, suspeito ou hostil.',
'help.term.level.do': 'IPs hostis são os candidatos à lista de bloqueio.',
'help.term.fcrdns': 'DNS reverso confirmado: o nome do IP resolve de volta para o mesmo IP. Buscadores reais passam; impostores não.',
'help.term.fcrdns.do': 'Um robô que diz ser Google sem FCrDNS é falso.',
'help.term.exposure': 'Um caminho sensível (como /.env) que respondeu com sucesso a um atacante. Exposição real, não apenas tentativa.',
'help.term.exposure.do': 'Remova ou proteja o recurso e troque qualquer segredo contido nele.',
'help.term.blocklist': 'A lista de IPs hostis pronta para importar em um firewall. Só entram endereços com evidência forte.',
'help.term.blocklist.do': 'Exporte em texto ou JSON e carregue no firewall ou no fail2ban.',
'help.term.peer': 'Outra instância do Urutau que compartilha seus dados com esta.',
'help.term.peer.do': 'Se um par está offline, os números dele faltam nos totais.',
'help.term.hub': 'A instância que reúne os dados dos pares em uma só visão.',
'help.term.hub.do': 'Abra o hub para ver todos os servidores juntos.',
'help.term.client_type': 'O tipo de cliente por trás de cada requisição: computador, celular, tablet, robô, ferramenta ou desconhecido, pelo user-agent.',
'help.term.client_type.do': 'Uma parcela grande de ferramentas ou desconhecidos merece verificação.',
'help.term.status_class': 'Respostas HTTP agrupadas pelo primeiro dígito: 2xx sucesso, 3xx redirecionamento, 4xx erro do cliente, 5xx erro do servidor.',
'help.term.status_class.do': '5xx indica problema do seu lado; muitos 4xx costumam ser varredura.',
'help.term.attack_profile': 'A parcela de cada categoria de ataque entre todos os ataques de um host. Formas diferentes indicam pressões diferentes.',
'help.term.attack_profile.do': 'Um host com forma muito diferente está sendo alvo de outro tipo de ataque.',
'help.term.categories': 'Categorias de ataque: 404 = página que não existe (em geral um robô chutando caminhos); varredura = busca automática por pontos fracos; força bruta = adivinhar senha em um login; exploração = requisição com carga de ataque; SSH falho = login SSH errado; sondagem SSH = conexão à porta SSH sem tentar entrar; ban = o fail2ban bloqueou o endereço.',
'help.term.categories.do': 'Passe o mouse ou o foco nos nomes da legenda para ver o detalhe de cada uma.',
'help.term.apdex': 'Apdex: nota de satisfação de 0 a 1 a partir dos tempos de resposta. Respostas rápidas valem tudo, toleráveis valem metade, lentas valem zero.',
'help.term.apdex.do': 'Abaixo de 0,85 os usuários sentem lentidão: veja os endpoints mais lentos.',
'help.term.slo': 'Objetivo de nível de serviço: a meta prometida, por exemplo 99,9% das requisições atendidas sem erro do servidor.',
'help.term.slo.do': 'Compare o número real com a meta; a diferença é o orçamento de erro.',
'help.term.error_budget': 'Quantas falhas o SLO ainda permite no período. Quando chega a zero, a meta foi quebrada.',
'help.term.error_budget.do': 'Se o orçamento queima rápido, pause mudanças arriscadas e corrija a causa primeiro.',
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
'help.term.error_class.app.do': 'São seus para corrigir: leia os logs da aplicação.',
'help.term.error_class.proxy': 'Erros produzidos pelo próprio proxy reverso (bad gateway, timeout, sem backend).',
'help.term.error_class.proxy.do': 'Veja se o backend está no ar e se os limites do proxy estão certos.',
'help.term.error_class.blocked': 'Requisições recusadas de propósito por uma regra (403, firewall ou ban).',
'help.term.error_class.blocked.do': 'Em geral é saudável. Verifique só se usuários reais estão sendo bloqueados.',
'help.term.error_class.attack': 'Erros causados por tráfego de ataque (sondagem de páginas inexistentes, tentativas de exploração).',
'help.term.error_class.attack.do': 'Não é problema do serviço. Não conte contra o SLO.',
'help.term.error_class.bot': 'Erros provocados por rastreadores e clientes automáticos que não são ataques.',
'help.term.error_class.bot.do': 'Corrija os links quebrados que eles acham ou limite-os no robots.txt.',
'help.term.error_class.client': 'Erros causados por visitantes reais (endereço digitado errado, link expirado).',
'help.term.error_class.client.do': 'Se forem frequentes em uma página, pode haver um link quebrado.',
'help.term.error_class.unknown': 'Erros que não puderam ser atribuídos a uma causa.',
'help.term.error_class.unknown.do': 'Veja os exemplos para decidir a que causa pertencem.',
'help.term.broken_link': 'Um endereço que visitantes reais pedem e que responde 404. Em geral um link apontando para uma página movida ou removida.',
'help.term.broken_link.do': 'Corrija o link ou crie um redirecionamento para o novo endereço.',
'help.term.gini': 'Índice de Gini: quanto os ataques estão concentrados, de 0 (bem espalhados) a 1 (poucas fontes fazem quase tudo).',
'help.term.gini.do': 'Valor alto significa que bloquear poucos endereços elimina a maior parte do ruído.',
'help.term.pareto': 'Curva de Pareto: a parcela de todos os ataques produzida pelas maiores fontes (visão 80/20).',
'help.term.pareto.do': 'Veja quantos poucos IPs explicam a maioria dos ataques e bloqueie esses primeiro.',
'help.term.kaplan_meier': 'Curva de sobrevivência (Kaplan-Meier): a parcela de atacantes ainda ativos após certo tempo. Mostra quanto tempo persistem.',
'help.term.kaplan_meier.do': 'Curva que se mantém alta indica atacantes persistentes: endureça as regras de ban.',
'help.term.recidivism': 'A parcela dos endereços banidos que voltaram depois do fim do ban.',
'help.term.recidivism.do': 'Reincidência alta sugere bans mais longos ou lista de bloqueio permanente.',
'help.term.mitre_tactic': 'Uma tática é o objetivo do atacante no catálogo MITRE ATT&CK (reconhecimento, acesso inicial, acesso a credenciais...). As técnicas são os jeitos de alcançá-lo.',
'help.term.mitre_tactic.do': 'Use as táticas para ver em qual estágio de ataque você mais está.',
'help.term.ttb': 'Tempo até o ban: quanto tempo o atacante agiu antes de ser banido.',
'help.term.ttb.do': 'Tempos longos indicam regras de ban que reagem tarde.',
'help.term.leak': 'Vazamento é uma requisição de um endereço já banido ou na lista de bloqueio que ainda assim foi atendida.',
'help.term.leak.do': 'Verifique se o firewall aplica a lista de bloqueio no lugar certo.',
'help.term.integrity_gap': 'Um período em que os logs têm um buraco: nenhuma linha foi lida, então podem faltar eventos.',
'help.term.integrity_gap.do': 'Veja a fonte de log e se o arquivo foi rotacionado ou o serviço parou.',
'help.term.nonhuman': 'Clientes não humanos: robôs, rastreadores, ferramentas e scripts, reconhecidos pelo user-agent ou pelo comportamento.',
'help.term.nonhuman.do': 'Não contam como visitantes. Limite os indesejados no robots.txt ou no proxy.',
'help.term.visit': 'Uma visita legítima, mostrada de forma anônima no mapa ao vivo: um visitante real, sem IP nem identidade guardados.',
'help.term.visit.do': 'Nada a fazer; apenas mostra de onde vem o seu público.',
'login.token': 'Token de acesso',
'login.submit': 'Entrar',
'login.err.bad': 'Token inválido.',
-8
View File
@@ -7,10 +7,6 @@
<title>Urutau</title>
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/geo.css">
<link rel="stylesheet" href="/live.css">
<link rel="stylesheet" href="/ip.css">
<link rel="stylesheet" href="/replay.css">
<script src="/i18n.js"></script>
</head>
<body>
@@ -65,9 +61,5 @@
<script src="/world.js"></script>
<script src="/app.js"></script>
<script src="/geo.js"></script>
<script src="/live.js"></script>
<script src="/ip.js"></script>
<script src="/replay.js"></script>
</body>
</html>
+24
View File
@@ -0,0 +1,24 @@
/* Urutau - INTEGRITY page. Selectors prefixed ig-. */
.ig { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; }
.ig-box { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; }
.ig-stats > * { grid-column: span 12; }
@media (min-width: 700px) { .ig-stats > .span-3 { grid-column: span 6; } }
@media (min-width: 1100px) { .ig-stats > .span-3 { grid-column: span 3; } }
@media (min-width: 1100px) {
.ig .grid-12 > .span-6 { grid-column: span 6; }
.ig .grid-12 > .span-8 { grid-column: span 8; }
.ig .grid-12 > .span-4 { grid-column: span 4; }
}
.ig-scroll { overflow-x: auto; max-width: 100%; }
.ig-table { width: 100%; border-collapse: collapse; font-size: .8125rem; }
.ig-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 6px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; }
.ig-table td { padding: 6px 10px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
.ig-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; font-size: .875rem; overflow-wrap: anywhere; }
.ig-muted { color: var(--ink-muted); font-size: .8125rem; }
.ig-kv { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 8px 0 0; font-size: .875rem; }
.ig-kv dt { color: var(--ink-muted); }
.ig-kv dd { margin: 0; text-align: right; overflow-wrap: anywhere; }
.ig .vz-heat { width: 100%; max-width: 100%; min-width: 0; overflow: hidden; }
.ig .vz-heat svg { max-width: 100%; height: auto; display: block; }
.ig .panel, .ig .panel-b { min-width: 0; max-width: 100%; }
.ig-heatbox { position: relative; overflow: hidden; max-width: 100%; }
+279
View File
@@ -0,0 +1,279 @@
/* Urutau - INTEGRITY page ("Is the data complete?"): volume ingested per host and
hour (holes show as empty cells), state of every source and peer, share of
malformed lines, event log and geolocation base. Log data is hostile: every
dynamic string goes through textContent (the shell's el/h helpers). */
(function () {
'use strict';
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, disabled: 1 };
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 4 6v6c0 4.5 3.2 7.8 8 9 4.8-1.2 8-4.5 8-9V6l-8-3z"/><path d="m9 12 2 2 4-4"/></svg>';
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'ig.title': 'Integrity',
'ig.lead.ok': 'The data is complete',
'ig.lead.okBody': 'No gaps of {n} hours or more, every source answers and few lines were rejected.',
'ig.lead.bad.one': '{n} hole in the data',
'ig.lead.bad.other': '{n} holes in the data',
'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline peers or sources in error. Check the panels below.',
'ig.lead.loading': 'Checking the data...',
'ig.stat.hosts': 'Hosts reporting',
'ig.stat.gaps': 'Gaps found',
'ig.stat.parse': 'Invalid lines',
'ig.stat.log': 'Event log',
'ig.stat.logSub': '{days} days, {size}',
'ig.stat.logOff': 'off',
'ig.heat.title': 'Events ingested per hour',
'ig.heat.hint': 'One row per host, one column per hour. Empty cells are hours with no event at all.',
'ig.heat.empty': 'No events in this period.',
'ig.gaps.title': 'Gaps',
'ig.gaps.none': 'No silence of two hours or more.',
'ig.gaps.line': '{host}: {from} to {to} ({h} h)',
'ig.src.title': 'Sources',
'ig.src.host': 'Host',
'ig.src.name': 'Source',
'ig.src.state': 'State',
'ig.src.lines': 'Lines',
'ig.src.bad': 'Invalid',
'ig.src.last': 'Last event',
'ig.src.none': 'No sources reported.',
'ig.state.following': 'following',
'ig.state.waiting': 'waiting',
'ig.state.backfill': 'catching up',
'ig.state.error': 'error',
'ig.state.disabled': 'disabled',
'ig.peers.title': 'Peers',
'ig.peers.none': 'No peers configured.',
'ig.peers.online': 'online',
'ig.peers.offline': 'offline',
'ig.peers.live': 'live',
'ig.peers.sync': 'synced {t}',
'ig.peers.never': 'never synced',
'ig.log.title': 'Event log and geolocation',
'ig.log.off': 'The event log is off: periods, sessions and replay have no data.',
'ig.log.days': 'Days kept',
'ig.log.size': 'Size on disk',
'ig.log.dropped': 'Events dropped',
'ig.geo.state': 'Geolocation base',
'ig.geo.city': 'City base build',
'ig.geo.asn': 'ASN base build',
'ig.geo.unknown': 'unknown',
'ig.lag': 'Delay',
'ig.host.lagLine': '{host}: last event {t}'
},
'pt-BR': {
'ig.title': 'Integridade',
'ig.lead.ok': 'Os dados estão completos',
'ig.lead.okBody': 'Nenhum buraco de {n} horas ou mais, todas as fontes respondem e poucas linhas foram rejeitadas.',
'ig.lead.bad.one': '{n} buraco nos dados',
'ig.lead.bad.other': '{n} buracos nos dados',
'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, peers fora do ar ou fontes com erro. Veja os painéis abaixo.',
'ig.lead.loading': 'Conferindo os dados...',
'ig.stat.hosts': 'Hosts reportando',
'ig.stat.gaps': 'Buracos encontrados',
'ig.stat.parse': 'Linhas inválidas',
'ig.stat.log': 'Registro de eventos',
'ig.stat.logSub': '{days} dias, {size}',
'ig.stat.logOff': 'desligado',
'ig.heat.title': 'Eventos ingeridos por hora',
'ig.heat.hint': 'Uma linha por host, uma coluna por hora. Células vazias são horas sem nenhum evento.',
'ig.heat.empty': 'Nenhum evento neste período.',
'ig.gaps.title': 'Buracos',
'ig.gaps.none': 'Nenhum silêncio de duas horas ou mais.',
'ig.gaps.line': '{host}: de {from} a {to} ({h} h)',
'ig.src.title': 'Fontes',
'ig.src.host': 'Host',
'ig.src.name': 'Fonte',
'ig.src.state': 'Estado',
'ig.src.lines': 'Linhas',
'ig.src.bad': 'Inválidas',
'ig.src.last': 'Último evento',
'ig.src.none': 'Nenhuma fonte informada.',
'ig.state.following': 'acompanhando',
'ig.state.waiting': 'aguardando',
'ig.state.backfill': 'recuperando',
'ig.state.error': 'erro',
'ig.state.disabled': 'desativada',
'ig.peers.title': 'Peers',
'ig.peers.none': 'Nenhum peer configurado.',
'ig.peers.online': 'no ar',
'ig.peers.offline': 'fora do ar',
'ig.peers.live': 'ao vivo',
'ig.peers.sync': 'sincronizado {t}',
'ig.peers.never': 'nunca sincronizou',
'ig.log.title': 'Registro de eventos e geolocalização',
'ig.log.off': 'O registro de eventos está desligado: períodos, sessões e replay ficam sem dados.',
'ig.log.days': 'Dias guardados',
'ig.log.size': 'Tamanho em disco',
'ig.log.dropped': 'Eventos descartados',
'ig.geo.state': 'Base de geolocalização',
'ig.geo.city': 'Build da base de cidades',
'ig.geo.asn': 'Build da base de ASN',
'ig.geo.unknown': 'desconhecida',
'ig.lag': 'Atraso',
'ig.host.lagLine': '{host}: último evento {t}'
}
});
var t = U.t, nf = U.fmt.num;
var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); };
function when(ts) { return ts ? U.fmt.date(ts) : '-'; }
var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null, timer = null;
function params(c) {
var p = U.rangeParams();
if (c && c.host && c.host !== 'all') p.host = c.host;
return p;
}
function load(c) {
var my = ++seq;
U.api('/api/v1/integrity', params(c || ctx0)).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
while (box.firstChild) box.removeChild(box.firstChild);
box.appendChild(U.ui.empty(t('error.load')));
});
}
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function hourLabel(hn) {
var d = new Date(hn * 3600000);
return ('0' + d.getDate()).slice(-2) + '/' + ('0' + d.getHours()).slice(-2);
}
function table(headers, rows) {
var tb = h('table', 'ig-table');
var tr = h('tr');
headers.forEach(function (x) { tr.appendChild(h('th', null, x)); });
tb.appendChild(h('thead', null, tr));
var body = h('tbody');
rows.forEach(function (r) {
var row = h('tr');
r.forEach(function (c) { row.appendChild(h('td', null, c)); });
body.appendChild(row);
});
tb.appendChild(body);
return h('div', 'ig-scroll', tb);
}
function paint() {
if (!data) return;
clear(box);
var hosts = data.hosts || [], peers = data.peers || [];
var gaps = 0, lines = 0, bad = 0, errors = 0, onlineN = 0;
hosts.forEach(function (x) {
gaps += (x.gaps || []).length;
if (x.online) onlineN++;
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error') errors++; });
});
var offline = peers.filter(function (p) { return !p.online; }).length;
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
var holes = gaps + offline + errors;
var ok = holes === 0 && rate < 0.01;
var title = ok ? t('ig.lead.ok') : U.pl('ig.lead.bad', holes || 1);
box.appendChild(U.ui.lead(title, ok ? t('ig.lead.okBody', { n: 2 }) : t('ig.lead.badBody'), ok ? 'ok' : 'danger'));
var stats = h('div', 'grid-12 ig-stats');
function sp(node) { node.classList.add('span-3'); stats.appendChild(node); }
sp(U.ui.stat(t('ig.stat.hosts'), nf(onlineN) + ' / ' + nf(hosts.length), null, onlineN === hosts.length ? 'ok' : 'danger'));
sp(U.ui.stat(t('ig.stat.gaps'), nf(gaps), null, gaps ? 'danger' : 'ok', null, 'term.integrity_gap'));
sp(U.ui.stat(t('ig.stat.parse'), (rate * 100).toFixed(rate < 0.1 ? 2 : 1) + '%', nf(bad) + ' / ' + nf(lines + bad), rate >= 0.01 ? 'danger' : 'ok'));
var lg = data.eventlog || {};
sp(U.ui.stat(t('ig.stat.log'), lg.enabled ? nf(lg.days) : t('ig.stat.logOff'), lg.enabled ? t('ig.stat.logSub', { days: nf(lg.days), size: U.fmt.bytes(lg.bytes) }) : null, lg.enabled ? 'ok' : 'neutral'));
box.appendChild(stats);
// heatmap
var hp = U.ui.panel({ title: t('ig.heat.title'), hint: t('ig.heat.hint'), variant: 'chart' });
var n = hosts.length ? (hosts[0].hourly || []).length : 0;
if (!n || !hosts.some(function (x) { return (x.hourly || []).some(function (v) { return v > 0; }); })) {
hp.body.appendChild(U.ui.empty(t('ig.heat.empty')));
} else {
var xl = [];
for (var i = 0; i < n; i++) xl.push(hourLabel(data.from_hour + i));
hp.body.appendChild(h('div', 'ig-heatbox', U.charts.heatmap(hosts.map(function (x) { return x.hourly; }), xl, hosts.map(function (x) { return x.name; }), { title: t('ig.heat.title') }))); }
box.appendChild(hp);
var grid = h('div', 'grid-12');
// gaps
var gp = U.ui.panel({ title: t('ig.gaps.title') });
gp.classList.add('span-6');
var gl = h('ul', 'ig-list');
hosts.forEach(function (x) {
(x.gaps || []).forEach(function (g) {
gl.appendChild(h('li', null, t('ig.gaps.line', { host: x.name, from: when(g.from), to: when(g.to), h: nf(Math.round((g.to - g.from) / 3600)) })));
});
});
gp.body.appendChild(gl.children.length ? gl : U.ui.empty(t('ig.gaps.none')));
grid.appendChild(gp);
// peers
var pp = U.ui.panel({ title: t('ig.peers.title') });
pp.classList.add('span-6');
if (!peers.length) pp.body.appendChild(U.ui.empty(t('ig.peers.none')));
else {
var pl = h('ul', 'ig-list');
peers.forEach(function (p) {
pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t(p.online ? 'ig.peers.online' : 'ig.peers.offline'), p.online ? 'ok' : 'danger'),
p.live ? ' ' : null, p.live ? U.ui.badge(t('ig.peers.live'), 'neutral') : null, ' ',
h('span', 'ig-muted', p.last_sync ? t('ig.peers.sync', { t: U.fmt.ago(p.last_sync) }) : t('ig.peers.never'))));
});
pp.body.appendChild(pl);
}
grid.appendChild(pp);
// sources
var sp2 = U.ui.panel({ title: t('ig.src.title') });
sp2.classList.add('span-8');
var rows = [];
hosts.forEach(function (x) {
(x.sources || []).forEach(function (s) {
var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
});
});
sp2.body.appendChild(rows.length ? table([t('ig.src.host'), t('ig.src.name'), t('ig.src.state'), t('ig.src.lines'), t('ig.src.bad'), t('ig.src.last')], rows) : U.ui.empty(t('ig.src.none')));
grid.appendChild(sp2);
// log + geo
var lp = U.ui.panel({ title: t('ig.log.title') });
lp.classList.add('span-4');
if (!lg.enabled) lp.body.appendChild(h('p', 'ig-muted', t('ig.log.off')));
var kv = h('dl', 'ig-kv');
function row(k, v) { kv.appendChild(h('dt', null, k)); kv.appendChild(h('dd', null, v)); }
if (lg.enabled) { row(t('ig.log.days'), nf(lg.days)); row(t('ig.log.size'), U.fmt.bytes(lg.bytes)); row(t('ig.log.dropped'), nf(lg.dropped)); }
var g = data.geo || {};
row(t('ig.geo.state'), g.state ? (STATES[g.state] ? t('ig.state.' + g.state) : String(g.state)) : t('ig.geo.unknown'));
row(t('ig.geo.city'), g.city_build ? U.fmt.date(g.city_build) : t('ig.geo.unknown'));
row(t('ig.geo.asn'), g.asn_build ? U.fmt.date(g.asn_build) : t('ig.geo.unknown'));
lp.body.appendChild(kv);
grid.appendChild(lp);
box.appendChild(grid);
}
U.registerPage({
id: 'integrity', group: 'operate', icon: ICON, titleKey: 'ig.title',
mount: function (el, c) {
ctx0 = c; alive = true; data = null;
root = h('div', 'ig');
box = h('div', 'ig-box');
root.appendChild(box);
box.appendChild(U.ui.lead(t('ig.lead.loading'), null, 'neutral'));
el.appendChild(root);
load(c);
},
update: function (c) { ctx0 = c; load(c); if (data) paint(); },
refresh: function () { load(ctx0); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+16
View File
@@ -164,3 +164,19 @@ button.lv-row[aria-pressed="false"] .lv-row-l { text-decoration: line-through; }
.lv-bar { gap: 6px; }
.lv-notes { margin-left: 0; width: 100%; }
}
/* legitimate traffic (anonymous visits) */
.lv-vis { gap: 8px; }
.lv-vis-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--lv-muted); flex: none; }
.lv-vis[aria-pressed="true"] { border-color: var(--accent); }
.lv-vis[aria-pressed="true"] .lv-vis-dot { background: var(--lv-muted); border-color: var(--lv-muted); }
.lv-devs, .lv-m-visit { display: none; }
.lv-vis-on .lv-devs { display: flex; }
.lv-vis-on .lv-m-visit { display: flex; }
.lv-k-visit { --k: var(--ink-muted, #9db3bd); }
.lv-ev-visit .lv-vtxt { grid-column: span 1; color: var(--lv-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
.lv-left .lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); }
.lv-leg { display: none; align-items: center; gap: 6px; }
.lv-vis-on .lv-leg { display: inline-flex; }
.lv-leg-sw { width: 16px; height: 2px; background: var(--ink-muted, #9db3bd); }
+186 -34
View File
@@ -15,7 +15,7 @@
var CAT_OK = {};
CATS.forEach(function (c) { CAT_OK[c] = 1; });
var MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300;
var MAX_VARCS = 150, MAX_VPENDING = 150, MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300;
var WORLD_W = 2000, WORLD_H = 789, LAT_TOP = 84, LAT_BOT = -58;
var DEFAULT_DST = { lat: -23.55, lon: -46.63 };
var RAD = Math.PI / 180, TAU = Math.PI * 2;
@@ -138,7 +138,7 @@
this.paused = false; this.hidden = document.hidden;
this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
this.T = 0; this.last = 0; this.raf = 0; this.dirty = true;
this.arcs = []; this.free = []; this.pending = []; this.frameKey = {};
this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.frameKey = {};
this.dests = {}; this.destList = []; this.dots = []; this.more = [];
this.frameAvg = 16; this.quality = 1;
this.W = 0; this.H = 0; this.dpr = 1; this.reserve = 0;
@@ -189,7 +189,7 @@
this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } });
this.listeners = [];
if (this.ro) { this.ro.disconnect(); this.ro = null; }
this.arcs = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = [];
this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = [];
if (this.cv.parentNode) this.cv.parentNode.removeChild(this.cv);
};
@@ -202,6 +202,8 @@
var rgb = parseColor(css(TOKEN[c]), FALLBACK[c]);
cols[c] = { rgb: rgb, c0: rgba(rgb, 0), c1: rgba(rgb, 1), css: rgba(rgb, 1) };
});
var vrgb = parseColor(tok('--ink-muted', '--muted'), '#9db3bd');
cols.visit = { rgb: vrgb, c0: rgba(vrgb, 0), c1: rgba(vrgb, 1), css: rgba(vrgb, 1) };
this.colors = cols;
this.dark = (bg[0] * 299 + bg[1] * 587 + bg[2] * 114) / 1000 < 128;
this.pal = { text: text, bg: bg, accent: parseColor(css('--accent'), '#38bdf8') };
@@ -211,8 +213,8 @@
M.setTheme = function () { this.readTheme(); this.kick(); };
M.setMode = function (m) { this.mode = m === 'globe' ? 'globe' : 'flat'; this.target = this.mode === 'globe' ? 1 : 0; this.cv.classList.toggle('lv-globe', this.mode === 'globe'); this.dirty = true; this.kick(); };
M.pause = function (p) { this.paused = !!p; if (p) this.pending.length = 0; this.last = 0; this.dirty = true; this.kick(); };
M.clear = function () { this.arcs = []; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); };
M.pause = function (p) { this.paused = !!p; if (p) { this.pending.length = 0; this.vpending.length = 0; } this.last = 0; this.dirty = true; this.kick(); };
M.clear = function () { this.arcs = []; this.varcs = []; this.vpending.length = 0; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); };
M.setDest = function (host, d, est) {
var cur = this.dests[host];
@@ -260,13 +262,21 @@
// ev: an event as sent by the server ({cat, host, src, dst, cc}); returns whether it can be drawn
M.spawnEvent = function (ev, o) {
if (!this.alive || !ev || !CAT_OK[ev.cat]) return false;
var vis = !!(o && o.visit);
if (!this.alive || !ev || (!vis && !CAT_OK[ev.cat])) return false;
var org = this.originOf(ev);
if (!org) return false;
var host = str(ev.host, 64) || 'local';
var d = this.destFor(host, ev.dst && typeof ev.dst === 'object' ? ev.dst : null);
var hl = !!(o && o.highlight) || !!HOSTILE[ev.cat];
var hl = !vis && (!!(o && o.highlight) || !!HOSTILE[ev.cat]);
if (this.paused || this.hidden) return true;
if (vis) {
if (this.reduced) return true;
if (this.vpending.length >= MAX_VPENDING) this.vpending.shift();
this.vpending.push({ o: org, d: d, cat: 'visit', hl: false, v: true });
this.kick();
return true;
}
if (this.reduced) {
this.dots.push({ lat: org.lat, lon: org.lon, v: vec(org.lat, org.lon), cat: ev.cat });
if (this.dots.length > 160) this.dots.shift();
@@ -353,7 +363,7 @@
M.onVisibility = function () {
this.hidden = document.hidden;
if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; }
if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; this.vpending.length = 0; }
else { this.last = 0; this.dirty = true; this.kick(); }
};
@@ -473,7 +483,7 @@
};
M.drawFlatLayer = function (g, layerAlpha, add) {
var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.arcs, i;
var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.ordered(), i;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs
var dd = this.dots[i];
@@ -485,12 +495,12 @@
for (i = 0; i < arcs.length; i++) {
var a = arcs[i], age = T - a.born;
if (age < 0) continue;
var col = this.colors[a.cat];
var col = a.visit ? this.colors.visit : this.colors[a.cat];
var x0 = ox + a.u0 * mw, y0 = oy + a.v0 * mh, x1 = ox + a.dest.u0 * mw, y1 = oy + a.dest.v0 * mh;
var dx = x1 - x0, dy = y1 - y0, dist = Math.sqrt(dx * dx + dy * dy);
var cx = (x0 + x1) / 2, cy = (y0 + y1) / 2 - Math.min(dist * 0.42, mh * 0.5) - 4;
var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1));
var fade = layerAlpha * (1 - 0.75 * tail);
var fade = layerAlpha * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1);
if (tail < 1 && head > tail) {
// exact sub-curve of the quadratic Bezier between parameters tail..head
var ut = 1 - tail, uh = 1 - head;
@@ -503,18 +513,18 @@
g.strokeStyle = gr;
g.beginPath(); g.moveTo(ax, ay); g.quadraticCurveTo(kx, ky, bx, by);
if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); }
g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.stroke();
if (head < 1) {
g.fillStyle = col.css;
g.beginPath(); g.arc(bx, by, a.hostile ? 2.8 : 2, 0, TAU); g.fill();
}
}
if (age < 0.7) {
if (age < 0.7 && !a.visit) {
g.globalAlpha = layerAlpha * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1;
g.beginPath(); g.arc(x0, y0, 2 + age * 9, 0, TAU); g.stroke();
}
this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha);
if (!a.visit) this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha);
}
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.destList.length; i++) {
@@ -660,7 +670,7 @@
};
M.drawGlobeLayer = function (g, m, add) {
var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.arcs, i, k;
var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.ordered(), i, k;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) {
var dd = this.dots[i];
@@ -674,9 +684,9 @@
for (i = 0; i < arcs.length; i++) {
var a = arcs[i], age = T - a.born;
if (age < 0) continue;
var col = this.colors[a.cat];
var col = a.visit ? this.colors.visit : this.colors[a.cat];
var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1));
var fade = m * (1 - 0.75 * tail);
var fade = m * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1);
var A = a.a, B = a.b, w = a.w, sw = Math.sin(w);
if (tail < 1 && head > tail) {
var lift = 0.05 + 0.22 * w / Math.PI;
@@ -700,16 +710,16 @@
gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1);
g.strokeStyle = gr;
if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); }
g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0);
g.stroke();
if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(lx, ly, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); }
}
}
if (age >= a.D) {
if (age >= a.D && !a.visit) {
this.rot(B[0], B[1], B[2]);
if (this.rz > 0.02) this.drawPulse(g, cx + this.rx * R, cy - this.ry * R, a, age, col, Math.atan2(-this.ry, this.rx), this.rz, m);
}
if (age < 0.7) {
if (age < 0.7 && !a.visit) {
this.rot(A[0], A[1], A[2]);
if (this.rz > 0.02) {
g.globalAlpha = m * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1;
@@ -753,7 +763,7 @@
M.spawn = function (it) {
var a = this.free.pop() || {};
var o = it.o, d = it.d, hostile = !!it.hl;
a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d;
a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; a.visit = !!it.v;
a.born = this.T;
a.u0 = (o.lon + 180) / 360; a.v0 = (LAT_TOP - clamp(o.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT);
a.a = vec(o.lat, o.lon); a.b = d.v;
@@ -761,8 +771,9 @@
a.D = hostile ? 1.35 : 1.0;
a.hold = hostile ? 1.4 : 0.2;
a.pl = hostile ? 1.9 : 1.1;
if (a.visit) { a.D = 0.75; a.hold = 0; a.pl = 0.1; }
a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D);
this.arcs.push(a);
(a.visit ? this.varcs : this.arcs).push(a);
return a;
};
@@ -782,6 +793,19 @@
if (merged) this.addMore(merged);
};
// legitimate visits: their own queue and cap, always drawn under the attacks
M.stepVisits = function () {
var q = this.vpending, n = 0, budget = q.length > 60 ? 30 : 8;
while (q.length && n < budget && this.varcs.length < Math.round(MAX_VARCS * this.quality)) { this.spawn(q.shift()); n++; }
};
M.ordered = function () {
var o = this.order || (this.order = []), i, j = 0;
for (i = 0; i < this.varcs.length; i++) o[j++] = this.varcs[i];
for (i = 0; i < this.arcs.length; i++) o[j++] = this.arcs[i];
o.length = j;
return o;
};
M.addMore = function (n) {
var s = Math.floor(Date.now() / 1000), m = this.more;
if (m.length && m[m.length - 1][0] === s) m[m.length - 1][1] += n; else m.push([s, n]);
@@ -811,7 +835,7 @@
if (this.frameAvg > 26) this.quality = Math.max(0.35, this.quality - 0.02);
else if (this.frameAvg < 20) this.quality = Math.min(1, this.quality + 0.01);
}
this.stepSpawn();
this.stepSpawn(); this.stepVisits();
}
var df = this.target - this.m, morph = false;
if (Math.abs(df) > 0.003) { this.m += df * (this.reduced ? 1 : Math.min(1, dt * 6.5)); morph = true; } else this.m = this.target;
@@ -826,11 +850,14 @@
if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle
this.dirty = false;
this.draw();
var arcs = this.arcs;
for (var i = arcs.length - 1; i >= 0; i--) {
if (this.T - arcs[i].born > arcs[i].life) {
this.free.push(arcs[i]);
arcs[i] = arcs[arcs.length - 1]; arcs.pop();
var lists = [this.arcs, this.varcs];
for (var li = 0; li < 2; li++) {
var arcs = lists[li];
for (var i = arcs.length - 1; i >= 0; i--) {
if (this.T - arcs[i].born > arcs[i].life) {
this.free.push(arcs[i]);
arcs[i] = arcs[arcs.length - 1]; arcs.pop();
}
}
}
if (!still || morph || this.dirty) this.kick();
@@ -845,6 +872,14 @@
U.registerI18n({
en: {
'live.title': 'Live',
'live.visits': 'Legitimate traffic',
'live.visit': 'visit',
'live.legend.visits': 'visits',
'live.m.vis': 'Visits, 15 min',
'live.m.pages': 'Pages, 15 min',
'live.unit.pages': 'distinct pages',
'live.devices': 'Devices',
'live.vis.empty': 'anonymous',
'live.mode': 'View',
'live.mode.flat': 'Flat map',
'live.mode.globe': 'Globe',
@@ -886,6 +921,14 @@
},
'pt-BR': {
'live.title': 'Ao vivo',
'live.visits': 'Tráfego legítimo',
'live.visit': 'visita',
'live.legend.visits': 'visitas',
'live.m.vis': 'Visitas, 15 min',
'live.m.pages': 'Páginas, 15 min',
'live.unit.pages': 'páginas distintas',
'live.vis.empty': 'anônima',
'live.devices': 'Dispositivos',
'live.mode': 'Visualização',
'live.mode.flat': 'Mapa plano',
'live.mode.globe': 'Globo',
@@ -951,12 +994,15 @@
this.minute = -1; this.listDirty = true; this.hoverList = false;
this.more = []; this.listeners = []; this.timers = []; this.dn = null; this.dnLang = '';
this.lastEv = null;
this.visitsOn = false; this.es = null; this.vring = []; this.vbk = {}; this.pathLast = new Map(); this.devs = {}; this.devChips = {}; this.offDev = {}; this.seen = {}; this.seenN = 0;
try { this.visitsOn = localStorage.getItem('urutau.live.visits') === '1'; } catch (x) { /* storage blocked */ }
this.build();
this.map = mapApi(new AttackMap(U, this.mapBox, { mode: this.pref(), interactive: true }));
this.map.onMore(function (n) { self.addMore(n); });
this.map.onPick(function (d) { self.toggleHost(d.host); });
this.syncMode(this.pref());
this.applyVisits();
this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null;
this.listen(document, 'visibilitychange', function () { self.onVisibility(); });
@@ -984,6 +1030,7 @@
P.destroy = function () {
this.alive = false;
if (this.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; }
this.closeStream();
this.timers.forEach(clearInterval); this.timers = [];
this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } });
this.listeners = [];
@@ -1003,14 +1050,16 @@
// language changed: rebuild the DOM keeping the map, the filters and the paused state
P.rebuild = function () {
var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused;
this.hostsSeen = {}; this.hostChips = {};
var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused, devs = Object.keys(this.devs);
this.hostsSeen = {}; this.hostChips = {}; this.devChips = {}; this.devs = {};
var mapEl = this.map._map.cv, was = this.stage.classList.contains('lv-nopanels');
this.build();
this.mapBox.appendChild(mapEl);
this.map._map.container = this.mapBox;
if (this.map._map.ro) { this.map._map.ro.disconnect(); this.map._map.ro.observe(this.mapBox); }
hosts.forEach(function (h) { self.noteHost(h); });
devs.forEach(function (d) { self.noteDevice(d); });
this.applyVisits();
this.stage.classList.toggle('lv-nopanels', was);
this.syncMode(this.map.getMode());
if (paused) this.setPaused(true);
@@ -1083,15 +1132,24 @@
this.bFs.setAttribute('aria-pressed', 'false');
ctl.appendChild(this.bFs);
}
this.bVis = document.createElement('button');
this.bVis.type = 'button'; this.bVis.className = 'lv-btn lv-vis';
this.bVis.appendChild(this.el('span', 'lv-vis-dot'));
this.bVis.appendChild(this.el('span', '', t('live.visits')));
this.bVis.addEventListener('click', function () { self.setVisits(!self.visitsOn); });
ctl.appendChild(this.bVis);
bar.appendChild(ctl);
this.hostBox = el('div', 'lv-hosts'); this.hostBox.setAttribute('role', 'group'); this.hostBox.setAttribute('aria-label', t('live.hosts'));
bar.appendChild(this.hostBox);
this.devBox = el('div', 'lv-hosts lv-devs'); this.devBox.setAttribute('role', 'group'); this.devBox.setAttribute('aria-label', t('live.devices'));
bar.appendChild(this.devBox);
var notes = el('div', 'lv-notes');
this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.hidden = true;
this.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true;
this.nMore = el('span', 'lv-note', ''); this.nMore.hidden = true;
this.nEst = el('span', 'lv-note', t('live.est')); this.nEst.hidden = true;
[this.nPaused, this.nFilter, this.nMore, this.nEst].forEach(function (n) { notes.appendChild(n); });
this.nLeg = el('span', 'lv-note lv-leg'); this.nLeg.appendChild(el('span', 'lv-leg-sw')); this.nLeg.appendChild(el('span', '', t('live.legend.visits')));
[this.nPaused, this.nFilter, this.nMore, this.nEst, this.nLeg].forEach(function (n) { notes.appendChild(n); });
bar.appendChild(notes);
stage.appendChild(bar);
@@ -1105,7 +1163,7 @@
var side = el('div', 'lv-side'); this.side = side;
var mets = el('div', 'lv-metrics');
this.mM = {};
['15m', '1h', 'avg', 'ips', 'new', 'last'].forEach(function (k) { self.mM[k] = self.metric(k); mets.appendChild(self.mM[k]); });
['15m', '1h', 'avg', 'ips', 'new', 'last', 'vis', 'pages'].forEach(function (k) { self.mM[k] = self.metric(k); if (k === 'vis' || k === 'pages') self.mM[k].classList.add('lv-m-visit'); mets.appendChild(self.mM[k]); });
this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true');
this.spark.width = 150; this.spark.height = 32;
this.mM['15m'].appendChild(this.spark);
@@ -1195,6 +1253,72 @@
this.map.resize();
};
// ---- legitimate traffic (anonymous visits): its own stream, only while the option is on
P.setVisits = function (on) {
this.visitsOn = on;
try { localStorage.setItem('urutau.live.visits', on ? '1' : '0'); } catch (x) { /* storage blocked */ }
this.applyVisits();
this.minute = -1; this.listDirty = true; this.tick(true);
};
P.applyVisits = function () {
var on = this.visitsOn;
this.bVis.setAttribute('aria-pressed', on ? 'true' : 'false');
this.stage.classList.toggle('lv-vis-on', on);
if (on) this.openStream(); else { this.closeStream(); this.vring = []; this.map.clear(); }
this.map._map.resize();
};
P.openStream = function () {
var self = this;
if (this.es || !window.EventSource) return;
var es = new EventSource('/api/v1/events/stream?visits=1');
es.addEventListener('ev', function (m) {
var e;
try { e = JSON.parse(m.data); } catch (x) { return; }
if (!e || typeof e !== 'object') return;
if (e.kind === 'visit') self.visit(e);
else if (e.kind === 'visit_batch') self.visitBatch(e);
else self.ingest(e);
});
this.es = es;
};
P.closeStream = function () { if (this.es) { this.es.close(); this.es = null; } };
P.noteDevice = function (d) {
if (!d || this.devs[d] || Object.keys(this.devs).length >= 8) return;
var self = this;
this.devs[d] = 1;
var b = document.createElement('button');
b.type = 'button'; b.className = 'lv-chip'; b.setAttribute('aria-pressed', this.offDev[d] ? 'false' : 'true');
b.appendChild(this.el('span', 'lv-chip-l', d));
b.addEventListener('click', function () {
self.offDev[d] = !self.offDev[d];
b.setAttribute('aria-pressed', self.offDev[d] ? 'false' : 'true');
self.listDirty = true;
});
this.devBox.appendChild(b); this.devChips[d] = b;
};
P.vcount = function (n, t, dev, path) {
var m = Math.floor(t / 60), b = this.vbk[m] || (this.vbk[m] = { n: 0 });
b.n += n;
if (path && (this.pathLast.size < 5000 || this.pathLast.has(path))) this.pathLast.set(path, m);
};
P.visit = function (e) {
var s = e.src && typeof e.src === 'object' ? e.src : null, tsec = isNum(e.t) ? e.t : Date.now() / 1000;
var dev = str(e.device, 16), path = str(e.path, 90);
var r = { visit: true, t: tsec, host: str(e.host, 64) || 'local', city: str(s && s.city, 48), cc: cc2(s && s.cc) || cc2(e.cc), domain: str(e.domain, 60), path: path, device: dev, ev: e };
this.noteHost(r.host); if (dev) this.noteDevice(dev);
this.vcount(1, tsec, dev, path);
this.vring.push(r);
if (this.vring.length > 200) this.vring.splice(0, 80);
this.listDirty = true;
if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return;
var h = this.ctx && this.ctx.host;
if (h && h !== 'all' && h !== r.host) return;
this.map.spawn(e, { visit: true });
};
P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); };
P.toggleHost = function (h) {
if (!this.hostChips[h]) return;
this.offHosts[h] = !this.offHosts[h];
@@ -1331,6 +1455,11 @@
else if (e.source === 'fail2ban') what = 'fail2ban [' + str(e.jail, 40) + ']';
var key = tsec + '|' + ip + '|' + e.cat + '|' + what;
if (have) { if (have[key]) return null; have[key] = 1; }
else if (this.es) {
if (this.seen[key]) return null;
this.seen[key] = 1;
if (++this.seenN > 3000) { this.seen = {}; this.seenN = 0; }
}
var r = { t: tsec, key: key, cat: e.cat, host: host, ip: ip, what: what, cc: cc2(s && s.cc) || cc2(e.cc), city: str(s && s.city, 48), ev: e };
this.noteHost(host);
this.ring.push(r);
@@ -1467,6 +1596,16 @@
for (var k in this.bk) if (+k < min - 1500) delete this.bk[k];
};
P.visitMetrics = function (min, fmtN) {
var vn = 0, pg = 0, vi, mm = this.mM, self = this;
for (vi = min - 14; vi <= min; vi++) if (this.vbk[vi]) vn += this.vbk[vi].n;
this.pathLast.forEach(function (last) { if (last >= min - 14) pg++; });
mm.vis.val.textContent = fmtN(vn); this.setSub(mm.vis, this.t('live.legend.visits'), '');
mm.pages.val.textContent = fmtN(pg); this.setSub(mm.pages, this.t('live.unit.pages'), '');
this.pathLast.forEach(function (last, p) { if (last < min - 30) self.pathLast.delete(p); });
for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk];
};
P.regionName = function (cc) {
if (this.U.fmt && this.U.fmt.country) { var n = this.U.fmt.country(cc); if (n) return n; }
var lang = this.ctx.lang || undefined;
@@ -1482,6 +1621,7 @@
var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String;
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); }
if (this.visitsOn) this.visitMetrics(min, fmtN);
// category and server counts, origins: the 15 minute window (partial minute included)
var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c;
CATS.forEach(function (k) {
@@ -1541,8 +1681,20 @@
var box = this.recList, ring = this.ring, n = 0, self = this, i, r;
var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; };
while (box.firstChild) box.removeChild(box.firstChild);
for (i = ring.length - 1; i >= 0 && n < 30; i--) {
r = ring[i];
var merged = ring;
if (this.visitsOn && this.vring.length) merged = ring.concat(this.vring).sort(function (a, b) { return a.t - b.t; });
for (i = merged.length - 1; i >= 0 && n < 30; i--) {
r = merged[i];
if (r.visit) {
if (!this.hostOk(r.host) || (r.device && this.offDev[r.device])) continue;
n++;
var vl = this.el('li', 'lv-ev lv-ev-visit');
vl.appendChild(this.el('time', 'lv-ev-t', new Date(r.t * 1000).toLocaleTimeString(this.ctx.lang || undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' })));
vl.appendChild(this.el('span', 'lv-tag lv-k-visit', this.t('live.visit')));
vl.appendChild(this.el('span', 'lv-vtxt', [r.city || this.t('live.vis.empty'), r.domain, r.path, r.device].filter(Boolean).join(' \u00B7 ')));
box.appendChild(vl);
continue;
}
if (!this.visible(r)) continue;
n++;
var li = this.el('li', 'lv-ev');
+28
View File
@@ -0,0 +1,28 @@
/* MITRE ATT&CK page */
.mt-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.mt-matrix { display: grid; gap: var(--s-3, 12px); grid-template-columns: repeat(auto-fit, minmax(10.5rem, 1fr)); }
.mt-col { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.mt-th { display: flex; flex-direction: column; padding: 6px 8px; border-bottom: 2px solid var(--accent); min-width: 0; }
.mt-th strong { font: 700 .875rem/1.25 var(--font-display, inherit); color: var(--heading, var(--ink)); overflow-wrap: anywhere; }
.mt-th-sub { color: var(--ink-muted); font-size: .75rem; }
.mt-cell { display: grid; grid-template-columns: 1fr auto; gap: 0 8px; text-align: left; cursor: pointer; min-width: 0;
color: var(--ink); font: inherit; padding: 7px 9px; border-radius: 6px; border: 1px solid var(--line);
background: color-mix(in srgb, var(--accent) calc(var(--i, .1) * 60%), var(--surface-panel)); }
.mt-cell:hover, .mt-cell:focus-visible { border-color: var(--accent); }
.mt-cell.on { outline: 2px solid var(--accent); outline-offset: 1px; }
.mt-id { font: 600 .75rem/1.2 var(--font-mono, monospace); color: var(--ink-muted); grid-column: 1; }
.mt-n { grid-column: 2; grid-row: 1 / span 2; align-self: center; font-weight: 700; }
.mt-name { grid-column: 1; font-size: .8125rem; line-height: 1.25; overflow-wrap: anywhere; }
.mt-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.mt-table th, .mt-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
.mt-table th.num, .mt-table td.num { text-align: right; }
.mt-tablewrap { min-width: 0; max-width: 100%; }
.mt-link { color: var(--accent); font-family: var(--font-mono, monospace); }
.mt-trend { white-space: nowrap; font-size: .8125rem; }
.mt-up { color: var(--danger); } .mt-down { color: var(--ok); } .mt-flat, .mt-new { color: var(--ink-muted); }
.mt-drill { margin-top: var(--s-4, 16px); padding-top: var(--s-3, 12px); border-top: 1px solid var(--line); }
.mt-drill-h { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.mt-drill-h h3 { margin-right: auto; font-size: 1rem; overflow-wrap: anywhere; }
.mt-drill h4 { margin: 12px 0 6px; font-size: .875rem; color: var(--ink-muted); }
.mt-ips { display: flex; flex-wrap: wrap; gap: 6px; }
.mt-path { font-family: var(--font-mono, monospace); }
+236
View File
@@ -0,0 +1,236 @@
/* Urutau - MITRE ATT&CK page: tactics x techniques matrix, radar per tactic and
ranking with trend. Data: /api/v1/techniques. Drill-down reads
/api/v1/events and keeps the events that carry the technique. Log data is
hostile: dynamic text goes through textContent only. */
(function () {
'use strict';
var TECH_RE = /^T\d{4}(\.\d{3})?$/;
var DRILL_LIMIT = 5000;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'mt.title': 'MITRE ATT&CK',
'mt.lead.some': '{n} techniques in {m} tactics {range}',
'mt.lead.sub': '{n} events matched a known technique.',
'mt.lead.none': 'No technique observed {range}',
'mt.lead.none.sub': 'Nothing matched the ATT&CK mapping in this window.',
'mt.matrix': 'Which tactics and techniques hit us?',
'mt.matrix.hint': 'Columns are tactics, cells are techniques; the darker, the more events. Click a cell to see who used it.',
'mt.radar': 'Pressure per tactic',
'mt.rank': 'Techniques by volume',
'mt.col.tech': 'Technique',
'mt.col.events': 'Events',
'mt.col.ips': 'IPs',
'mt.col.trend': 'Trend',
'mt.trend.new': 'new',
'mt.trend.vs': 'against the previous period of the same length',
'mt.cell': '{name}: {events} events, {ips} IPs',
'mt.drill.title': 'Who used {id}',
'mt.drill.loading': 'Loading events...',
'mt.drill.none': 'No recent event with this technique in the loaded sample.',
'mt.drill.note': 'Showing {n} of the most recent events ({ips} IPs).',
'mt.drill.ips': 'IPs',
'mt.drill.events': 'Latest events',
'mt.drill.open': 'Open on attack.mitre.org',
'mt.drill.close': 'Close',
'mt.error': 'Could not load the techniques.',
'mt.disabled': 'The event registry is off',
'mt.disabled.sub': 'Techniques are read from the event registry; enable it to see this page.',
'mt.empty': 'No technique in this window',
'mt.partial': 'Partial result: the study hit its time or size limit.'
},
'pt-BR': {
'mt.title': 'MITRE ATT&CK',
'mt.lead.some': '{n} técnicas em {m} táticas {range}',
'mt.lead.sub': '{n} eventos corresponderam a uma técnica conhecida.',
'mt.lead.none': 'Nenhuma técnica observada {range}',
'mt.lead.none.sub': 'Nada correspondeu ao mapeamento ATT&CK nesta janela.',
'mt.matrix': 'Que táticas e técnicas nos atingem?',
'mt.matrix.hint': 'As colunas são táticas e as células, técnicas; quanto mais escuro, mais eventos. Clique numa célula para ver quem a usou.',
'mt.radar': 'Pressão por tática',
'mt.rank': 'Técnicas por volume',
'mt.col.tech': 'Técnica',
'mt.col.events': 'Eventos',
'mt.col.ips': 'IPs',
'mt.col.trend': 'Tendência',
'mt.trend.new': 'nova',
'mt.trend.vs': 'em relação ao período anterior de mesma duração',
'mt.cell': '{name}: {events} eventos, {ips} IPs',
'mt.drill.title': 'Quem usou {id}',
'mt.drill.loading': 'Carregando eventos...',
'mt.drill.none': 'Nenhum evento recente com esta técnica na amostra carregada.',
'mt.drill.note': 'Mostrando {n} dos eventos mais recentes ({ips} IPs).',
'mt.drill.ips': 'IPs',
'mt.drill.events': 'Últimos eventos',
'mt.drill.open': 'Abrir em attack.mitre.org',
'mt.drill.close': 'Fechar',
'mt.error': 'Não foi possível carregar as técnicas.',
'mt.disabled': 'O registro de eventos está desligado',
'mt.disabled.sub': 'As técnicas vêm do registro de eventos; ative-o para ver esta página.',
'mt.empty': 'Nenhuma técnica nesta janela',
'mt.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.'
}
});
var el = U.el, t = U.t, nf = U.fmt.num;
var root = null, seq = 0, alive = false, ctx = null, data = null, errBox = null, sel = null, drillSeq = 0;
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function when(s) { return s ? U.fmt.ago(s) : ''; }
function techURL(id) {
if (!TECH_RE.test(id)) return 'https://attack.mitre.org/techniques/';
return 'https://attack.mitre.org/techniques/' + id.replace('.', '/') + '/';
}
function trendNode(row) {
if (row.trend_pct === null || row.trend_pct === undefined) return el('span', { class: 'mt-trend mt-new', title: t('mt.trend.vs') }, t('mt.trend.new'));
var v = row.trend_pct, up = v > 0.5, down = v < -0.5;
var txt = (up ? '▲ ' : down ? '▼ ' : '■ ') + Math.abs(Math.round(v)) + '%';
return el('span', { class: 'mt-trend ' + (up ? 'mt-up' : down ? 'mt-down' : 'mt-flat'), title: t('mt.trend.vs') }, txt);
}
function renderMatrix(tactics, max) {
var grid = el('div', { class: 'mt-matrix' });
tactics.forEach(function (ta) {
var col = el('div', { class: 'mt-col' });
var total = ta.techniques.reduce(function (a, x) { return a + x.events; }, 0);
col.appendChild(el('div', { class: 'mt-th' },
el('strong', null, ta.name),
el('span', { class: 'mt-th-sub' }, (ta.id || '-') + ' · ' + nf(total))));
ta.techniques.forEach(function (tc) {
var ratio = Math.max(0.08, Math.min(1, tc.events / max));
var b = el('button', {
type: 'button', class: 'mt-cell' + (sel === tc.id ? ' on' : ''), style: { '--i': ratio.toFixed(3) },
title: t('mt.cell', { name: tc.name, events: nf(tc.events), ips: nf(tc.ips) })
}, el('span', { class: 'mt-id' }, tc.id), el('span', { class: 'mt-name' }, tc.name), el('span', { class: 'mt-n num' }, nf(tc.events)));
b.addEventListener('click', function () { sel = sel === tc.id ? null : tc.id; paint(); });
col.appendChild(b);
});
grid.appendChild(col);
});
return grid;
}
function renderRank(rows) {
var tb = el('tbody');
rows.slice(0, 15).forEach(function (r) {
tb.appendChild(el('tr', null,
el('td', null, el('a', { class: 'mt-link', href: techURL(r.id), target: '_blank', rel: 'noopener noreferrer' }, r.id), ' ', r.name),
el('td', { class: 'num' }, nf(r.events)),
el('td', { class: 'num' }, nf(r.ips)),
el('td', null, trendNode(r))));
});
return el('div', { class: 'mt-tablewrap' }, el('table', { class: 'mt-table' },
el('thead', null, el('tr', null, el('th', null, t('mt.col.tech')), el('th', { class: 'num' }, t('mt.col.events')), el('th', { class: 'num' }, t('mt.col.ips')), el('th', null, t('mt.col.trend')))), tb));
}
var drillBox = null;
function drill(tc) {
var my = ++drillSeq;
if (!drillBox) return;
clear(drillBox);
drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.loading')));
var p = ctx && ctx.from ? { from: ctx.from, to: ctx.to } : U.rangeParams();
var q = {}; Object.keys(p).forEach(function (k) { q[k] = p[k]; });
if (ctx && ctx.host && ctx.host !== 'all') q.host = ctx.host;
q.limit = DRILL_LIMIT;
U.api('/api/v1/events', q).then(function (d) {
if (!alive || my !== drillSeq) return;
var evs = (d.events || []).filter(function (e) { return Array.isArray(e.tech) && e.tech.indexOf(tc.id) >= 0; });
var byIP = {};
evs.forEach(function (e) { byIP[e.ip] = (byIP[e.ip] || 0) + 1; });
var ips = Object.keys(byIP).sort(function (a, b) { return byIP[b] - byIP[a]; });
clear(drillBox);
drillBox.appendChild(el('div', { class: 'mt-drill-h' },
el('h3', null, t('mt.drill.title', { id: tc.id }) + ' · ' + tc.name),
el('a', { class: 'btn', href: techURL(tc.id), target: '_blank', rel: 'noopener noreferrer' }, t('mt.drill.open')),
(function () { var b = el('button', { type: 'button', class: 'btn' }, t('mt.drill.close')); b.addEventListener('click', function () { sel = null; paint(); }); return b; })()));
if (!evs.length) { drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.none'))); return; }
drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.note', { n: nf(evs.length), ips: nf(ips.length) })));
var chips = el('div', { class: 'mt-ips' });
ips.slice(0, 24).forEach(function (ip) {
var b = el('button', { type: 'button', class: 'chip' }, ip + ' ×' + nf(byIP[ip]));
b.addEventListener('click', function () { U.openIP(ip); });
chips.appendChild(b);
});
var tb = el('tbody');
evs.slice(0, 20).forEach(function (e) {
tb.appendChild(el('tr', null, el('td', null, e.t ? U.fmt.clock(e.t) : ''), el('td', null, String(e.ip || '')), el('td', null, String(e.cat || '')),
el('td', { class: 'mt-path' }, String(e.path || e.user || e.jail || ''))));
});
drillBox.appendChild(el('h4', null, t('mt.drill.ips')));
drillBox.appendChild(chips);
drillBox.appendChild(el('h4', null, t('mt.drill.events')));
drillBox.appendChild(el('div', { class: 'mt-tablewrap' }, el('table', { class: 'mt-table' }, tb)));
}).catch(function () {
if (!alive || my !== drillSeq) return;
clear(drillBox); drillBox.appendChild(el('p', { class: 'hint' }, t('mt.error')));
});
}
function paint() {
if (!root) return;
clear(root);
drillBox = null;
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
if (!data.enabled) { root.appendChild(U.ui.empty(t('mt.disabled'), t('mt.disabled.sub'))); return; }
var tactics = data.tactics || [], all = [];
tactics.forEach(function (ta) { ta.techniques.forEach(function (x) { all.push(x); }); });
var range = U.rangeLabel({ inline: true });
if (!all.length) {
root.appendChild(U.ui.lead(t('mt.lead.none', { range: range }), t('mt.lead.none.sub'), 'ok'));
root.appendChild(U.ui.empty(t('mt.empty')));
return;
}
root.appendChild(U.ui.lead(t('mt.lead.some', { n: nf(all.length), m: nf(tactics.length), range: range }), t('mt.lead.sub', { n: nf(data.total) }), 'danger'));
if (data.truncated) root.appendChild(el('p', { class: 'hint' }, t('mt.partial')));
var max = Math.max.apply(null, all.map(function (x) { return x.events; }));
var grid = el('div', { class: 'grid-12' });
var mp = U.ui.panel({ title: t('mt.matrix'), hint: t('mt.matrix.hint'), cls: 'span-12' }, renderMatrix(tactics, max));
drillBox = el('div', { class: 'mt-drill' });
if (sel) { mp.body.appendChild(drillBox); } else drillBox = null;
grid.appendChild(mp);
var axes = tactics.map(function (ta) { return { key: ta.id || 'other', label: ta.name }; });
var vals = tactics.map(function (ta) { return ta.techniques.reduce(function (a, x) { return a + x.events; }, 0); });
var rp = U.ui.panel({ title: t('mt.radar'), cls: 'span-4' });
if (U.charts && U.charts.radar && axes.length >= 3) rp.body.appendChild(U.charts.radar(axes, [{ label: t('mt.col.events'), values: vals }], { title: t('mt.radar'), format: nf }));
else if (U.charts && U.charts.bars) rp.body.appendChild(U.charts.bars(tactics.map(function (ta, i) { return { key: ta.id || 'other', label: ta.name, value: vals[i] }; }), { title: t('mt.radar'), format: nf }));
grid.appendChild(rp);
grid.appendChild(U.ui.panel({ title: t('mt.rank'), cls: 'span-8' }, renderRank(all.slice().sort(function (a, b) { return b.events - a.events; }))));
root.appendChild(grid);
if (sel) {
var tc = all.filter(function (x) { return x.id === sel; })[0];
if (tc) drill(tc); else { sel = null; }
}
}
function load() {
var my = ++seq;
U.api('/api/v1/techniques', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(root);
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('mt.error'))));
});
}
U.registerPage({
id: 'mitre', group: 'analyze', titleKey: 'mt.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="5" height="18" rx="1"/><rect x="10" y="3" width="5" height="11" rx="1"/><rect x="17" y="3" width="4" height="7" rx="1"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'mt-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; sel = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { if (!sel) load(); },
unmount: function () { alive = false; seq++; drillSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+72
View File
@@ -0,0 +1,72 @@
{
"pages": [
{
"name": "geo",
"css": true
},
{
"name": "live",
"css": true
},
{
"name": "ip",
"css": true
},
{
"name": "replay",
"css": true
},
{
"name": "sessions",
"css": true
},
{
"name": "campaigns",
"css": true
},
{
"name": "search",
"css": true
},
{
"name": "mitre",
"css": true
},
{
"name": "defense",
"css": true
},
{
"name": "evolution",
"css": true
},
{
"name": "concentration",
"css": true
},
{
"name": "survival",
"css": true
},
{
"name": "errors",
"css": true
},
{
"name": "slo",
"css": true
},
{
"name": "protocol",
"css": true
},
{
"name": "integrity",
"css": true
},
{
"name": "reports",
"css": true
}
]
}
+10
View File
@@ -0,0 +1,10 @@
/* Errors page */
.hl-scroll { max-height: 420px; overflow: auto; }
.hl-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.hl-table th, .hl-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; }
.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.hl-page .panel { min-width: 0; }
@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } }
.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); }
.hl-help { display: inline-flex; align-items: center; gap: 4px; }
+141
View File
@@ -0,0 +1,141 @@
/* Urutau - page PROTOCOL ("Protocols and TLS"): HTTP version and TLS version by error class,
cipher suites, unusual methods, http against https. Data: /api/v1/protocols. textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var CLS = ['ok', 'app', 'proxy', 'blocked', 'attack', 'bot', 'client'];
var COLOR = { ok: '--ok', app: '--danger', proxy: '--warn', blocked: '--info', attack: '--cat-exploit', bot: '--viz-6', client: '--viz-5' };
var PROTO = ['http1', 'http2', 'http3', 'other'];
var TLS = ['tls13', 'tls12', 'tls_old', 'none'];
U.registerI18n({
en: {
'hl.pr.title': 'Protocols and TLS',
'hl.pr.lead': '{pct} of requests use HTTP/2 or newer over TLS 1.3',
'hl.pr.lead.body': '{plain} arrive over plain http {range}. Attack traffic leans on {atk}.',
'hl.pr.lead.empty': 'No protocol data yet',
'hl.pr.lead.empty.body': 'No Traefik requests with protocol fields {range}. Older log formats do not carry them.',
'hl.pr.proto': 'HTTP version by class', 'hl.pr.proto.hint': 'Share of each class per protocol. Scripts and scanners often speak HTTP/1.1 or 1.0.',
'hl.pr.tls': 'TLS version by class', 'hl.pr.tls.hint': 'Plain http and old TLS versions stand out here.',
'hl.pr.ciphers': 'Cipher suites', 'hl.pr.ciphers.hint': 'What clients negotiated.',
'hl.pr.methods': 'Methods', 'hl.pr.methods.hint': 'Methods outside GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are marked.',
'hl.pr.scheme': 'http against https', 'hl.pr.scheme.hint': 'Requests that reached the proxy on each entry point.',
'hl.pr.odd': 'unusual', 'hl.pr.col.method': 'Method', 'hl.pr.col.n': 'Requests', 'hl.pr.col.errs': 'Errors',
'hl.pr.p.http1': 'HTTP/1.x', 'hl.pr.p.http2': 'HTTP/2', 'hl.pr.p.http3': 'HTTP/3', 'hl.pr.p.other': 'Other',
'hl.pr.t.tls13': 'TLS 1.3', 'hl.pr.t.tls12': 'TLS 1.2', 'hl.pr.t.tls_old': 'TLS 1.1 or older', 'hl.pr.t.none': 'No TLS (http)',
'hl.pr.s.https': 'https', 'hl.pr.s.http': 'http',
'hl.pr.c.ok': 'Succeeded', 'hl.pr.c.app': 'Application', 'hl.pr.c.proxy': 'Proxy', 'hl.pr.c.blocked': 'Blocked', 'hl.pr.c.attack': 'Attack', 'hl.pr.c.bot': 'Crawlers', 'hl.pr.c.client': 'Client',
'hl.pr.err': 'Could not load the protocol data.', 'hl.pr.retry': 'Try again', 'hl.pr.empty': 'Nothing to show for this range.'
},
'pt-BR': {
'hl.pr.title': 'Protocolos e TLS',
'hl.pr.lead': '{pct} das requisições usam HTTP/2 ou mais novo sobre TLS 1.3',
'hl.pr.lead.body': '{plain} chegam por http puro {range}. O tráfego de ataque se concentra em {atk}.',
'hl.pr.lead.empty': 'Ainda sem dados de protocolo',
'hl.pr.lead.empty.body': 'Nenhuma requisição do Traefik com campos de protocolo {range}. Formatos de log antigos não os trazem.',
'hl.pr.proto': 'Versão do HTTP por classe', 'hl.pr.proto.hint': 'Parcela de cada classe por protocolo. Scripts e varreduras costumam falar HTTP/1.1 ou 1.0.',
'hl.pr.tls': 'Versão do TLS por classe', 'hl.pr.tls.hint': 'Http puro e versões antigas de TLS aparecem aqui.',
'hl.pr.ciphers': 'Suítes de cifra', 'hl.pr.ciphers.hint': 'O que os clientes negociaram.',
'hl.pr.methods': 'Métodos', 'hl.pr.methods.hint': 'Métodos fora de GET, HEAD, POST, PUT, PATCH, DELETE e OPTIONS ficam marcados.',
'hl.pr.scheme': 'http contra https', 'hl.pr.scheme.hint': 'Requisições que chegaram ao proxy em cada entrada.',
'hl.pr.odd': 'incomum', 'hl.pr.col.method': 'Método', 'hl.pr.col.n': 'Requisições', 'hl.pr.col.errs': 'Erros',
'hl.pr.p.http1': 'HTTP/1.x', 'hl.pr.p.http2': 'HTTP/2', 'hl.pr.p.http3': 'HTTP/3', 'hl.pr.p.other': 'Outro',
'hl.pr.t.tls13': 'TLS 1.3', 'hl.pr.t.tls12': 'TLS 1.2', 'hl.pr.t.tls_old': 'TLS 1.1 ou anterior', 'hl.pr.t.none': 'Sem TLS (http)',
'hl.pr.s.https': 'https', 'hl.pr.s.http': 'http',
'hl.pr.c.ok': 'Sucesso', 'hl.pr.c.app': 'Aplicação', 'hl.pr.c.proxy': 'Proxy', 'hl.pr.c.blocked': 'Bloqueado', 'hl.pr.c.attack': 'Ataque', 'hl.pr.c.bot': 'Rastreadores', 'hl.pr.c.client': 'Cliente',
'hl.pr.err': 'Não foi possível carregar os dados de protocolo.', 'hl.pr.retry': 'Tentar de novo', 'hl.pr.empty': 'Nada para mostrar neste período.'
}
});
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function sum(o) { var n = 0; Object.keys(o || {}).forEach(function (k) { n += o[k]; }); return n; }
// rows (one per protocol/version) of parts (one per class), each row scaled to 100%
function stacked(rows, label, host) {
var data = rows.map(function (r) {
var tot = sum(r.c);
return { key: r.k, label: label(r.k) + ' (' + U.fmt.num(tot) + ')', value: 100,
parts: CLS.map(function (k) { return { label: t('hl.pr.c.' + k), value: tot ? (r.c[k] || 0) / tot * 100 : 0, color: COLOR[k] }; }) };
});
if (U.charts && U.charts.bars) host.appendChild(U.charts.bars(data, { horizontal: true, stacked: true, format: function () { return ''; }, title: '' }));
else host.appendChild(U.ui.empty(t('hl.pr.empty')));
var lg = el('div', { class: 'hl-legend' });
CLS.forEach(function (k) { lg.appendChild(el('span', null, el('i', { style: { background: 'var(' + COLOR[k] + ')' } }), t('hl.pr.c.' + k))); });
host.appendChild(lg);
}
// a client class collapses its subtypes (the API already sums them under "client")
function rowsOf(map, names) {
return names.filter(function (k) { return map && map[k]; }).map(function (k) { return { k: k, c: map[k] }; });
}
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 hl-page' });
var lead = el('div', { class: 'span-12' });
var pp = U.ui.panel({ title: t('hl.pr.proto'), hint: t('hl.pr.proto.hint'), variant: 'chart', loading: true, cls: 'span-6' });
var pt = U.ui.panel({ title: t('hl.pr.tls'), hint: t('hl.pr.tls.hint'), variant: 'chart', loading: true, cls: 'span-6' });
var ps = U.ui.panel({ title: t('hl.pr.scheme'), hint: t('hl.pr.scheme.hint'), loading: true, cls: 'span-4' });
var pc = U.ui.panel({ title: t('hl.pr.ciphers'), hint: t('hl.pr.ciphers.hint'), variant: 'chart', loading: true, cls: 'span-8' });
var pm = U.ui.panel({ title: t('hl.pr.methods'), hint: t('hl.pr.methods.hint'), variant: 'list', loading: true, cls: 'span-12' });
[lead, pp, pt, ps, pc, pm].forEach(function (n) { grid.appendChild(n); });
root.appendChild(grid);
function paint() {
clear(lead); [pp, pt, ps, pc, pm].forEach(function (p) { clear(p.body); });
if (!data) return;
var d = data, range = U.rangeLabel({ inline: true });
var protoTot = {}, total = 0;
PROTO.forEach(function (k) { protoTot[k] = sum((d.protocols || {})[k]); total += protoTot[k]; });
if (!total) {
lead.appendChild(U.ui.lead(t('hl.pr.lead.empty'), t('hl.pr.lead.empty.body', { range: range }), 'neutral'));
[pp, pt, ps, pc, pm].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.pr.empty'))); });
return;
}
var modern = ((d.tls || {}).tls13 ? sum(d.tls.tls13) : 0), h2 = protoTot.http2 + protoTot.http3;
var plain = (d.scheme || {}).http || 0, https = (d.scheme || {}).https || 0;
var atkP = PROTO.slice().sort(function (a, b) { return ((d.protocols[b] || {}).attack || 0) - ((d.protocols[a] || {}).attack || 0); })[0];
lead.appendChild(U.ui.lead(t('hl.pr.lead', { pct: U.fmt.pct(Math.min(modern, h2) / total) }),
t('hl.pr.lead.body', { plain: U.fmt.pct(plain / Math.max(1, plain + https)), range: range, atk: t('hl.pr.p.' + atkP) }), plain > 0 ? 'warn' : 'neutral'));
stacked(rowsOf(d.protocols, PROTO), function (k) { return t('hl.pr.p.' + k); }, pp.body);
stacked(rowsOf(d.tls, TLS), function (k) { return t('hl.pr.t.' + k); }, pt.body);
// http vs https
if (U.charts && U.charts.donut) ps.body.appendChild(U.charts.donut([{ key: 'https', label: t('hl.pr.s.https'), value: https }, { key: 'http', label: t('hl.pr.s.http'), value: plain }],
{ title: t('hl.pr.scheme'), colors: ['--ok', '--warn'], centerLabel: t('hl.pr.col.n') }));
var ci = (d.ciphers || []).slice(0, 12).map(function (x) { return { key: x.name, label: x.name, value: x.n }; });
if (ci.length && U.charts && U.charts.bars) pc.body.appendChild(U.charts.bars(ci, { horizontal: true, title: t('hl.pr.ciphers') }));
else pc.body.appendChild(U.ui.empty(t('hl.pr.empty')));
var tb = el('tbody');
(d.methods || []).forEach(function (m) {
var errs = sum(m.classes) - (m.classes.ok || 0);
tb.appendChild(el('tr', null, el('td', { class: 'mono' }, m.method, m.odd ? U.ui.badge(t('hl.pr.odd'), 'warn') : null), el('td', { class: 'num' }, U.fmt.num(m.n)), el('td', { class: 'num' }, U.fmt.num(errs)),
el('td', null, CLS.filter(function (k) { return m.classes[k] || (k === 'client' && false); }).map(function (k) { return t('hl.pr.c.' + k) + ' ' + U.fmt.num(m.classes[k]); }).join(' · '))));
});
pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' },
el('thead', null, el('tr', null, el('th', null, t('hl.pr.col.method')), el('th', { class: 'num' }, t('hl.pr.col.n')), el('th', { class: 'num' }, t('hl.pr.col.errs')), el('th', null, ''))), tb)));
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.domain && c.domain !== 'all') p.host = c.domain;
U.api('/api/v1/protocols', p).then(function (r) { if (alive && my === seq) { data = r; paint(); } }, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('hl.pr.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.pr.err')), b));
});
}
load();
return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } };
}
U.registerPage({
id: 'protocol', group: 'analyze', titleKey: 'hl.pr.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/></svg>',
mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+78
View File
@@ -0,0 +1,78 @@
/* Urutau - REPORTS page. Selectors prefixed rpt-. On screen the report is a sheet; with
@media print it fills A4 pages and the shell chrome disappears. */
.rpt { min-width: 0; }
.rpt-box { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; }
.rpt-sheet { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius, 10px); padding: clamp(14px, 3vw, 32px); display: flex; flex-direction: column; gap: 22px; min-width: 0; color: var(--ink); }
.rpt-cover { border-bottom: 2px solid var(--accent); padding-bottom: 14px; }
.rpt-kicker { margin: 0; font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-muted); }
.rpt-cover h1 { margin: 4px 0 10px; font: 700 1.75rem/1.15 var(--font-display); color: var(--heading); }
.rpt-meta { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 3px 14px; margin: 0; font-size: .875rem; }
.rpt-meta dt { color: var(--ink-muted); }
.rpt-meta dd { margin: 0; overflow-wrap: anywhere; }
.rpt-sec h2 { margin: 0 0 10px; font: 650 1.0625rem/1.2 var(--font-display); color: var(--heading); }
.rpt-sents p { margin: 0 0 6px; font-size: .9375rem; line-height: 1.5; max-width: 90ch; overflow-wrap: anywhere; }
.rpt-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 12px; }
.rpt-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); min-width: 0; }
.rpt-kl { font-size: .75rem; color: var(--ink-muted); }
.rpt-kpi strong { font-size: 1.375rem; color: var(--heading); }
.rpt-kd { font-size: .6875rem; color: var(--ink-muted); }
.rpt-warn { color: var(--warn); font-size: .8125rem; }
.rpt-charts { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; }
@media (min-width: 900px) { .rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); } .rpt-wide { grid-column: 1 / -1; } }
.rpt-chart { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); padding: 10px 12px; }
.rpt-chart h3 { margin: 0 0 8px; font-size: .8125rem; font-weight: 600; color: var(--ink-muted); }
.rpt-p2 { display: flex; flex-direction: column; gap: 18px; min-width: 0; }
.rpt-scroll { overflow-x: auto; max-width: 100%; }
.rpt-table { width: 100%; border-collapse: collapse; font-size: .8125rem; }
.rpt-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 5px 8px; border-bottom: 1px solid var(--line-strong, var(--line)); }
.rpt-table td { padding: 5px 8px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; vertical-align: top; }
.rpt-none { margin: 0; color: var(--ink-muted); font-size: .8125rem; }
.rpt-foot { margin: 0; font-size: .75rem; color: var(--ink-faint); }
@page { size: A4; margin: 12mm; }
@media print {
:root, :root[data-theme] {
--surface-base: #fff; --surface-panel: #fff; --surface-sunken: #f4f6f8; --surface-raised: #fff;
--line: #cfd6dc; --line-strong: #8a96a0; --ink: #14202a; --ink-muted: #46545f; --ink-faint: #5d6b76; --heading: #000;
--accent: #0a78b5; --warn: #8a5a00;
color-scheme: light;
}
html, body { background: #fff !important; color: #14202a; }
.rail, .topbar, .slice, .tabbar, .more-sheet, .err-banner, .shell-foot, .toasts, .scrim, .skip, .rpt-bar, #detail { display: none !important; }
.app { display: block !important; background: none !important; min-height: 0; }
.main, main#view { display: block !important; padding: 0 !important; margin: 0 !important; overflow: visible !important; }
.rpt-sheet { border: 0; padding: 0; gap: 12px; border-radius: 0; }
.rpt-cover h1 { font-size: 1.5rem; }
.rpt-sec, .rpt-chart, .rpt-kpi { break-inside: avoid; }
.rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; }
.rpt-wide { grid-column: 1 / -1; }
.rpt-p2 { break-before: page; gap: 10px; }
.rpt-p2 .rpt-sec { break-inside: avoid; }
.rpt-scroll { overflow: visible; }
.rpt-table { font-size: 8.5pt; }
.rpt-sents p { font-size: 10pt; }
.rpt-kpi strong { font-size: 1.125rem; }
}
.rpt .vz svg, .rpt .chart-wrap svg { max-width: 100%; height: auto; }
@media print {
.rpt-sec-charts { break-inside: auto; }
.rpt-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.rpt-kpi { padding: 6px 8px; }
.rpt-chart { padding: 6px 8px; }
.rpt-chart svg { max-height: 150px; width: 100%; }
.rpt-chart .vz-legend, .rpt-chart ul { font-size: 8pt; }
.rpt-sheet { gap: 10px; }
}
@media print {
.rpt-chart svg { max-height: 120px; }
.rpt-chart .vz-donut, .rpt-chart .vz-donut svg { max-height: 120px; }
.rpt-chart .bar-row, .rpt-chart .vz-row { font-size: 8.5pt; }
.rpt-chart .vz-row { margin: 2px 0; }
}
@media print {
.rpt-noprint { display: none !important; }
.rpt-charts { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.rpt-table td, .rpt-table th { padding: 3px 6px; }
.rpt-p2 .rpt-sec h2 { margin-bottom: 4px; font-size: 11pt; }
}
+357
View File
@@ -0,0 +1,357 @@
/* Urutau - REPORTS page: executive report of the chosen period, printable on A4
(window.print() with @page / @media print in reports.css, no libraries) and
exportable as JSON or CSV. Data: GET /api/v1/report. Log data is hostile:
every dynamic string goes through textContent; CSV cells that start with
= + - @ get a leading apostrophe (spreadsheet formula injection). */
(function () {
'use strict';
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 3h7l5 5v13H7z"/><path d="M14 3v5h5M10 13h6M10 17h6"/></svg>';
function csvCell(v) {
if (v === null || v === undefined) return '';
if (typeof v === 'number') return isFinite(v) ? String(v) : '';
var s = String(v);
if (/^[=+\-@\t\r]/.test(s)) s = "'" + s;
if (/[",\n\r]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
return s;
}
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'rpt.title': 'Reports',
'rpt.print': 'Print',
'rpt.json': 'Export JSON',
'rpt.csv': 'Export CSV',
'rpt.cover.kicker': 'Executive report',
'rpt.cover.title': 'Security report',
'rpt.cover.period': 'Period',
'rpt.cover.hosts': 'Hosts',
'rpt.cover.generated': 'Generated',
'rpt.cover.all': 'all hosts',
'rpt.sum.title': 'Executive summary',
'rpt.sum.lead': 'In this period {hosts} recorded {attacks} attacks from {ips} distinct addresses; {hostile} of them were hostile and {bans} are banned.',
'rpt.sum.up': 'Attacks rose {pct}% against the previous period.',
'rpt.sum.down': 'Attacks fell {pct}% against the previous period.',
'rpt.sum.flat': 'Attack volume is in line with the previous period.',
'rpt.sum.noPrev': 'There is no previous period to compare with.',
'rpt.sum.top': 'The most frequent attack family was {fam}, and most traffic came from {cc}.',
'rpt.sum.ban': 'The median time to ban was {t}; {cov}% of hostile addresses are covered by a ban.',
'rpt.sum.expo': '{n} attack requests were answered with success and deserve review.',
'rpt.sum.noExpo': 'No attack request reached an exposed resource.',
'rpt.k.requests': 'Requests',
'rpt.k.attacks': 'Attacks',
'rpt.k.unique_ips': 'Unique IPs',
'rpt.k.hostile_ips': 'Hostile IPs',
'rpt.k.bans': 'Bans',
'rpt.k.visitors': 'Visitors',
'rpt.k.nonhuman': 'Non-human clients',
'rpt.k.page_views': 'Page views',
'rpt.k.prev': 'before: {v}',
'rpt.chart.timeline': 'Attacks over time',
'rpt.chart.families': 'Attack families',
'rpt.chart.countries': 'Origin countries',
'rpt.chart.asns': 'Networks (ASN)',
'rpt.chart.techniques': 'Techniques',
'rpt.table.ips': 'Top addresses',
'rpt.table.campaigns': 'Main campaigns',
'rpt.table.escalations': 'Escalations',
'rpt.table.exposure': 'Exposures',
'rpt.table.defense': 'Defence',
'rpt.col.ip': 'Address',
'rpt.col.score': 'Score',
'rpt.col.level': 'Level',
'rpt.col.country': 'Country',
'rpt.col.network': 'Network',
'rpt.col.events': 'Events',
'rpt.col.banned': 'Banned',
'rpt.col.campaign': 'Campaign',
'rpt.col.ips': 'IPs',
'rpt.col.period': 'Active',
'rpt.col.techs': 'Techniques',
'rpt.col.stage': 'Stage',
'rpt.col.host': 'Host',
'rpt.col.path': 'Path',
'rpt.col.status': 'Status',
'rpt.col.family': 'Family',
'rpt.col.when': 'When',
'rpt.yes': 'yes',
'rpt.no': 'no',
'rpt.empty': 'Nothing to report in this period.',
'rpt.none': 'None in this period.',
'rpt.def.mttb': 'Median time to ban',
'rpt.def.mttbP90': 'Time to ban (90th percentile)',
'rpt.def.cover': 'Ban coverage',
'rpt.def.blocklist': 'Blocklist coverage',
'rpt.def.exposure': 'Exposure rate',
'rpt.def.refused': 'Exploits refused',
'rpt.def.n': 'Bans measured',
'rpt.truncated': 'The study was cut at its limits; the figures may be partial.',
'rpt.foot': 'Generated by Urutau. Addresses come from logs and are shown as recorded.'
},
'pt-BR': {
'rpt.title': 'Relatórios',
'rpt.print': 'Imprimir',
'rpt.json': 'Exportar JSON',
'rpt.csv': 'Exportar CSV',
'rpt.cover.kicker': 'Relatório executivo',
'rpt.cover.title': 'Relatório de segurança',
'rpt.cover.period': 'Período',
'rpt.cover.hosts': 'Hosts',
'rpt.cover.generated': 'Gerado em',
'rpt.cover.all': 'todos os hosts',
'rpt.sum.title': 'Sumário executivo',
'rpt.sum.lead': 'Neste período {hosts} registrou {attacks} ataques de {ips} endereços distintos; {hostile} deles foram hostis e {bans} estão banidos.',
'rpt.sum.up': 'Os ataques subiram {pct}% em relação ao período anterior.',
'rpt.sum.down': 'Os ataques caíram {pct}% em relação ao período anterior.',
'rpt.sum.flat': 'O volume de ataques está em linha com o período anterior.',
'rpt.sum.noPrev': 'Não há período anterior para comparar.',
'rpt.sum.top': 'A família de ataque mais frequente foi {fam}, e a maior parte do tráfego veio de {cc}.',
'rpt.sum.ban': 'O tempo mediano até o banimento foi {t}; {cov}% dos endereços hostis estão cobertos por um ban.',
'rpt.sum.expo': '{n} requisições de ataque foram respondidas com sucesso e merecem revisão.',
'rpt.sum.noExpo': 'Nenhuma requisição de ataque chegou a um recurso exposto.',
'rpt.k.requests': 'Requisições',
'rpt.k.attacks': 'Ataques',
'rpt.k.unique_ips': 'IPs únicos',
'rpt.k.hostile_ips': 'IPs hostis',
'rpt.k.bans': 'Bans',
'rpt.k.visitors': 'Visitantes',
'rpt.k.nonhuman': 'Clientes não humanos',
'rpt.k.page_views': 'Páginas vistas',
'rpt.k.prev': 'antes: {v}',
'rpt.chart.timeline': 'Ataques ao longo do tempo',
'rpt.chart.families': 'Famílias de ataque',
'rpt.chart.countries': 'Países de origem',
'rpt.chart.asns': 'Redes (ASN)',
'rpt.chart.techniques': 'Técnicas',
'rpt.table.ips': 'Principais endereços',
'rpt.table.campaigns': 'Principais campanhas',
'rpt.table.escalations': 'Escaladas',
'rpt.table.exposure': 'Exposições',
'rpt.table.defense': 'Defesa',
'rpt.col.ip': 'Endereço',
'rpt.col.score': 'Pontuação',
'rpt.col.level': 'Nível',
'rpt.col.country': 'País',
'rpt.col.network': 'Rede',
'rpt.col.events': 'Eventos',
'rpt.col.banned': 'Banido',
'rpt.col.campaign': 'Campanha',
'rpt.col.ips': 'IPs',
'rpt.col.period': 'Atividade',
'rpt.col.techs': 'Técnicas',
'rpt.col.stage': 'Estágio',
'rpt.col.host': 'Host',
'rpt.col.path': 'Caminho',
'rpt.col.status': 'Status',
'rpt.col.family': 'Família',
'rpt.col.when': 'Quando',
'rpt.yes': 'sim',
'rpt.no': 'não',
'rpt.empty': 'Nada a relatar neste período.',
'rpt.none': 'Nenhum neste período.',
'rpt.def.mttb': 'Tempo mediano até o ban',
'rpt.def.mttbP90': 'Tempo até o ban (percentil 90)',
'rpt.def.cover': 'Cobertura de bans',
'rpt.def.blocklist': 'Cobertura da lista de bloqueio',
'rpt.def.exposure': 'Taxa de exposição',
'rpt.def.refused': 'Exploits recusados',
'rpt.def.n': 'Bans medidos',
'rpt.truncated': 'O estudo foi cortado nos seus limites; os números podem estar parciais.',
'rpt.foot': 'Gerado pelo Urutau. Os endereços vêm dos logs e aparecem como registrados.'
}
});
var t = U.t, nf = U.fmt.num;
var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); };
var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null;
function dur(s) {
s = Math.round(s || 0);
if (s < 60) return t('dur.s', { n: nf(s) });
if (s < 3600) return t('dur.m', { n: nf(Math.round(s / 60)) });
if (s < 86400) return t('dur.h', { n: nf(Math.round(s / 3600)) });
return t('dur.d', { n: nf(Math.round(s / 86400)) });
}
function day(ts) { return new Date(ts * 1000).toLocaleDateString((ctx0 && ctx0.lang) || undefined, { day: 'numeric', month: 'short', year: 'numeric' }); }
function pctTxt(v) { return nf(Math.round(v * 10) / 10) + '%'; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function params(c) {
var p = U.rangeParams();
if (c && c.host && c.host !== 'all') p.host = c.host;
p.format = 'json';
return p;
}
function load(c) {
var my = ++seq;
U.api('/api/v1/report', params(c || ctx0)).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(box);
box.appendChild(U.ui.empty(t('error.load')));
});
}
function save(name, type, text) {
try {
var url = URL.createObjectURL(new Blob([text], { type: type }));
var a = document.createElement('a');
a.href = url; a.download = name;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
} catch (e) { console.error(e); }
}
function stamp(ext) {
var r = data && data.range ? data.range : { from: 0, to: 0 };
var f = function (x) { return new Date(x * 1000).toISOString().slice(0, 10); };
return 'urutau-report-' + f(r.from) + '_' + f(r.to) + '.' + ext;
}
function toCSV(d) {
var rows = [['section', 'key', 'value', 'extra']];
function add() { rows.push([].slice.call(arguments)); }
add('range', 'from', new Date(d.range.from * 1000).toISOString());
add('range', 'to', new Date(d.range.to * 1000).toISOString());
add('range', 'hosts', (d.hosts || []).join(' '));
Object.keys(d.summary || {}).forEach(function (k) {
var v = d.summary[k];
if (typeof v === 'number') add('summary', k, v, d.summary.prev && typeof d.summary.prev[k] === 'number' ? d.summary.prev[k] : '');
});
['families', 'techniques', 'countries', 'asns'].forEach(function (s) { (d[s] || []).forEach(function (r) { add(s, r.key, r.n, r.label || ''); }); });
(d.top_ips || []).forEach(function (r) { add('top_ips', r.ip, r.score, [r.level, r.cc, r.as_org, r.events, r.banned ? 'banned' : ''].join(' ')); });
(d.campaigns || []).forEach(function (c) { add('campaigns', c.id, c.ips_n, (c.techs || []).join(' ')); });
(d.escalations || []).forEach(function (e) { add('escalations', e.ip, e.stage, e.host || ''); });
((d.exposures || {}).items || []).forEach(function (e) { add('exposures', e.ip, e.path, [e.host, e.domain, e.status, e.fam].join(' ')); });
Object.keys(d.defense || {}).forEach(function (k) { add('defense', k, d.defense[k]); });
return rows.map(function (r) { return r.map(csvCell).join(','); }).join('\r\n') + '\r\n';
}
function toolbar() {
var bar = h('div', 'rpt-bar');
var b1 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.print'));
b1.addEventListener('click', function () { window.print(); });
var b2 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.json'));
b2.addEventListener('click', function () { if (data) save(stamp('json'), 'application/json', JSON.stringify(data, null, 2)); });
var b3 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.csv'));
b3.addEventListener('click', function () { if (data) save(stamp('csv'), 'text/csv;charset=utf-8', '' + toCSV(data)); });
bar.appendChild(b1); bar.appendChild(b2); bar.appendChild(b3);
return bar;
}
function table(headers, rows) {
var tb = h('table', 'rpt-table'), tr = h('tr');
headers.forEach(function (x) { tr.appendChild(h('th', null, x)); });
tb.appendChild(h('thead', null, tr));
var body = h('tbody');
rows.forEach(function (r) { var row = h('tr'); r.forEach(function (c) { row.appendChild(h('td', null, c)); }); body.appendChild(row); });
tb.appendChild(body);
return h('div', 'rpt-scroll', tb);
}
function section(title, body, cls) {
return h('section', 'rpt-sec' + (cls ? ' ' + cls : ''), h('h2', null, title), body);
}
function emptyNote(key) { return h('p', 'rpt-none', t(key || 'rpt.none')); }
function barRows(list) { return (list || []).map(function (r) { return { key: r.key, label: r.label ? r.key + ' ' + r.label : r.key, value: r.n }; }); }
function paint() {
if (!data) return;
clear(box);
var d = data, s = d.summary || {}, doc = h('article', 'rpt-sheet');
var hosts = (d.hosts && d.hosts.length) ? d.hosts.join(', ') : t('rpt.cover.all');
// cover
doc.appendChild(h('header', 'rpt-cover',
h('p', 'rpt-kicker', t('rpt.cover.kicker')),
h('h1', null, t('rpt.cover.title')),
h('dl', 'rpt-meta',
h('dt', null, t('rpt.cover.period')), h('dd', null, day(d.range.from) + ' - ' + day(d.range.to)),
h('dt', null, t('rpt.cover.hosts')), h('dd', null, hosts),
h('dt', null, t('rpt.cover.generated')), h('dd', null, U.fmt.date(d.generated)))));
// executive summary
var sents = [];
sents.push(t('rpt.sum.lead', { hosts: hosts, attacks: nf(s.attacks), ips: nf(s.unique_ips), hostile: nf(s.hostile_ips), bans: nf(s.bans) }));
var dp = s.delta_pct && typeof s.delta_pct.attacks === 'number' ? s.delta_pct.attacks : null;
if (!s.has_prev || dp === null) sents.push(t('rpt.sum.noPrev'));
else if (Math.abs(dp) < 5) sents.push(t('rpt.sum.flat'));
else sents.push(t(dp > 0 ? 'rpt.sum.up' : 'rpt.sum.down', { pct: nf(Math.round(Math.abs(dp))) }));
if ((d.families || []).length && (d.countries || []).length) sents.push(t('rpt.sum.top', { fam: d.families[0].key, cc: U.fmt.country(d.countries[0].key) }));
var df = d.defense || {};
if (df.mttb_n > 0) sents.push(t('rpt.sum.ban', { t: dur(df.mttb_median_s), cov: nf(Math.round(df.ban_coverage)) }));
var ex = d.exposures || {};
sents.push(ex.total > 0 ? t('rpt.sum.expo', { n: nf(ex.total) }) : t('rpt.sum.noExpo'));
var kp = h('div', 'rpt-kpis');
['requests', 'attacks', 'unique_ips', 'hostile_ips', 'bans', 'visitors', 'nonhuman', 'page_views'].forEach(function (k) {
var delta = s.delta_pct && typeof s.delta_pct[k] === 'number' ? s.delta_pct[k] : null;
kp.appendChild(h('div', 'rpt-kpi', h('span', 'rpt-kl', t('rpt.k.' + k)), h('strong', 'num', nf(s[k] || 0)),
s.has_prev ? h('span', 'rpt-kd', (delta === null ? '' : (delta > 0 ? '▲ ' : delta < 0 ? '▼ ' : '') + nf(Math.abs(Math.round(delta))) + '% · ') + t('rpt.k.prev', { v: nf((s.prev || {})[k] || 0) })) : null));
});
var sumBox = h('div', null, h('div', 'rpt-sents', sents.map(function (x) { return h('p', null, x); })), kp);
if (d.truncated) sumBox.appendChild(h('p', 'rpt-warn', t('rpt.truncated')));
doc.appendChild(section(t('rpt.sum.title'), sumBox, 'rpt-first'));
// charts
var tl = d.timeline || {};
var chartsBox = h('div', 'rpt-charts');
var c1 = h('div', 'rpt-chart rpt-wide', h('h3', null, t('rpt.chart.timeline')));
c1.appendChild(U.charts.stackedArea([{ key: 'attacks', label: t('rpt.k.attacks'), values: tl.values || [] }], tl.step, { start: tl.start, title: t('rpt.chart.timeline') }));
chartsBox.appendChild(c1);
function cbox(title, node, cls) { var c = h('div', 'rpt-chart' + (cls ? ' ' + cls : ''), h('h3', null, title)); c.appendChild(node); chartsBox.appendChild(c); }
cbox(t('rpt.chart.families'), (d.families || []).length ? U.charts.donut(d.families.slice(0, 5).map(function (r) { return { key: r.key, label: r.key, value: r.n }; }), { title: t('rpt.chart.families') }) : emptyNote());
cbox(t('rpt.chart.countries'), (d.countries || []).length ? U.charts.bars((d.countries || []).slice(0, 5).map(function (r) { return { key: r.key, label: U.fmt.country(r.key), value: r.n }; }), { title: t('rpt.chart.countries') }) : emptyNote());
cbox(t('rpt.chart.asns'), (d.asns || []).length ? U.charts.bars(barRows(d.asns.slice(0, 5)), { title: t('rpt.chart.asns') }) : emptyNote());
cbox(t('rpt.chart.techniques'), (d.techniques || []).length ? U.charts.bars(barRows(d.techniques.slice(0, 5)), { title: t('rpt.chart.techniques') }) : emptyNote(), 'rpt-noprint');
doc.appendChild(section(t('rpt.chart.timeline'), chartsBox, 'rpt-sec-charts'));
// tables (page 2)
var p2 = h('div', 'rpt-p2');
p2.appendChild(section(t('rpt.table.ips'), (d.top_ips || []).length ? table([t('rpt.col.ip'), t('rpt.col.score'), t('rpt.col.level'), t('rpt.col.country'), t('rpt.col.network'), t('rpt.col.events'), t('rpt.col.banned')],
d.top_ips.map(function (r) { return [r.ip, nf(r.score), r.level, r.cc ? U.fmt.country(r.cc) : '-', r.as_org || '-', nf(r.events), t(r.banned ? 'rpt.yes' : 'rpt.no')]; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.campaigns'), (d.campaigns || []).length ? table([t('rpt.col.campaign'), t('rpt.col.ips'), t('rpt.col.period'), t('rpt.col.techs')],
d.campaigns.map(function (c) { return [c.id, nf(c.ips_n), day(Date.parse(c.first) / 1000) + ' - ' + day(Date.parse(c.last) / 1000), (c.techs || []).slice(0, 4).join(', ')]; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.escalations'), (d.escalations || []).length ? table([t('rpt.col.ip'), t('rpt.col.stage'), t('rpt.col.host')],
d.escalations.map(function (e) { return [e.ip, e.stage, e.host || '-']; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.exposure'), (ex.items || []).length ? table([t('rpt.col.when'), t('rpt.col.ip'), t('rpt.col.host'), t('rpt.col.path'), t('rpt.col.status'), t('rpt.col.family')],
ex.items.map(function (e) { return [U.fmt.date(e.t), e.ip, e.domain || e.host || '-', e.path, String(e.status), e.fam || '-']; })) : emptyNote('rpt.sum.noExpo')));
p2.appendChild(section(t('rpt.table.defense'), table(['', ''], [
[t('rpt.def.mttb'), df.mttb_n > 0 ? dur(df.mttb_median_s) : '-'],
[t('rpt.def.mttbP90'), df.mttb_n > 0 ? dur(df.mttb_p90_s) : '-'],
[t('rpt.def.n'), nf(df.mttb_n || 0)],
[t('rpt.def.cover'), pctTxt(df.ban_coverage || 0)],
[t('rpt.def.blocklist'), pctTxt(df.blocklist_coverage || 0)],
[t('rpt.def.exposure'), pctTxt(df.exposure_rate || 0)],
[t('rpt.def.refused'), pctTxt(df.exploits_refused_pct || 0)]
])));
p2.appendChild(h('p', 'rpt-foot', t('rpt.foot')));
doc.appendChild(p2);
box.appendChild(toolbar());
box.appendChild(doc);
}
U.registerPage({
id: 'reports', group: 'reports', icon: ICON, titleKey: 'rpt.title',
mount: function (el, c) {
ctx0 = c; alive = true; data = null;
root = h('div', 'rpt');
box = h('div', 'rpt-box');
root.appendChild(box);
box.appendChild(h('div', 'skeleton'));
el.appendChild(root);
load(c);
},
update: function (c) { ctx0 = c; load(c); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+25
View File
@@ -0,0 +1,25 @@
/* Urutau - SEARCH page. Selectors prefixed sr-. */
.sr { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
.sr-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 10px; align-items: end; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-panel); }
.sr-fld { display: flex; flex-direction: column; gap: 4px; min-width: 0; font-size: .75rem; color: var(--ink-muted); }
.sr-fld input, .sr-fld select { width: 100%; min-width: 0; }
.sr-period { font-size: .875rem; color: var(--ink); min-height: 36px; display: flex; align-items: center; }
.sr-act { display: flex; gap: 8px; }
.sr-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; }
.sr-path { overflow-wrap: anywhere; word-break: break-all; }
.sr-table td { vertical-align: top; }
.sr-cat { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; background: var(--ink-faint); }
.sr-c-notfound { background: var(--info); } .sr-c-scanner { background: var(--warn); } .sr-c-bruteforce { background: #fb923c; }
.sr-c-exploit { background: var(--danger); } .sr-c-ssh-fail { background: #fb923c; } .sr-c-ssh-probe { background: var(--warn); }
.sr-c-ssh-ok { background: #c026d3; } .sr-c-ban { background: var(--ink-muted); }
.sr-more { align-self: center; }
/* Wide table: stack into cards up to 1023px (the shared rule starts at 767px). */
@media (max-width: 1023px) {
table.sr-table thead { display: none; }
table.sr-table, table.sr-table tbody, table.sr-table tr, table.sr-table td { display: block; width: 100%; }
table.sr-table tr { border-top: 1px solid var(--line); padding: 8px 0; }
table.sr-table tr:first-child { border-top: 0; }
table.sr-table td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; min-width: 0; overflow-wrap: anywhere; }
table.sr-table td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; }
}
+220
View File
@@ -0,0 +1,220 @@
/* Urutau - SEARCH page: event search over /api/v1/events with cursor paging, CSV export
in the browser. Hostile data: textContent only; CSV cells starting with = + - @ get a ' prefix. */
(function () {
'use strict';
var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
var CAT_OK = {}; CATS.concat(['ok']).forEach(function (c) { CAT_OK[c] = 1; });
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l5 5"/></svg>';
var PAGE = 100, MAXROWS = 5000;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
var t = U.t, nf = U.fmt.num;
function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); }
U.registerI18n({
en: {
'sr.title': 'Event search',
'sr.lead.one': '{n} event found',
'sr.lead.other': '{n} events found',
'sr.lead.more': 'More events match; load more to continue.',
'sr.lead.body': 'Events {range}, newest first.',
'sr.lead.empty': 'No event matches',
'sr.lead.emptyBody': 'Nothing {range} fits these filters, or the event registry is off.',
'sr.f.ip': 'IP or prefix',
'sr.f.q': 'Path contains',
'sr.f.fam': 'Family',
'sr.f.cat': 'Category',
'sr.f.status': 'Status',
'sr.f.host': 'Host',
'sr.f.period': 'Period',
'sr.f.all': 'All',
'sr.f.s2': '2xx',
'sr.f.s3': '3xx',
'sr.f.s4': '4xx',
'sr.f.s5': '5xx',
'sr.search': 'Search',
'sr.clear': 'Clear',
'sr.more': 'Load more',
'sr.csv': 'Export CSV',
'sr.csv.done': 'CSV saved',
'sr.c.time': 'Time',
'sr.c.ip': 'Address',
'sr.c.cat': 'Category',
'sr.c.host': 'Host',
'sr.c.path': 'Request',
'sr.c.status': 'Status',
'sr.c.fam': 'Family',
'sr.statusnote': 'The status filter applies to the rows already loaded.',
'sr.cap': 'Row limit reached ({n}); narrow the search.',
'sr.err': 'Search failed.',
'sr.retry': 'Try again',
'sr.busy': 'The server is busy; try again in a few seconds.',
'sr.badq': 'The server rejected these filters.'
},
'pt-BR': {
'sr.title': 'Busca de eventos',
'sr.lead.one': '{n} evento encontrado',
'sr.lead.other': '{n} eventos encontrados',
'sr.lead.more': 'Há mais eventos; carregue mais para continuar.',
'sr.lead.body': 'Eventos {range}, do mais novo ao mais antigo.',
'sr.lead.empty': 'Nenhum evento encontrado',
'sr.lead.emptyBody': 'Nada {range} combina com estes filtros, ou o registro de eventos está desligado.',
'sr.f.ip': 'IP ou prefixo',
'sr.f.q': 'Caminho contém',
'sr.f.fam': 'Família',
'sr.f.cat': 'Categoria',
'sr.f.status': 'Status',
'sr.f.host': 'Servidor',
'sr.f.period': 'Período',
'sr.f.all': 'Todos',
'sr.f.s2': '2xx',
'sr.f.s3': '3xx',
'sr.f.s4': '4xx',
'sr.f.s5': '5xx',
'sr.search': 'Buscar',
'sr.clear': 'Limpar',
'sr.more': 'Carregar mais',
'sr.csv': 'Exportar CSV',
'sr.csv.done': 'CSV salvo',
'sr.c.time': 'Hora',
'sr.c.ip': 'Endereço',
'sr.c.cat': 'Categoria',
'sr.c.host': 'Servidor',
'sr.c.path': 'Requisição',
'sr.c.status': 'Status',
'sr.c.fam': 'Família',
'sr.statusnote': 'O filtro de status vale para as linhas já carregadas.',
'sr.cap': 'Limite de linhas atingido ({n}); restrinja a busca.',
'sr.err': 'A busca falhou.',
'sr.retry': 'Tentar de novo',
'sr.busy': 'O servidor está ocupado; tente de novo em alguns segundos.',
'sr.badq': 'O servidor recusou estes filtros.'
}
});
function catKey(c) { return CAT_OK[c] ? c : 'ok'; }
function csvCell(v) {
var s = v === null || v === undefined ? '' : String(v);
if (/^[=+\-@\t\r]/.test(s)) s = "'" + s;
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}
function statusOk(f, st) { return !f || String(Math.floor((st || 0) / 100)) === f; }
function iso(sec) { return new Date(sec * 1000).toISOString(); }
var inst = null;
function Page(root, ctx) {
var self = this, alive = true, seq = 0, rows = [], next = '', total = 0, loaded = false, busy = false, err = '', capped = false;
this.ctx = ctx;
var q0 = (ctx.params && ctx.params.query) || {};
var F = { ip: q0.ip || '', q: q0.q || '', fam: q0.fam || '', cat: CATS.indexOf(q0.cat) >= 0 ? q0.cat : '', status: '', host: '' };
var wrap = h('div', 'sr'), leadBox = h('div'), form = h('form', { class: 'sr-form', novalidate: true }), out = h('div');
root.appendChild(wrap); wrap.appendChild(leadBox); wrap.appendChild(form); wrap.appendChild(out);
var inputs = {};
function field(key, label, el) { inputs[key] = el; return h('label', 'sr-fld', h('span', { text: label }), el); }
function buildForm() {
form.textContent = ''; inputs = {};
function text(key, label, ph, max) { var i = h('input', { type: 'text', maxlength: max, autocomplete: 'off', spellcheck: 'false', placeholder: ph || '' }); i.value = F[key]; return field(key, label, i); }
form.appendChild(text('ip', t('sr.f.ip'), '198.51.100.7', 64));
form.appendChild(text('q', t('sr.f.q'), '/.env', 200));
form.appendChild(text('fam', t('sr.f.fam'), '', 40));
var cat = h('select'); cat.appendChild(h('option', { value: '', text: t('sr.f.all') }));
CATS.forEach(function (c) { cat.appendChild(h('option', { value: c, text: t('cat.short.' + c) })); }); cat.value = F.cat;
form.appendChild(field('cat', t('sr.f.cat'), cat));
var stt = h('select'); [['', t('sr.f.all')], ['2', t('sr.f.s2')], ['3', t('sr.f.s3')], ['4', t('sr.f.s4')], ['5', t('sr.f.s5')]].forEach(function (o) { stt.appendChild(h('option', { value: o[0], text: o[1] })); });
stt.value = F.status; stt.title = t('sr.statusnote');
form.appendChild(field('status', t('sr.f.status'), stt));
form.appendChild(text('host', t('sr.f.host'), '', 64));
form.appendChild(h('div', 'sr-fld', h('span', { text: t('sr.f.period') }), h('b', { class: 'sr-period', text: U.rangeLabel() })));
var go = h('button', { type: 'submit', class: 'btn primary', text: t('sr.search') });
var clr = h('button', { type: 'button', class: 'btn', text: t('sr.clear') });
clr.addEventListener('click', function () { F = { ip: '', q: '', fam: '', cat: '', status: '', host: '' }; buildForm(); run(); });
form.appendChild(h('div', 'sr-act', go, clr));
}
form.addEventListener('submit', function (e) { e.preventDefault(); readForm(); run(); });
inputs = {};
function readForm() { Object.keys(F).forEach(function (k) { if (inputs[k]) F[k] = String(inputs[k].value || '').trim(); }); }
function params(cursor) {
var p = Object.assign({ limit: PAGE }, U.rangeParams());
var host = F.host || (self.ctx.host && self.ctx.host !== 'all' ? self.ctx.host : '');
if (host) p.host = host;
['ip', 'q', 'fam', 'cat'].forEach(function (k) { if (F[k]) p[k] = F[k]; });
if (cursor) p.cursor = cursor;
return p;
}
function run() { rows = []; next = ''; total = 0; loaded = false; err = ''; capped = false; fetchPage(''); }
function fetchPage(cursor) {
var my = ++seq; busy = true; paint();
U.api('/api/v1/events', params(cursor)).then(function (d) {
if (!alive || my !== seq) return;
busy = false; loaded = true; err = '';
rows = rows.concat(d.events || []); total = d.total_estimate || rows.length; next = d.next || '';
if (rows.length >= MAXROWS) { capped = true; next = ''; }
paint();
}).catch(function (e) {
if (!alive || my !== seq) return;
busy = false; loaded = true; err = e && e.status === 503 ? 'sr.busy' : e && e.status === 400 ? 'sr.badq' : 'sr.err'; paint();
});
}
function visible() { return rows.filter(function (r) { return statusOk(F.status, r.status); }); }
function exportCsv() {
var cols = ['t', 'ip', 'cat', 'host', 'domain', 'method', 'path', 'status', 'fam', 'cc'];
var lines = [cols.join(',')];
visible().forEach(function (r) { lines.push(cols.map(function (c) { return csvCell(c === 't' ? iso(r.t) : r[c]); }).join(',')); });
var url = URL.createObjectURL(new Blob([lines.join('\r\n') + '\r\n'], { type: 'text/csv;charset=utf-8' }));
var a = document.createElement('a'); a.href = url; a.download = 'urutau-events.csv'; document.body.appendChild(a); a.click();
setTimeout(function () { URL.revokeObjectURL(url); if (a.parentNode) a.parentNode.removeChild(a); }, 500);
U.toast(t('sr.csv.done'));
}
function paint() {
leadBox.textContent = ''; out.textContent = '';
var vis = visible(), range = U.rangeLabel({ inline: true });
if (err) {
var rb = h('button', { type: 'button', class: 'btn', text: t('sr.retry') }); rb.addEventListener('click', run);
out.appendChild(h('div', 'state-error', h('strong', { text: t(err) }), rb)); return;
}
if (!loaded) { out.appendChild(h('div', 'skeleton')); return; }
leadBox.appendChild(vis.length ? U.ui.lead(U.pl('sr.lead', vis.length, { n: nf(vis.length) + (next ? '+' : '') }), t('sr.lead.body', { range: range }) + (next ? ' ' + t('sr.lead.more') : ''), 'ok')
: U.ui.lead(t('sr.lead.empty'), t('sr.lead.emptyBody', { range: range }), 'neutral'));
if (!vis.length) { if (next) out.appendChild(moreBtn()); return; }
var tb = h('tbody');
vis.forEach(function (r) {
function td(l, k, c) { return h('td', { 'data-label': l, class: c || null }, k); }
var c = catKey(r.cat), st = r.status ? String(r.status) : '';
tb.appendChild(h('tr', 'row',
td(t('sr.c.time'), h('span', { text: U.fmt.date(r.t) }), 'nw'),
td(t('sr.c.ip'), h('a', { class: 'mono sr-ip', href: '#/ip/' + encodeURIComponent(r.ip || ''), text: r.ip || '' })),
td(t('sr.c.cat'), h('span', { class: 'sr-cat sr-c-' + c, text: t('cat.short.' + c) })),
td(t('sr.c.host'), h('span', { text: r.domain || r.host || '' })),
td(t('sr.c.path'), h('span', { class: 'mono sr-path', text: ((r.method || '') + ' ' + (r.path || r.user || r.jail || '')).trim() })),
td(t('sr.c.status'), h('span', { class: 'num', text: st })),
td(t('sr.c.fam'), h('span', { text: r.fam || '' }))));
});
var th = h('tr'); ['time', 'ip', 'cat', 'host', 'path', 'status', 'fam'].forEach(function (k) { th.appendChild(h('th', { text: t('sr.c.' + k) })); });
var csv = h('button', { type: 'button', class: 'btn', text: t('sr.csv') }); csv.addEventListener('click', exportCsv);
out.appendChild(U.ui.panel({ title: t('sr.title'), help: 'cat.scanner', actions: [csv] }, h('table', 'stack sr-table', h('thead', null, th), tb)));
if (capped) out.appendChild(h('p', { class: 'note', text: t('sr.cap', { n: nf(MAXROWS) }) }));
if (next) out.appendChild(moreBtn());
}
function moreBtn() { var b = h('button', { type: 'button', class: 'btn sr-more', text: t('sr.more') }); b.disabled = busy; b.addEventListener('click', function () { fetchPage(next); }); return b; }
buildForm();
this.update = function (c) {
var lang = self.ctx.lang; self.ctx = c;
if (lang !== c.lang) { readForm(); buildForm(); }
else { var p = form.querySelector('.sr-period'); if (p) p.textContent = U.rangeLabel(); }
var key = JSON.stringify(U.rangeParams()) + c.host;
if (key !== self.lastKey) { self.lastKey = key; run(); }
};
this.destroy = function () { alive = false; seq++; root.textContent = ''; };
this.lastKey = JSON.stringify(U.rangeParams()) + ctx.host;
run();
}
U.registerPage({
id: 'search', group: 'investigate', icon: ICON, titleKey: 'sr.title',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
return true;
}
if (!boot()) document.addEventListener('DOMContentLoaded', boot);
})();
+34
View File
@@ -0,0 +1,34 @@
/* Urutau - SESSIONS page. Selectors prefixed ss-. */
.ss { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; }
.ss-funnel { display: flex; flex-direction: column; gap: 6px; }
.ss-fr { display: grid; grid-template-columns: 110px minmax(0, 1fr) 64px; gap: 10px; align-items: center; min-height: 36px; padding: 2px 8px; border: 1px solid transparent; border-radius: var(--radius-sm, 7px); background: none; color: var(--ink); font: inherit; cursor: pointer; text-align: left; }
.ss-fr:hover, .ss-fr.on { background: var(--surface-raised); border-color: var(--line-strong); }
.ss-fl { font-size: .875rem; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; }
.ss-fbar { display: block; height: 14px; border-radius: 7px; background: var(--surface-sunken); overflow: hidden; }
.ss-fbar i { display: block; height: 100%; border-radius: 7px; }
.ss-fn { text-align: right; font-weight: 600; }
.ss-s-recon { background: var(--info); }
.ss-s-probe { background: var(--warn); }
.ss-s-exploit { background: var(--danger); }
.ss-s-access { background: #c026d3; }
.ss-s-banned { background: var(--ink-faint); }
.ss-badge, .ss-step { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; }
.ss-filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.ss-filters select { max-width: 100%; min-width: 0; }
.ss-table td { vertical-align: middle; }
.ss-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; }
.ss-rp { min-height: 32px; padding: 2px 10px; font-size: .8125rem; }
.ss-chains { display: flex; flex-direction: column; gap: 8px; }
.ss-chain { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; }
.ss-steps { display: flex; flex-wrap: wrap; gap: 4px; }
@media (max-width: 640px) { .ss-fr { grid-template-columns: 84px minmax(0, 1fr) 48px; gap: 6px; } }
/* Wide table: stack into cards up to 1023px (the shared rule starts at 767px). */
@media (max-width: 1023px) {
table.ss-table thead { display: none; }
table.ss-table, table.ss-table tbody, table.ss-table tr, table.ss-table td { display: block; width: 100%; }
table.ss-table tr { border-top: 1px solid var(--line); padding: 8px 0; }
table.ss-table tr:first-child { border-top: 0; }
table.ss-table td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; min-width: 0; overflow-wrap: anywhere; }
table.ss-table td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; }
}
+216
View File
@@ -0,0 +1,216 @@
/* Urutau - SESSIONS page: funnel by escalation stage and the sessions that escalated.
Data: /api/v1/sessions/funnel. Log data is hostile: textContent only, classes from whitelists. */
(function () {
'use strict';
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 5h18l-7 8v6l-4 2v-8z"/></svg>';
var SHOW = 100;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
var t = U.t, nf = U.fmt.num;
function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); }
U.registerI18n({
en: {
'ss.title': 'Sessions',
'ss.lead.one': '{n} session; {k} reached exploitation',
'ss.lead.other': '{n} sessions; {k} reached exploitation',
'ss.lead.body': 'Sessions {range}, grouped by the furthest stage each one reached.',
'ss.lead.empty': 'No sessions in this slice',
'ss.lead.emptyBody': 'Nothing was recorded {range}, or the event registry is off.',
'ss.sampled': 'Showing the {n} most severe of {m} sessions.',
'ss.funnel': 'Escalation funnel',
'ss.funnel.hint': 'Sessions that reached each stage or went beyond it. Click a stage to filter the list.',
'ss.stage.recon': 'Recon',
'ss.stage.probe': 'Probe',
'ss.stage.exploit': 'Exploit',
'ss.stage.access': 'Access',
'ss.stage.banned': 'Banned',
'ss.f.stage': 'Stage',
'ss.f.host': 'Host',
'ss.f.fam': 'Family',
'ss.f.all': 'All',
'ss.list': 'Sessions',
'ss.c.ip': 'Address',
'ss.c.stage': 'Stage',
'ss.c.start': 'Start',
'ss.c.dur': 'Duration',
'ss.c.events': 'Events',
'ss.c.hosts': 'Hosts',
'ss.c.fam': 'Family',
'ss.c.replay': 'Replay',
'ss.replay': 'Replay',
'ss.more': 'Show more',
'ss.none': 'No session matches these filters',
'ss.esc': 'Escalation chains',
'ss.esc.hint': 'The steps of the most serious sessions.',
'ss.err': 'Could not load the sessions.',
'ss.retry': 'Try again',
'ss.dur.s': '{n} s',
'ss.dur.m': '{n} min',
'ss.dur.h': '{n} h'
},
'pt-BR': {
'ss.title': 'Sessões',
'ss.lead.one': '{n} sessão; {k} chegaram a exploração',
'ss.lead.other': '{n} sessões; {k} chegaram a exploração',
'ss.lead.body': 'Sessões {range}, agrupadas pelo estágio mais avançado de cada uma.',
'ss.lead.empty': 'Nenhuma sessão neste recorte',
'ss.lead.emptyBody': 'Nada foi registrado {range}, ou o registro de eventos está desligado.',
'ss.sampled': 'Mostrando as {n} mais graves de {m} sessões.',
'ss.funnel': 'Funil de escalada',
'ss.funnel.hint': 'Sessões que chegaram a cada estágio ou foram além. Clique num estágio para filtrar a lista.',
'ss.stage.recon': 'Reconhecimento',
'ss.stage.probe': 'Sondagem',
'ss.stage.exploit': 'Exploração',
'ss.stage.access': 'Acesso',
'ss.stage.banned': 'Banido',
'ss.f.stage': 'Estágio',
'ss.f.host': 'Servidor',
'ss.f.fam': 'Família',
'ss.f.all': 'Todos',
'ss.list': 'Sessões',
'ss.c.ip': 'Endereço',
'ss.c.stage': 'Estágio',
'ss.c.start': 'Início',
'ss.c.dur': 'Duração',
'ss.c.events': 'Eventos',
'ss.c.hosts': 'Servidores',
'ss.c.fam': 'Família',
'ss.c.replay': 'Reprodução',
'ss.replay': 'Reproduzir',
'ss.more': 'Mostrar mais',
'ss.none': 'Nenhuma sessão combina com estes filtros',
'ss.esc': 'Cadeias de escalada',
'ss.esc.hint': 'Os passos das sessões mais graves.',
'ss.err': 'Não foi possível carregar as sessões.',
'ss.retry': 'Tentar de novo',
'ss.dur.s': '{n} s',
'ss.dur.m': '{n} min',
'ss.dur.h': '{n} h'
}
});
function stg(s) { return STAGES.indexOf(s) >= 0 ? s : 'recon'; }
function dur(s) { return s < 90 ? t('ss.dur.s', s) : s < 5400 ? t('ss.dur.m', Math.round(s / 60)) : t('ss.dur.h', Math.round(s / 360) / 10); }
function iso(sec) { return new Date(sec * 1000).toISOString(); }
function topFam(s) { var b = '', n = 0; Object.keys(s.fams || {}).forEach(function (k) { if (s.fams[k] > n) { n = s.fams[k]; b = k; } }); return b; }
function link(ip) { return h('a', { class: 'mono ss-ip', href: '#/ip/' + encodeURIComponent(ip), text: ip }); }
function opt(sel, v, label) { sel.appendChild(h('option', { value: v, text: label })); }
var inst = null;
function Page(root, ctx) {
var self = this, data = null, seq = 0, alive = true, st = { stage: '', host: '', fam: '', shown: SHOW };
this.ctx = ctx;
var wrap = h('div', 'ss');
root.appendChild(wrap);
function load() {
var my = ++seq;
U.api('/api/v1/sessions/funnel', Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) {
if (!alive || my !== seq) return; data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
var b = h('button', { type: 'button', class: 'btn', text: t('ss.retry') });
b.addEventListener('click', load);
wrap.textContent = '';
wrap.appendChild(h('div', 'state-error', h('strong', { text: t('ss.err') }), b));
});
}
function paint() {
wrap.textContent = '';
var d = data, n = d.sessions_n || 0, k = d.exploited || 0, range = U.rangeLabel({ inline: true });
wrap.appendChild(n ? U.ui.lead(U.pl('ss.lead', n, { n: nf(n), k: nf(k) }), t('ss.lead.body', { range: range }), k > 0 ? 'danger' : 'ok')
: U.ui.lead(t('ss.lead.empty'), t('ss.lead.emptyBody', { range: range }), 'neutral'));
if (!n) return;
// funnel
var max = Math.max(1, d.reached.recon || 1), fb = h('div', 'ss-funnel');
STAGES.forEach(function (g) {
var v = d.reached[g] || 0, b = h('button', { type: 'button', class: 'ss-fr' + (st.stage === g ? ' on' : '') });
b.appendChild(h('span', { class: 'ss-fl', text: t('ss.stage.' + g) }));
var bar = h('span', 'ss-fbar'), i = h('i', 'ss-s-' + g);
i.style.width = Math.max(v ? 2 : 0, v / max * 100) + '%';
bar.appendChild(i);
b.appendChild(bar);
b.appendChild(h('span', { class: 'ss-fn num', text: nf(v) }));
b.addEventListener('click', function () { st.stage = st.stage === g ? '' : g; st.shown = SHOW; paint(); });
fb.appendChild(b);
});
wrap.appendChild(U.ui.panel({ title: t('ss.funnel'), help: 'term.session', hint: t('ss.funnel.hint') }, fb));
// filters
var hosts = {}, fams = {};
d.sessions.forEach(function (s) { (s.hosts || []).forEach(function (x) { hosts[x] = 1; }); Object.keys(s.fams || {}).forEach(function (x) { fams[x] = 1; }); });
var f = h('div', 'ss-filters');
function sel(label, key, values, labeler) {
var s = h('select', { 'aria-label': label });
opt(s, '', label + ': ' + t('ss.f.all'));
values.forEach(function (v) { opt(s, v, labeler ? labeler(v) : v); });
s.value = values.indexOf(st[key]) >= 0 ? st[key] : '';
s.addEventListener('change', function () { st[key] = s.value; st.shown = SHOW; paint(); });
f.appendChild(s);
}
sel(t('ss.f.stage'), 'stage', STAGES, function (g) { return t('ss.stage.' + g); });
sel(t('ss.f.host'), 'host', Object.keys(hosts).sort());
sel(t('ss.f.fam'), 'fam', Object.keys(fams).sort());
// list
var rows = d.sessions.filter(function (s) {
return (!st.stage || stg(s.stage) === st.stage) && (!st.host || (s.hosts || []).indexOf(st.host) >= 0) && (!st.fam || (s.fams || {})[st.fam]);
});
var body = h('div');
if (d.sampled) body.appendChild(h('p', { class: 'note', text: t('ss.sampled', { n: nf(d.sessions.length), m: nf(n) }) }));
body.appendChild(f);
if (!rows.length) body.appendChild(U.ui.empty(t('ss.none')));
else {
var tb = h('tbody');
rows.slice(0, st.shown).forEach(function (s) {
var a = Math.floor(Date.parse(s.start) / 1000), b = Math.floor(Date.parse(s.end) / 1000);
var rp = h('a', { class: 'btn ss-rp', href: '#/replay?ip=' + encodeURIComponent(s.ip) + '&from=' + encodeURIComponent(iso(a - 60)) + '&to=' + encodeURIComponent(iso(b + 60)), text: t('ss.replay') });
function td(label, kid, cls) { return h('td', { 'data-label': label, class: cls || null }, kid); }
tb.appendChild(h('tr', 'row',
td(t('ss.c.ip'), link(s.ip)),
td(t('ss.c.stage'), h('span', { class: 'ss-badge ss-s-' + stg(s.stage), text: t('ss.stage.' + stg(s.stage)) })),
td(t('ss.c.start'), h('span', { text: U.fmt.date(a) }), 'nw'),
td(t('ss.c.dur'), h('span', { text: dur(s.dur_s || 0) })),
td(t('ss.c.events'), h('span', { class: 'num', text: nf(s.n || 0) })),
td(t('ss.c.hosts'), h('span', { text: (s.hosts || []).slice(0, 3).join(', ') })),
td(t('ss.c.fam'), h('span', { text: topFam(s) })),
td(t('ss.c.replay'), rp)));
});
var th = h('tr');
['ip', 'stage', 'start', 'dur', 'events', 'hosts', 'fam', 'replay'].forEach(function (c) { th.appendChild(h('th', { text: t('ss.c.' + c) })); });
body.appendChild(h('table', 'stack ss-table', h('thead', null, th), tb));
if (rows.length > st.shown) {
var more = h('button', { type: 'button', class: 'btn', text: t('ss.more') });
more.addEventListener('click', function () { st.shown += SHOW; paint(); });
body.appendChild(more);
}
}
wrap.appendChild(U.ui.panel({ title: t('ss.list') }, body));
// escalation chains
if (d.escalations && d.escalations.length) {
var ul = h('div', 'ss-chains');
d.escalations.slice(0, 20).forEach(function (e) {
var steps = h('div', 'ss-steps');
(e.steps || []).slice(0, 12).forEach(function (p) {
steps.appendChild(h('span', { class: 'ss-step ss-s-' + stg(p.stage), title: String(p.evidence || ''), text: t('ss.stage.' + stg(p.stage)) }));
});
ul.appendChild(h('div', 'ss-chain', link(e.ip), steps));
});
wrap.appendChild(U.ui.panel({ title: t('ss.esc'), help: 'term.stage.exploit', hint: t('ss.esc.hint') }, ul));
}
}
this.update = function (c) { var lang = self.ctx.lang; self.ctx = c; if (lang !== c.lang && data) paint(); data = null; load(); };
this.refresh = function () { load(); };
this.destroy = function () { alive = false; seq++; root.textContent = ''; };
load();
}
U.registerPage({
id: 'sessions', group: 'investigate', icon: ICON, titleKey: 'ss.title',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); },
update: function (ctx) { if (inst) inst.update(ctx); },
refresh: function () { if (inst) inst.refresh(); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
return true;
}
if (!boot()) document.addEventListener('DOMContentLoaded', boot);
})();
+31
View File
@@ -0,0 +1,31 @@
/* Services (SLO) page */
.hl-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--grid-gap, 16px); }
.hl-card { border: 1px solid var(--line); border-radius: var(--radius); padding: var(--s-4, 14px); background: var(--surface-raised); display: grid; gap: 8px; min-width: 0; border-top: 3px solid var(--ok); }
.hl-card.tone-warn { border-top-color: var(--warn); }
.hl-card.tone-danger { border-top-color: var(--danger); }
.hl-card header { display: grid; gap: 2px; min-width: 0; }
.hl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; color: var(--heading); }
.hl-svc { color: var(--ink-faint); font-size: .75rem; overflow-wrap: anywhere; }
.hl-big { font: 600 1.75rem var(--font-display); color: var(--heading); display: flex; align-items: baseline; gap: 8px; }
.hl-big small { font: 500 .75rem var(--font-sans); color: var(--ink-muted); }
.hl-bar { height: 6px; border-radius: 3px; background: var(--surface-sunken); overflow: hidden; }
.hl-bar i { display: block; height: 100%; background: var(--ok); }
.tone-warn .hl-bar i { background: var(--warn); } .tone-danger .hl-bar i { background: var(--danger); }
.hl-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.hl-st { display: grid; min-width: 0; }
.hl-sv { font-weight: 600; font-size: .9375rem; color: var(--ink); }
.hl-sl { font-size: .6875rem; color: var(--ink-muted); }
.hl-spark { height: 28px; color: var(--accent); }
.hl-spark svg { width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.5; }
.hl-card footer { font-size: .75rem; color: var(--ink-muted); }
.hl-bands { display: grid; gap: var(--s-4, 14px); }
.hl-bgrp h4 { margin: 0 0 4px; font-size: .875rem; color: var(--heading); overflow-wrap: anywhere; }
.hl-brow { display: grid; grid-template-columns: 34px repeat(3, minmax(0, 1fr)); gap: 8px; align-items: center; margin: 2px 0; }
.hl-bq { font-size: .75rem; color: var(--ink-muted); }
.hl-btrack { position: relative; display: block; height: 16px; background: var(--surface-sunken); border-radius: 3px; overflow: hidden; }
.hl-btrack i { display: block; height: 100%; opacity: .85; }
.hl-btrack b { position: absolute; left: 6px; top: 0; font-weight: 500; font-size: .6875rem; line-height: 16px; color: var(--ink); }
.hl-legend { display: flex; gap: 14px; font-size: .75rem; color: var(--ink-muted); }
.hl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 5px; }
.hl-page .panel { min-width: 0; }
@media (max-width: 900px) { .hl-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
+157
View File
@@ -0,0 +1,157 @@
/* Urutau - page SLO ("Services"): one card per backend service with its SLI, error budget,
Apdex, p95 latency and traffic; latency bands (total, origin, proxy) and a profile radar.
Data: /api/v1/services. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
U.registerI18n({
en: {
'hl.sl.title': 'Services',
'hl.sl.lead': '{n} services, {ok} within their objective',
'hl.sl.lead.body': 'Objective: 99.5% of legitimate requests without an application or proxy error. {worst} has the least budget left ({budget}) {range}.',
'hl.sl.lead.body.all': 'Objective: 99.5% of legitimate requests without an application or proxy error, {range}.',
'hl.sl.lead.empty': 'No services seen yet',
'hl.sl.lead.empty.body': 'No Traefik requests with service data {range}.',
'hl.sl.cards': 'Service health', 'hl.sl.cards.hint': 'SLI is the share of legitimate requests answered without an application or proxy error.',
'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Budget left', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'peak req/s', 'hl.sl.burn': 'Burn 1h',
'hl.sl.req': '{n} requests',
'hl.sl.bands': 'Latency bands', 'hl.sl.bands.hint': 'p50, p95 and p99 of the total time, the backend time and the proxy overhead (ms), for the busiest services.',
'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy',
'hl.sl.radar': 'Profile', 'hl.sl.radar.hint': 'Each axis is scaled to the best service: availability, Apdex, speed (p95), retries and traffic.',
'hl.sl.ax.avail': 'Availability', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Speed', 'hl.sl.ax.retry': 'No retries', 'hl.sl.ax.traffic': 'Traffic',
'hl.sl.err': 'Could not load the services.', 'hl.sl.retry': 'Try again', 'hl.sl.empty': 'Nothing to show for this range.'
},
'pt-BR': {
'hl.sl.title': 'Serviços',
'hl.sl.lead': '{n} serviços, {ok} dentro do objetivo',
'hl.sl.lead.body': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy. {worst} tem o menor orçamento restante ({budget}) {range}.',
'hl.sl.lead.body.all': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy, {range}.',
'hl.sl.lead.empty': 'Nenhum serviço visto ainda',
'hl.sl.lead.empty.body': 'Nenhuma requisição do Traefik com dados de serviço {range}.',
'hl.sl.cards': 'Saúde dos serviços', 'hl.sl.cards.hint': 'O SLI é a parcela das requisições legítimas respondidas sem erro de aplicação ou de proxy.',
'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Orçamento restante', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'pico req/s', 'hl.sl.burn': 'Consumo 1h',
'hl.sl.req': '{n} requisições',
'hl.sl.bands': 'Faixas de latência', 'hl.sl.bands.hint': 'p50, p95 e p99 do tempo total, do tempo no backend e da sobrecarga do proxy (ms), nos serviços mais ocupados.',
'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy',
'hl.sl.radar': 'Perfil', 'hl.sl.radar.hint': 'Cada eixo é relativo ao melhor serviço: disponibilidade, Apdex, rapidez (p95), retentativas e tráfego.',
'hl.sl.ax.avail': 'Disponibilidade', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Rapidez', 'hl.sl.ax.retry': 'Sem retentativas', 'hl.sl.ax.traffic': 'Tráfego',
'hl.sl.err': 'Não foi possível carregar os serviços.', 'hl.sl.retry': 'Tentar de novo', 'hl.sl.empty': 'Nada para mostrar neste período.'
}
});
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function ms(v) { return v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + ' s' : (v >= 10 ? Math.round(v) : v.toFixed(1)) + ' ms'; }
function pct1(v) { return (v * 100).toFixed(v >= 0.9995 ? 2 : 1) + '%'; }
function tone(s) { return s.budget_left <= 0.1 || s.burn_1h >= 6 ? 'danger' : s.budget_left <= 0.5 || s.burn_1h >= 2 ? 'warn' : 'ok'; }
function card(s) {
var tn = tone(s);
var spark = U.charts && U.charts.sparkline && s.spark && s.spark.length > 1 ? U.charts.sparkline(s.spark) : null;
var stat = function (label, value, key) {
var l = el('span', { class: 'hl-sl' }, label);
if (key && U.help && U.glossary && U.glossary.has(key)) U.help(l, key);
return el('div', { class: 'hl-st' }, el('span', { class: 'hl-sv num' }, value), l);
};
return el('article', { class: 'hl-card tone-' + tn },
el('header', null, el('h3', { class: 'hl-name' }, s.alias), el('span', { class: 'hl-svc mono' }, s.svc)),
el('div', { class: 'hl-big num' }, pct1(s.sli), el('small', null, t('hl.sl.sli'))),
el('div', { class: 'hl-bar', role: 'img', 'aria-label': t('hl.sl.budget') + ' ' + U.fmt.pct(s.budget_left) }, el('i', { style: { width: Math.round(s.budget_left * 100) + '%' } })),
el('div', { class: 'hl-stats' }, stat(t('hl.sl.budget'), U.fmt.pct(s.budget_left), 'term.error_budget'), stat(t('hl.sl.apdex'), s.apdex.toFixed(2), 'term.apdex'), stat(t('hl.sl.p95'), ms(s.p95.total)), stat(t('hl.sl.rps'), s.rps_peak.toFixed(2))),
spark ? el('div', { class: 'hl-spark' }, spark) : null,
el('footer', null, t('hl.sl.req', { n: U.fmt.num(s.req) })));
}
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 hl-page' });
var lead = el('div', { class: 'span-12' });
var pc = U.ui.panel({ title: t('hl.sl.cards'), hint: t('hl.sl.cards.hint'), loading: true, cls: 'span-12' });
var pb = U.ui.panel({ title: t('hl.sl.bands'), hint: t('hl.sl.bands.hint'), variant: 'chart', loading: true, cls: 'span-8' });
var pr = U.ui.panel({ title: t('hl.sl.radar'), hint: t('hl.sl.radar.hint'), variant: 'chart', loading: true, cls: 'span-4' });
[lead, pc, pb, pr].forEach(function (n) { grid.appendChild(n); });
root.appendChild(grid);
function bands(list) {
var box = el('div', { class: 'hl-bands' });
var mx = 0; list.slice(0, 8).forEach(function (s) { ['p50', 'p95', 'p99'].forEach(function (q) { ['total', 'origin', 'overhead'].forEach(function (k) { if (s[q][k] > mx) mx = s[q][k]; }); }); });
list.slice(0, 8).forEach(function (s) {
var g = el('div', { class: 'hl-bgrp' }, el('h4', null, s.alias));
['p50', 'p95', 'p99'].forEach(function (q) {
var v = s[q];
var line = el('div', { class: 'hl-brow' }, el('span', { class: 'hl-bq' }, q));
[['total', 'hl.sl.band.total', '--viz-1'], ['origin', 'hl.sl.band.origin', '--viz-3'], ['overhead', 'hl.sl.band.overhead', '--viz-5']].forEach(function (p) {
var w = mx ? Math.max(v[p[0]] > 0 ? 1.5 : 0, v[p[0]] / mx * 100) : 0;
var i = el('i', { style: { width: w + '%', background: 'var(' + p[2] + ')' } });
i.title = t(p[1]) + ' ' + ms(v[p[0]]);
line.appendChild(el('span', { class: 'hl-btrack' }, i, el('b', { class: 'num' }, ms(v[p[0]]))));
});
g.appendChild(line);
});
box.appendChild(g);
});
var lg = el('div', { class: 'hl-legend' });
[['hl.sl.band.total', '--viz-1'], ['hl.sl.band.origin', '--viz-3'], ['hl.sl.band.overhead', '--viz-5']].forEach(function (p) {
lg.appendChild(el('span', null, el('i', { style: { background: 'var(' + p[1] + ')' } }), t(p[0])));
});
box.appendChild(lg);
return box;
}
function radar(list) {
var top = list.slice(0, 5);
if (!(U.charts && U.charts.radar) || top.length < 1) return U.ui.empty(t('hl.sl.empty'));
var maxReq = 0, minP = Infinity;
top.forEach(function (s) { if (s.req > maxReq) maxReq = s.req; if (s.p95.total > 0 && s.p95.total < minP) minP = s.p95.total; });
var axes = [{ key: 'avail', label: t('hl.sl.ax.avail') }, { key: 'apdex', label: t('hl.sl.ax.apdex') }, { key: 'speed', label: t('hl.sl.ax.speed') }, { key: 'retry', label: t('hl.sl.ax.retry') }, { key: 'traffic', label: t('hl.sl.ax.traffic') }];
var series = top.map(function (s) {
return { label: s.alias, values: [s.sli * 100, s.apdex * 100, s.p95.total > 0 ? Math.min(100, minP / s.p95.total * 100) : 100, Math.max(0, 100 - s.retries_pct * 10), maxReq ? s.req / maxReq * 100 : 0] };
});
return U.charts.radar(axes, series, { max: 100, title: t('hl.sl.radar'), format: function (v) { return Math.round(v) + ''; } });
}
function paint() {
clear(lead); [pc, pb, pr].forEach(function (p) { clear(p.body); });
if (!data) return;
var range = U.rangeLabel({ inline: true });
if (!data.length) {
lead.appendChild(U.ui.lead(t('hl.sl.lead.empty'), t('hl.sl.lead.empty.body', { range: range }), 'neutral'));
[pc, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.sl.empty'))); });
return;
}
var ok = data.filter(function (s) { return s.budget_left > 0; }).length;
var worst = data.slice().sort(function (a, b) { return a.budget_left - b.budget_left; })[0];
lead.appendChild(U.ui.lead(t('hl.sl.lead', { n: data.length, ok: ok }),
worst.budget_left >= 1 ? t('hl.sl.lead.body.all', { range: range }) : t('hl.sl.lead.body', { worst: worst.alias, budget: U.fmt.pct(worst.budget_left), range: range }),
ok === data.length ? 'ok' : 'warn'));
var cards = el('div', { class: 'hl-cards' });
data.forEach(function (s) { cards.appendChild(card(s)); });
pc.body.appendChild(cards);
pb.body.appendChild(bands(data));
pr.body.appendChild(radar(data));
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.domain && c.domain !== 'all') p.host = c.domain;
U.api('/api/v1/services', p).then(function (r) { if (alive && my === seq) { data = r || []; paint(); } }, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('hl.sl.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.sl.err')), b));
});
}
load();
return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } };
}
U.registerPage({
id: 'slo', group: 'monitor', titleKey: 'hl.sl.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="4" width="18" height="6" rx="1.5"/><rect x="3" y="14" width="18" height="6" rx="1.5"/><path d="M7 7h.01M7 17h.01"/></svg>',
mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();
+60
View File
@@ -585,3 +585,63 @@ input[type="datetime-local"] { background: var(--surface-raised); border: 1px so
.iv-cuts { font-size: .75rem; }
.mini-days span { white-space: nowrap; }
.mini-days { font-size: 10px; }
/* ================================================================ charts and help */
.sr-only { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; padding: 0; margin: -1px; }
.vz { min-width: 0; }
.vz-donut-wrap { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-3) var(--s-4); }
.vz-donut-svg { flex: 0 1 190px; min-width: 140px; }
.vz-donut { width: 100%; height: auto; display: block; }
.vz-seg { transition: opacity .15s, stroke-width .15s; cursor: pointer; outline: none; }
.vz-seg:hover, .vz-seg:focus { stroke-width: 31; }
.vz-seg:focus-visible { stroke: var(--ink) !important; }
.vz-seg.dim { opacity: .35; }
.vz-c-v { font: 800 26px var(--font-display); fill: var(--heading); font-variant-numeric: tabular-nums; }
.vz-c-l { font: 500 12px var(--font-sans); fill: var(--ink-muted); }
.vz-gauge-wrap .vz-c-l { text-align: center; }
.vz-legend { list-style: none; padding: 0; display: grid; gap: 4px; flex: 1 1 140px; min-width: 0; }
.vz-legend li { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: .875rem; }
.vz-legend .vz-l { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.vz-legend .vz-v { color: var(--ink-muted); white-space: nowrap; }
.vz-area + .legend, .vz > .vz-legend { margin-top: var(--s-2); display: flex; flex-wrap: wrap; gap: 4px 14px; }
.vz-area-s { stroke: var(--surface-panel); stroke-width: 1; fill-opacity: .9; }
.vz-guide { stroke: var(--ink-muted); stroke-width: 1; stroke-dasharray: 3 3; pointer-events: none; }
.vz-radar-wrap svg { width: 100%; height: auto; display: block; }
.vz-ring { fill: none; stroke: var(--line); stroke-width: 1; }
.vz-rs { fill-opacity: .18; stroke-width: 2; }
.vz-dot { stroke: var(--surface-panel); stroke-width: 1; outline: none; }
.vz-dot:focus-visible { stroke: var(--ink); stroke-width: 2; }
.vz-axl { font: 500 11px var(--font-sans); fill: var(--ink-muted); }
.vz-bars { display: grid; gap: 8px; }
.vz-row { display: grid; grid-template-columns: minmax(70px, 38%) minmax(0, 1fr) auto; gap: 8px; align-items: center; font-size: .875rem; }
.vz-row .vz-l { overflow-wrap: anywhere; min-width: 0; }
.vz-row .vz-v { color: var(--ink-muted); }
.vz-track { display: flex; height: 12px; background: var(--surface-raised); border-radius: 6px; overflow: hidden; }
.vz-track i { display: block; height: 100%; }
.vz-cols { display: flex; align-items: flex-end; gap: 8px; height: 180px; }
.vz-cols .vz-row { display: flex; flex-direction: column-reverse; align-items: center; height: 100%; flex: 1; min-width: 0; }
.vz-cols .vz-track { flex-direction: column-reverse; width: 100%; height: 100%; }
.vz-cols .vz-track i { width: 100%; }
.vz-heat svg { width: 100%; height: auto; display: block; }
.vz-cell { fill: var(--surface-raised); }
.vz-cell.s1 { fill: var(--seq-1); } .vz-cell.s2 { fill: var(--seq-2); } .vz-cell.s3 { fill: var(--seq-3); } .vz-cell.s4 { fill: var(--seq-4); } .vz-cell.s5 { fill: var(--seq-5); }
.vz-cell:focus-visible { stroke: var(--ink); stroke-width: 2; outline: none; }
.vz-gauge { width: 100%; max-width: 220px; height: auto; display: block; margin: 0 auto; }
.vz-g-bg, .vz-g-fg { fill: none; stroke-width: 14; stroke-linecap: round; }
.vz-g-bg { stroke: var(--surface-raised); }
.vz-g-fg { stroke: var(--ok); } .vz-g-fg.tone-warn { stroke: var(--warn); } .vz-g-fg.tone-danger { stroke: var(--danger); } .vz-g-fg.tone-info { stroke: var(--info); }
.card-chart .vz-area { min-height: var(--h-chart); }
.help-btn { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; margin-left: 6px; padding: 0; border-radius: 50%; border: 1px solid var(--line-strong); background: var(--surface-raised); color: var(--ink-muted); font: 700 11px/1 var(--font-sans); cursor: help; vertical-align: middle; text-transform: none; letter-spacing: 0; flex: none; }
.help-btn:hover, .help-btn:focus-visible { color: var(--on-accent); background: var(--accent); border-color: transparent; }
.cm-label, .panel-h h2, .legend { }
.cm-label { display: block; }
.panel-h h2 { display: inline-flex; align-items: center; }
.help-pop { position: fixed; z-index: 95; width: min(320px, calc(100vw - 16px)); background: var(--surface-overlay); color: var(--ink); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); box-shadow: var(--shadow); padding: 10px 12px; font-size: .875rem; line-height: 1.45; text-transform: none; letter-spacing: 0; font-weight: 400; }
.help-pop[hidden] { display: none; }
.help-pop .help-do { margin-top: 6px; color: var(--ink-muted); }
.nav-group { margin: 10px 0 2px; padding: 0 var(--s-3); color: var(--rail-ink-muted); font: 600 11px var(--font-sans); text-transform: uppercase; letter-spacing: .1em; }
.nav-group:first-child { margin-top: 0; }
.more-sheet .nav-group { color: var(--ink-muted); padding: 6px var(--s-3) 0; }
@media (max-width: 1199px) { .nav-group { font-size: 0; height: 1px; background: var(--rail-line); margin: 8px 6px; padding: 0; } }
@media (max-width: 767px) { .more-sheet .nav-group { font-size: 11px; height: auto; background: none; margin: 6px 0 0; padding: 6px var(--s-3) 0; } }
+26
View File
@@ -0,0 +1,26 @@
/* Survival page (shared .an-* rules are repeated so each page file stands alone) */
.an-boxes { display: grid; gap: var(--s-3); }
.an-boxrow { display: grid; grid-template-columns: minmax(70px, 28%) minmax(0, 1fr) auto; align-items: center; gap: var(--s-3); min-width: 0; }
.an-boxrow .an-fam { overflow-wrap: anywhere; font-size: .8125rem; }
.an-boxrow .an-val { font-variant-numeric: tabular-nums; color: var(--ink-muted); font-size: .8125rem; white-space: nowrap; }
.an-track { position: relative; height: 18px; border-radius: 4px; background: var(--surface-sunken); border: 1px solid var(--line); }
.an-box { position: absolute; top: 2px; bottom: 2px; border-radius: 3px; background: color-mix(in srgb, var(--accent) 45%, transparent); border: 1px solid var(--accent); }
.an-med { position: absolute; top: -2px; bottom: -2px; width: 3px; margin-left: -1px; border-radius: 2px; background: var(--heading); }
.an-rec { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0 var(--s-6); }
.an-chart { min-width: 0; }
.an-svg { display: block; width: 100%; height: auto; max-width: 100%; overflow: visible; }
.an-svg .an-grid { stroke: var(--line); stroke-width: 1; }
.an-svg .an-guide { stroke: var(--warn); stroke-width: 1; stroke-dasharray: 4 4; }
.an-svg .an-line { fill: none; stroke: var(--accent); stroke-width: 2.25; stroke-linejoin: round; stroke-linecap: round; }
.an-svg .an-fill { fill: var(--accent); fill-opacity: .14; stroke: none; }
.an-svg .an-dot { fill: var(--accent); stroke: var(--surface-panel); stroke-width: 1.5; }
.an-svg .an-tick { fill: var(--ink-muted); font-size: 11px; }
.an-svg .an-strong { fill: var(--ink); font-weight: 600; }
.an-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; }
.an-list li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 4px 0; border-bottom: 1px solid var(--line); min-width: 0; }
.an-list li:last-child { border-bottom: 0; }
.an-list .an-k, .an-list a { overflow-wrap: anywhere; min-width: 0; }
.an-list .an-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); white-space: nowrap; }
.an-list .an-bad { color: var(--danger); }
.an-list .an-good { color: var(--ok); }
.an-rec li { margin-right: var(--s-5); }
+218
View File
@@ -0,0 +1,218 @@
/* Urutau - SOBREVIVENCIA page: how long until the ban, and who comes back?
Kaplan-Meier curve (attackers never banned are censored), time-to-ban range
per family (p25-p75 bar with the median) and the list of repeat offenders.
Data: /api/v1/survival. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
U.registerI18n({
en: {
'an.sv.title': 'Survival',
'an.sv.lead': 'Half of the attack episodes end in a ban within {dur}',
'an.sv.lead.unknown': 'Fewer than half of the attack episodes ended in a ban',
'an.sv.lead.empty': 'No attackers to follow',
'an.sv.lead.body': '{banned} of {n} attackers banned {range}; {rec} of the banned came back and were banned again. 90% banned within {p90}.',
'an.sv.lead.body.nop90': '{banned} of {n} attackers banned {range}; {rec} of the banned came back and were banned again.',
'an.sv.lead.empty.body': 'Nothing was recorded {range}.',
'an.sv.km': 'Share still unbanned over time',
'an.sv.km.hint': 'Kaplan-Meier curve per attack episode, from its first malicious event. Episodes that ended without a ban only count as time observed.',
'an.sv.x': 'Time since the start of the episode',
'an.sv.y': 'Not banned yet',
'an.sv.median': 'median {dur}',
'an.sv.fam': 'Time to ban by family',
'an.sv.fam.hint': 'The bar spans the 25th to the 75th percentile; the mark is the median.',
'an.sv.fam.row': '{fam}: median {p50}, from {p25} to {p75} ({n} banned)',
'an.sv.rec': 'Repeat offenders',
'an.sv.rec.hint': 'Addresses banned more than once. Open one to see its history.',
'an.sv.rec.none': 'Nobody was banned twice in this slice.',
'an.sv.rec.row': '{bans} bans, last {ago}',
'an.sv.recpct': 'Recidivism',
'an.sv.none': 'No banned attackers with a known family in this slice.',
'an.sv.dur.s': '{n} s',
'an.sv.dur.m': '{n} min',
'an.sv.dur.h': '{n} h',
'an.sv.dur.d': '{n} d',
'an.sv.off': 'The event registry is off',
'an.sv.off.d': 'This analysis reads the event registry, which is not enabled on this instance.',
'an.sv.err': 'Could not load this analysis.',
'an.sv.retry': 'Try again'
},
'pt-BR': {
'an.sv.title': 'Sobrevivência',
'an.sv.lead': 'Metade dos episódios de ataque termina em ban em até {dur}',
'an.sv.lead.unknown': 'Menos da metade dos episódios de ataque terminou em ban',
'an.sv.lead.empty': 'Nenhum atacante para acompanhar',
'an.sv.lead.body': '{banned} de {n} atacantes banidos {range}; {rec} dos banidos voltaram e foram banidos de novo. 90% banidos em até {p90}.',
'an.sv.lead.body.nop90': '{banned} de {n} atacantes banidos {range}; {rec} dos banidos voltaram e foram banidos de novo.',
'an.sv.lead.empty.body': 'Nada foi registrado {range}.',
'an.sv.km': 'Parcela ainda sem ban ao longo do tempo',
'an.sv.km.hint': 'Curva de Kaplan-Meier por episódio de ataque, desde o primeiro evento malicioso. Episódios que terminaram sem ban contam só como tempo observado.',
'an.sv.x': 'Tempo desde o início do episódio',
'an.sv.y': 'Ainda não banido',
'an.sv.median': 'mediana {dur}',
'an.sv.fam': 'Tempo até o ban por família',
'an.sv.fam.hint': 'A barra vai do percentil 25 ao 75; a marca é a mediana.',
'an.sv.fam.row': '{fam}: mediana {p50}, de {p25} a {p75} ({n} banidos)',
'an.sv.rec': 'Reincidentes',
'an.sv.rec.hint': 'Endereços banidos mais de uma vez. Abra um para ver o histórico.',
'an.sv.rec.none': 'Ninguém foi banido duas vezes neste recorte.',
'an.sv.rec.row': '{bans} bans, último {ago}',
'an.sv.recpct': 'Reincidência',
'an.sv.none': 'Nenhum atacante banido com família conhecida neste recorte.',
'an.sv.dur.s': '{n} s',
'an.sv.dur.m': '{n} min',
'an.sv.dur.h': '{n} h',
'an.sv.dur.d': '{n} d',
'an.sv.off': 'O registro de eventos está desligado',
'an.sv.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.',
'an.sv.err': 'Não foi possível carregar esta análise.',
'an.sv.retry': 'Tentar de novo'
}
});
function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function one(x) { return U.fmt.num(Math.round(x * 10) / 10); }
function dur(sec) {
if (sec < 90) return t('an.sv.dur.s', { n: Math.round(sec) });
if (sec < 5400) return t('an.sv.dur.m', { n: Math.round(sec / 60) });
if (sec < 129600) return t('an.sv.dur.h', { n: one(sec / 3600) });
return t('an.sv.dur.d', { n: one(sec / 86400) });
}
// step curve of the survival function; x linear in time
function km(points, median) {
var W = 640, H = 280, L = 44, R = 14, T = 12, B = 34, w = W - L - R, h = H - T - B;
var tmax = points.length ? points[points.length - 1].t_s : 0;
if (tmax <= 0) tmax = 1;
var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'an-svg', role: 'img', 'aria-label': t('an.sv.km'), preserveAspectRatio: 'xMidYMid meet' });
function X(v) { return L + v / tmax * w; }
function Y(v) { return T + (1 - v) * h; }
[0, 0.25, 0.5, 0.75, 1].forEach(function (v) {
svg.appendChild(el('line', { class: 'an-grid', x1: L, x2: W - R, y1: Y(v), y2: Y(v) }));
svg.appendChild(el('text', { class: 'an-tick', x: L - 6, y: Y(v) + 4, 'text-anchor': 'end' }, Math.round(v * 100) + '%'));
});
[0, 0.5, 1].forEach(function (f) {
svg.appendChild(el('text', { class: 'an-tick', x: X(f * tmax), y: H - 16, 'text-anchor': f === 0 ? 'start' : f === 1 ? 'end' : 'middle' }, dur(f * tmax)));
});
svg.appendChild(el('text', { class: 'an-tick', x: L + w / 2, y: H - 2, 'text-anchor': 'middle' }, t('an.sv.x')));
var d = '';
points.forEach(function (p, i) {
d += (i ? 'H' + X(p.t_s).toFixed(1) + 'V' : 'M' + X(p.t_s).toFixed(1) + ',') + Y(p.survival).toFixed(1);
if (!i) d += '';
});
if (points.length) {
svg.appendChild(el('path', { class: 'an-fill', d: d + 'V' + Y(0) + 'H' + X(0) + 'Z' }));
svg.appendChild(el('path', { class: 'an-line', d: d }));
}
if (typeof median === 'number') {
svg.appendChild(el('line', { class: 'an-guide', x1: X(median), x2: X(median), y1: T, y2: T + h }));
svg.appendChild(el('line', { class: 'an-guide', x1: L, x2: X(median), y1: Y(0.5), y2: Y(0.5) }));
svg.appendChild(el('text', { class: 'an-tick an-strong', x: Math.min(X(median) + 6, W - R), y: T + 12, 'text-anchor': X(median) > W - 120 ? 'end' : 'start' }, t('an.sv.median', { dur: dur(median) })));
}
points.forEach(function (p) {
if (points.length > 60) return;
svg.appendChild(el('circle', { class: 'an-dot', cx: X(p.t_s), cy: Y(p.survival), r: 3 }, el('title', null, dur(p.t_s) + ': ' + Math.round(p.survival * 1000) / 10 + '%')));
});
return el('div', { class: 'an-chart' }, svg);
}
function boxes(rows) {
if (!rows.length) return U.ui.empty(t('an.sv.none'));
var max = 1;
rows.forEach(function (r) { if (r.p75 > max) max = r.p75; });
max *= 1.08;
var box = el('div', { class: 'an-boxes' });
rows.forEach(function (r) {
var left = r.p25 / max * 100, width = Math.max((r.p75 - r.p25) / max * 100, 1.2), med = r.p50 / max * 100;
var track = el('div', { class: 'an-track' },
el('div', { class: 'an-box', style: { left: left + '%', width: width + '%' } }),
el('div', { class: 'an-med', style: { left: med + '%' } }));
var row = el('div', { class: 'an-boxrow', role: 'img', 'aria-label': t('an.sv.fam.row', { fam: r.fam, p50: dur(r.p50), p25: dur(r.p25), p75: dur(r.p75), n: r.n }) },
el('span', { class: 'an-fam mono' }, r.fam), track, el('span', { class: 'an-val' }, dur(r.p50)));
row.setAttribute('title', t('an.sv.fam.row', { fam: r.fam, p50: dur(r.p50), p25: dur(r.p25), p75: dur(r.p75), n: r.n }));
box.appendChild(row);
});
return box;
}
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 an-page' });
var lead = el('div', { class: 'span-12' });
var curve = U.ui.panel({ title: t('an.sv.km'), hint: t('an.sv.km.hint'), variant: 'chart', loading: true });
tip(curve, 'term.kaplan_meier');
var fam = U.ui.panel({ title: t('an.sv.fam'), hint: t('an.sv.fam.hint'), loading: true });
tip(fam, 'metric.mttb');
var rec = U.ui.panel({ title: t('an.sv.rec'), hint: t('an.sv.rec.hint'), loading: true });
tip(rec, 'term.recidivism');
grid.appendChild(lead);
grid.appendChild(curve); curve.classList.add('span-8');
grid.appendChild(fam); fam.classList.add('span-4');
grid.appendChild(rec); rec.classList.add('span-12');
root.appendChild(grid);
function paint() {
clear(lead); [curve, fam, rec].forEach(function (p) { clear(p.body); });
if (!data) return;
var d = data, range = U.rangeLabel({ inline: true });
if (!d.enabled) { lead.appendChild(U.ui.empty(t('an.sv.off'), t('an.sv.off.d'))); return; }
if (!d.attackers) {
lead.appendChild(U.ui.lead(t('an.sv.lead.empty'), t('an.sv.lead.empty.body', { range: range }), 'neutral'));
curve.body.appendChild(U.ui.empty(t('charts.empty')));
fam.body.appendChild(U.ui.empty(t('charts.empty')));
rec.body.appendChild(U.ui.empty(t('charts.empty')));
return;
}
var med = d.median_to_ban_s, p90 = d.p90_to_ban_s, recpct = U.fmt.pct(d.recidivism_pct / 100);
var vars = { banned: U.fmt.num(d.banned), n: U.fmt.num(d.attackers), range: range, rec: recpct, p90: typeof p90 === 'number' ? dur(p90) : '' };
var title = typeof med === 'number' ? t('an.sv.lead', { dur: dur(med) }) : t('an.sv.lead.unknown');
lead.appendChild(U.ui.lead(title, t(typeof p90 === 'number' ? 'an.sv.lead.body' : 'an.sv.lead.body.nop90', vars), typeof med === 'number' && med <= 3600 ? 'ok' : 'danger'));
curve.body.appendChild(km(d.km || [], typeof med === 'number' ? med : null));
fam.body.appendChild(boxes(d.by_family || []));
if (!d.recidivists || !d.recidivists.length) { rec.body.appendChild(U.ui.empty(t('an.sv.rec.none'))); return; }
var ul = el('ul', { class: 'an-list an-rec' });
d.recidivists.forEach(function (r) {
var a = el('a', { class: 'mono', href: '#/ip/' + encodeURIComponent(r.ip) }, r.ip);
ul.appendChild(el('li', null, a, el('span', { class: 'an-n' }, t('an.sv.rec.row', { bans: r.bans, ago: U.fmt.ago(r.last) }))));
});
rec.body.appendChild(ul);
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.host && c.host !== 'all') p.host = c.host;
U.api('/api/v1/survival', p).then(function (r) {
if (!alive || my !== seq) return;
data = r; paint();
}, function () {
if (!alive || my !== seq || data) return;
clear(lead);
var b = el('button', { type: 'button', class: 'btn' }, t('an.sv.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.sv.err')), b));
});
}
load();
return {
root: root, lang: ctx.lang,
update: function (cx) { c = cx; load(); },
destroy: function () { alive = false; seq++; clear(root); }
};
}
U.registerPage({
id: 'survival', group: 'analyze', titleKey: 'an.sv.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 20V4"/><path d="M4 20h16"/><path d="M4 6h4v4h4v5h4v3h4"/></svg>',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); },
update: function (ctx) {
ctx = ctx || {};
if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx);
},
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
})();