Files

1435 lines
78 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Urutau - REPLAY page: pick a period and replay the attacks of that period in
order (map + ordered list + incident timeline). Events are streamed in pages
from /api/v1/events (sliding window, never the whole period); the period
summary (sessions, campaigns, escalations, spikes) comes from /api/v1/period.
Log data is hostile: every dynamic string goes through textContent, and every
class name comes from a whitelist. */
(function () {
'use strict';
var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
var CAT_OK = {};
CATS.forEach(function (c) { CAT_OK[c] = 1; });
CAT_OK.ok = 1;
// category filter: '' = threats (everything but "ok", the default), 'all' = no filter, else one category
function catVal(c) { return c === 'all' || CAT_OK[c] ? c : ''; }
function catParam(c) { return c === '' ? '!ok' : c === 'all' ? '' : c; }
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
var RANK = { recon: 1, probe: 2, exploit: 3, access: 4, banned: 5 };
var WEIGHT = { notfound: 1, scanner: 3, bruteforce: 4, 'ssh-fail': 2, 'ssh-probe': 3, exploit: 15, 'ssh-ok': 30, ban: 0, ok: 0 };
var SPEEDS = [1, 10, 60, 300, 900, 3600];
var MARK_KINDS = ['session', 'exploit', 'access', 'ban', 'spike', 'tech'];
var MARK_PRIO = { exploit: 5, access: 6, ban: 4, spike: 3, tech: 2, session: 1 };
var NAV_KINDS = { exploit: 1, access: 1, ban: 1, spike: 1, tech: 1 };
var SENSITIVE = /(\.env|\.git|wp-config|passwd|shadow|id_rsa|\.aws|\.ssh|backup|\.sql|phpmyadmin|\.htpasswd|config\.(php|json|ya?ml)|credentials|secret)/i;
var ROW = 34; // list row height (px)
var PAGE = 2000; // events per request (API limit is 5000)
var AHEAD = 1000; // prefetch when fewer events than this remain ahead of the cursor
var KEEP_BEHIND = 1500; // events kept behind the cursor after a trim
var BUF_MAX = 6000; // trim when the buffer grows past this
var SILENCE = 120; // seconds of replay time considered a gap
var MAX_SPAN = 30 * 86400;
var FIRE_CAP = 600; // events handled per frame at most
var SPAWN_CAP = 10; // arcs started per frame at most
var NS = 'http://www.w3.org/2000/svg';
var instance = null;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'rp.title': 'Replay',
'rp.play': 'Play',
'rp.pause': 'Pause',
'rp.prev': 'Previous incident',
'rp.next': 'Next incident',
'rp.stepb': 'Previous event',
'rp.stepf': 'Next event',
'rp.speed': 'Speed',
'rp.compress': 'Skip silence',
'rp.only': 'Incidents only',
'rp.select': 'Select segment',
'rp.loopclear': 'Clear segment',
'rp.repeat': 'Repeat',
'rp.loop': 'Looping {a} to {b}',
'rp.share': 'Copy link',
'rp.copied': 'Link copied',
'rp.restart': 'Restart',
'rp.follow': 'Follow cursor',
'rp.cat': 'Category',
'rp.cat.all': 'Threats (default)',
'rp.cat.every': 'All, including legitimate traffic',
'rp.fam': 'Family',
'rp.fam.all': 'All families',
'rp.q': 'IP or country',
'rp.q.ph': 'IP or country (BR)',
'rp.clear': 'Clear filters',
'rp.mode.flat': 'Flat map',
'rp.mode.globe': 'Globe',
'rp.detail': 'Details',
'rp.close': 'Close',
'rp.lead.one': '{n} event {range}',
'rp.lead.other': '{n} events {range}',
'rp.stat.sessions': 'Sessions',
'rp.stat.campaigns': 'Campaigns',
'rp.stat.newret': 'New / returning IPs',
'rp.stat.techs': 'First-seen techniques',
'rp.stat.esc': 'Escalations',
'rp.empty.title': 'No events in this period',
'rp.empty.body': 'Widen the period or clear the filters.',
'rp.big.title': 'Period too large',
'rp.big.body': 'Choose up to 30 days, or filter by server, category or IP.',
'rp.end.title': 'End of the period',
'rp.end.body': 'All events of the period were replayed.',
'rp.lead.noreg': 'The event registry does not cover this period yet ({n} events counted in the totals {range})',
'rp.lead.none': 'No events {range}',
'rp.noreg.title': 'The event registry does not cover this period yet',
'rp.noreg.body': 'The totals count activity here, but there are no individual events to replay. Pick a more recent period, or wait for the registry to fill in.',
'rp.err': 'Could not load the events of this period.',
'rp.off.title': 'Event registry is off',
'rp.off.body': 'Replay needs the event registry (30 days of events). Enable it in the server settings.',
'rp.d.none': 'No event replayed yet. Press play or pick a point on the timeline.',
'rp.d.time': 'Time',
'rp.d.host': 'Server',
'rp.d.ip': 'IP',
'rp.d.asn': 'ASN',
'rp.d.where': 'Origin',
'rp.d.cat': 'Category',
'rp.d.fam': 'Family',
'rp.d.tech': 'MITRE technique',
'rp.d.req': 'Request',
'rp.d.status': 'Status',
'rp.d.ua': 'Client / tool',
'rp.d.user': 'SSH user',
'rp.d.jail': 'Jail',
'rp.d.bytes': 'Bytes',
'rp.d.score': 'IP score so far',
'rp.d.stage': 'Stage',
'rp.d.sess': 'Session',
'rp.d.sess.n': '{n} events',
'rp.d.sess.dur': 'duration {d}',
'rp.d.sess.peak': 'peak {n} req/min',
'rp.d.sess.ok': 'succeeded',
'rp.d.camp': 'Campaign',
'rp.d.camp.ips': '{n} IPs',
'rp.d.sens': 'success on a sensitive path',
'rp.d.openip': 'Open IP',
'rp.stage.recon': 'recon',
'rp.stage.probe': 'probe',
'rp.stage.exploit': 'exploit',
'rp.stage.access': 'access',
'rp.stage.banned': 'banned',
'rp.mk.n': '{n} marks',
'rp.mk.session': 'session start',
'rp.mk.exploit': 'exploit / escalation',
'rp.mk.access': 'access obtained',
'rp.mk.ban': 'ban',
'rp.mk.spike': 'traffic spike',
'rp.mk.tech': 'first-seen technique',
'rp.map.alt': 'Map of the replayed attacks. The ordered list below is the text alternative.',
'rp.list.label': 'Events in order',
'rp.tl.label': 'Replay timeline',
'rp.tl.legend': 'Incident marks',
'rp.clock': 'Replay clock',
'rp.loading': 'Loading the period...',
'rp.window': 'Window of {n} events in memory'
},
'pt-BR': {
'rp.title': 'Replay',
'rp.play': 'Reproduzir',
'rp.pause': 'Pausar',
'rp.prev': 'Incidente anterior',
'rp.next': 'Próximo incidente',
'rp.stepb': 'Evento anterior',
'rp.stepf': 'Próximo evento',
'rp.speed': 'Velocidade',
'rp.compress': 'Comprimir silêncio',
'rp.only': 'Só incidentes',
'rp.select': 'Selecionar trecho',
'rp.loopclear': 'Limpar trecho',
'rp.repeat': 'Repetir',
'rp.loop': 'Repetindo de {a} a {b}',
'rp.share': 'Copiar link',
'rp.copied': 'Link copiado',
'rp.restart': 'Reiniciar',
'rp.follow': 'Seguir o cursor',
'rp.cat': 'Categoria',
'rp.cat.all': 'Ameaças (padrão)',
'rp.cat.every': 'Tudo, inclusive tráfego legítimo',
'rp.fam': 'Família',
'rp.fam.all': 'Todas as famílias',
'rp.q': 'IP ou país',
'rp.q.ph': 'IP ou país (BR)',
'rp.clear': 'Limpar filtros',
'rp.mode.flat': 'Mapa plano',
'rp.mode.globe': 'Globo',
'rp.detail': 'Detalhes',
'rp.close': 'Fechar',
'rp.lead.one': '{n} evento {range}',
'rp.lead.other': '{n} eventos {range}',
'rp.stat.sessions': 'Sessões',
'rp.stat.campaigns': 'Campanhas',
'rp.stat.newret': 'IPs novos / recorrentes',
'rp.stat.techs': 'Primeiras técnicas',
'rp.stat.esc': 'Escaladas',
'rp.empty.title': 'Nenhum evento neste período',
'rp.empty.body': 'Amplie o período ou limpe os filtros.',
'rp.big.title': 'Período grande demais',
'rp.big.body': 'Escolha até 30 dias, ou filtre por servidor, categoria ou IP.',
'rp.end.title': 'Fim do período',
'rp.end.body': 'Todos os eventos do período foram reproduzidos.',
'rp.lead.noreg': 'O registro de eventos ainda não cobre este período ({n} eventos contados nos totais {range})',
'rp.lead.none': 'Nenhum evento {range}',
'rp.noreg.title': 'O registro de eventos ainda não cobre este período',
'rp.noreg.body': 'Os totais contam atividade aqui, mas não há eventos individuais para reproduzir. Escolha um período mais recente ou aguarde o registro acumular.',
'rp.err': 'Não foi possível carregar os eventos deste período.',
'rp.off.title': 'O registro de eventos está desligado',
'rp.off.body': 'O replay precisa do registro de eventos (30 dias). Ative-o nas configurações do servidor.',
'rp.d.none': 'Nenhum evento reproduzido ainda. Aperte reproduzir ou escolha um ponto na linha do tempo.',
'rp.d.time': 'Hora',
'rp.d.host': 'Servidor',
'rp.d.ip': 'IP',
'rp.d.asn': 'ASN',
'rp.d.where': 'Origem',
'rp.d.cat': 'Categoria',
'rp.d.fam': 'Família',
'rp.d.tech': 'Técnica MITRE',
'rp.d.req': 'Requisição',
'rp.d.status': 'Status',
'rp.d.ua': 'Cliente / ferramenta',
'rp.d.user': 'Usuário SSH',
'rp.d.jail': 'Jail',
'rp.d.bytes': 'Bytes',
'rp.d.score': 'Pontuação do IP até aqui',
'rp.d.stage': 'Estágio',
'rp.d.sess': 'Sessão',
'rp.d.sess.n': '{n} eventos',
'rp.d.sess.dur': 'duração {d}',
'rp.d.sess.peak': 'pico de {n} req/min',
'rp.d.sess.ok': 'teve sucesso',
'rp.d.camp': 'Campanha',
'rp.d.camp.ips': '{n} IPs',
'rp.d.sens': 'sucesso em caminho sensível',
'rp.d.openip': 'Abrir IP',
'rp.stage.recon': 'recon',
'rp.stage.probe': 'sondagem',
'rp.stage.exploit': 'exploit',
'rp.stage.access': 'acesso',
'rp.stage.banned': 'banido',
'rp.mk.n': '{n} marcas',
'rp.mk.session': 'início de sessão',
'rp.mk.exploit': 'exploração / escalada',
'rp.mk.access': 'acesso obtido',
'rp.mk.ban': 'ban',
'rp.mk.spike': 'pico de tráfego',
'rp.mk.tech': 'primeira técnica vista',
'rp.map.alt': 'Mapa dos ataques reproduzidos. A lista ordenada abaixo é a alternativa em texto.',
'rp.list.label': 'Eventos em ordem',
'rp.tl.label': 'Linha do tempo do replay',
'rp.tl.legend': 'Marcas de incidente',
'rp.clock': 'Relógio do replay',
'rp.loading': 'Carregando o período...',
'rp.window': 'Janela de {n} eventos na memória'
}
});
U.registerPage({
id: 'replay',
titleKey: 'rp.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 12a8 8 0 1 0 2.6-5.9"/><path d="M4 4v4.5h4.5"/><path d="M10.5 9v6l5-3z" fill="currentColor"/></svg>',
mount: function (el, ctx) { if (instance) instance.destroy(); instance = create(U, el, ctx || {}); },
update: function (ctx) { if (instance) instance.update(ctx || {}); },
unmount: function () { if (instance) { instance.destroy(); instance = null; } }
});
return true;
}
// ------------------------------------------------------------------ helpers
function h(tag, cls) {
var n = document.createElement(tag);
if (cls) n.className = cls;
for (var i = 2; i < arguments.length; i++) {
var c = arguments[i];
if (c === null || c === undefined || c === false) continue;
n.appendChild(c instanceof Node ? c : document.createTextNode(String(c)));
}
return n;
}
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function ico(paths, fill) {
var s = document.createElementNS(NS, 'svg');
s.setAttribute('viewBox', '0 0 24 24');
s.setAttribute('aria-hidden', 'true');
if (fill) s.setAttribute('class', 'rp-f');
paths.split('|').forEach(function (d) { var p = document.createElementNS(NS, 'path'); p.setAttribute('d', d); s.appendChild(p); });
return s;
}
var ICON = {
play: ['M8 5.5v13l10.5-6.5z', 1],
pause: ['M7 5h3.5v14H7z|M13.5 5H17v14h-3.5z', 1],
prev: ['M5 5h2.5v14H5z|M19 5.5v13L9.5 12z', 1],
next: ['M16.5 5H19v14h-2.5z|M5 5.5v13L14.5 12z', 1],
stepb: ['M16 5.5v13L7 12z', 1],
stepf: ['M8 5.5v13L17 12z', 1],
repeat: ['M17 2l4 4-4 4|M3 11V9a3 3 0 0 1 3-3h15|M7 22l-4-4 4-4|M21 13v2a3 3 0 0 1-3 3H3', 0],
restart: ['M4 4v6h6|M5.5 15a8 8 0 1 0 2-8L4 10', 0],
share: ['M4 12v7h16v-7|M12 3v12|M8 7l4-4 4 4', 0],
seg: ['M4 8v8|M20 8v8|M4 12h16', 0],
close: ['M6 6l12 12|M18 6L6 18', 0]
};
function icon(n) { return ico(ICON[n][0], ICON[n][1]); }
function pad(n) { return n < 10 ? '0' + n : String(n); }
function num(v) { var n = +v; return isFinite(n) ? n : 0; }
function str(v, max) { return (v === undefined || v === null) ? '' : String(v).slice(0, max || 300); }
function clamp(v, a, b) { return v < a ? a : v > b ? b : v; }
function secs(v) { v = num(v); return v > 1e12 ? Math.floor(v / 1000) : v; }
function catClass(c) { return CAT_OK[c] ? c : 'x'; }
function lowerBound(arr, t) { var lo = 0, hi = arr.length; while (lo < hi) { var m = (lo + hi) >> 1; if (arr[m].t < t) lo = m + 1; else hi = m; } return lo; }
function upperBound(arr, t) { var lo = 0, hi = arr.length; while (lo < hi) { var m = (lo + hi) >> 1; if (arr[m].t <= t) lo = m + 1; else hi = m; } return lo; }
// time as unix seconds: numbers, numeric strings and RFC 3339 strings
function ts(v) {
if (v === undefined || v === null || v === '') return 0;
if (typeof v === 'string' && !/^\d+(\.\d+)?$/.test(v)) { var d = Date.parse(v); return isFinite(d) ? Math.floor(d / 1000) : 0; }
return secs(v);
}
function qget(params, name) {
if (!params) return '';
var v = typeof params.get === 'function' ? params.get(name) : (params.query ? params.query[name] : params[name]);
return v === undefined || v === null ? '' : String(v);
}
function ipLike(s) { return /^[0-9a-fA-F:.]+$/.test(s) && /[.:]/.test(s); }
// ------------------------------------------------------------------ the page
function create(U, rootEl, ctx0) {
var t = U.t, pl = U.pl;
var ctx = ctx0, alive = true, lang = ctx.lang || '';
var P = ctx.params || {};
var reduced = false, mqReduced = null;
try { mqReduced = window.matchMedia('(prefers-reduced-motion: reduce)'); reduced = mqReduced.matches; } catch (e) { /* ignore */ }
var mqSmall = null;
try { mqSmall = window.matchMedia('(max-width: 1199px)'); } catch (e) { /* ignore */ }
// ---- state
var from = 0, to = 0, tooBig = false, routeT = '', noReg = false, campStarted = false, campId = '', campIps = null;
var F = { cat: '', fam: '', q: '', host: '' };
var speed = 60, compress = false, only = false;
var playing = false, ended = false, repeat = false;
try { repeat = localStorage.getItem('urutau.replay.repeat') === '1'; } catch (x) { /* storage blocked */ }
var clock = 0;
var buf = [], idx = 0, nextTok = null, loading = false, epoch = 0, startFrom = 0, firstBatch = true, landBefore = null;
var failed = false, drained = false;
var ipSt = {}, ipChain = {}, sessByIp = {}, campById = {};
var sumDone = false, seriesTotal = 0, period = null, periodLoading = true, periodSeq = 0, summarySeq = 0, tlData = null;
var marks = [], bins = [], binStart = 0, binStep = 60, binMax = 1, spikeMin = Infinity;
var loop = null, selecting = false;
var follow = true, expectedTop = -1;
var sel = null; // event pinned by a click (cleared as soon as playback moves on)
var mode = 'flat';
var map = null, dests = {}, destCount = 0;
var raf = 0, last = 0, detailDirty = true, detailAt = 0, listDirty = true, tlDirty = true, clockDirty = true, hashAt = 0, lastActive = null;
var drag = null;
var lastWork = 0;
var colors = {};
var ui = {}; // DOM nodes
var listeners = []; // bound to the page DOM (rebuilt on language change)
var globals = []; // document / media listeners, removed on destroy
var ro = null;
function on(target, type, fn, opts) { target.addEventListener(type, fn, opts); listeners.push([target, type, fn, opts]); }
function onG(target, type, fn) { target.addEventListener(type, fn); globals.push([target, type, fn]); }
// ---- period / filters from the shell and the URL
function presetSecs(r) { var m = /^(\d+)([hd])$/.exec(String(r || '')); return m ? +m[1] * (m[2] === 'h' ? 3600 : 86400) : 86400; }
function readRange(c) {
var f = ts(c.from), tt = ts(c.to);
if (!f || !tt || tt <= f) { tt = Math.floor(Date.now() / 1000); f = tt - presetSecs(c.range); }
return { from: f, to: tt };
}
function applyParams(c, params, initial) {
var r = readRange(c);
from = r.from; to = r.to;
tooBig = to - from > MAX_SPAN + 3600;
var cat = qget(params, 'cat');
F.cat = catVal(cat);
F.fam = str(qget(params, 'fam'), 40);
F.q = str(qget(params, 'ip'), 60);
campId = str(qget(params, 'campaign'), 80);
campIps = null;
F.host = c.host && c.host !== 'all' ? c.host : '';
var sp = num(qget(params, 'speed'));
if (SPEEDS.indexOf(sp) >= 0) speed = sp;
routeT = qget(params, 't');
clock = clamp(ts(routeT) || from, from, to);
if (initial) { compress = qget(params, 'compress') === '1'; only = qget(params, 'only') === '1'; }
}
applyParams(ctx, P, true);
// ---- colours (design tokens, re-read on theme change)
function readColors() {
var g = function (n, fb) { var v = U.css ? U.css(n) : ''; return v || fb; };
colors = { accent: g('--accent', '#38bdf8'), danger: g('--danger', '#f87171'), warn: g('--warn', '#f0b35b'), info: g('--info', '#60a5fa'), ink: g('--ink-muted', '#9db3bd'), faint: g('--ink-faint', '#7f96a1'), line: g('--line', '#223546'), ok: g('--ok', '#34d399') };
}
// ---- formatting
function clockStr(ts) { var d = new Date(ts * 1000); return pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); }
function dateStr(ts) { try { return new Date(ts * 1000).toLocaleDateString(lang || undefined, { day: '2-digit', month: 'short', year: 'numeric' }); } catch (e) { return ''; } }
function stampStr(ts) { return dateStr(ts) + ' ' + clockStr(ts); }
function durStr(s) { s = Math.max(0, Math.round(s)); if (s < 60) return s + 's'; if (s < 3600) return Math.floor(s / 60) + 'm ' + (s % 60) + 's'; return Math.floor(s / 3600) + 'h ' + Math.floor((s % 3600) / 60) + 'm'; }
function nf(n) { return U.fmt && U.fmt.num ? U.fmt.num(n) : String(n); }
function flag(cc) { return U.fmt && U.fmt.flag ? U.fmt.flag(cc) : ''; }
function rangeLabel() {
if (U.rangeLabel) { try { var s = U.rangeLabel({ inline: true }); if (s) return s; } catch (e) { /* ignore */ } }
return to - from > 2 * 86400 ? dateStr(from) + ' - ' + dateStr(to) : stampStr(from).replace(/:\d\d$/, '') + ' - ' + (dateStr(from) === dateStr(to) ? '' : dateStr(to) + ' ') + clockStr(to).slice(0, 5);
}
// ------------------------------------------------------------ event model
function sensitiveOk(e) { return e.status >= 200 && e.status < 300 && e.path && SENSITIVE.test(e.path) && e.cat !== 'ok'; }
function stageOf(e) {
if (e.cat === 'ban') return 'banned';
if (e.cat === 'ssh-ok' || e._sens) return 'access';
if (e.cat === 'exploit') return 'exploit';
if (e.cat === 'bruteforce' || e.cat === 'ssh-fail' || e.cat === 'ssh-probe') return 'probe';
return 'recon';
}
function normStage(s) { s = String(s || '').toLowerCase(); return s === 'ban' ? 'banned' : RANK[s] ? s : ''; }
function prepare(e) {
e.t = num(e.t);
delete e._st; // prepare() also re-annotates events already in the buffer
e.ip = str(e.ip, 64);
e.cat = CAT_OK[e.cat] ? e.cat : 'notfound';
e.status = num(e.status);
e.path = str(e.path, 600);
e.marker = str(e.marker, 200);
e._sens = sensitiveOk(e);
var st = ipSt[e.ip] || (ipSt[e.ip] = { rank: 0, score: 0 });
var sg = stageOf(e), r = RANK[sg], hit = '';
st.score = Math.min(100, st.score + (WEIGHT[e.cat] || 0) + (e._sens ? 30 : 0));
e._sc = st.score;
var chain = ipChain[e.ip];
if (chain) {
for (var i = 0; i < chain.length; i++) {
var it = chain[i];
if (it.t <= e.t + 0.999 && e.t - it.t <= 5 && (it.eid === undefined || it.eid === e.id)) { it.eid = e.id; if (!hit || RANK[it.stage] > RANK[hit]) hit = it.stage; }
}
if (hit) e._st = hit;
} else if (r > st.rank && (st.rank > 0 || r >= 3)) e._st = sg;
if (r > st.rank) st.rank = r;
e._inc = e.cat === 'exploit' || e.cat === 'ban' || e._sens || (e._st && RANK[e._st] >= 3) ? 1 : 0;
return e;
}
function accept(e) {
if (campIps && !campIps[e.ip]) return false;
if (only && !e._inc) return false;
var q = F.q;
if (q && !ipLike(q)) {
if (/^[A-Za-z]{2}$/.test(q)) { if (String(e.cc || (e.src && e.src.cc) || '').toUpperCase() !== q.toUpperCase()) return false; }
else if (/^AS?\d+$/i.test(q)) { if (String(e.asn || '').toUpperCase().replace(/^AS/, '') !== q.toUpperCase().replace(/^AS/, '')) return false; }
}
return true;
}
function sessionFor(e) {
if (e._ses !== undefined) return e._ses;
var arr = sessByIp[e.ip], found = null;
if (arr) for (var i = 0; i < arr.length; i++) { if (e.t >= arr[i].start - 1 && e.t <= arr[i].end + 1) { found = arr[i]; break; } }
e._ses = found;
return found;
}
// ------------------------------------------------------------ data loading
function evParams(extra) {
var o = { from: Math.floor(startFrom), to: Math.ceil(to), limit: PAGE, order: 'asc' };
if (F.host) o.host = F.host;
if (catParam(F.cat)) o.cat = catParam(F.cat);
if (F.fam) o.fam = F.fam;
if (F.q && !/^[A-Za-z]{2}$/.test(F.q) && !/^AS?\d+$/i.test(F.q)) o.ip = F.q;
if (extra) for (var k in extra) o[k] = extra[k];
return o;
}
function fetchMore() {
if (loading || tooBig || failed || drained) return;
loading = true; tlDirty = true;
var my = epoch;
var p = evParams(nextTok ? { cursor: nextTok } : null);
U.api('/api/v1/events', p).then(function (r) {
if (!alive || my !== epoch) return;
loading = false;
var list = (r && r.events) || [];
for (var i = 0; i < list.length; i++) {
var e = prepare(list[i]);
noteDest(e);
if (accept(e)) buf.push(e);
}
nextTok = r && r.next ? String(r.next) : null;
if (!nextTok) drained = true;
if (firstBatch) {
firstBatch = false;
if (landBefore !== null) {
idx = lowerBound(buf, landBefore);
if (idx > 0) clock = buf[idx - 1].t;
landBefore = null;
}
}
// an empty page that still has a cursor: keep walking
if (!list.length && nextTok) { fetchMore(); return; }
listDirty = true; detailDirty = true; tlDirty = true;
kick();
}).catch(function () {
if (!alive || my !== epoch) return;
loading = false; failed = true; playing = false;
listDirty = true; tlDirty = true; kick();
});
}
function resetBuffer(t0) {
epoch++;
buf = []; idx = 0; nextTok = null; loading = false; firstBatch = true; drained = false; failed = false;
ipSt = {}; resetChains();
startFrom = t0;
lastActive = null; sel = null; ended = false;
if (map && map.clear) { try { map.clear(); } catch (e) { /* ignore */ } }
listDirty = true; detailDirty = true; tlDirty = true; clockDirty = true;
}
function resetChains() { Object.keys(ipChain).forEach(function (k) { ipChain[k].forEach(function (it) { delete it.eid; }); }); }
function seek(t0, landOn) {
t0 = clamp(t0, from, to);
clock = t0;
// inside the buffered window: just move the pointer
if (buf.length && t0 >= buf[0].t && (t0 <= buf[buf.length - 1].t || drained) && landBefore === null) {
idx = upperBound(buf, t0);
ended = false; sel = null; detailDirty = true; listDirty = true; tlDirty = true; clockDirty = true; follow = true;
if (map && map.clear) { try { map.clear(); } catch (e) { /* ignore */ } }
kick(); return;
}
if (landOn === 'before') { resetBuffer(Math.max(from, t0 - 600)); landBefore = t0; clock = t0; }
else resetBuffer(t0);
follow = true;
fetchMore();
kick();
}
function noteDest(e) {
if (!e.host || !e.dst || dests[e.host] || typeof e.dst.lat !== 'number') return;
dests[e.host] = { host: e.host, lat: e.dst.lat, lon: e.dst.lon, label: str(e.dst.label || e.host, 60) };
destCount++;
pushDests();
}
function pushDests() { if (map && map.setDests) { try { map.setDests(Object.keys(dests).map(function (k) { return dests[k]; })); } catch (e) { /* ignore */ } } }
function loadPeriod() {
var my = ++periodSeq;
periodLoading = true; tlDirty = true; drawStrip();
if (tooBig) { periodLoading = false; period = null; buildDerived(); return; }
var p = { from: Math.floor(from), to: Math.ceil(to) };
if (F.host) p.host = F.host;
if (catParam(F.cat)) p.cat = catParam(F.cat);
if (F.fam) p.fam = F.fam;
if (F.q && ipLike(F.q)) p.ip = F.q;
U.api('/api/v1/period', p).then(function (d) {
if (!alive || my !== periodSeq) return;
period = d || {}; periodLoading = false; noReg = period.enabled === false; buildDerived(); resetChainsAfterPeriod();
}).catch(function () {
if (!alive || my !== periodSeq) return;
period = null; periodLoading = false; buildDerived();
});
}
function resetChainsAfterPeriod() {
// transitions come from the period: rebuild the buffer so rows pick them up
if (tooBig) return;
if (campId && campById[campId] && !routeT && !campStarted) { campStarted = true; clock = clamp(campById[campId].first, from, to); }
// a campaign link jumps and filters by IP, "only incidents" and country/ASN filters depend on the
// chains: those need a fresh buffer. Otherwise annotate what is loaded in place (a page still in
// flight is prepared against the new chains when it arrives), without downloading it again.
if (campId || only || (F.q && !ipLike(F.q))) { var c = clock; resetBuffer(c); fetchMore(); return; }
if (!buf.length) return;
ipSt = {}; resetChains();
for (var i = 0; i < buf.length; i++) prepare(buf[i]);
listDirty = true; detailDirty = true; tlDirty = true; kick();
}
function loadSummary() {
// histogram (timeline) and server locations from the summary of the same window
var my = ++summarySeq; sumDone = false;
// same request as the shell's, so its short-lived cache serves both
var req;
if (typeof U.summary === 'function') req = U.summary(ctx);
else { var p = { from: Math.floor(from), to: Math.ceil(to) }; if (F.host) p.host = F.host; req = U.api('/api/v1/summary', p); }
req.then(function (d) {
if (!alive || my !== summarySeq || !d) return;
(d.hosts || []).forEach(function (x) { if (x && x.location && typeof x.location.lat === 'number') { var nm = str(x.name, 80); dests[nm] = { host: nm, lat: x.location.lat, lon: x.location.lon, label: str(x.location.label || nm, 60) }; } });
pushDests();
tlData = d.timeline || null; sumDone = true;
buildBins(); tlDirty = true; drawStrip(); lastStateKey = '#'; kick();
}).catch(function () { if (my === summarySeq) { sumDone = true; drawStrip(); } });
}
function stepList(es) { return es.chain || es.steps || []; }
function buildDerived() {
var d = period || {};
sessByIp = {}; ipChain = {}; campById = {}; marks = [];
(d.campaigns || []).forEach(function (c) { c.first = ts(c.first); c.last = ts(c.last); campById[c.id] = c; });
var sessions = d.sessions || [];
sessions.forEach(function (s) {
s.start = ts(s.start); s.end = ts(s.end) || s.start; s.ip = str(s.ip, 64);
if (s.n === undefined) s.n = s.events;
(sessByIp[s.ip] || (sessByIp[s.ip] = [])).push(s);
});
var chainSess = {}, sessById = {};
sessions.forEach(function (s) { sessById[s.id] = s; });
(d.escalations || []).forEach(function (es) {
chainSess[es.session] = es;
var s = sessById[es.session], ip = str(es.ip || (s && s.ip), 64);
if (!ip) return;
var arr = ipChain[ip] || (ipChain[ip] = []);
stepList(es).forEach(function (it) {
var st = normStage(it.stage); if (!st) return;
var tt = ts(it.t); arr.push({ t: tt, stage: st });
if (st === 'exploit' || st === 'access' || st === 'banned') marks.push({ t: tt, kind: st === 'banned' ? 'ban' : st, ip: ip });
});
});
Object.keys(ipChain).forEach(function (k) { ipChain[k].sort(function (a, b) { return a.t - b.t; }); });
sessions.forEach(function (s) {
marks.push({ t: s.start, kind: 'session', ip: s.ip });
var ba = ts(s.banned_at);
if (ba) marks.push({ t: ba, kind: 'ban', ip: s.ip });
if (!chainSess[s.id] && (s.stage === 'exploit' || s.stage === 'access' || s.success)) marks.push({ t: s.start, kind: s.success || s.stage === 'access' ? 'access' : 'exploit', ip: s.ip });
});
(d.spikes || []).forEach(function (sp) { marks.push({ t: ts(sp.at || sp.t), kind: 'spike', n: num(sp.value || sp.n) }); });
(d.first_seen_technique || []).forEach(function (ft) { marks.push({ t: ts(ft.t), kind: 'tech', ip: str(ft.ip, 64), tech: str(ft.id || ft.tech, 24) }); });
marks = marks.filter(function (m) { return m.t >= from - 1 && m.t <= to + 1; });
// drop duplicated bans/exploits (same ip within one minute)
var seen = {};
marks = marks.filter(function (m) { if (m.kind !== 'ban' && m.kind !== 'exploit' && m.kind !== 'access') return true; var k = m.kind + '|' + m.ip + '|' + Math.floor(m.t / 60); if (seen[k]) return false; seen[k] = 1; return true; });
marks.sort(function (a, b) { return a.t - b.t; });
campIps = null;
if (campId) {
campIps = {};
var cp = campById[campId];
if (cp) (cp.ips || []).forEach(function (x) { campIps[str(x, 64)] = 1; });
sessions.forEach(function (x) { if (x.campaign_id === campId) campIps[x.ip] = 1; });
}
buildBins();
detailDirty = true; tlDirty = true; clockDirty = true;
drawStrip(); fillFam(); kick();
}
// histogram of the period: the summary timeline (filtered like the events),
// else the sessions spread over their span
function buildBins() {
var span = Math.max(1, to - from), i, k;
var tl = tlData;
if (tl && tl.series && num(tl.step) > 0) {
binStep = num(tl.step); binStart = ts(tl.start);
// the strip counts what the filter lets through: threats (all but "ok"), everything, or one category
var n0 = 0, cats = Object.keys(tl.series).filter(function (c) { return F.cat === '' ? c !== 'ok' : F.cat === 'all' || c === F.cat; });
cats.forEach(function (c) { n0 = Math.max(n0, tl.series[c].length); });
bins = new Array(n0);
for (i = 0; i < n0; i++) { var v = 0; for (k = 0; k < cats.length; k++) v += num(tl.series[cats[k]][i]); bins[i] = v; }
} else {
var steps = [60, 300, 900, 3600, 10800, 21600];
binStep = steps[steps.length - 1];
for (i = 0; i < steps.length; i++) if (span / steps[i] <= 720) { binStep = steps[i]; break; }
binStart = Math.floor(from / binStep) * binStep;
var n = Math.ceil((to - binStart) / binStep) + 1;
bins = new Array(n);
for (i = 0; i < n; i++) bins[i] = 0;
((period && period.sessions) || []).forEach(function (s) {
var b0 = clamp(Math.floor((s.start - binStart) / binStep), 0, n - 1), b1 = clamp(Math.floor((s.end - binStart) / binStep), b0, n - 1);
var per = num(s.n) / (b1 - b0 + 1);
for (var q = b0; q <= b1; q++) bins[q] += per;
});
}
binMax = 1; var sum = 0;
bins.forEach(function (v) { if (v > binMax) binMax = v; sum += v; });
seriesTotal = tl && tl.series ? sum : 0;
var mean = sum / Math.max(1, bins.length);
spikeMin = Math.max(mean * 3, binMax * 0.6);
}
// ------------------------------------------------------------ playback
function incidentMarks() { return marks.filter(function (m) { return NAV_KINDS[m.kind]; }); }
function jumpIncident(dir) {
var ms = incidentMarks(), i;
if (!ms.length) return;
var c = clock;
if (dir > 0) { for (i = 0; i < ms.length; i++) if (ms[i].t > c + 0.5) { seek(ms[i].t - 0.5); writeHash(true); return; } }
else { for (i = ms.length - 1; i >= 0; i--) if (ms[i].t < c - 1.5) { seek(ms[i].t - 0.5); writeHash(true); return; } }
}
function step(dir) {
playing = false; syncPlay();
if (dir > 0) {
if (idx < buf.length) { fire(idx + 1); clock = buf[idx - 1].t; }
else if (!drained) fetchMore();
} else {
if (idx >= 2) { idx--; clock = buf[idx - 1].t; sel = null; detailDirty = true; listDirty = true; clockDirty = true; tlDirty = true; follow = true; }
else if (idx >= 1 && buf[0].t > from) seek(buf[0].t, 'before');
}
kick();
}
// fire events [idx, upTo) in order (spawns arcs, updates the detail)
function fire(upTo) {
var batch = [], i;
for (i = idx; i < upTo && i < buf.length; i++) batch.push(buf[i]);
idx = Math.min(upTo, buf.length);
if (!batch.length) return;
lastActive = batch[batch.length - 1];
if (map && map.spawn) {
var n = 0, hi = [], lo = [];
batch.forEach(function (e) { (e._inc ? hi : lo).push(e); });
var step2 = lo.length > SPAWN_CAP ? Math.ceil(lo.length / SPAWN_CAP) : 1;
for (i = 0; i < hi.length && n < SPAWN_CAP; i++, n++) { try { map.spawn(hi[i], { highlight: true }); } catch (e) { /* ignore */ } }
for (i = 0; i < lo.length && n < SPAWN_CAP; i += step2, n++) { try { map.spawn(lo[i], { highlight: false }); } catch (e) { /* ignore */ } }
}
sel = null; detailDirty = true; listDirty = true;
}
function advance(dtReplay) {
var target = clock + dtReplay;
if (idx >= buf.length) {
if (!drained) { if (!loading) fetchMore(); return; } // starved: hold until the next page arrives
}
var next = buf[idx];
var gap = only ? 20 : SILENCE;
if (compress || only) { if (next && next.t - clock > gap) target = Math.max(target, next.t - 1); else if (!next && drained) target = to; }
var upTo = upperBound(buf, target);
if (upTo - idx > FIRE_CAP) { upTo = idx + FIRE_CAP; target = buf[upTo - 1].t; }
if (upTo > idx) fire(upTo);
clock = Math.min(target, to);
clockDirty = true; tlDirty = true;
if (buf.length - idx < AHEAD && !drained && !loading) fetchMore();
if (loop && clock > loop.b) { seek(loop.a); return; }
if (clock >= to && idx >= buf.length && drained) { playing = false; ended = true; syncPlay(); if (repeat) restart(); }
trim();
}
function trim() {
if (buf.length <= BUF_MAX || idx < KEEP_BEHIND * 2) return;
var k = idx - KEEP_BEHIND;
buf.splice(0, k); idx -= k;
if (ui.list) { ui.list.scrollTop -= k * ROW; expectedTop = ui.list.scrollTop; }
listDirty = true;
}
function setPlaying(p) {
if (p && ended) { restart(); return; }
if (p && clock >= to) { restart(); return; }
playing = !!p; last = 0;
syncPlay(); kick(); writeHash(true);
}
function restart() {
ended = false;
var s = loop ? loop.a : from;
seek(s);
playing = true; last = 0; syncPlay(); kick();
}
function setSpeed(s) { speed = s; syncSpeed(); writeHash(true); }
// ------------------------------------------------------------ frame loop
function kick() { if (!raf && alive && !document.hidden) raf = requestAnimationFrame(frame); }
function frame(ts) {
raf = 0;
if (!alive) return;
var dt = last ? Math.min(0.1, (ts - last) / 1000) : 0;
last = ts;
if (playing && dt > 0) advance(dt * speed);
render(ts);
if (playing || listDirty || tlDirty || detailDirty || clockDirty) { if (playing) raf = requestAnimationFrame(frame); else if (listDirty || tlDirty || detailDirty || clockDirty) raf = requestAnimationFrame(frame); }
if (!playing) last = 0;
}
function render(ts) {
if (clockDirty) { paintClock(); clockDirty = false; }
if (listDirty) { paintList(); listDirty = false; }
if (tlDirty) { drawTL(); tlDirty = false; }
if (detailDirty && (!playing || ts - detailAt > 250)) { renderDetail(); detailDirty = false; detailAt = ts; }
if (ui.tip && drag === null) { /* tooltip is driven by pointer events */ }
if (playing && ts - hashAt > 1000) writeHash();
paintState();
}
function onVisibility() {
if (document.hidden) { if (raf) { cancelAnimationFrame(raf); raf = 0; } if (map && map.pause) { try { map.pause(true); } catch (e) { /* ignore */ } } }
else { last = 0; if (map && map.pause) { try { map.pause(!playing); } catch (e) { /* ignore */ } } listDirty = tlDirty = detailDirty = clockDirty = true; kick(); }
}
// ------------------------------------------------------------ URL
function writeHash() {
hashAt = performance.now();
var x = { t: Math.floor(clock), speed: speed };
if (F.q) x.ip = F.q;
if (F.cat) x.cat = F.cat; // default (threats) is the absence of cat
if (F.fam) x.fam = F.fam;
if (campId) x.campaign = campId;
if (compress) x.compress = '1';
if (only) x.only = '1';
var hs;
if (typeof U.href === 'function') hs = U.href('replay', [], x);
else { var p = new URLSearchParams(); Object.keys(x).forEach(function (k) { p.set(k, x[k]); }); hs = '#/replay?' + p.toString(); }
try { if (location.hash !== hs) history.replaceState(null, '', hs); } catch (e) { /* ignore */ }
return hs;
}
// ------------------------------------------------------------ UI build
function btn(cls, name, label, fn) {
var b = h('button', 'btn rp-btn ' + cls, icon(name));
b.type = 'button'; b.setAttribute('aria-label', label); b.title = label;
b.addEventListener('click', fn);
return b;
}
function toggle(label, fn) {
var b = h('button', 'btn rp-tog', label);
b.type = 'button'; b.setAttribute('aria-pressed', 'false');
b.addEventListener('click', fn);
return b;
}
function build() {
clear(rootEl);
detachListeners();
lang = ctx.lang || lang;
readColors();
var root = h('div', 'rp');
ui.root = root;
// summary strip
ui.strip = h('section', 'rp-strip');
ui.strip.setAttribute('aria-live', 'polite');
// filters
var fb = h('div', 'rp-filters');
ui.cat = h('select', 'rp-sel'); ui.cat.setAttribute('aria-label', t('rp.cat'));
ui.cat.appendChild(opt('', t('rp.cat.all')));
ui.cat.appendChild(opt('all', t('rp.cat.every')));
['ok'].concat(CATS).forEach(function (c) { ui.cat.appendChild(opt(c, t('cat.' + c))); });
ui.cat.value = F.cat;
ui.cat.addEventListener('change', function () { F.cat = ui.cat.value; refilter(); });
ui.fam = h('select', 'rp-sel'); ui.fam.setAttribute('aria-label', t('rp.fam'));
fillFam();
ui.fam.addEventListener('change', function () { F.fam = ui.fam.value; refilter(); });
ui.q = h('input', 'rp-q'); ui.q.type = 'text'; ui.q.setAttribute('aria-label', t('rp.q')); ui.q.placeholder = t('rp.q.ph'); ui.q.value = F.q; ui.q.maxLength = 60; ui.q.autocomplete = 'off'; ui.q.spellcheck = false;
ui.q.addEventListener('change', function () { F.q = ui.q.value.trim(); refilter(); });
ui.clearF = h('button', 'btn rp-tog', t('rp.clear')); ui.clearF.type = 'button';
ui.clearF.addEventListener('click', function () { F.cat = ''; F.fam = ''; F.q = ''; campId = ''; ui.cat.value = ''; ui.fam.value = ''; ui.q.value = ''; refilter(); });
ui.chips = h('span', 'rp-chips');
fb.appendChild(ui.cat); fb.appendChild(ui.fam); fb.appendChild(ui.q); fb.appendChild(ui.clearF); fb.appendChild(ui.chips);
// grid: map, list, side
var grid = h('div', 'rp-grid');
var haveMap = typeof U.createAttackMap === 'function';
ui.mapBox = h('div', 'rp-mapbox' + (haveMap ? '' : ' rp-nomap'));
ui.map = h('div', 'rp-map'); ui.map.setAttribute('role', 'img'); ui.map.setAttribute('aria-label', t('rp.map.alt'));
ui.mapBox.appendChild(ui.map);
if (haveMap) {
var seg = h('div', 'rp-mode seg'); seg.setAttribute('role', 'group');
['flat', 'globe'].forEach(function (m) {
var b = h('button', '', t('rp.mode.' + m)); b.type = 'button'; b.setAttribute('aria-pressed', mode === m ? 'true' : 'false');
b.addEventListener('click', function () { mode = m; Array.prototype.forEach.call(seg.children, function (x, i) { x.setAttribute('aria-pressed', ['flat', 'globe'][i] === m ? 'true' : 'false'); }); if (map && map.setMode) map.setMode(m); });
seg.appendChild(b);
});
ui.mapBox.appendChild(seg);
}
ui.overlay = h('div', 'rp-overlay'); ui.overlay.hidden = true;
ui.mapBox.appendChild(ui.overlay);
// list
ui.listBox = h('section', 'rp-listbox');
ui.list = h('div', 'rp-list'); ui.list.setAttribute('role', 'list'); ui.list.setAttribute('aria-label', t('rp.list.label')); ui.list.tabIndex = 0;
ui.vp = h('div', 'rp-vp'); ui.list.appendChild(ui.vp);
ui.rows = [];
ui.followBtn = h('button', 'btn rp-follow', t('rp.follow')); ui.followBtn.type = 'button'; ui.followBtn.hidden = true;
ui.followBtn.addEventListener('click', function () { follow = true; listDirty = true; kick(); });
ui.listBox.appendChild(ui.list); ui.listBox.appendChild(ui.followBtn);
on(ui.list, 'scroll', function () {
listDirty = true;
if (expectedTop >= 0 && Math.abs(ui.list.scrollTop - expectedTop) < 3) { kick(); return; }
if (follow) { follow = false; ui.followBtn.hidden = false; }
kick();
}, { passive: true });
on(ui.list, 'click', function (ev) {
var r = ev.target; while (r && r !== ui.list && !(r.rpIdx !== undefined)) r = r.parentNode;
if (!r || r === ui.list || r.rpIdx === undefined || !buf[r.rpIdx]) return;
pick(r.rpIdx);
});
// side / detail
ui.side = h('aside', 'rp-side');
ui.side.setAttribute('aria-label', t('rp.detail'));
var sh = h('div', 'rp-side-h', h('h2', '', t('rp.detail')));
var cb = h('button', 'btn icon rp-sheet-x', icon('close')); cb.type = 'button'; cb.setAttribute('aria-label', t('rp.close'));
cb.addEventListener('click', function () { closeSheet(); });
sh.appendChild(cb);
ui.detail = h('div', 'rp-detail');
ui.side.appendChild(sh); ui.side.appendChild(ui.detail);
ui.scrim = h('div', 'rp-scrim'); ui.scrim.hidden = true;
ui.scrim.addEventListener('click', function () { closeSheet(); });
grid.appendChild(ui.mapBox);
// dock: transport + timeline
ui.dock = h('div', 'rp-dock');
var tr = h('div', 'rp-transport');
ui.prevB = btn('', 'prev', t('rp.prev') + ' (j)', function () { jumpIncident(-1); });
ui.stepbB = btn('', 'stepb', t('rp.stepb') + ' (,)', function () { step(-1); });
ui.playB = btn('rp-play', 'play', t('rp.play') + ' (' + (lang === 'pt-BR' ? 'espaço' : 'space') + ')', function () { setPlaying(!playing); });
ui.stepfB = btn('', 'stepf', t('rp.stepf') + ' (.)', function () { step(1); });
ui.nextB = btn('', 'next', t('rp.next') + ' (k)', function () { jumpIncident(1); });
ui.clock = h('div', 'rp-clock');
ui.clockT = h('span', 'rp-clock-t num'); ui.clockD = h('span', 'rp-clock-d');
ui.clock.appendChild(ui.clockT); ui.clock.appendChild(ui.clockD);
ui.clock.setAttribute('aria-label', t('rp.clock'));
ui.speedSeg = h('div', 'rp-speed seg'); ui.speedSeg.setAttribute('role', 'group'); ui.speedSeg.setAttribute('aria-label', t('rp.speed'));
SPEEDS.forEach(function (s) {
var b = h('button', 'num', s + '×'); b.type = 'button'; b.dataset.s = String(s);
b.addEventListener('click', function () { setSpeed(s); });
ui.speedSeg.appendChild(b);
});
ui.speedSel = h('select', 'rp-sel rp-speedsel'); ui.speedSel.setAttribute('aria-label', t('rp.speed'));
SPEEDS.forEach(function (s) { ui.speedSel.appendChild(opt(String(s), s + '\u00d7')); });
ui.speedSel.addEventListener('change', function () { setSpeed(+ui.speedSel.value); });
ui.compB = toggle(t('rp.compress'), function () { compress = !compress; syncToggles(); writeHash(true); });
ui.onlyB = toggle(t('rp.only'), function () { only = !only; syncToggles(); refilter(); });
ui.selB = toggle(t('rp.select'), function () { selecting = !selecting; if (!selecting && loop) { loop = null; tlDirty = true; } syncToggles(); kick(); });
ui.repB = toggle(t('rp.repeat'), function () {
repeat = !repeat; syncToggles();
try { localStorage.setItem('urutau.replay.repeat', repeat ? '1' : '0'); } catch (x) { /* storage blocked */ }
if (repeat && ended) restart();
});
ui.shareB = btn('rp-share', 'share', t('rp.share'), function () { share(); });
ui.detB = h('button', 'btn rp-det', t('rp.detail')); ui.detB.type = 'button';
ui.detB.addEventListener('click', function () { openSheet(); });
[ui.prevB, ui.stepbB, ui.playB, ui.stepfB, ui.nextB, ui.clock, ui.speedSeg, ui.speedSel, ui.compB, ui.onlyB, ui.selB, ui.repB, ui.shareB, ui.detB].forEach(function (n) { tr.appendChild(n); });
ui.loopNote = h('span', 'rp-loopnote'); tr.appendChild(ui.loopNote);
var tw = h('div', 'rp-tl');
ui.tl = h('div', 'rp-tlwrap'); ui.tl.tabIndex = 0; ui.tl.setAttribute('role', 'slider'); ui.tl.setAttribute('aria-label', t('rp.tl.label'));
ui.skel = h('div', 'rp-skel'); ui.skel.hidden = true;
ui.cv = h('canvas', 'rp-cv'); ui.cv.setAttribute('aria-hidden', 'true');
ui.tip = h('div', 'rp-tip'); ui.tip.hidden = true;
ui.tl.appendChild(ui.skel); ui.tl.appendChild(ui.cv); ui.tl.appendChild(ui.tip);
var lg = h('ul', 'rp-legend'); lg.setAttribute('aria-label', t('rp.tl.legend'));
MARK_KINDS.forEach(function (k) { var li = h('li', ''); li.appendChild(h('i', 'rp-k rp-k-' + k)); li.appendChild(h('span', '', t('rp.mk.' + k))); lg.appendChild(li); });
tw.appendChild(ui.tl); tw.appendChild(lg);
ui.dock.appendChild(tr); ui.dock.appendChild(tw);
root.appendChild(ui.strip); root.appendChild(fb); root.appendChild(grid);
ui.right = h('div', 'rp-right'); ui.right.appendChild(ui.side); ui.right.appendChild(ui.listBox);
grid.appendChild(ui.right);
root.appendChild(ui.dock); root.appendChild(ui.scrim);
rootEl.appendChild(root);
bindTimeline();
if (typeof ResizeObserver === 'function') {
if (ro) ro.disconnect();
ro = new ResizeObserver(function () { sizeCanvas(); tlDirty = true; listDirty = true; if (map && map.resize) { try { map.resize(); } catch (e) { /* ignore */ } } kick(); });
ro.observe(ui.tl); ro.observe(ui.list); ro.observe(ui.map);
}
mountMap();
fit();
sizeCanvas();
syncPlay(); syncSpeed(); syncToggles(); drawStrip(); paintChips();
listDirty = tlDirty = detailDirty = clockDirty = true;
}
function opt(v, text) { var o = document.createElement('option'); o.value = v; o.textContent = text; return o; }
function fillFam() {
clear(ui.fam);
ui.fam.appendChild(opt('', t('rp.fam.all')));
var seen = {};
((period && period.top_fams) || []).forEach(function (f) { var n = str(f.key || f.name || f.fam || f, 40); if (n && !seen[n]) { seen[n] = 1; ui.fam.appendChild(opt(n, n)); } });
if (F.fam && !seen[F.fam]) ui.fam.appendChild(opt(F.fam, F.fam));
ui.fam.value = F.fam;
}
function mountMap() {
if (map) { try { map.destroy(); } catch (e) { /* ignore */ } map = null; }
if (typeof U.createAttackMap !== 'function') return;
try {
map = U.createAttackMap(ui.map, { mode: mode, interactive: true });
if (map.onPick) map.onPick(function (ev) { if (ev && ev.ip) { var i = findEvent(ev); if (i >= 0) { sel = buf[i]; detailDirty = true; if (mqSmall && mqSmall.matches) openSheet(); kick(); } } });
if (map.setTheme) map.setTheme();
pushDests();
if (map.pause) map.pause(!playing);
} catch (e) { map = null; }
}
function findEvent(ev) { for (var i = Math.max(0, idx - 200); i < Math.min(buf.length, idx + 5); i++) if (buf[i].id === ev.id && ev.id !== undefined) return i; for (var j = Math.min(idx, buf.length) - 1; j >= 0 && j > idx - 400; j--) if (buf[j].ip === ev.ip && buf[j].t === ev.t) return j; return -1; }
function detachListeners() { listeners.forEach(function (l) { l[0].removeEventListener(l[1], l[2], l[3]); }); listeners = []; }
function fit() {
if (!ui.root || !alive) return;
var big = window.matchMedia && matchMedia('(min-width: 1200px)').matches;
if (!big) { ui.root.style.removeProperty('--rp-h'); return; }
var top = ui.root.getBoundingClientRect().top + (window.pageYOffset || 0);
ui.root.style.setProperty('--rp-h', Math.max(640, window.innerHeight - top - 56) + 'px');
}
// ---- sync of control state
function syncPlay() {
if (!ui.playB) return;
var lbl = playing ? t('rp.pause') : t('rp.play');
clear(ui.playB); ui.playB.appendChild(icon(playing ? 'pause' : 'play'));
ui.playB.setAttribute('aria-label', lbl); ui.playB.title = lbl + ' (' + (lang === 'pt-BR' ? 'espaço' : 'space') + ')';
ui.root.classList.toggle('is-playing', playing);
if (map && map.pause) { try { map.pause(!playing); } catch (e) { /* ignore */ } }
}
function syncSpeed() { if (!ui.speedSeg) return; ui.speedSel.value = String(speed); Array.prototype.forEach.call(ui.speedSeg.children, function (b) { b.setAttribute('aria-pressed', b.dataset.s === String(speed) ? 'true' : 'false'); }); }
function syncToggles() {
ui.compB.setAttribute('aria-pressed', compress ? 'true' : 'false');
ui.onlyB.setAttribute('aria-pressed', only ? 'true' : 'false');
ui.repB.setAttribute('aria-pressed', repeat ? 'true' : 'false');
ui.selB.setAttribute('aria-pressed', selecting ? 'true' : 'false');
ui.selB.textContent = loop ? t('rp.loopclear') : t('rp.select');
ui.loopNote.textContent = loop ? t('rp.loop', { a: clockStr(loop.a), b: clockStr(loop.b) }) : '';
}
function paintChips() {
clear(ui.chips);
if (F.host) ui.chips.appendChild(h('span', 'rp-chip', F.host));
ui.clearF.hidden = !(F.cat || F.fam || F.q || campId);
if (campId) ui.chips.appendChild(h('span', 'rp-chip', t('rp.d.camp') + ' ' + campId.slice(0, 24)));
}
function paintClock() {
ui.clockT.textContent = clockStr(clock);
ui.clockD.textContent = dateStr(clock);
var pct = Math.round((clock - from) / Math.max(1, to - from) * 100);
ui.tl.setAttribute('aria-valuemin', '0'); ui.tl.setAttribute('aria-valuemax', '100'); ui.tl.setAttribute('aria-valuenow', String(pct));
ui.tl.setAttribute('aria-valuetext', stampStr(clock));
}
function share() {
var hs = writeHash(true), url = location.href.split('#')[0] + hs;
var done = function () { if (U.toast) U.toast(t('rp.copied')); };
try { if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(url).then(done, function () { /* ignore */ }); return; } } catch (e) { /* ignore */ }
done();
}
function refilter() {
var c = clock;
paintChips(); syncToggles();
loadPeriod();
resetBuffer(c);
fetchMore(); writeHash(true); kick();
}
// ------------------------------------------------------------ summary strip
function drawStrip() {
if (!ui.strip) return;
clear(ui.strip);
if (tooBig) return;
if (periodLoading && !period) { ui.strip.appendChild(h('p', 'rp-lead rp-skeltxt', t('rp.loading'))); return; }
var d = period;
if (!d) { ui.strip.appendChild(h('p', 'rp-lead', rangeLabel())); return; }
var sessions = d.sessions || [];
var total = 0; sessions.forEach(function (x) { total += num(x.n); });
if (d.events !== undefined) total = num(d.events); else if (d.total_events !== undefined) total = num(d.total_events);
if (!total && seriesTotal > 0) { ui.strip.appendChild(h('p', 'rp-lead', t('rp.lead.noreg', { n: nf(seriesTotal), range: rangeLabel() }))); return; }
if (!total && !seriesTotal && sumDone) { ui.strip.appendChild(h('p', 'rp-lead', t('rp.lead.none', { range: rangeLabel() }))); return; }
var sessN = d.sessions_n !== undefined ? num(d.sessions_n) : sessions.length;
ui.strip.appendChild(h('p', 'rp-lead', pl('rp.lead', total, { n: nf(total), range: rangeLabel() })));
var cpS = campId && campById[campId];
if (cpS) { var sg = sigText(cpS.signature); ui.strip.appendChild(h('p', 'rp-lead rp-camplead untrusted', t('rp.d.camp') + ': ' + (sg || campId.slice(0, 24)) + ' \u00b7 ' + t('rp.d.camp.ips', { n: nf(num(cpS.ips_n)) }))); }
var st = h('ul', 'rp-stats');
function stat(label, val, tone) { var li = h('li', tone ? 'rp-st rp-t-' + tone : 'rp-st'); li.appendChild(h('b', 'num', val)); li.appendChild(h('span', '', label)); st.appendChild(li); }
stat(t('rp.stat.sessions'), nf(sessN));
stat(t('rp.stat.campaigns'), nf((d.campaigns || []).length), (d.campaigns || []).length ? 'warn' : '');
var nv = d.new_vs_returning || {};
stat(t('rp.stat.newret'), nf(num(nv.new)) + ' / ' + nf(num(nv.returning)));
stat(t('rp.stat.techs'), nf((d.first_seen_technique || []).length));
stat(t('rp.stat.esc'), nf((d.escalations || []).length), (d.escalations || []).length ? 'danger' : '');
ui.strip.appendChild(st);
fit();
}
// ------------------------------------------------------------ list (virtualised)
function ensureRows() {
var need = Math.ceil(ui.list.clientHeight / ROW) + 10;
while (ui.rows.length < need) {
var r = h('div', 'rp-row');
r.setAttribute('role', 'listitem');
r.time = h('span', 'rp-c-time num'); r.stg = h('span', 'rp-c-stg'); r.host = h('span', 'rp-c-host');
r.ip = h('span', 'rp-c-ip'); r.ipf = h('span', 'rp-fl'); r.ipt = h('span', 'num'); r.ip.appendChild(r.ipf); r.ip.appendChild(r.ipt);
r.cat = h('span', 'rp-c-cat'); r.dot = h('i', 'rp-dot'); r.catt = h('span', 'rp-catt'); r.cat.appendChild(r.dot); r.cat.appendChild(r.catt);
r.req = h('span', 'rp-c-req'); r.meth = h('span', 'rp-meth'); r.p0 = h('span', ''); r.pm = h('mark', 'rp-mk'); r.p1 = h('span', '');
r.req.appendChild(r.meth); r.req.appendChild(r.p0); r.req.appendChild(r.pm); r.req.appendChild(r.p1);
r.st = h('span', 'rp-c-st num');
[r.time, r.stg, r.host, r.ip, r.cat, r.req, r.st].forEach(function (c) { r.appendChild(c); });
ui.vp.appendChild(r); ui.rows.push(r);
}
}
function paintList() {
ensureRows();
var H = ui.list.clientHeight || 240;
ui.vp.style.height = (buf.length * ROW) + 'px';
var active = idx - 1;
if (follow && buf.length && active >= 0) {
var want = clamp(active * ROW - H * 0.4, 0, Math.max(0, buf.length * ROW - H));
if (Math.abs(ui.list.scrollTop - want) > 1) { ui.list.scrollTop = want; expectedTop = ui.list.scrollTop; }
}
ui.followBtn.hidden = follow || !buf.length;
var first = Math.max(0, Math.floor(ui.list.scrollTop / ROW) - 3);
for (var i = 0; i < ui.rows.length; i++) {
var r = ui.rows[i], k = first + i, e = buf[k];
if (!e) { r.hidden = true; r.rpIdx = undefined; continue; }
r.hidden = false; r.rpIdx = k;
r.style.transform = 'translateY(' + (k * ROW) + 'px)';
var cls = 'rp-row' + (k === active ? ' is-active' : k < idx ? ' is-past' : ' is-future') + (e._inc ? ' is-inc' : '') + (e._st ? ' st-' + e._st : '');
if (r.className !== cls) r.className = cls;
r.time.textContent = clockStr(e.t);
var sg = e._st;
r.stg.className = 'rp-c-stg' + (sg ? ' rp-s-' + sg : '');
r.stg.textContent = sg ? t('rp.stage.' + sg) + ' · ' + e._sc : '';
r.host.textContent = str(e.host, 40);
r.ipf.textContent = flag(e.cc || (e.src && e.src.cc));
r.ipt.textContent = e.ip;
r.dot.className = 'rp-dot rp-c-' + catClass(e.cat);
r.catt.textContent = t('cat.' + e.cat);
r.meth.textContent = e.method ? str(e.method, 10) + ' ' : (e.user ? str(e.user, 32) : e.jail ? str(e.jail, 32) : '');
setPath(e, r.p0, r.pm, r.p1);
r.st.textContent = e.status ? String(e.status) : '';
r.st.className = 'rp-c-st num' + (e._sens ? ' rp-bad' : '');
}
}
function setPath(e, a, m, b) {
var p = e.path || '', mk = e.marker, i = mk ? p.indexOf(mk) : -1;
if (i < 0) { a.textContent = p; m.textContent = ''; b.textContent = ''; m.hidden = true; return; }
a.textContent = p.slice(0, i); m.textContent = mk; m.hidden = false; b.textContent = p.slice(i + mk.length);
}
function pick(k) {
var e = buf[k]; if (!e) return;
idx = k + 1; clock = e.t; sel = e; ended = false; lastActive = e;
detailDirty = true; listDirty = true; tlDirty = true; clockDirty = true;
if (map && map.spawn) { try { map.spawn(e, { highlight: true }); } catch (x) { /* ignore */ } }
if (mqSmall && mqSmall.matches) openSheet();
writeHash(true); kick();
}
// ------------------------------------------------------------ detail
function activeEvent() { return sel || lastActive; }
function kv(label, node) { var r = h('div', 'rp-kv'); r.appendChild(h('dt', '', label)); var dd = h('dd', ''); dd.appendChild(node); r.appendChild(dd); return r; }
function txt(s, cls) { return h('span', cls || '', s); }
function renderDetail() {
var box = ui.detail; clear(box);
var e = activeEvent();
if (!e) { box.appendChild(h('p', 'rp-muted', t('rp.d.none'))); return; }
var dl = h('dl', 'rp-dl');
dl.appendChild(kv(t('rp.d.time'), txt(stampStr(e.t), 'num')));
if (e.host) dl.appendChild(kv(t('rp.d.host'), txt(str(e.host, 80))));
var ipn = h('span', 'rp-ipline');
var fl = flag(e.cc || (e.src && e.src.cc)); if (fl) ipn.appendChild(h('span', 'rp-fl', fl));
var ipb = h('button', 'rp-link num', e.ip); ipb.type = 'button'; ipb.title = t('rp.d.openip');
ipb.addEventListener('click', function () { if (U.openIP) U.openIP(e.ip); });
ipn.appendChild(ipb);
dl.appendChild(kv(t('rp.d.ip'), ipn));
if (e.asn || e.as_name) dl.appendChild(kv(t('rp.d.asn'), txt(str(e.asn, 20) + (e.as_name ? ' ' + str(e.as_name, 80) : ''))));
var where = [e.src && e.src.city, (e.cc || (e.src && e.src.cc)) && (U.fmt && U.fmt.country ? U.fmt.country(e.cc || e.src.cc) : e.cc)].filter(Boolean).map(function (s) { return str(s, 80); }).join(', ');
if (where) dl.appendChild(kv(t('rp.d.where'), txt(where, 'untrusted')));
var cat = h('span', 'rp-catline'); cat.appendChild(h('i', 'rp-dot rp-c-' + catClass(e.cat))); cat.appendChild(txt(t('cat.' + e.cat)));
dl.appendChild(kv(t('rp.d.cat'), cat));
if (e.fam) dl.appendChild(kv(t('rp.d.fam'), txt(str(e.fam, 60))));
if (Array.isArray(e.tech) && e.tech.length) {
var tc = h('span', 'rp-techs');
e.tech.slice(0, 8).forEach(function (x) { tc.appendChild(h('span', 'chip-mitre rp-mitre', str(x, 24))); });
dl.appendChild(kv(t('rp.d.tech'), tc));
}
if (e.path || e.method) {
var rq = h('span', 'rp-req untrusted');
if (e.method) rq.appendChild(h('b', '', str(e.method, 10) + ' '));
var a = h('span', ''), m = h('mark', 'rp-mk'), b = h('span', '');
setPath(e, a, m, b); rq.appendChild(a); rq.appendChild(m); rq.appendChild(b);
dl.appendChild(kv(t('rp.d.req'), rq));
}
if (e.status) { dl.appendChild(kv(t('rp.d.status'), txt(String(e.status) + (e._sens ? ' · ' + t('rp.d.sens') : ''), e._sens ? 'rp-bad num' : 'num'))); }
if (e.ua) dl.appendChild(kv(t('rp.d.ua'), txt(str(e.ua, 300), 'untrusted')));
if (e.user) dl.appendChild(kv(t('rp.d.user'), txt(str(e.user, 64), 'untrusted')));
if (e.jail) dl.appendChild(kv(t('rp.d.jail'), txt(str(e.jail, 64))));
if (e.bytes) dl.appendChild(kv(t('rp.d.bytes'), txt(U.fmt && U.fmt.bytes ? U.fmt.bytes(num(e.bytes)) : String(num(e.bytes)), 'num')));
var sc = h('span', 'rp-scoreline');
var bar = h('span', 'rp-score'); var fill = h('i', ''); fill.style.width = clamp(e._sc || 0, 0, 100) + '%'; bar.appendChild(fill);
sc.appendChild(txt(String(e._sc || 0), 'num')); sc.appendChild(bar);
dl.appendChild(kv(t('rp.d.score'), sc));
if (e._st) dl.appendChild(kv(t('rp.d.stage'), txt(t('rp.stage.' + e._st), 'rp-s-' + e._st + ' rp-stgbadge')));
box.appendChild(dl);
var s = sessionFor(e);
if (s) {
var card = h('div', 'session-card rp-session');
card.appendChild(h('h3', '', t('rp.d.sess')));
var line = h('p', 'rp-sess-l');
line.appendChild(txt(clockStr(s.start) + ' - ' + clockStr(s.end), 'num'));
line.appendChild(txt(' · ' + t('rp.d.sess.dur', { d: durStr(num(s.dur_s) || s.end - s.start) }) + ' · ' + t('rp.d.sess.n', { n: nf(num(s.n)) })));
card.appendChild(line);
var meta = [];
if (num(s.peak_rpm)) meta.push(t('rp.d.sess.peak', { n: nf(num(s.peak_rpm)) }));
if (s.success) meta.push(t('rp.d.sess.ok'));
if (meta.length) card.appendChild(h('p', 'rp-sess-l' + (s.success ? ' rp-bad' : ''), meta.join(' · ')));
var st = h('div', 'rp-stagebar');
var reach = RANK[normStage(s.stage)] || 0;
STAGES.forEach(function (g) { var sp = h('span', 'rp-sg' + (RANK[g] <= reach ? ' on rp-s-' + g : '')); sp.textContent = t('rp.stage.' + g); st.appendChild(sp); });
card.appendChild(st);
box.appendChild(card);
var c = s.campaign_id ? campById[s.campaign_id] : null;
if (c) {
var cc = h('div', 'session-card rp-session rp-camp');
cc.appendChild(h('h3', '', t('rp.d.camp')));
var sig = sigText(c.signature); if (sig) cc.appendChild(h('p', 'rp-sess-l untrusted', sig));
cc.appendChild(h('p', 'rp-sess-l', t('rp.d.camp.ips', { n: nf(num(c.ips_n)) }) + ' · ' + clockStr(c.first) + ' - ' + clockStr(c.last) + ' · ' + t('rp.d.sess.n', { n: nf(num(c.sessions_n)) })));
var tt = h('p', 'rp-techs');
(c.techs || []).slice(0, 6).forEach(function (x) { tt.appendChild(h('span', 'chip-mitre rp-mitre', str(x, 24))); });
if (tt.firstChild) cc.appendChild(tt);
box.appendChild(cc);
}
}
}
function sigText(g) {
if (!g) return '';
if (typeof g === 'string') return str(g, 160);
var parts = [];
if (g.tool) parts.push(str(g.tool, 40));
if (Array.isArray(g.paths)) parts.push(g.paths.slice(0, 3).map(function (x) { return str(x, 60); }).join(' '));
return parts.join(' \u00b7 ');
}
// sheet (small screens)
function openSheet() { ui.side.classList.add('is-open'); ui.scrim.hidden = false; renderDetail(); }
function closeSheet() { ui.side.classList.remove('is-open'); ui.scrim.hidden = true; }
// ------------------------------------------------------------ states (overlay on the map)
var lastStateKey = '';
function paintState() {
var key = '', title = '', body = '', action = null;
if (tooBig) { key = 'big'; title = t('rp.big.title'); body = t('rp.big.body'); }
else if (noReg) { key = 'off'; title = t('rp.off.title'); body = t('rp.off.body'); }
else if (failed) { key = 'err'; title = t('rp.err'); }
else if (!loading && firstBatch === false && buf.length === 0 && drained && seriesTotal > 0 && !(F.cat || F.fam || F.q || only || campId)) { key = 'noreg'; title = t('rp.noreg.title'); body = t('rp.noreg.body'); }
else if (!loading && firstBatch === false && buf.length === 0 && drained) { key = 'empty'; title = t('rp.empty.title'); body = t('rp.empty.body'); if (F.cat || F.fam || F.q || only) action = 'clear'; }
else if (ended) { key = 'end'; title = t('rp.end.title'); body = t('rp.end.body'); action = 'restart'; }
if (key === lastStateKey) return;
lastStateKey = key;
clear(ui.overlay);
ui.overlay.hidden = !key;
ui.mapBox.classList.toggle('has-state', !!key);
if (!key) return;
var card = h('div', 'rp-state state-card');
card.appendChild(h('h3', '', title));
if (body) card.appendChild(h('p', '', body));
if (action) {
var b = h('button', 'btn primary', action === 'restart' ? t('rp.restart') : t('rp.clear')); b.type = 'button';
b.addEventListener('click', function () { if (action === 'restart') restart(); else { F.cat = ''; F.fam = ''; F.q = ''; campId = ''; only = false; ui.cat.value = ''; ui.fam.value = ''; ui.q.value = ''; refilter(); } });
card.appendChild(b);
}
ui.overlay.appendChild(card);
}
// ------------------------------------------------------------ timeline
var cw = 0, chh = 0, dpr = 1, cg = null;
var BAND = 32, AXIS = 14, LANE_Y = [9, 24], CL_PX = 9;
var clusters = [];
function sizeCanvas() {
var r = ui.tl.getBoundingClientRect();
cw = Math.max(50, Math.floor(r.width)); chh = Math.max(60, Math.floor(r.height));
dpr = Math.min(2, window.devicePixelRatio || 1);
ui.cv.width = Math.floor(cw * dpr); ui.cv.height = Math.floor(chh * dpr);
ui.cv.style.width = cw + 'px'; ui.cv.style.height = chh + 'px';
cg = ui.cv.getContext('2d');
}
function xOf(ts) { return (ts - from) / Math.max(1, to - from) * cw; }
function tOf(x) { return clamp(from + x / Math.max(1, cw) * (to - from), from, to); }
function niceTicks() {
var span = to - from, steps = [60, 300, 900, 1800, 3600, 10800, 21600, 43200, 86400, 172800, 604800], i, s = steps[steps.length - 1];
for (i = 0; i < steps.length; i++) if (span / steps[i] <= Math.max(2, cw / 90)) { s = steps[i]; break; }
var off = -new Date(from * 1000).getTimezoneOffset() * 60, out = [];
for (var tt = Math.ceil((from + off) / s) * s - off; tt <= to; tt += s) out.push({ t: tt, step: s });
return out;
}
function drawTL() {
if (!cg) return;
ui.skel.hidden = !periodLoading;
cg.setTransform(dpr, 0, 0, dpr, 0, 0);
cg.clearRect(0, 0, cw, chh);
var barTop = BAND + 4, barH = chh - barTop - AXIS;
var span = Math.max(1, to - from), cx = xOf(clock), i;
// baseline
cg.fillStyle = colors.line; cg.globalAlpha = 0.7; cg.fillRect(0, barTop + barH, cw, 1); cg.globalAlpha = 1;
// loop selection
var sa = loop ? loop : (drag && drag.sel ? { a: Math.min(drag.t0, drag.t1), b: Math.max(drag.t0, drag.t1) } : null);
if (sa) { cg.fillStyle = colors.accent; cg.globalAlpha = 0.18; cg.fillRect(xOf(sa.a), 0, Math.max(2, xOf(sa.b) - xOf(sa.a)), chh - AXIS); cg.globalAlpha = 0.9; cg.fillRect(xOf(sa.a), 0, 1.5, chh - AXIS); cg.fillRect(xOf(sa.b) - 1, 0, 1.5, chh - AXIS); cg.globalAlpha = 1; }
// histogram (sqrt scale keeps small activity visible next to a spike)
var bw = Math.max(1, binStep / span * cw);
for (i = 0; i < bins.length; i++) {
var v = bins[i]; if (v <= 0) continue;
var x0 = xOf(binStart + i * binStep), hh = Math.max(1.5, Math.sqrt(v / binMax) * barH);
var past = x0 + bw <= cx;
cg.fillStyle = v >= spikeMin ? colors.warn : colors.accent;
cg.globalAlpha = past ? 0.95 : 0.42;
cg.fillRect(x0, barTop + barH - hh, Math.max(1, bw - (bw > 3 ? 1 : 0)), hh);
}
cg.globalAlpha = 1;
// axis
cg.font = '10px ui-monospace, Menlo, Consolas, monospace'; cg.textBaseline = 'alphabetic'; cg.fillStyle = colors.faint;
var tk = niceTicks(), lastX = -100;
for (i = 0; i < tk.length; i++) {
var x = xOf(tk[i].t); if (x < 2 || x > cw - 24) continue;
var d = new Date(tk[i].t * 1000), lab = tk[i].step >= 86400 || (d.getHours() === 0 && d.getMinutes() === 0) ? pad(d.getDate()) + '/' + pad(d.getMonth() + 1) : pad(d.getHours()) + ':' + pad(d.getMinutes());
if (x - lastX < 46) continue;
lastX = x; cg.fillRect(x, barTop + barH, 1, 3); cg.fillText(lab, x + 2, chh - 3);
}
// marks: two lanes (incidents on top, context below), clustered per 9px column with a count
var cmap = {}, big = marks.length > 600;
clusters = [];
for (i = 0; i < marks.length; i++) {
var m = marks[i];
if (m.kind === 'session' && big) continue;
var lane = m.kind === 'exploit' || m.kind === 'access' || m.kind === 'ban' ? 0 : 1, key = lane * 1e6 + Math.round(xOf(m.t) / CL_PX), c0 = cmap[key];
if (!c0) { c0 = cmap[key] = { lane: lane, list: [], best: m }; clusters.push(c0); }
c0.list.push(m);
if (MARK_PRIO[m.kind] > MARK_PRIO[c0.best.kind]) c0.best = m;
}
var lastLab = [-99, -99];
cg.font = 'bold 9px ui-monospace, Menlo, Consolas, monospace'; cg.textBaseline = 'middle';
for (i = 0; i < clusters.length; i++) {
var cl = clusters[i], x = xOf(cl.best.t); cl.x = x;
drawMark(cl.best, x, LANE_Y[cl.lane], barTop, barH);
var lab = String(cl.list.length);
if (cl.list.length > 1 && cl.best.kind !== 'session' && x - lastLab[cl.lane] > 8 + lab.length * 6) { cg.fillStyle = colors.ink; cg.fillText(lab, x + 6, LANE_Y[cl.lane]); lastLab[cl.lane] = x; }
}
cg.textBaseline = 'alphabetic';
// cursor
cg.fillStyle = colors.accent; cg.fillRect(cx - 1, 0, 2, chh - AXIS + 2);
cg.beginPath(); cg.moveTo(cx - 5, 0); cg.lineTo(cx + 5, 0); cg.lineTo(cx, 7); cg.closePath(); cg.fill();
}
function drawMark(m, x, y, barTop, barH) {
var c = cg;
c.fillStyle = c.strokeStyle = colors.accent; c.lineWidth = 1.5;
if (m.kind === 'exploit') { c.fillStyle = colors.danger; c.beginPath(); c.moveTo(x - 5, y - 4); c.lineTo(x + 5, y - 4); c.lineTo(x, y + 5); c.closePath(); c.fill(); lineDown(x, colors.danger, barTop, barH); }
else if (m.kind === 'access') { c.fillStyle = colors.danger; c.beginPath(); c.moveTo(x, y - 6); c.lineTo(x + 5, y); c.lineTo(x, y + 6); c.lineTo(x - 5, y); c.closePath(); c.fill(); lineDown(x, colors.danger, barTop, barH); }
else if (m.kind === 'ban') { c.fillStyle = colors.warn; c.fillRect(x - 4, y - 4, 8, 8); lineDown(x, colors.warn, barTop, barH); }
else if (m.kind === 'spike') { c.fillStyle = colors.warn; c.fillRect(x - 1, y - 5, 2, 10); }
else if (m.kind === 'tech') { c.strokeStyle = colors.info; c.beginPath(); c.arc(x, y, 4, 0, 6.2832); c.stroke(); }
else { c.fillStyle = colors.faint; c.beginPath(); c.arc(x, y, 1.8, 0, 6.2832); c.fill(); }
}
function lineDown(x, color, barTop, barH) { cg.globalAlpha = 0.28; cg.fillStyle = color; cg.fillRect(x, BAND + 2, 1, barH + barTop - BAND - 2); cg.globalAlpha = 1; }
// the cluster under the pointer (lane chosen by y, then the closest in x)
function nearestCluster(x, y) {
var best = null, bd = CL_PX + 2, i, lane = y < BAND / 2 + 2 ? 0 : 1;
for (i = 0; i < clusters.length; i++) { var d = Math.abs(clusters[i].x - x) + (clusters[i].lane === lane ? 0 : 6); if (d < bd) { bd = d; best = clusters[i]; } }
return best;
}
function clusterLabel(cl) { return (cl.list.length > 1 ? t('rp.mk.n', { n: nf(cl.list.length) }) + ' \u00b7 ' : '') + markLabel(cl.best); }
function markLabel(m) {
var s = t('rp.mk.' + m.kind);
if (m.ip) s += ' · ' + m.ip;
if (m.tech) s += ' · ' + m.tech;
if (m.kind === 'spike' && m.n) s += ' · ' + nf(m.n);
return s;
}
function bindTimeline() {
var el = ui.tl;
function xy(ev) { var r = el.getBoundingClientRect(); return ev.clientX - r.left; }
on(el, 'pointerdown', function (ev) {
if (ev.button !== undefined && ev.button !== 0) return;
var x = xy(ev), ts = tOf(x), yy = ev.clientY - el.getBoundingClientRect().top, cl = yy < BAND + 4 ? nearestCluster(x, yy) : null;
try { el.setPointerCapture(ev.pointerId); } catch (e) { /* ignore */ }
if (cl && !ev.shiftKey && !selecting) {
// a cluster steps through its marks: the next one after the cursor, then back to the first
var nx = null; for (var q = 0; q < cl.list.length; q++) if (cl.list[q].t > clock + 1) { nx = cl.list[q]; break; }
nx = nx || cl.list[0]; seek(nx.t - 0.5); writeHash(true); return;
}
drag = { sel: !!(ev.shiftKey || selecting), t0: ts, t1: ts, moved: false, resume: playing };
if (!drag.sel) { playing = false; syncPlay(); clock = ts; clockDirty = tlDirty = true; kick(); }
});
on(el, 'pointermove', function (ev) {
var x = xy(ev), ts = tOf(x);
if (drag) {
drag.t1 = ts; drag.moved = true;
if (!drag.sel) clock = ts;
clockDirty = tlDirty = true; kick();
}
var cl2 = nearestCluster(x, ev.clientY - el.getBoundingClientRect().top);
ui.tip.hidden = false;
ui.tip.textContent = stampStr(ts) + (cl2 ? ' ' + clusterLabel(cl2) : '');
var w = ui.tip.offsetWidth || 120;
ui.tip.style.left = clamp(x - w / 2, 0, Math.max(0, cw - w)) + 'px';
});
on(el, 'pointerleave', function () { ui.tip.hidden = true; });
var end = function (ev) {
if (!drag) return;
var d = drag; drag = null;
try { el.releasePointerCapture(ev.pointerId); } catch (e) { /* ignore */ }
if (d.sel) {
if (Math.abs(d.t1 - d.t0) > (to - from) / 200) { loop = { a: Math.min(d.t0, d.t1), b: Math.max(d.t0, d.t1) }; selecting = false; seek(loop.a); }
syncToggles(); tlDirty = true; kick(); return;
}
seek(d.moved ? d.t1 : d.t0);
if (d.resume) { playing = true; last = 0; syncPlay(); }
writeHash(true); kick();
};
on(el, 'pointerup', end);
on(el, 'pointercancel', end);
on(el, 'keydown', function (ev) {
var d = (to - from) / 100;
if (ev.key === 'ArrowLeft') { seek(clock - d); ev.preventDefault(); }
else if (ev.key === 'ArrowRight') { seek(clock + d); ev.preventDefault(); }
else if (ev.key === 'Home') { seek(from); ev.preventDefault(); }
else if (ev.key === 'End') { seek(to); ev.preventDefault(); }
});
}
// ------------------------------------------------------------ keyboard
function onKey(ev) {
if (ev.ctrlKey || ev.metaKey || ev.altKey) return;
var tg = ev.target, tag = tg && tg.tagName;
if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA' || (tg && tg.isContentEditable)) return;
var k = ev.key;
if (k === ' ' || k === 'Spacebar') { if (tag === 'BUTTON' || tag === 'A' || (tg && tg.getAttribute && tg.getAttribute('role') === 'slider')) { if (tag === 'BUTTON' || tag === 'A') return; } ev.preventDefault(); setPlaying(!playing); }
else if (k === 'j') jumpIncident(-1);
else if (k === 'k') jumpIncident(1);
else if (k === ',') step(-1);
else if (k === '.') step(1);
else if (k === '[') setSpeed(SPEEDS[Math.max(0, SPEEDS.indexOf(speed) - 1)]);
else if (k === ']') setSpeed(SPEEDS[Math.min(SPEEDS.length - 1, SPEEDS.indexOf(speed) + 1)]);
else if (k === 'Escape') { if (ui.side.classList.contains('is-open')) closeSheet(); else if (loop) { loop = null; syncToggles(); tlDirty = true; kick(); } }
}
// ------------------------------------------------------------ lifecycle
build();
onG(window, 'resize', function () { fit(); });
onG(window, 'resize', function () { fit(); });
onG(document, 'keydown', onKey);
onG(document, 'visibilitychange', onVisibility);
if (mqReduced && mqReduced.addEventListener) onG(mqReduced, 'change', function (e) { reduced = e.matches; });
loadPeriod();
loadSummary();
resetBuffer(clock);
if (!tooBig && !campId) fetchMore();
if (!reduced && P.autoplay === '1') setPlaying(true);
kick();
return {
update: function (c) {
var prev = ctx; ctx = c;
var np = c.params || {};
var r = readRange(c), f2 = r.from, t2 = r.to;
var hostNew = c.host && c.host !== 'all' ? c.host : '';
var ntq = qget(np, 't');
var linkT = ntq && ntq !== routeT ? ts(ntq) : 0; // a new link to an exact moment (IP page, spike)
routeT = ntq;
// presets move with the clock: only a real change of window counts
var rangeChanged = c.range !== prev.range || ts(c.from) !== ts(prev.from) || ts(c.to) !== ts(prev.to);
if (c.lang !== prev.lang) { var s0 = playing; build(); drawStrip(); renderDetail(); playing = s0; syncPlay(); }
else if (c.theme !== prev.theme) { readColors(); if (map && map.setTheme) { try { map.setTheme(); } catch (e) { /* ignore */ } } tlDirty = true; kick(); }
var q2 = { cat: qget(np, 'cat'), fam: qget(np, 'fam'), q: qget(np, 'ip'), camp: str(qget(np, 'campaign'), 80) };
var filtersLink = (linkT || q2.camp !== campId) && (q2.cat !== F.cat || q2.fam !== F.fam || q2.q !== F.q || q2.camp !== campId);
if (rangeChanged || hostNew !== F.host || filtersLink) {
from = f2; to = t2; tooBig = to - from > MAX_SPAN + 3600; F.host = hostNew;
if (filtersLink || rangeChanged) { F.cat = catVal(q2.cat); F.fam = q2.fam; F.q = q2.q; campId = q2.camp; campStarted = false; campIps = null; ui.cat.value = F.cat; ui.q.value = F.q; }
clock = linkT && linkT >= from && linkT <= to ? linkT : (rangeChanged ? from : clamp(clock, from, to));
playing = false; ended = false; syncPlay();
tlData = null; paintChips(); loadPeriod(); loadSummary(); resetBuffer(clock); if (!tooBig) fetchMore(); kick();
} else if (linkT && Math.abs(linkT - clock) > 1) {
playing = false; syncPlay(); seek(linkT);
}
},
destroy: function () {
alive = false; epoch++; periodSeq++;
if (raf) { cancelAnimationFrame(raf); raf = 0; }
if (ro) { ro.disconnect(); ro = null; }
detachListeners();
globals.forEach(function (l) { l[0].removeEventListener(l[1], l[2]); }); globals = [];
if (map) { try { map.destroy(); } catch (e) { /* ignore */ } map = null; }
buf = []; marks = []; bins = []; sessByIp = {}; ipChain = {}; campById = {}; ipSt = {}; dests = {};
clear(rootEl);
}
};
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();