Files
urutau/internal/server/web/live.js
T
Lucas RayanandClaude Opus 5.5 8f1ac462d1
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 22s
CI / Tests (Linux, race detector) (push) Successful in 33s
CI / Dependency audit (push) Successful in 13s
Release / Plan (reuse the published image?) (push) Successful in 3s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Successful in 3s
fix(live): globe sea and land colors, world map antimeridian rings
The globe clipped country rings by pushing hidden vertices to the limb
and closing them with chords, so the fill flipped between sea and land
as it turned. Rings are now clipped at the horizon and closed along the
limb in their own orientation; the path parser returns to the subpath
start after z; long edges follow the map projection.

gen-world.mjs unwraps longitudes and clips rings that cross the 180th
meridian (Russia, Fiji) at the map edge instead of leaving them open,
which filled the Sea of Okhotsk as land.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 19:27:57 -03:00

1265 lines
59 KiB
JavaScript

/* Urutau - AO VIVO page: attacks arriving at the monitored servers, drawn as
animated arcs on a flat map or a 3D globe (canvas 2D, no libraries).
Every string coming from logs is written with textContent / fillText only,
and CSS classes come from a whitelist of known categories. */
(function () {
'use strict';
// category -> design token (same palette as the rest of the dashboard)
var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
var TOKEN = { notfound: '--cat-notfound', scanner: '--cat-scanner', bruteforce: '--cat-bruteforce', exploit: '--cat-exploit', 'ssh-fail': '--cat-ssh-fail', 'ssh-probe': '--cat-ssh-probe', ban: '--cat-ban' };
var FALLBACK = { notfound: '#64748b', scanner: '#f59e0b', bruteforce: '#f97316', exploit: '#ef4444', 'ssh-fail': '#38bdf8', 'ssh-probe': '#a5b4fc', ban: '#f0b35b' };
var HOSTILE = { exploit: 1, ban: 1 };
var CAT_OK = {};
CATS.forEach(function (c) { CAT_OK[c] = 1; });
var MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 6000, RING_TRIM = 1000;
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;
var HOST_COLORS = ['#38bdf8', '#f0b35b', '#10b981', '#a5b4fc', '#f97316'];
var inst = null;
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'live.title': 'Live',
'live.mode': 'View',
'live.mode.flat': 'Flat map',
'live.mode.globe': 'Globe',
'live.pause': 'Pause animation',
'live.resume': 'Resume animation',
'live.paused': 'paused',
'live.fullscreen': 'Presentation mode (full screen)',
'live.exitfs': 'Leave presentation mode',
'live.panels': 'Show or hide the panels',
'live.collapse': 'Collapse panel',
'live.expand': 'Expand panel',
'live.rate': 'events / min',
'live.rate.title': 'Rate',
'live.cats': 'Categories',
'live.hosts': 'Servers',
'live.countries': 'Origins (5 min)',
'live.recent': 'Latest events',
'live.empty': 'Waiting for events...',
'live.more': '+{n} not drawn individually',
'live.est': 'Destination estimated (server without coordinates)',
'live.alt': 'Live map of attacks arriving at the servers. The list of latest events is the text alternative.',
'live.hostile': 'highlighted: exploit and ban · click to filter',
'live.filtered': 'filter active',
'live.drag': 'Drag to rotate'
},
'pt-BR': {
'live.title': 'Ao vivo',
'live.mode': 'Visualização',
'live.mode.flat': 'Mapa plano',
'live.mode.globe': 'Globo',
'live.pause': 'Pausar animação',
'live.resume': 'Retomar animação',
'live.paused': 'pausado',
'live.fullscreen': 'Modo apresentação (tela cheia)',
'live.exitfs': 'Sair do modo apresentação',
'live.panels': 'Mostrar ou ocultar os painéis',
'live.collapse': 'Recolher painel',
'live.expand': 'Expandir painel',
'live.rate': 'eventos / min',
'live.rate.title': 'Ritmo',
'live.cats': 'Categorias',
'live.hosts': 'Servidores',
'live.countries': 'Origens (5 min)',
'live.recent': 'Últimos eventos',
'live.empty': 'Aguardando eventos...',
'live.more': '+{n} sem arco individual',
'live.est': 'Destino estimado (servidor sem coordenadas)',
'live.alt': 'Mapa ao vivo dos ataques que chegam aos servidores. A lista dos últimos eventos é a alternativa em texto.',
'live.hostile': 'destaque: exploit e ban · clique filtra',
'live.filtered': 'filtro ativo',
'live.drag': 'Arraste para girar'
}
});
U.registerPage({
id: 'live',
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="12" r="9"/><path d="M3 12h18M12 3c3 3.2 3 14.8 0 18M12 3c-3 3.2-3 14.8 0 18"/></svg>',
titleKey: 'live.title',
mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Live(U, el, ctx); },
update: function (ctx) { if (inst) inst.update(ctx); },
unmount: function () { if (inst) { inst.destroy(); inst = null; } }
});
return true;
}
// ------------------------------------------------------------------ world geometry (parsed once)
var geo = null;
function worldGeo(world) {
if (geo) return geo;
var rings = [], total = 0;
var re = /([MmLlHhVvZz])|(-?\d*\.?\d+)/g;
Object.keys(world.paths).forEach(function (cc) {
var d = world.paths[cc], m, cmd = '', nums = [], cur = null, x = 0, y = 0, sx = 0, sy = 0;
function flush() {
if (!cmd) return;
var up = cmd.toUpperCase(), rel = cmd !== up, i;
if (up === 'M' || up === 'L') {
for (i = 0; i + 1 < nums.length; i += 2) {
x = rel ? x + nums[i] : nums[i]; y = rel ? y + nums[i + 1] : nums[i + 1];
if (up === 'M' && i === 0) { cur = [[x, y]]; rings.push(cur); sx = x; sy = y; } else if (cur) cur.push([x, y]);
}
} else if (up === 'H') { nums.forEach(function (n) { x = rel ? x + n : n; if (cur) cur.push([x, y]); }); }
else if (up === 'V') { nums.forEach(function (n) { y = rel ? y + n : n; if (cur) cur.push([x, y]); }); }
nums = [];
}
re.lastIndex = 0;
while ((m = re.exec(d))) {
if (m[1]) { flush(); cmd = m[1]; if (cmd === 'z' || cmd === 'Z') { cmd = ''; x = sx; y = sy; } } // after z the pen returns to the subpath start
else nums.push(parseFloat(m[2]));
}
flush();
});
var out = [];
rings.forEach(function (r) {
var pts = [], last = null;
r.forEach(function (p) {
if (last && Math.abs(p[0] - last[0]) + Math.abs(p[1] - last[1]) < 1.1) return;
pts.push(p); last = p;
});
if (pts.length < 3) return;
// orientation in lon/lat space (y up): ccw when the shoelace sum of the map (y down) is negative
var area = 0, k0;
for (k0 = 0; k0 < pts.length; k0++) { var pa = pts[k0], pb = pts[(k0 + 1) % pts.length]; area += pa[0] * pb[1] - pb[0] * pa[1]; }
var items = []; // [x, y, z, edge]
for (var i = 0; i < pts.length; i++) {
var q = pts[(i + pts.length - 1) % pts.length];
// segments lying on the map border (antimeridian cut) or on the clipped
// southern edge are not borders: they are not stroked on the globe
var onEdge = ((pts[i][0] < 1.5 && q[0] < 1.5) || (pts[i][0] > WORLD_W - 1.5 && q[0] > WORLD_W - 1.5) ||
(pts[i][1] > WORLD_H - 1.5 && q[1] > WORLD_H - 1.5)) ? 1 : 0;
// a ring that runs along the clipped southern edge across the whole map
// (Antarctica) really wraps around the pole: go through it
if (pts[i][1] > WORLD_H - 1.5 && q[1] > WORLD_H - 1.5 && Math.abs(pts[i][0] - q[0]) > WORLD_W * 0.5) items.push([0, -1, 0, 1]);
// long edges follow the straight line of the flat map (which is how the data
// is drawn there), so they are cut into short pieces rather than one 3D chord
var dd = Math.sqrt((pts[i][0] - q[0]) * (pts[i][0] - q[0]) + (pts[i][1] - q[1]) * (pts[i][1] - q[1])), steps = Math.min(200, Math.ceil(dd / 10));
if (dd > 60) onEdge = 1; // a closing chord of the data, not a coastline: no outline
if (Math.abs(pts[i][0] - q[0]) > WORLD_W * 0.5) steps = 1; // wraps the antimeridian: keep it a single edge
for (var sIdx = 1; sIdx <= steps; sIdx++) {
var f = sIdx / steps, mx = q[0] + (pts[i][0] - q[0]) * f, my = q[1] + (pts[i][1] - q[1]) * f;
var lon = mx / WORLD_W * 360 - 180, lat = LAT_TOP - my / WORLD_H * (LAT_TOP - LAT_BOT);
var cl = Math.cos(lat * RAD);
items.push([cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD), onEdge]);
}
}
var n = items.length, v = new Float32Array(n * 3), edge = new Uint8Array(n);
for (var j = 0; j < n; j++) { v[j * 3] = items[j][0]; v[j * 3 + 1] = items[j][1]; v[j * 3 + 2] = items[j][2]; edge[j] = items[j][3]; }
out.push({ v: v, edge: edge, n: n, ccw: area < 0 });
total += n;
});
geo = { rings: out, total: total, scratch: new Float32Array(total * 3), maxN: out.reduce(function (m, r) { return Math.max(m, r.n); }, 0) };
return geo;
}
// ------------------------------------------------------------------ helpers
function clamp(x, a, b) { return x < a ? a : x > b ? b : x; }
function isNum(x) { return typeof x === 'number' && isFinite(x); }
function validLL(lat, lon) { return isNum(lat) && isNum(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180; }
function vec(lat, lon) {
var cl = Math.cos(lat * RAD);
return [cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD)];
}
function ease(x) { return x < 0.5 ? 2 * x * x : 1 - 2 * (1 - x) * (1 - x); }
function cc2(s) { return typeof s === 'string' && /^[A-Za-z]{2}$/.test(s) ? s.toUpperCase() : ''; }
function str(s, n) { return typeof s === 'string' ? s.slice(0, n) : ''; }
var colorProbe = null;
function parseColor(s, fb) {
var m;
if (typeof s !== 'string') s = '';
s = s.trim();
try {
if (!colorProbe) colorProbe = document.createElement('canvas').getContext('2d');
colorProbe.fillStyle = '#000000'; colorProbe.fillStyle = s || fb; s = colorProbe.fillStyle;
} catch (x) { s = fb; }
if ((m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(s))) return [parseInt(m[1], 16), parseInt(m[2], 16), parseInt(m[3], 16)];
if ((m = /rgba?\(\s*(\d+)[ ,]+(\d+)[ ,]+(\d+)/.exec(s))) return [+m[1], +m[2], +m[3]];
return fb === '#888888' ? [136, 136, 136] : parseColor(fb, '#888888');
}
function rgba(c, a) { return 'rgba(' + c[0] + ',' + c[1] + ',' + c[2] + ',' + a + ')'; }
// local DOM helper (the shell's Urutau.el takes an attrs object); textContent only
function mk(tag, cls, text) {
var e = document.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined && text !== null) e.textContent = text;
return e;
}
// ------------------------------------------------------------------ the page
function Live(U, root, ctx) {
var self = this;
this.U = U; this.root = root; this.ctx = ctx || {};
this.alive = true;
this.t = U.t; this.el = mk; this.lang = (ctx && ctx.lang) || '';
this.world = window.URUTAU_WORLD || U.world || null;
this.geo = this.world ? worldGeo(this.world) : null;
this.mode = 'flat'; this.target = 0; this.m = 0;
var pref = '';
try { pref = localStorage.getItem('urutau.live.mode') || ''; } catch (x) { /* storage blocked */ }
if (pref === 'globe' || (!pref && (root.clientWidth || window.innerWidth) < 560)) { this.mode = 'globe'; this.target = 1; this.m = 1; }
this.lon0 = -45; this.lat0 = 16; this.vlon = 0; this.vlat = 0; this.dragging = false; this.idleAt = 0;
this.paused = false; this.hidden = document.hidden;
this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);
this.offCats = {}; this.offHosts = {};
this.T = 0; this.last = 0; this.raf = 0; this.dirty = true;
this.arcs = []; this.free = []; this.pending = []; this.frameKey = {};
this.ring = []; this.hostsSeen = {}; this.hostLoc = {}; 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;
this.flatCache = null; this.cacheKey = '';
this.listDirty = true; this.hoverList = false;
this.listeners = []; this.timers = [];
this.colors = {}; this.dn = null; this.dnLang = '';
this.build();
this.readTheme();
this.resize();
if (window.__URUTAU_LIVE_TEST) window.__URUTAU_LIVE_TEST.inst = this; // test hook, unset in production
this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null;
this.listen(document, 'visibilitychange', function () { self.onVisibility(); });
this.listen(document, 'fullscreenchange', function () { self.onFullscreen(); });
if (window.matchMedia) {
var mq = matchMedia('(prefers-reduced-motion: reduce)');
var fn = function () { self.reduced = mq.matches; self.dirty = true; self.kick(); };
if (mq.addEventListener) this.listen(mq, 'change', fn);
}
if (window.ResizeObserver) {
this.ro = new ResizeObserver(function () { self.resize(); });
this.ro.observe(this.view); this.ro.observe(this.dock);
} else this.listen(window, 'resize', function () { self.resize(); });
this.timers.push(setInterval(function () { self.tick(); }, 500));
this.loadSummary();
this.timers.push(setInterval(function () { self.loadSummary(); }, 120000));
this.loadRecent();
this.kick();
}
var P = Live.prototype;
P.listen = function (target, type, fn, opt) {
target.addEventListener(type, fn, opt);
this.listeners.push([target, type, fn, opt]);
};
P.destroy = function () {
this.alive = false;
if (this.raf) cancelAnimationFrame(this.raf);
this.raf = 0;
if (this.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; }
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 = [];
if (this.ro) { this.ro.disconnect(); this.ro = null; }
if (document.fullscreenElement === this.stage && document.exitFullscreen) { try { document.exitFullscreen(); } catch (x) { /* ignore */ } }
this.arcs = []; this.free = []; this.pending = []; this.ring = []; this.dots = []; this.flatCache = null;
while (this.root.firstChild) this.root.removeChild(this.root.firstChild);
};
P.update = function (ctx) {
this.ctx = ctx || this.ctx;
if (this.ctx.lang !== this.lang) { this.lang = this.ctx.lang; this.rebuild(); }
this.readTheme();
this.listDirty = true; this.dirty = true;
this.tick(true);
this.kick();
};
// language changed: rebuild the DOM keeping filters and the paused/panel state
P.rebuild = function () {
var hosts = Object.keys(this.hostsSeen), self = this, paused = this.paused;
this.hostsSeen = {}; this.hostChips = {};
if (this.ro) this.ro.disconnect();
this.listeners = this.listeners.filter(function (l) {
if (l[0] === self.cv) { l[0].removeEventListener(l[1], l[2]); return false; }
return true;
});
this.build();
hosts.forEach(function (h) { self.noteHost(h); });
if (this.ro) { this.ro.observe(this.view); this.ro.observe(this.dock); }
if (paused) this.setPaused(true);
this.dn = null; this.readTheme(); this.filtersChanged(); this.resize();
};
// ------------------------------------------------------------------ DOM
P.icon = function (d) {
var ns = 'http://www.w3.org/2000/svg', s = document.createElementNS(ns, 'svg');
s.setAttribute('viewBox', '0 0 24 24'); s.setAttribute('aria-hidden', 'true'); s.setAttribute('class', 'lv-ic');
var p = document.createElementNS(ns, 'path'); p.setAttribute('d', d); s.appendChild(p);
return s;
};
P.btn = function (cls, label, svg, onclick) {
var b = document.createElement('button');
b.type = 'button'; b.className = 'lv-btn ' + cls;
b.setAttribute('aria-label', label); b.title = label;
b.appendChild(this.icon(svg));
b.addEventListener('click', onclick);
return b;
};
P.card = function (cls, titleKey, collapsed) {
var self = this, t = this.t;
var c = this.el('section', 'lv-card ' + cls);
var h = document.createElement('button');
h.type = 'button'; h.className = 'lv-card-h';
h.appendChild(this.el('span', 'lv-card-t', t(titleKey)));
h.appendChild(this.icon('M6 9l6 6 6-6'));
var body = this.el('div', 'lv-card-b');
function set(col) {
c.classList.toggle('lv-collapsed', col);
h.setAttribute('aria-expanded', col ? 'false' : 'true');
h.setAttribute('aria-label', t(col ? 'live.expand' : 'live.collapse') + ': ' + t(titleKey));
self.dirty = true;
}
h.addEventListener('click', function () { set(!c.classList.contains('lv-collapsed')); });
set(!!collapsed);
c.appendChild(h); c.appendChild(body);
c.body = body;
return c;
};
P.build = function () {
var self = this, t = this.t, el = this.el, root = this.root;
while (root.firstChild) root.removeChild(root.firstChild);
var narrow = (root.clientWidth || window.innerWidth) < 1300;
var stage = el('div', 'lv'); this.stage = stage;
var view = el('div', 'lv-view'); this.view = view;
var cv = document.createElement('canvas');
cv.className = 'lv-cv'; cv.tabIndex = 0; cv.setAttribute('role', 'img'); cv.setAttribute('aria-label', t('live.alt'));
this.cv = cv; this.g = cv.getContext('2d');
view.appendChild(cv);
var bar = el('div', 'lv-bar');
var seg = el('div', 'lv-seg'); seg.setAttribute('role', 'group'); seg.setAttribute('aria-label', t('live.mode'));
this.segFlat = el('button', 'lv-btn', t('live.mode.flat')); this.segGlobe = el('button', 'lv-btn', t('live.mode.globe'));
[['flat', this.segFlat], ['globe', this.segGlobe]].forEach(function (p) {
p[1].type = 'button';
p[1].addEventListener('click', function () { self.setMode(p[0]); });
seg.appendChild(p[1]);
});
bar.appendChild(seg);
this.bPause = this.btn('lv-pause', t('live.pause'), 'M8 5v14M16 5v14', function () { self.setPaused(!self.paused); });
this.bPause.setAttribute('aria-pressed', 'false');
this.bPan = this.btn('lv-pan', t('live.panels'), 'M4 6h16M4 12h16M4 18h16', function () {
var off = !self.stage.classList.contains('lv-nodock');
self.stage.classList.toggle('lv-nodock', off);
self.bPan.setAttribute('aria-pressed', off ? 'false' : 'true');
self.resize();
});
this.bPan.setAttribute('aria-pressed', 'true');
bar.appendChild(this.bPause); bar.appendChild(this.bPan);
if (document.fullscreenEnabled && stage.requestFullscreen) {
this.bFs = this.btn('lv-fs', t('live.fullscreen'), 'M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5', function () { self.toggleFs(); });
this.bFs.setAttribute('aria-pressed', 'false');
bar.appendChild(this.bFs);
}
view.appendChild(bar);
var note = el('div', 'lv-notes');
this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.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.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true;
note.appendChild(this.nPaused); note.appendChild(this.nFilter); note.appendChild(this.nMore); note.appendChild(this.nEst);
view.appendChild(note);
this.hint = el('div', 'lv-hint', t('live.drag')); view.appendChild(this.hint);
stage.appendChild(view);
var dock = el('div', 'lv-dock'); this.dock = dock;
var cRate = this.card('lv-c-rate', 'live.rate.title', false);
this.rateV = el('div', 'lv-rate-v', '0'); this.rateU = el('div', 'lv-rate-u', t('live.rate'));
this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true');
this.spark.width = 360; this.spark.height = 56;
cRate.body.appendChild(this.rateV); cRate.body.appendChild(this.rateU); cRate.body.appendChild(this.spark);
var cCats = this.card('lv-c-cats', 'live.cats', false);
this.catBox = el('div', 'lv-chips'); this.catChips = {};
CATS.forEach(function (c) {
var b = document.createElement('button');
b.type = 'button'; b.className = 'lv-chip lv-k-' + c + (HOSTILE[c] ? ' lv-hot' : ''); b.setAttribute('aria-pressed', self.offCats[c] ? 'false' : 'true');
b.appendChild(el('span', 'lv-sw'));
b.appendChild(el('span', 'lv-chip-l', t('cat.' + c)));
var n = el('span', 'lv-chip-n', '0'); b.appendChild(n); b.num = n;
b.addEventListener('click', function () {
self.offCats[c] = !self.offCats[c];
b.setAttribute('aria-pressed', self.offCats[c] ? 'false' : 'true');
self.filtersChanged();
});
self.catBox.appendChild(b); self.catChips[c] = b;
});
cCats.body.appendChild(this.catBox);
cCats.body.appendChild(el('div', 'lv-legend', t('live.hostile')));
var cHosts = this.card('lv-c-hosts', 'live.hosts', false);
this.hostBox = el('div', 'lv-chips lv-hostchips'); this.hostChips = {};
cHosts.body.appendChild(this.hostBox);
var cCty = this.card('lv-c-cty', 'live.countries', narrow);
this.ctyList = el('ol', 'lv-cty'); cCty.body.appendChild(this.ctyList);
var cRec = this.card('lv-c-rec', 'live.recent', false);
this.recList = el('ul', 'lv-rec');
this.recList.addEventListener('pointerenter', function () { self.hoverList = true; });
this.recList.addEventListener('pointerleave', function () { self.hoverList = false; self.listDirty = true; });
this.recList.addEventListener('focusin', function () { self.hoverList = true; });
this.recList.addEventListener('focusout', function () { self.hoverList = false; self.listDirty = true; });
cRec.body.appendChild(this.recList);
[cRate, cCats, cHosts, cCty, cRec].forEach(function (c) { dock.appendChild(c); });
stage.appendChild(dock);
root.appendChild(stage);
this.updateModeButtons();
this.listen(cv, 'pointerdown', function (e) { self.onDown(e); });
this.listen(cv, 'pointermove', function (e) { self.onMove(e); });
this.listen(cv, 'pointerup', function (e) { self.onUp(e); });
this.listen(cv, 'pointercancel', function (e) { self.onUp(e); });
this.listen(cv, 'keydown', function (e) { self.onKey(e); });
};
P.updateModeButtons = function () {
this.segFlat.setAttribute('aria-pressed', this.mode === 'flat' ? 'true' : 'false');
this.segGlobe.setAttribute('aria-pressed', this.mode === 'globe' ? 'true' : 'false');
this.hint.hidden = this.mode !== 'globe';
this.cv.classList.toggle('lv-globe', this.mode === 'globe');
};
P.setMode = function (m) {
this.mode = m; this.target = m === 'globe' ? 1 : 0;
try { localStorage.setItem('urutau.live.mode', m); } catch (x) { /* storage blocked */ }
this.updateModeButtons(); this.dirty = true; this.kick();
};
P.setPaused = function (p) {
this.paused = p;
var lab = this.t(p ? 'live.resume' : 'live.pause');
this.bPause.setAttribute('aria-label', lab); this.bPause.title = lab;
this.bPause.setAttribute('aria-pressed', p ? 'true' : 'false');
this.bPause.firstChild.firstChild.setAttribute('d', p ? 'M7 5l12 7-12 7z' : 'M8 5v14M16 5v14');
this.nPaused.hidden = !p;
if (p) this.pending.length = 0;
this.last = 0; this.dirty = true; this.kick();
};
P.toggleFs = function () {
try {
if (document.fullscreenElement) document.exitFullscreen();
else this.stage.requestFullscreen();
} catch (x) { /* ignore */ }
};
P.onFullscreen = function () {
if (!this.bFs) return;
var on = document.fullscreenElement === this.stage;
this.stage.classList.toggle('lv-full', on);
var lab = this.t(on ? 'live.exitfs' : 'live.fullscreen');
this.bFs.setAttribute('aria-label', lab); this.bFs.title = lab; this.bFs.setAttribute('aria-pressed', on ? 'true' : 'false');
this.resize();
};
P.filtersChanged = function () {
var any = false, k;
for (k in this.offCats) if (this.offCats[k]) any = true;
for (k in this.offHosts) if (this.offHosts[k]) any = true;
this.nFilter.hidden = !any;
this.listDirty = true; this.dirty = true; this.tick(true);
};
// ------------------------------------------------------------------ theme
P.readTheme = function () {
var U = this.U, css = U.css ? function (n) { return U.css(n); } : function () { return ''; };
var text = parseColor(css('--text'), '#e8f2f4'), bg = parseColor(css('--bg'), '#070d14');
var cols = {};
CATS.forEach(function (c) {
var rgb = parseColor(css(TOKEN[c]), FALLBACK[c]);
cols[c] = { rgb: rgb, c0: rgba(rgb, 0), c1: rgba(rgb, 1), css: rgba(rgb, 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') };
this.cacheKey = '';
if (this.catChips) CATS.forEach(function (c) { this.catChips[c].style.setProperty('--k', cols[c].css); }, this);
this.dirty = true;
};
// ------------------------------------------------------------------ data
P.loadRecent = function () {
var self = this;
if (!this.U.api) return;
var p;
try { p = this.U.api('/api/v1/live/recent', { limit: 200 }); } catch (x) { return; }
if (!p || !p.then) return;
p.then(function (res) {
var arr = Array.isArray(res) ? res : res && Array.isArray(res.events) ? res.events : null;
if (!self.alive || !arr) return;
var have = {}, seed = [];
self.ring.forEach(function (r) { have[r.key] = 1; });
arr.slice(0, 200).reverse().forEach(function (e) { // oldest first
var r = self.record(e, true, have);
if (r) seed.push(r);
});
// the latest part of the history plays back as arcs, whatever its age and
// spread over ~20 s, so the map never opens still on a quiet server; the
// timer lives in this.timers and dies with the page (destroy)
var replay = seed.slice(-40), id = setInterval(function () {
if (!self.alive || !replay.length) { clearInterval(id); return; }
if (!self.paused && !self.hidden) self.enqueue(replay.shift());
}, 500);
self.timers.push(id);
self.ring.sort(function (a, b) { return a.ts - b.ts; });
self.listDirty = true; self.tick(true);
}).catch(function () { /* endpoint not available yet */ });
};
P.loadSummary = function () {
var self = this;
if (!this.U.api || this.hidden) return;
var p;
try { p = this.U.api('/api/v1/summary', { range: '1h', host: 'all' }); } catch (x) { return; }
if (!p || !p.then) return;
p.then(function (s) {
if (!self.alive || !s || !Array.isArray(s.hosts)) return;
s.hosts.forEach(function (h) {
if (!h || typeof h.name !== 'string') return;
var name = h.name.slice(0, 64), l = h.location;
self.noteHost(name);
if (l && validLL(l.lat, l.lon)) {
self.hostLoc[name] = { lat: l.lat, lon: l.lon, label: str(l.label, 48) };
var d = self.dests[name];
if (d && d.est) self.setDest(name, self.hostLoc[name], false);
}
});
}).catch(function () { /* summary unavailable: keep what the events tell */ });
};
P.noteHost = function (h) {
if (!h || this.hostsSeen[h]) return;
var self = this, order = Object.keys(this.hostsSeen).length;
this.hostsSeen[h] = 1;
var b = document.createElement('button');
b.type = 'button'; b.className = 'lv-chip lv-host'; b.setAttribute('aria-pressed', this.offHosts[h] ? 'false' : 'true');
b.appendChild(this.el('span', 'lv-dot'));
b.appendChild(this.el('span', 'lv-chip-l', h));
var n = this.el('span', 'lv-chip-n', '0'); b.appendChild(n); b.num = n;
b.style.setProperty('--h', HOST_COLORS[order % HOST_COLORS.length]);
b.addEventListener('click', function () {
self.offHosts[h] = !self.offHosts[h];
b.setAttribute('aria-pressed', self.offHosts[h] ? 'false' : 'true');
self.filtersChanged();
});
this.hostBox.appendChild(b); this.hostChips[h] = b;
};
P.setDest = function (host, d, est) {
var cur = this.dests[host];
if (!cur) {
cur = this.dests[host] = { host: host, est: est, jit: this.destList.length };
this.destList.push(cur);
}
var lat = d.lat, lon = d.lon;
if (est) { lat += cur.jit * 1.4; lon += cur.jit * 1.8; }
cur.lat = lat; cur.lon = lon; cur.est = est;
cur.label = str(d.label, 48) || host || '';
cur.v = vec(lat, lon);
cur.u0 = (lon + 180) / 360; cur.v0 = (LAT_TOP - clamp(lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT);
if (this.destList.length === 1 && !this.centred) { this.centred = true; this.lon0 = lon; this.lat0 = clamp(lat * 0.5, -30, 40); }
return cur;
};
P.destFor = function (host, d) {
if (d && validLL(d.lat, d.lon)) {
var cur = this.dests[host];
if (!cur || cur.est || cur.lat !== d.lat || cur.lon !== d.lon) this.setDest(host, d, false);
return this.dests[host];
}
if (this.dests[host]) return this.dests[host];
var l = this.hostLoc[host];
return l ? this.setDest(host, l, false) : this.setDest(host, DEFAULT_DST, true);
};
// normalises one event into a ring entry; null for events that are not attacks
P.record = function (e, fromHistory, have) {
if (!e || typeof e !== 'object' || e.unban || !CAT_OK[e.cat]) return null;
var host = str(e.host, 64) || 'local';
var s = e.src && typeof e.src === 'object' ? e.src : null;
var tsec = isNum(e.t) ? e.t : Date.now() / 1000;
var what = '', ip = str(e.ip, 64);
if (e.source === 'traefik') what = (str(e.method, 8) + ' ' + str(e.path, 90)).trim();
else if (e.source === 'ssh') what = e.user ? 'ssh ' + str(e.user, 40) : 'ssh';
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; }
var r = {
ts: fromHistory ? tsec * 1000 : Date.now(), 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),
slat: s ? s.lat : NaN, slon: s ? s.lon : NaN,
dst: e.dst && typeof e.dst === 'object' ? { lat: e.dst.lat, lon: e.dst.lon, label: e.dst.label } : null
};
this.noteHost(host);
this.ring.push(r);
if (this.ring.length > RING_MAX) this.ring.splice(0, RING_TRIM);
this.listDirty = true;
return r;
};
P.ingest = function (e) {
if (!this.alive) return;
var r = this.record(e, false);
if (!r || this.paused || this.hidden) return;
this.enqueue(r);
};
P.visible = function (r) {
if (this.offCats[r.cat] || this.offHosts[r.host]) return false;
var h = this.ctx && this.ctx.host;
return !h || h === 'all' || h === r.host;
};
P.originOf = function (r) {
if (validLL(r.slat, r.slon)) return { lat: r.slat, lon: r.slon };
var c = this.world && this.world.centroids && this.world.centroids[r.cc];
if (c) return { lat: LAT_TOP - c[1] / WORLD_H * (LAT_TOP - LAT_BOT), lon: c[0] / WORLD_W * 360 - 180 };
return null;
};
P.enqueue = function (r) {
if (!this.visible(r)) return;
var o = this.originOf(r);
if (!o) return;
var d = this.destFor(r.host, r.dst);
if (this.reduced) {
this.dots.push({ lat: o.lat, lon: o.lon, v: vec(o.lat, o.lon), cat: r.cat });
if (this.dots.length > 160) this.dots.shift();
this.dirty = true; this.kick();
return;
}
if (this.pending.length >= MAX_PENDING) {
var drop = this.pending.length - 300;
this.pending.splice(0, drop);
this.addMore(drop);
}
this.pending.push({ o: o, d: d, cat: r.cat });
this.kick();
};
P.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]);
while (m.length && m[0][0] < s - 10) m.shift();
};
// ------------------------------------------------------------------ arcs
P.spawn = function (it) {
var a = this.free.pop() || {};
var o = it.o, d = it.d, hostile = !!HOSTILE[it.cat];
a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d;
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;
a.w = Math.acos(clamp(a.a[0] * a.b[0] + a.a[1] * a.b[1] + a.a[2] * a.b[2], -1, 1));
a.D = hostile ? 1.35 : 1.0;
a.hold = hostile ? 1.4 : 0.2;
a.pl = hostile ? 1.9 : 1.1;
a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D);
this.arcs.push(a);
return a;
};
P.stepSpawn = function () {
var q = this.pending;
if (!q.length) return;
var budget = q.length > 80 ? 48 : q.length > 24 ? 14 : 6;
var maxArcs = Math.round(MAX_ARCS * this.quality);
var keys = this.frameKey, n = 0, merged = 0, k;
for (k in keys) delete keys[k];
while (q.length && n < budget && this.arcs.length < maxArcs) {
var it = q.shift(); n++;
var key = Math.round(it.o.lat / 2) + ',' + Math.round(it.o.lon / 2) + '|' + it.d.host + '|' + it.cat;
if (q.length > 24 && keys[key]) { keys[key].n++; merged++; continue; }
keys[key] = this.spawn(it);
}
if (merged) this.addMore(merged);
};
// ------------------------------------------------------------------ geometry / layout
P.resize = function () {
if (!this.alive) return;
var r = this.view.getBoundingClientRect();
var w = Math.max(10, Math.round(r.width)), h = Math.max(10, Math.round(r.height));
var dpr = Math.min(window.devicePixelRatio || 1, 2);
var overlay = getComputedStyle(this.dock).position === 'absolute' && !this.stage.classList.contains('lv-nodock');
this.reserve = overlay ? this.dock.offsetHeight + 20 : 0;
if (w !== this.W || h !== this.H || dpr !== this.dpr) {
this.W = w; this.H = h; this.dpr = dpr;
this.cv.width = Math.round(w * dpr); this.cv.height = Math.round(h * dpr);
}
var top = w < 560 ? 50 : 54;
var availH = Math.max(80, h - top - this.reserve - 6), availW = w - 16;
var s = Math.min(availW / WORLD_W, availH / WORLD_H);
this.mw = WORLD_W * s; this.mh = WORLD_H * s;
this.ox = (w - this.mw) / 2; this.oy = top + (availH - this.mh) / 2;
this.cx = w / 2; this.cy = top + (h - top - this.reserve) / 2;
this.R = Math.max(40, Math.min(availW / 2 - 4, (h - top - this.reserve) / 2 - 8));
this.cacheKey = '';
this.dirty = true; this.kick();
};
P.buildFlatCache = function () {
var key = [Math.round(this.mw), Math.round(this.mh), this.dpr, this.dark ? 1 : 0, this.pal.text.join()].join('|');
if (this.cacheKey === key && this.flatCache) return;
this.cacheKey = key;
var cv = this.flatCache || document.createElement('canvas');
this.flatCache = cv;
var d = this.dpr, w = Math.ceil(this.mw), h = Math.ceil(this.mh);
cv.width = Math.ceil(w * d); cv.height = Math.ceil(h * d);
var g = cv.getContext('2d');
g.setTransform(d, 0, 0, d, 0, 0);
g.clearRect(0, 0, w, h);
var tx = this.pal.text, lon, lat;
g.strokeStyle = rgba(tx, this.dark ? 0.06 : 0.09); g.lineWidth = 1; g.beginPath();
for (lon = -150; lon <= 150; lon += 30) { var x = (lon + 180) / 360 * w; g.moveTo(x, 0); g.lineTo(x, h); }
for (lat = -30; lat <= 60; lat += 30) { var y = (LAT_TOP - lat) / (LAT_TOP - LAT_BOT) * h; g.moveTo(0, y); g.lineTo(w, y); }
g.stroke();
if (this.world) {
var s = w / WORLD_W;
g.save(); g.scale(s, s);
g.fillStyle = rgba(tx, 0.13);
g.strokeStyle = rgba(tx, this.dark ? 0.26 : 0.32);
g.lineWidth = 0.7 / s;
var paths = this.world.paths;
Object.keys(paths).forEach(function (cc) {
var p = new Path2D(paths[cc]);
g.fill(p); g.stroke(p);
});
g.restore();
}
};
// ------------------------------------------------------------------ input (globe)
P.onDown = function (e) {
if (this.mode !== 'globe') return;
this.dragging = true; this.px = e.clientX; this.py = e.clientY; this.vlon = 0; this.vlat = 0;
try { this.cv.setPointerCapture(e.pointerId); } catch (x) { /* ignore */ }
this.cv.classList.add('lv-grab');
};
P.onMove = function (e) {
if (!this.dragging) return;
var k = 57.3 / this.R, dx = e.clientX - this.px, dy = e.clientY - this.py;
this.px = e.clientX; this.py = e.clientY;
this.lon0 -= dx * k; this.lat0 = clamp(this.lat0 + dy * k, -75, 75);
this.vlon = -dx * k * 40; this.vlat = dy * k * 40;
this.dirty = true; this.kick();
};
P.onUp = function (e) {
if (!this.dragging) return;
this.dragging = false; this.idleAt = this.T + 2.5;
this.cv.classList.remove('lv-grab');
try { this.cv.releasePointerCapture(e.pointerId); } catch (x) { /* ignore */ }
this.dirty = true; this.kick();
};
P.onKey = function (e) {
var k = e.key, used = true;
if (k === 'ArrowLeft') this.lon0 -= 10;
else if (k === 'ArrowRight') this.lon0 += 10;
else if (k === 'ArrowUp') this.lat0 = clamp(this.lat0 + 10, -75, 75);
else if (k === 'ArrowDown') this.lat0 = clamp(this.lat0 - 10, -75, 75);
else used = false;
if (used) { e.preventDefault(); this.idleAt = this.T + 4; this.dirty = true; this.kick(); }
};
// ------------------------------------------------------------------ loop
P.onVisibility = function () {
this.hidden = document.hidden;
if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; }
else { this.last = 0; this.dirty = true; this.kick(); this.loadSummary(); this.tick(true); }
};
P.kick = function () {
var self = this;
if (!this.alive || this.raf || this.hidden) return;
this.raf = requestAnimationFrame(function (now) { self.frame(now); });
};
P.frame = function (now) {
this.raf = 0;
if (!this.alive || this.hidden) return;
var raw = this.last ? now - this.last : 16;
var dt = this.last ? Math.min(0.1, raw / 1000) : 0.016;
this.last = now;
var wasDirty = this.dirty;
var still = this.paused || this.reduced;
if (!this.paused) {
this.T += this.reduced ? 0.2 : dt;
if (!this.reduced) {
// adaptive quality: shed arcs when frames get slow, recover when they are cheap again
this.frameAvg += (raw - this.frameAvg) * 0.05;
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();
}
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;
if (this.m > 0.01 && !this.paused && !this.dragging) {
if (Math.abs(this.vlon) > 0.05 || Math.abs(this.vlat) > 0.05) {
this.lon0 += this.vlon * dt; this.lat0 = clamp(this.lat0 + this.vlat * dt, -75, 75);
var f = Math.pow(0.04, dt); this.vlon *= f; this.vlat *= f;
} else if (!this.reduced && this.T > this.idleAt) {
this.lon0 += 4.5 * dt;
}
}
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();
}
}
if (!still || morph || this.dirty) this.kick();
};
// ------------------------------------------------------------------ drawing
P.draw = function () {
var g = this.g, d = this.dpr, W = this.W, H = this.H, m = this.m;
g.setTransform(d, 0, 0, d, 0, 0);
g.globalCompositeOperation = 'source-over';
g.globalAlpha = 1;
g.clearRect(0, 0, W, H);
this.buildFlatCache();
var add = this.dark ? 'lighter' : 'source-over';
if (m < 0.995) {
g.globalAlpha = 1 - m;
g.drawImage(this.flatCache, this.ox, this.oy, this.mw, this.mh);
this.drawFlatLayer(g, 1 - m, add);
}
if (m > 0.005) {
this.prepGlobe(m);
this.drawGlobeBase(g, m);
this.drawGlobeLayer(g, m, add);
}
g.globalAlpha = 1; g.globalCompositeOperation = 'source-over';
};
P.drawLabel = function (g, text, x, y, alpha) {
g.font = '600 11px system-ui, -apple-system, "Segoe UI", sans-serif';
g.textBaseline = 'middle';
var w = g.measureText(text).width;
var left = x + 10 + w > this.W - 6;
var tx = left ? x - 10 : x + 10;
g.textAlign = left ? 'right' : 'left';
g.globalAlpha = alpha;
g.lineWidth = 3; g.lineJoin = 'round';
g.strokeStyle = rgba(this.pal.bg, 0.85); g.strokeText(text, tx, y);
g.fillStyle = rgba(this.pal.text, 0.95); g.fillText(text, tx, y);
};
P.drawDestDot = function (g, x, y, alpha, ang, zz, est) {
var acc = this.pal.accent;
var br = (Math.sin(this.T * 2.2) + 1) / 2, rr = 7 + br * 5;
g.globalAlpha = alpha * (0.25 + 0.2 * br);
g.strokeStyle = rgba(acc, 1); g.lineWidth = 1.2;
g.beginPath();
if (ang === null) g.arc(x, y, rr, 0, TAU); else g.ellipse(x, y, rr * zz, rr, ang, 0, TAU);
g.stroke();
g.globalAlpha = alpha;
g.fillStyle = rgba(this.pal.bg, 1);
g.beginPath(); g.arc(x, y, 5, 0, TAU); g.fill();
g.fillStyle = rgba(acc, 1);
g.beginPath(); g.arc(x, y, 3.4, 0, TAU); g.fill();
if (est) {
g.strokeStyle = rgba(this.pal.text, 0.8); g.lineWidth = 1;
g.setLineDash([2, 2]); g.beginPath(); g.arc(x, y, 6, 0, TAU); g.stroke(); g.setLineDash([]);
}
};
P.drawPulse = function (g, x, y, a, age, col, ang, zz, fade) {
var pa = (age - a.D) / a.pl;
if (pa < 0 || pa >= 1) return;
var rmax = a.hostile ? 30 : 17, n = a.hostile ? 2 : 1, i;
g.lineWidth = a.hostile ? 2 : 1.4; g.strokeStyle = col.css;
for (i = 0; i < n; i++) {
var q = pa - i * 0.22;
if (q <= 0) continue;
var r = 3 + (1 - (1 - q) * (1 - q)) * rmax;
g.globalAlpha = fade * (1 - q) * 0.9;
g.beginPath();
if (ang === null) g.arc(x, y, r, 0, TAU); else g.ellipse(x, y, r * zz, r, ang, 0, TAU);
g.stroke();
}
if (pa < 0.35) {
g.globalAlpha = fade * (1 - pa / 0.35);
g.fillStyle = col.css;
g.beginPath(); g.arc(x, y, 3 + pa * 6 + (a.n > 1 ? Math.min(3, Math.log(a.n)) : 0), 0, TAU); g.fill();
}
};
P.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;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs
var dd = this.dots[i];
g.globalAlpha = layerAlpha * 0.75; g.fillStyle = this.colors[dd.cat].css;
g.beginPath(); g.arc(ox + (dd.lon + 180) / 360 * mw, oy + (LAT_TOP - clamp(dd.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT) * mh, 2.6, 0, TAU); g.fill();
}
g.globalCompositeOperation = add;
g.lineCap = 'round';
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 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);
if (tail < 1 && head > tail) {
// exact sub-curve of the quadratic Bezier between parameters tail..head
var ut = 1 - tail, uh = 1 - head;
var ax = ut * ut * x0 + 2 * tail * ut * cx + tail * tail * x1, ay = ut * ut * y0 + 2 * tail * ut * cy + tail * tail * y1;
var bx = uh * uh * x0 + 2 * head * uh * cx + head * head * x1, by = uh * uh * y0 + 2 * head * uh * cy + head * head * y1;
var kx = ax + (head - tail) * (ut * (cx - x0) + tail * (x1 - cx));
var ky = ay + (head - tail) * (ut * (cy - y0) + tail * (y1 - cy));
var gr = g.createLinearGradient(ax, ay, bx, by);
gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1);
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.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) {
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);
}
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.destList.length; i++) {
var ds = this.destList[i], x = ox + ds.u0 * mw, y = oy + ds.v0 * mh;
this.drawDestDot(g, x, y, layerAlpha, null, 1, ds.est);
this.drawLabel(g, ds.label, x, y + (i % 2 ? 15 : -15), layerAlpha);
}
};
// ---- globe
P.prepGlobe = function (m) {
var l0 = this.lon0 * RAD, p0 = this.lat0 * RAD;
this.cl = Math.cos(l0); this.sl = Math.sin(l0); this.cp = Math.cos(p0); this.sp = Math.sin(p0);
this.gR = this.R * (0.9 + 0.1 * m);
};
// rotates a vector into the view: screen x (rx), screen y up (ry), depth (rz, > 0 faces the viewer)
P.rot = function (x, y, z) {
var x1 = x * this.cl - z * this.sl, z1 = x * this.sl + z * this.cl;
this.rx = x1; this.ry = y * this.cp - z1 * this.sp; this.rz = y * this.sp + z1 * this.cp;
};
// Adds one ring (unit-sphere view coordinates x, y, z at sc[base..]) to the current
// path, clipped to the visible hemisphere: edges that cross the horizon are cut
// where they meet it and the gap is closed by an arc along the limb, walked in the
// ring's own direction, so the fill never covers the wrong side.
P.clipRing = function (g, sc, base, n, ccw, cx, cy, R) {
var j, p, q, runs = [], TWO = Math.PI * 2, EPS = 0.015; // a hair above the horizon: grazing vertices would give unstable cut points
function limb(a, b) { // where edge a->b meets z = 0, on the unit circle
var t = (sc[a + 2] - EPS) / (sc[a + 2] - sc[b + 2]);
var x = sc[a] + (sc[b] - sc[a]) * t, y = sc[a + 1] + (sc[b + 1] - sc[a + 1]) * t, h = Math.sqrt(x * x + y * y) || 1;
return [x / h, y / h];
}
for (j = 0; j < n; j++) {
p = base + ((j + n - 1) % n) * 3; q = base + j * 3;
if (sc[q + 2] > EPS && sc[p + 2] <= EPS) {
var len = 1;
while (len < n && sc[base + ((j + len) % n) * 3 + 2] > EPS) len++;
var last = base + ((j + len - 1) % n) * 3, nxt = base + ((j + len) % n) * 3;
var en = limb(p, q), ex = limb(last, nxt);
runs.push({ s: j, len: len, en: en, ex: ex, ae: Math.atan2(-en[1], en[0]), ax: Math.atan2(-ex[1], ex[0]), done: false });
}
}
if (!runs.length) {
if (sc[base + 2] <= EPS) return; // wholly hidden
for (j = 0; j < n; j++) { q = base + j * 3; if (j) g.lineTo(cx + sc[q] * R, cy - sc[q + 1] * R); else g.moveTo(cx + sc[q] * R, cy - sc[q + 1] * R); }
g.closePath();
return;
}
// Stitch the visible runs into closed contours the way a polygon clipper does:
// from where a run leaves the disc, follow the limb in the ring's own direction
// to the nearest point where some run comes back in.
for (var r0 = 0; r0 < runs.length; r0++) {
if (runs[r0].done) continue;
var run = runs[r0];
g.moveTo(cx + run.en[0] * R, cy - run.en[1] * R);
for (;;) {
run.done = true;
for (var k = 0; k < run.len; k++) { q = base + ((run.s + k) % n) * 3; g.lineTo(cx + sc[q] * R, cy - sc[q + 1] * R); }
g.lineTo(cx + run.ex[0] * R, cy - run.ex[1] * R);
var best = null, bd = 1e9;
for (var m = 0; m < runs.length; m++) {
var d = ccw ? run.ax - runs[m].ae : runs[m].ae - run.ax;
d = ((d % TWO) + TWO) % TWO;
// an arc of almost a full turn is a rounding artefact (the cut points of a sliver
// came out in the wrong order): walk the short way back instead
if (d > TWO * 0.95) d -= TWO;
if (d < bd) { bd = d; best = runs[m]; }
}
g.arc(cx, cy, R, run.ax, best.ae, bd < 0 ? !ccw : !!ccw);
if (best === runs[r0] || best.done) break;
run = best;
}
g.closePath();
}
};
P.drawGlobeBase = function (g, m) {
var cx = this.cx, cy = this.cy, R = this.gR, acc = this.pal.accent, tx = this.pal.text, dark = this.dark;
var lat, lon, k, up, cl;
g.globalCompositeOperation = 'source-over';
g.globalAlpha = m;
var ga = g.createRadialGradient(cx, cy, R * 0.98, cx, cy, R * 1.16);
ga.addColorStop(0, rgba(acc, dark ? 0.28 : 0.2)); ga.addColorStop(1, rgba(acc, 0));
g.fillStyle = ga; g.beginPath(); g.arc(cx, cy, R * 1.16, 0, TAU); g.fill();
var go = g.createRadialGradient(cx - R * 0.35, cy - R * 0.4, R * 0.1, cx, cy, R);
go.addColorStop(0, rgba(acc, dark ? 0.22 : 0.16)); go.addColorStop(1, rgba(acc, dark ? 0.05 : 0.05));
g.fillStyle = rgba(this.pal.bg, 0.6); g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.fill();
g.fillStyle = go; g.fill();
g.save();
g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.clip();
g.strokeStyle = rgba(tx, dark ? 0.07 : 0.1); g.lineWidth = 1; g.beginPath();
for (lat = -60; lat <= 60; lat += 30) {
up = false; cl = Math.cos(lat * RAD);
for (k = 0; k <= 72; k++) {
lon = k * 5 - 180;
this.rot(cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD));
if (this.rz > 0) { if (up) g.lineTo(cx + this.rx * R, cy - this.ry * R); else g.moveTo(cx + this.rx * R, cy - this.ry * R); up = true; } else up = false;
}
}
for (lon = -180; lon < 180; lon += 30) {
up = false;
for (k = 0; k <= 36; k++) {
lat = k * 5 - 90; cl = Math.cos(lat * RAD);
this.rot(cl * Math.sin(lon * RAD), Math.sin(lat * RAD), cl * Math.cos(lon * RAD));
if (this.rz > 0) { if (up) g.lineTo(cx + this.rx * R, cy - this.ry * R); else g.moveTo(cx + this.rx * R, cy - this.ry * R); up = true; } else up = false;
}
}
g.stroke();
if (this.geo) {
var rings = this.geo.rings, sc = this.geo.scratch, o = 0, i, j;
g.beginPath();
for (i = 0; i < rings.length; i++) {
var r = rings[i], v = r.v, n = r.n, base = o;
// rotate every vertex (true screen position and depth, nothing pinned)
for (j = 0; j < n; j++) {
this.rot(v[j * 3], v[j * 3 + 1], v[j * 3 + 2]);
sc[o] = this.rx; sc[o + 1] = this.ry; sc[o + 2] = this.rz; o += 3;
}
this.clipRing(g, sc, base, n, r.ccw, cx, cy, R);
}
g.fillStyle = rgba(tx, 0.2); g.fill();
g.strokeStyle = rgba(tx, dark ? 0.38 : 0.45); g.lineWidth = 0.8; g.beginPath();
o = 0;
for (i = 0; i < rings.length; i++) {
var e = rings[i].edge, n2 = rings[i].n;
for (j = 1; j <= n2; j++) {
var p = (j - 1) * 3 + o, q = (j % n2) * 3 + o;
if (sc[p + 2] > 0 && sc[q + 2] > 0 && !e[j % n2]) { g.moveTo(cx + sc[p] * R, cy - sc[p + 1] * R); g.lineTo(cx + sc[q] * R, cy - sc[q + 1] * R); }
}
o += n2 * 3;
}
g.stroke();
}
var gs = g.createRadialGradient(cx, cy, R * 0.6, cx, cy, R);
gs.addColorStop(0, rgba(this.pal.bg, 0)); gs.addColorStop(1, rgba(this.pal.bg, dark ? 0.55 : 0.25));
g.fillStyle = gs; g.fillRect(cx - R, cy - R, R * 2, R * 2);
g.restore();
g.strokeStyle = rgba(acc, dark ? 0.5 : 0.6); g.lineWidth = 1.2;
g.beginPath(); g.arc(cx, cy, R, 0, TAU); g.stroke();
};
P.drawGlobeLayer = function (g, m, add) {
var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.arcs, i, k;
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.dots.length; i++) {
var dd = this.dots[i];
this.rot(dd.v[0], dd.v[1], dd.v[2]);
if (this.rz <= 0.02) continue;
g.globalAlpha = m * 0.8; g.fillStyle = this.colors[dd.cat].css;
g.beginPath(); g.arc(cx + this.rx * R, cy - this.ry * R, 2.6, 0, TAU); g.fill();
}
g.globalCompositeOperation = add;
g.lineCap = 'round';
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 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 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;
var N = Math.max(4, Math.min(Math.round(22 * this.quality), Math.ceil((head - tail) * 24) + 2));
var cnt = 0, run = false, fx = 0, fy = 0, lx = 0, ly = 0;
g.beginPath();
for (k = 0; k <= N; k++) {
var f = tail + (head - tail) * k / N, s1, s2;
if (sw < 1e-4) { s1 = 1 - f; s2 = f; } else { s1 = Math.sin((1 - f) * w) / sw; s2 = Math.sin(f * w) / sw; }
var h = 1 + lift * Math.sin(Math.PI * f);
this.rot((A[0] * s1 + B[0] * s2) * h, (A[1] * s1 + B[1] * s2) * h, (A[2] * s1 + B[2] * s2) * h);
if (this.rz > 0 || (this.rx * this.rx + this.ry * this.ry) > 1) {
var px = cx + this.rx * R, py = cy - this.ry * R;
if (run) g.lineTo(px, py); else g.moveTo(px, py);
if (!cnt) { fx = px; fy = py; }
run = true; lx = px; ly = py; cnt++;
} else run = false;
}
if (cnt > 1) {
var gr = g.createLinearGradient(fx, fy, lx, ly);
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.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) {
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) {
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;
g.beginPath(); g.arc(cx + this.rx * R, cy - this.ry * R, 2 + age * 9, 0, TAU); g.stroke();
}
}
}
g.globalCompositeOperation = 'source-over';
for (i = 0; i < this.destList.length; i++) {
var ds = this.destList[i];
this.rot(ds.v[0], ds.v[1], ds.v[2]);
if (this.rz <= 0.05) continue;
var x = cx + this.rx * R, y = cy - this.ry * R, al = m * clamp(this.rz * 3, 0, 1);
this.drawDestDot(g, x, y, al, Math.atan2(-this.ry, this.rx), this.rz, ds.est);
this.drawLabel(g, ds.label, x, y + (i % 2 ? 15 : -15), al);
}
};
// ------------------------------------------------------------------ panels
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;
try {
if (!this.dn || this.dnLang !== lang) { this.dn = new Intl.DisplayNames([lang || 'en'], { type: 'region' }); this.dnLang = lang; }
return this.dn.of(cc) || cc;
} catch (x) { return cc; }
};
P.tick = function (force) {
if (!this.alive || (this.hidden && !force)) return;
var now = Date.now(), ring = this.ring, i, r, b, self = this;
// The ring is bounded by RING_MAX, not by age: the 5 min window only applies
// to the statistics, so the latest-events list still shows something on a
// quiet server.
var cut5 = now - 300000;
var cut1 = now - 60000, perMin = 0, cats = {}, hosts = {}, ctys = {}, bins = [];
for (b = 0; b < 60; b++) bins.push(0);
for (i = 0; i < ring.length; i++) {
r = ring[i];
if (r.ts < cut5) continue;
if (r.cc && this.visible(r)) ctys[r.cc] = (ctys[r.cc] || 0) + 1;
if (r.ts >= cut1) {
perMin++;
cats[r.cat] = (cats[r.cat] || 0) + 1;
hosts[r.host] = (hosts[r.host] || 0) + 1;
b = 59 - Math.floor((now - r.ts) / 1000);
if (b >= 0 && b < 60) bins[b]++;
}
}
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 ''; };
this.rateV.textContent = fmtN(perMin);
CATS.forEach(function (c) { self.catChips[c].num.textContent = fmtN(cats[c] || 0); });
Object.keys(this.hostChips).forEach(function (h) { self.hostChips[h].num.textContent = fmtN(hosts[h] || 0); });
this.drawSpark(bins);
var s = Math.floor(now / 1000), more = 0;
this.more.forEach(function (x) { if (x[0] >= s - 10) more += x[1]; });
this.nMore.hidden = more <= 0;
if (more > 0) this.nMore.textContent = this.t('live.more', fmtN(more));
var est = false;
this.destList.forEach(function (d) { if (d.est) est = true; });
this.nEst.hidden = !est;
var top = Object.keys(ctys).sort(function (a, c) { return ctys[c] - ctys[a]; }).slice(0, 6);
var box = this.ctyList, max = top.length ? ctys[top[0]] : 1;
while (box.firstChild) box.removeChild(box.firstChild);
if (!top.length) box.appendChild(this.el('li', 'lv-empty', this.t('live.empty')));
top.forEach(function (cc) {
var li = self.el('li', 'lv-cty-i');
li.appendChild(self.el('span', 'lv-cty-n', fl(cc) + ' ' + self.regionName(cc)));
li.appendChild(self.el('span', 'lv-cty-v', fmtN(ctys[cc])));
var bar = self.el('span', 'lv-cty-b'); bar.style.setProperty('--w', Math.round(ctys[cc] / max * 100) + '%');
li.appendChild(bar);
box.appendChild(li);
});
this.renderList(force);
};
P.drawSpark = function (bins) {
var c = this.spark, g = c.getContext('2d'), w = c.width, h = c.height, max = 1, i;
for (i = 0; i < bins.length; i++) if (bins[i] > max) max = bins[i];
g.clearRect(0, 0, w, h);
var col = this.pal.accent, bw = w / bins.length;
for (i = 0; i < bins.length; i++) {
var bh = bins[i] ? Math.max(3, bins[i] / max * (h - 4)) : 1.5;
g.fillStyle = rgba(col, bins[i] ? 0.4 + 0.55 * (i / bins.length) : 0.2);
g.fillRect(i * bw + 0.5, h - bh, bw - 1.5, bh);
}
};
P.renderList = function (force) {
if (!this.listDirty && !force) return;
if (this.hoverList && !force) return;
this.listDirty = false;
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];
if (!this.visible(r)) continue;
n++;
var li = this.el('li', 'lv-ev');
li.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' })));
li.appendChild(this.el('span', 'lv-tag lv-k-' + r.cat + (HOSTILE[r.cat] ? ' lv-hot' : ''), this.t('cat.' + r.cat)));
var b = this.el('button', 'lv-ip', (r.cc ? fl(r.cc) + ' ' : '') + r.ip);
b.type = 'button';
(function (ip) { b.addEventListener('click', function () { if (self.U.openIP) self.U.openIP(ip); }); })(r.ip);
li.appendChild(b);
li.appendChild(this.el('span', 'lv-ev-w', (r.city ? r.city + ' · ' : '') + '[' + r.host + '] ' + r.what));
box.appendChild(li);
}
if (!n) box.appendChild(this.el('li', 'lv-empty', this.t('live.empty')));
};
// ------------------------------------------------------------------ bootstrap
if (!boot()) document.addEventListener('DOMContentLoaded', boot, { once: true });
})();