/* Urutau - AO VIVO page and the reusable attack map. Urutau.createAttackMap(container, {mode, interactive}) draws attacks as animated arcs on a flat map or a 3D globe (canvas 2D, no libraries); the Live page is built on it. Every string that comes 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_VARCS = 150, MAX_VPENDING = 150, MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300; var WORLD_W = 2000, WORLD_H = 789, LAT_TOP = 84, LAT_BOT = -58; var DEFAULT_DST = { lat: -23.55, lon: -46.63 }; var RAD = Math.PI / 180, TAU = Math.PI * 2; var HOST_COLORS = ['#38bdf8', '#f0b35b', '#10b981', '#a5b4fc', '#f97316']; // ------------------------------------------------------------------ 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 (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 reusable map // opts: { mode: 'flat'|'globe', interactive: true } function AttackMap(U, container, opts) { var self = this; opts = opts || {}; this.U = U; this.container = container; this.alive = true; this.interactive = opts.interactive !== false; this.world = window.URUTAU_WORLD || (U && U.world) || null; this.geo = this.world ? worldGeo(this.world) : null; this.mode = opts.mode === 'globe' ? 'globe' : 'flat'; this.target = this.mode === 'globe' ? 1 : 0; this.m = this.target; this.lon0 = -45; this.lat0 = 16; this.vlon = 0; this.vlat = 0; this.dragging = false; this.idleAt = 0; this.moved = 0; this.paused = false; this.hidden = document.hidden; this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches); this.T = 0; this.last = 0; this.raf = 0; this.dirty = true; this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.frameKey = {}; this.dests = {}; this.destList = []; this.dots = []; this.more = []; this.frameAvg = 16; this.quality = 1; this.W = 0; this.H = 0; this.dpr = 1; this.reserve = 0; this.flatCache = null; this.cacheKey = ''; this.colors = {}; this.pickCbs = []; this.moreCb = null; this.listeners = []; var cv = document.createElement('canvas'); cv.className = 'lv-cv'; cv.setAttribute('role', 'img'); cv.setAttribute('aria-label', U && U.t ? U.t('live.alt') : 'Live attack map'); if (this.interactive) cv.tabIndex = 0; this.cv = cv; this.g = cv.getContext('2d'); container.appendChild(cv); this.readTheme(); this.resize(); if (window.__URUTAU_LIVE_TEST) window.__URUTAU_LIVE_TEST.inst = this; // test hook, unset in production this.listen(document, 'visibilitychange', function () { self.onVisibility(); }); if (this.interactive) { 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); }); this.listen(cv, 'click', function (e) { self.onClick(e); }); } 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(container); } else this.listen(window, 'resize', function () { self.resize(); }); this.kick(); } var M = AttackMap.prototype; M.listen = function (target, type, fn, opt) { target.addEventListener(type, fn, opt); this.listeners.push([target, type, fn, opt]); }; M.destroy = function () { this.alive = false; if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } }); this.listeners = []; if (this.ro) { this.ro.disconnect(); this.ro = null; } this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = []; if (this.cv.parentNode) this.cv.parentNode.removeChild(this.cv); }; M.readTheme = function () { var U = this.U, css = U && U.css ? function (n) { return U.css(n); } : function () { return ''; }; function tok(a, b) { return css(a) || css(b); } var text = parseColor(tok('--ink', '--text'), '#e8f2f4'), bg = parseColor(tok('--surface-base', '--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) }; }); var vrgb = parseColor(tok('--ink-muted', '--muted'), '#9db3bd'); cols.visit = { rgb: vrgb, c0: rgba(vrgb, 0), c1: rgba(vrgb, 1), css: rgba(vrgb, 1) }; this.colors = cols; this.dark = (bg[0] * 299 + bg[1] * 587 + bg[2] * 114) / 1000 < 128; this.pal = { text: text, bg: bg, accent: parseColor(css('--accent'), '#38bdf8') }; this.cacheKey = ''; this.dirty = true; }; M.setTheme = function () { this.readTheme(); this.kick(); }; M.setMode = function (m) { this.mode = m === 'globe' ? 'globe' : 'flat'; this.target = this.mode === 'globe' ? 1 : 0; this.cv.classList.toggle('lv-globe', this.mode === 'globe'); this.dirty = true; this.kick(); }; M.pause = function (p) { this.paused = !!p; if (p) { this.pending.length = 0; this.vpending.length = 0; } this.last = 0; this.dirty = true; this.kick(); }; M.clear = function () { this.arcs = []; this.varcs = []; this.vpending.length = 0; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); }; M.setDest = function (host, d, est) { var cur = this.dests[host]; 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); } this.dirty = true; return cur; }; M.setDests = function (list) { var self = this; (list || []).forEach(function (d) { if (d && typeof d.host === 'string' && validLL(d.lat, d.lon)) self.setDest(d.host.slice(0, 64), d, false); }); this.kick(); }; M.hasEstimatedDest = function () { return this.destList.some(function (d) { return d.est; }); }; M.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]; } return this.dests[host] || this.setDest(host, DEFAULT_DST, true); }; M.originOf = function (ev) { var s = ev.src && typeof ev.src === 'object' ? ev.src : null; if (s && validLL(s.lat, s.lon)) return { lat: s.lat, lon: s.lon }; var cc = cc2(s && s.cc) || cc2(ev.cc), c = this.world && this.world.centroids && this.world.centroids[cc]; if (c) return { lat: LAT_TOP - c[1] / WORLD_H * (LAT_TOP - LAT_BOT), lon: c[0] / WORLD_W * 360 - 180 }; return null; }; // ev: an event as sent by the server ({cat, host, src, dst, cc}); returns whether it can be drawn M.spawnEvent = function (ev, o) { var vis = !!(o && o.visit); if (!this.alive || !ev || (!vis && !CAT_OK[ev.cat])) return false; var org = this.originOf(ev); if (!org) return false; var host = str(ev.host, 64) || 'local'; var d = this.destFor(host, ev.dst && typeof ev.dst === 'object' ? ev.dst : null); var hl = !vis && (!!(o && o.highlight) || !!HOSTILE[ev.cat]); if (this.paused || this.hidden) return true; if (vis) { if (this.reduced) return true; if (this.vpending.length >= MAX_VPENDING) this.vpending.shift(); this.vpending.push({ o: org, d: d, cat: 'visit', hl: false, v: true }); this.kick(); return true; } if (this.reduced) { this.dots.push({ lat: org.lat, lon: org.lon, v: vec(org.lat, org.lon), cat: ev.cat }); if (this.dots.length > 160) this.dots.shift(); this.dirty = true; this.kick(); return true; } if (this.pending.length >= MAX_PENDING) { var drop = this.pending.length - 300; this.pending.splice(0, drop); this.addMore(drop); } this.pending.push({ o: org, d: d, cat: ev.cat, hl: hl }); this.kick(); return true; }; M.onPick = function (cb) { if (typeof cb === 'function') this.pickCbs.push(cb); }; M.destScreen = function (d) { if (this.m > 0.5) { this.prepGlobe(this.m); this.rot(d.v[0], d.v[1], d.v[2]); return this.rz > 0.05 ? [this.cx + this.rx * this.gR, this.cy - this.ry * this.gR] : null; } return [this.ox + d.u0 * this.mw, this.oy + d.v0 * this.mh]; }; M.onClick = function (e) { if (this.moved > 5 || !this.pickCbs.length) return; var r = this.cv.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top, best = null, bd = 18 * 18; for (var i = 0; i < this.destList.length; i++) { var p = this.destScreen(this.destList[i]); if (!p) continue; var dd = (p[0] - x) * (p[0] - x) + (p[1] - y) * (p[1] - y); if (dd < bd) { bd = dd; best = this.destList[i]; } } if (best) { var info = { host: best.host, lat: best.lat, lon: best.lon, label: best.label }; this.pickCbs.slice().forEach(function (cb) { cb(info); }); } }; M.resize = function () { if (!this.alive) return; var r = this.container.getBoundingClientRect(); var w = Math.round(r.width), h = Math.round(r.height); if (w < 40 || h < 40) { this.noSize = true; return; } // hidden or not laid out yet: wait for the ResizeObserver this.noSize = false; var dpr = Math.min(window.devicePixelRatio || 1, 2); 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 pad = w < 560 ? 6 : 12; var availH = Math.max(60, h - pad * 2), availW = w - pad * 2; 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 = (h - this.mh) / 2; this.cx = w / 2; this.cy = h / 2; this.R = Math.max(40, Math.min(availW / 2 - 6, availH / 2 - 8)); this.cacheKey = ''; this.dirty = true; this.kick(); }; M.onDown = function (e) { this.moved = 0; 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'); }; M.onMove = function (e) { if (!this.dragging) return; var k = 57.3 / this.R, dx = e.clientX - this.px, dy = e.clientY - this.py; this.moved += Math.abs(dx) + Math.abs(dy); 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(); }; M.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(); }; M.onVisibility = function () { this.hidden = document.hidden; if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; this.vpending.length = 0; } else { this.last = 0; this.dirty = true; this.kick(); } }; // the public face of the map function mapApi(map) { return { spawn: function (ev, o) { return map.spawnEvent(ev, o); }, setDests: function (l) { map.setDests(l); }, setMode: function (m) { map.setMode(m); }, setTheme: function () { map.setTheme(); }, pause: function (b) { map.pause(b); }, clear: function () { map.clear(); }, resize: function () { map.resize(); }, destroy: function () { map.destroy(); }, onPick: function (cb) { map.onPick(cb); }, onMore: function (cb) { map.moreCb = typeof cb === 'function' ? cb : null; }, hasEstimatedDest: function () { return map.hasEstimatedDest(); }, getMode: function () { return map.mode; }, _map: map }; } M.buildFlatCache = function () { if (this.mw < 4 || this.mh < 4) return; 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(); } }; M.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(); } }; M.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); }; M.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([]); } }; M.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(); } }; M.drawFlatLayer = function (g, layerAlpha, add) { var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.ordered(), i; g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs var dd = this.dots[i]; 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 = a.visit ? this.colors.visit : this.colors[a.cat]; var x0 = ox + a.u0 * mw, y0 = oy + a.v0 * mh, x1 = ox + a.dest.u0 * mw, y1 = oy + a.dest.v0 * mh; var dx = x1 - x0, dy = y1 - y0, dist = Math.sqrt(dx * dx + dy * dy); var cx = (x0 + x1) / 2, cy = (y0 + y1) / 2 - Math.min(dist * 0.42, mh * 0.5) - 4; var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); var fade = layerAlpha * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1); if (tail < 1 && head > tail) { // exact sub-curve of the quadratic Bezier between parameters tail..head var ut = 1 - tail, uh = 1 - head; 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.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); g.stroke(); if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(bx, by, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); } } if (age < 0.7 && !a.visit) { g.globalAlpha = layerAlpha * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; g.beginPath(); g.arc(x0, y0, 2 + age * 9, 0, TAU); g.stroke(); } if (!a.visit) this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha); } g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.destList.length; i++) { 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 M.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) M.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. M.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(); } }; M.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(); }; M.drawGlobeLayer = function (g, m, add) { var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.ordered(), i, k; g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.dots.length; i++) { var dd = this.dots[i]; 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 = a.visit ? this.colors.visit : this.colors[a.cat]; var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); var fade = m * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1); var A = a.a, B = a.b, w = a.w, sw = Math.sin(w); if (tail < 1 && head > tail) { var lift = 0.05 + 0.22 * w / Math.PI; 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.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); g.stroke(); if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(lx, ly, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); } } } if (age >= a.D && !a.visit) { this.rot(B[0], B[1], B[2]); if (this.rz > 0.02) this.drawPulse(g, cx + this.rx * R, cy - this.ry * R, a, age, col, Math.atan2(-this.ry, this.rx), this.rz, m); } if (age < 0.7 && !a.visit) { this.rot(A[0], A[1], A[2]); if (this.rz > 0.02) { g.globalAlpha = m * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; 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); } }; M.draw = function () { if (!this.alive || this.noSize || this.W < 40 || this.mw < 4 || this.mh < 4) return; 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; if (this.flatCache && this.flatCache.width > 0 && this.flatCache.height > 0) 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'; }; M.spawn = function (it) { var a = this.free.pop() || {}; var o = it.o, d = it.d, hostile = !!it.hl; a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; a.visit = !!it.v; a.born = this.T; a.u0 = (o.lon + 180) / 360; a.v0 = (LAT_TOP - clamp(o.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT); a.a = vec(o.lat, o.lon); a.b = d.v; 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; if (a.visit) { a.D = 0.75; a.hold = 0; a.pl = 0.1; } a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D); (a.visit ? this.varcs : this.arcs).push(a); return a; }; M.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); }; // legitimate visits: their own queue and cap, always drawn under the attacks M.stepVisits = function () { var q = this.vpending, n = 0, budget = q.length > 60 ? 30 : 8; while (q.length && n < budget && this.varcs.length < Math.round(MAX_VARCS * this.quality)) { this.spawn(q.shift()); n++; } }; M.ordered = function () { var o = this.order || (this.order = []), i, j = 0; for (i = 0; i < this.varcs.length; i++) o[j++] = this.varcs[i]; for (i = 0; i < this.arcs.length; i++) o[j++] = this.arcs[i]; o.length = j; return o; }; M.addMore = function (n) { var s = Math.floor(Date.now() / 1000), m = this.more; if (m.length && m[m.length - 1][0] === s) m[m.length - 1][1] += n; else m.push([s, n]); while (m.length && m[0][0] < s - 10) m.shift(); if (this.moreCb) this.moreCb(n); }; M.kick = function () { var self = this; if (!this.alive || this.raf || this.hidden) return; this.raf = requestAnimationFrame(function (now) { self.frame(now); }); }; M.frame = function (now) { this.raf = 0; if (!this.alive || this.hidden || this.noSize) 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(); this.stepVisits(); } var df = this.target - this.m, morph = false; if (Math.abs(df) > 0.003) { this.m += df * (this.reduced ? 1 : Math.min(1, dt * 6.5)); morph = true; } else this.m = this.target; 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; } } if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle this.dirty = false; this.draw(); var lists = [this.arcs, this.varcs]; for (var li = 0; li < 2; li++) { var arcs = lists[li]; for (var i = arcs.length - 1; i >= 0; i--) { if (this.T - arcs[i].born > arcs[i].life) { this.free.push(arcs[i]); arcs[i] = arcs[arcs.length - 1]; arcs.pop(); } } } if (!still || morph || this.dirty) this.kick(); }; // ------------------------------------------------------------------ the Live page var inst = null; function boot() { var U = window.Urutau; if (!U || !U.registerPage) return false; U.registerI18n({ en: { 'live.title': 'Live', 'live.visits': 'Legitimate traffic', 'live.visit': 'visit', 'live.legend.visits': 'visits', 'live.m.vis': 'Visitors, 1 h', 'live.m.pages': 'Pages viewed, 1 h', 'live.unit.pages': 'distinct pages', 'live.sub.vis': '{n} requests', 'live.sub.top': 'top: {x}', 'live.devices': 'Devices', 'live.vis.empty': 'anonymous', '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.hide': 'Hide the panels', 'live.show': 'Show the panels', 'live.hosts': 'Servers', 'live.cats': 'Categories (15 min)', 'live.countries': 'Origins (15 min)', 'live.countries1h': 'Origins (1 h, none in 15 min)', 'live.noorigin': 'No origins in the last 15 min', 'live.recent': 'Latest events', 'live.empty': 'No events yet.', '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', 'live.filtered': 'filter active', 'live.drag': 'Drag to rotate', 'live.m.15m': 'Last 15 min', 'live.m.1h': 'Last hour', 'live.m.avg': 'Hourly avg, 24 h', 'live.m.ips': 'Distinct IPs, 1 h', 'live.m.new': 'New IPs, 1 h', 'live.m.last': 'Last event', 'live.vs': '{p} vs prev. h', 'live.vsfull': 'Change versus the previous hour', 'live.above': 'above normal', 'live.below': 'below normal', 'live.normal': 'normal', 'live.perhour': 'events / hour', 'live.events': 'events', 'live.unit.ips': 'addresses', 'live.none': 'none yet' }, 'pt-BR': { 'live.title': 'Ao vivo', 'live.visits': 'Tráfego legítimo', 'live.visit': 'visita', 'live.legend.visits': 'visitas', 'live.m.vis': 'Visitantes, 1 h', 'live.m.pages': 'Páginas vistas, 1 h', 'live.unit.pages': 'páginas distintas', 'live.sub.vis': '{n} requisições', 'live.sub.top': 'mais: {x}', 'live.vis.empty': 'anônima', 'live.devices': 'Dispositivos', '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.hide': 'Ocultar os painéis', 'live.show': 'Mostrar os painéis', 'live.hosts': 'Servidores', 'live.cats': 'Categorias (15 min)', 'live.countries': 'Origens (15 min)', 'live.countries1h': 'Origens (1 h, nenhuma em 15 min)', 'live.noorigin': 'Nenhuma origem nos últimos 15 min', 'live.recent': 'Últimos eventos', 'live.empty': 'Nenhum evento ainda.', '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', 'live.filtered': 'filtro ativo', 'live.drag': 'Arraste para girar', 'live.m.15m': 'Últimos 15 min', 'live.m.1h': 'Última hora', 'live.m.avg': 'Média/h, 24 h', 'live.m.ips': 'IPs distintos, 1 h', 'live.m.new': 'IPs novos, 1 h', 'live.m.last': 'Último evento', 'live.vs': '{p} vs h. ant.', 'live.vsfull': 'Variação em relação à hora anterior', 'live.above': 'acima do normal', 'live.below': 'abaixo do normal', 'live.normal': 'normal', 'live.perhour': 'eventos / hora', 'live.events': 'eventos', 'live.unit.ips': 'endereços', 'live.none': 'nenhum ainda' } }); U.createAttackMap = function (container, opts) { return mapApi(new AttackMap(U, container, opts)); }; U.registerPage({ id: 'live', icon: '', 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; } 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 = this.ctx.lang || ''; this.paused = false; this.hidden = document.hidden; this.offCats = {}; this.offHosts = {}; this.ring = []; this.hostsSeen = {}; this.hostChips = {}; this.bk = {}; // minute -> { host -> { n, cat:{}, cc:{ cc: { n, city:{} } } } } this.ipLast = new Map(); this.ipFirst = new Map(); this.firstMin = 0; this.back = null; this.backAt = 0; this.noMetrics = false; this.noMetricsAt = 0; this.minute = -1; this.listDirty = true; this.hoverList = false; this.more = []; this.listeners = []; this.timers = []; this.dn = null; this.dnLang = ''; this.lastEv = null; this.visitsOn = false; this.es = null; this.vring = []; this.vbk = {}; this.pathLast = new Map(); this.devs = {}; this.devChips = {}; this.offDev = {}; this.seen = {}; this.seenN = 0; try { this.visitsOn = localStorage.getItem('urutau.live.visits') === '1'; } catch (x) { /* storage blocked */ } this.build(); this.map = mapApi(new AttackMap(U, this.mapBox, { mode: this.pref(), interactive: true })); this.map.onMore(function (n) { self.addMore(n); }); this.map.onPick(function (d) { self.toggleHost(d.host); }); this.syncMode(this.pref()); this.applyVisits(); this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null; this.listen(document, 'visibilitychange', function () { self.onVisibility(); }); this.listen(document, 'fullscreenchange', function () { self.onFullscreen(); }); if (window.matchMedia) { var mqw = matchMedia('(min-width: 1200px)'); if (mqw.addEventListener) this.listen(mqw, 'change', function () { self.placeRec(); self.map._map.resize(); }); } this.timers.push(setInterval(function () { self.tick(); }, 1000)); this.timers.push(setInterval(function () { self.loadSummary(); self.loadMetrics(); }, 60000)); this.timers.push(setInterval(function () { self.loadTraffic(); }, 30000)); this.loadSummary(); this.loadMetrics(); this.loadRecent(); this.loadTraffic(); this.tick(true); } var P = Live.prototype; P.pref = function () { var v = ''; try { v = localStorage.getItem('urutau.live.mode') || ''; } catch (x) { /* storage blocked */ } if (v === 'globe' || v === 'flat') return v; return (this.root.clientWidth || window.innerWidth) < 560 ? 'globe' : 'flat'; }; 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.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; } this.closeStream(); this.timers.forEach(clearInterval); this.timers = []; this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } }); this.listeners = []; if (document.fullscreenElement === this.stage && document.exitFullscreen) { try { document.exitFullscreen(); } catch (x) { /* ignore */ } } if (this.map) this.map.destroy(); this.map = null; this.ring = []; this.bk = {}; this.ipLast.clear(); this.ipFirst.clear(); 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.map.setTheme(); this.minute = -1; this.listDirty = true; this.tick(true); }; // language changed: rebuild the DOM keeping the map, the filters and the paused state P.rebuild = function () { var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused, devs = Object.keys(this.devs); this.hostsSeen = {}; this.hostChips = {}; this.devChips = {}; this.devs = {}; var mapEl = this.map._map.cv, was = this.stage.classList.contains('lv-nopanels'); this.build(); this.mapBox.appendChild(mapEl); this.map._map.container = this.mapBox; if (this.map._map.ro) { this.map._map.ro.disconnect(); this.map._map.ro.observe(this.mapBox); } hosts.forEach(function (h) { self.noteHost(h); }); devs.forEach(function (d) { self.noteDevice(d); }); this.applyVisits(); this.stage.classList.toggle('lv-nopanels', was); this.syncMode(this.map.getMode()); if (paused) this.setPaused(true); this.dn = null; this.filtersChanged(); this.map.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 lv-icon ' + 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) { var c = this.el('section', 'lv-card ' + cls); c.appendChild(this.el('h2', 'lv-card-t', this.t(titleKey))); c.body = this.el('div', 'lv-card-b'); c.appendChild(c.body); return c; }; P.metric = function (key) { var c = this.el('div', 'lv-metric'); c.appendChild(this.el('div', 'lv-m-label', this.t('live.m.' + key))); c.val = this.el('div', 'lv-m-value', '-'); c.appendChild(c.val); c.sub = this.el('div', 'lv-m-sub', ''); c.appendChild(c.sub); 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 stage = el('div', 'lv'); this.stage = stage; // top bar: view, controls, server filter chips, notes 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); var ctl = el('div', 'lv-ctl'); 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.hide'), 'M4 6h16M4 12h16M4 18h16', function () { var off = !self.stage.classList.contains('lv-nopanels'); self.stage.classList.toggle('lv-nopanels', off); var lab = t(off ? 'live.show' : 'live.hide'); self.bPan.setAttribute('aria-label', lab); self.bPan.title = lab; self.bPan.setAttribute('aria-pressed', off ? 'true' : 'false'); self.map._map.resize(); }); this.bPan.setAttribute('aria-pressed', 'false'); ctl.appendChild(this.bPause); ctl.appendChild(this.bPan); this.bFs = null; 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'); ctl.appendChild(this.bFs); } this.bVis = document.createElement('button'); this.bVis.type = 'button'; this.bVis.className = 'lv-btn lv-vis'; this.bVis.appendChild(this.el('span', 'lv-vis-dot')); this.bVis.appendChild(this.el('span', '', t('live.visits'))); this.bVis.addEventListener('click', function () { self.setVisits(!self.visitsOn); }); ctl.appendChild(this.bVis); bar.appendChild(ctl); this.hostBox = el('div', 'lv-hosts'); this.hostBox.setAttribute('role', 'group'); this.hostBox.setAttribute('aria-label', t('live.hosts')); bar.appendChild(this.hostBox); this.devBox = el('div', 'lv-hosts lv-devs'); this.devBox.setAttribute('role', 'group'); this.devBox.setAttribute('aria-label', t('live.devices')); bar.appendChild(this.devBox); var notes = el('div', 'lv-notes'); this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.hidden = true; this.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true; this.nMore = el('span', 'lv-note', ''); this.nMore.hidden = true; this.nEst = el('span', 'lv-note', t('live.est')); this.nEst.hidden = true; this.nLeg = el('span', 'lv-note lv-leg'); this.nLeg.appendChild(el('span', 'lv-leg-sw')); this.nLeg.appendChild(el('span', '', t('live.legend.visits'))); [this.nPaused, this.nFilter, this.nMore, this.nEst, this.nLeg].forEach(function (n) { notes.appendChild(n); }); bar.appendChild(notes); stage.appendChild(bar); var main = el('div', 'lv-main'); var mapwrap = el('div', 'lv-mapwrap'); this.mapBox = el('div', 'lv-map'); mapwrap.appendChild(this.mapBox); this.hint = el('div', 'lv-hint', t('live.drag')); mapwrap.appendChild(this.hint); var left = el('div', 'lv-left'); this.left = left; left.appendChild(mapwrap); main.appendChild(left); var side = el('div', 'lv-side'); this.side = side; var mets = el('div', 'lv-metrics'); this.mM = {}; ['15m', '1h', 'avg', 'ips', 'new', 'last', 'vis', 'pages'].forEach(function (k) { self.mM[k] = self.metric(k); if (k === 'vis' || k === 'pages') self.mM[k].classList.add('lv-m-visit'); mets.appendChild(self.mM[k]); }); this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true'); this.spark.width = 150; this.spark.height = 32; this.mM['15m'].appendChild(this.spark); side.appendChild(mets); var cCats = this.card('lv-c-cats', 'live.cats'); this.catBox = el('div', 'lv-list'); this.catRows = {}; CATS.forEach(function (c) { var b = document.createElement('button'); b.type = 'button'; b.className = 'lv-row lv-k-' + c + (HOSTILE[c] ? ' lv-hot' : ''); b.setAttribute('aria-pressed', self.offCats[c] ? 'false' : 'true'); var bar2 = el('span', 'lv-row-bar'); b.appendChild(bar2); b.bar = bar2; b.appendChild(el('span', 'lv-sw')); b.appendChild(el('span', 'lv-row-l', t('cat.' + c))); var n = el('span', 'lv-row-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.catRows[c] = b; }); cCats.body.appendChild(this.catBox); side.appendChild(cCats); var cCty = this.card('lv-c-cty', 'live.countries'); this.ctyTitle = cCty.firstChild; this.ctyList = el('ol', 'lv-list lv-cty'); cCty.body.appendChild(this.ctyList); side.appendChild(cCty); var cRec = this.card('lv-c-rec', 'live.recent'); 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); this.cRec = cRec; side.appendChild(cRec); main.appendChild(side); stage.appendChild(main); root.appendChild(stage); this.updateModeButtons(this.map ? this.map.getMode() : 'flat'); }; P.updateModeButtons = function (m) { this.segFlat.setAttribute('aria-pressed', m === 'flat' ? 'true' : 'false'); this.segGlobe.setAttribute('aria-pressed', m === 'globe' ? 'true' : 'false'); this.hint.hidden = m !== 'globe'; }; // desktop, flat map: the latest events go under the map; otherwise they close the side column P.placeRec = function () { if (!this.cRec) return; var wide = window.matchMedia && matchMedia('(min-width: 1200px)').matches; var left = wide && this.map && this.map.getMode() === 'flat'; var to = left ? this.left : this.side; if (this.cRec.parentNode !== to) to.appendChild(this.cRec); this.stage.classList.toggle('lv-rec-left', !!left); }; P.syncMode = function (m) { this.map.setMode(m); this.updateModeButtons(m); this.stage.classList.toggle('lv-isflat', m === 'flat'); this.placeRec(); this.map._map.resize(); }; P.setMode = function (m) { try { localStorage.setItem('urutau.live.mode', m); } catch (x) { /* storage blocked */ } this.syncMode(m); }; 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; this.map.pause(p); }; 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.map.resize(); }; // ---- legitimate traffic (anonymous visits): its own stream, only while the option is on P.setVisits = function (on) { this.visitsOn = on; try { localStorage.setItem('urutau.live.visits', on ? '1' : '0'); } catch (x) { /* storage blocked */ } this.applyVisits(); this.minute = -1; this.listDirty = true; this.tick(true); }; P.applyVisits = function () { var on = this.visitsOn; this.bVis.setAttribute('aria-pressed', on ? 'true' : 'false'); this.stage.classList.toggle('lv-vis-on', on); if (on) this.openStream(); else { this.closeStream(); this.vring = []; this.map.clear(); } this.map._map.resize(); }; P.openStream = function () { var self = this; if (this.es || !window.EventSource) return; var es = new EventSource('/api/v1/events/stream?visits=1'); es.addEventListener('ev', function (m) { var e; try { e = JSON.parse(m.data); } catch (x) { return; } if (!e || typeof e !== 'object') return; if (e.kind === 'visit') self.visit(e); else if (e.kind === 'visit_batch') self.visitBatch(e); else self.ingest(e); }); this.es = es; }; P.closeStream = function () { if (this.es) { this.es.close(); this.es = null; } }; P.noteDevice = function (d) { if (!d || this.devs[d] || Object.keys(this.devs).length >= 8) return; var self = this; this.devs[d] = 1; var b = document.createElement('button'); b.type = 'button'; b.className = 'lv-chip'; b.setAttribute('aria-pressed', this.offDev[d] ? 'false' : 'true'); b.appendChild(this.el('span', 'lv-chip-l', d)); b.addEventListener('click', function () { self.offDev[d] = !self.offDev[d]; b.setAttribute('aria-pressed', self.offDev[d] ? 'false' : 'true'); self.listDirty = true; }); this.devBox.appendChild(b); this.devChips[d] = b; }; P.vcount = function (n, t, dev, path) { var m = Math.floor(t / 60), b = this.vbk[m] || (this.vbk[m] = { n: 0 }); b.n += n; if (path && (this.pathLast.size < 5000 || this.pathLast.has(path))) this.pathLast.set(path, m); }; P.visit = function (e) { var s = e.src && typeof e.src === 'object' ? e.src : null, tsec = isNum(e.t) ? e.t : Date.now() / 1000; var dev = str(e.device, 16), path = str(e.path, 90); var r = { visit: true, t: tsec, host: str(e.host, 64) || 'local', city: str(s && s.city, 48), cc: cc2(s && s.cc) || cc2(e.cc), domain: str(e.domain, 60), path: path, device: dev, ev: e }; this.noteHost(r.host); if (dev) this.noteDevice(dev); this.vcount(1, tsec, dev, path); this.vring.push(r); if (this.vring.length > 200) this.vring.splice(0, 80); this.listDirty = true; if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return; var h = this.ctx && this.ctx.host; if (h && h !== 'all' && h !== r.host) return; this.map.spawn(e, { visit: true }); }; P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); }; P.toggleHost = function (h) { if (!this.hostChips[h]) return; this.offHosts[h] = !this.offHosts[h]; this.hostChips[h].setAttribute('aria-pressed', this.offHosts[h] ? 'false' : 'true'); this.filtersChanged(); }; 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.minute = -1; this.tick(true); }; P.onVisibility = function () { this.hidden = document.hidden; if (!this.hidden) { this.loadSummary(); this.loadMetrics(); this.loadTraffic(); this.tick(true); } }; 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(); }; // ------------------------------------------------------------------ data 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'; 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.toggleHost(h); }); this.hostBox.appendChild(b); this.hostChips[h] = b; }; 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, have); if (r) seed.push(r); }); // the latest events play back as arcs, whatever their age and spread over ~20 s, // so the map never opens still on a quiet server var replay = seed.slice(-40), id = setInterval(function () { if (!self.alive || !replay.length) { clearInterval(id); return; } if (!self.paused && !self.hidden) self.draw(replay.shift()); }, 500); self.timers.push(id); self.ring.sort(function (a, b) { return a.t - b.t; }); self.listDirty = true; self.minute = -1; 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) return; var dests = []; (Array.isArray(s.hosts) ? 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)) dests.push({ host: name, lat: l.lat, lon: l.lon, label: str(l.label, 48) }); }); if (dests.length) self.map.setDests(dests); var r = s.rates; if (r && typeof r === 'object') { var b = self.back || (self.back = {}); var n15 = metricOf(r.last15m), n1 = metricOf(r.last1h); if (n15) b.m15 = n15; if (n1) { n1.prev = isNum(r.prev_period) ? r.prev_period : null; n1.delta = isNum(r.change_pct) ? r.change_pct : null; b.h1 = n1; } var a24 = metricOf(r.per_hour_avg_24h), a7 = metricOf(r.per_hour_avg_7d), ac = metricOf(r.active_attackers), na = metricOf(r.new_attackers); if (a24) b.avg = a24; if (a7) b.norm = a7; if (ac) b.ips = ac; if (na) b.nw = na; self.backAt = Date.now(); self.minute = -1; self.tick(true); } }).catch(function () { /* summary unavailable: keep what the events tell */ }); }; function metricOf(x) { if (isNum(x)) return { value: x }; if (x && typeof x === 'object' && isNum(x.value)) return { value: x.value, prev: isNum(x.prev) ? x.prev : null, delta: isNum(x.delta_pct) ? x.delta_pct : null, spark: Array.isArray(x.spark) ? x.spark : null }; return null; } P.loadMetrics = function () { var self = this; if (!this.U.api || this.hidden) return; if (this.noMetrics && Date.now() - this.noMetricsAt < 300000) return; var p; try { p = this.U.api('/api/v1/metrics', { range: '24h', host: 'all' }); } catch (x) { return; } if (!p || !p.then) return; p.then(function (m) { if (!self.alive || !m || typeof m !== 'object') return; self.noMetrics = false; var b = self.back || (self.back = {}); var set = function (k, v) { if (v) b[k] = v; }; set('avg', metricOf(m.attacks_per_hour_24h)); set('norm', metricOf(m.moving_avg_7d_per_hour)); set('ips', metricOf(m.active_attackers_1h)); set('nw', metricOf(m.new_attackers)); self.backAt = Date.now(); self.minute = -1; self.tick(true); }).catch(function () { self.noMetrics = true; self.noMetricsAt = Date.now(); }); }; // normalises one event into a ring entry and the minute buckets; null for events that are not attacks P.record = function (e, 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; } else if (this.es) { if (this.seen[key]) return null; this.seen[key] = 1; if (++this.seenN > 3000) { this.seen = {}; this.seenN = 0; } } var r = { t: tsec, key: key, cat: e.cat, host: host, ip: ip, what: what, cc: cc2(s && s.cc) || cc2(e.cc), city: str(s && s.city, 48), ev: e }; this.noteHost(host); this.ring.push(r); if (this.ring.length > RING_MAX) this.ring.splice(0, RING_TRIM); this.count(r); this.listDirty = true; return r; }; P.count = function (r) { var m = Math.floor(r.t / 60), b = this.bk[m] || (this.bk[m] = {}); var h = b[r.host] || (b[r.host] = { n: 0, cat: {}, cc: {} }); h.n++; h.cat[r.cat] = (h.cat[r.cat] || 0) + 1; if (r.cc) { var c = h.cc[r.cc] || (h.cc[r.cc] = { n: 0, city: {} }); c.n++; if (r.city && (c.city[r.city] || Object.keys(c.city).length < 24)) c.city[r.city] = (c.city[r.city] || 0) + 1; } if (!this.firstMin || m < this.firstMin) this.firstMin = m; if (r.ip) { if (this.ipLast.size < 60000 || this.ipLast.has(r.ip)) { if (!this.ipLast.has(r.ip)) this.ipFirst.set(r.ip, m); if ((this.ipLast.get(r.ip) || 0) < m) this.ipLast.set(r.ip, m); } } }; P.ingest = function (e) { if (!this.alive) return; var r = this.record(e, null); if (!r || this.paused || this.hidden) return; this.draw(r); }; P.draw = function (r) { if (this.offCats[r.cat] || this.offHosts[r.host]) return; var h = this.ctx && this.ctx.host; if (h && h !== 'all' && h !== r.host) return; this.map.spawn(r.ev); }; 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; }; // ------------------------------------------------------------------ panels and metrics P.hostOk = function (h) { if (this.offHosts[h]) return false; var c = this.ctx && this.ctx.host; return !c || c === 'all' || c === h; }; // sums the minute buckets from..to (inclusive) over the visible hosts (or all of them) P.agg = function (from, to, allHosts) { var out = { n: 0, cat: {}, host: {}, cc: {} }, m, h, b, hb, k; for (m = from; m <= to; m++) { b = this.bk[m]; if (!b) continue; for (h in b) { hb = b[h]; out.host[h] = (out.host[h] || 0) + hb.n; if (!allHosts && !this.hostOk(h)) continue; out.n += hb.n; for (k in hb.cat) out.cat[k] = (out.cat[k] || 0) + hb.cat[k]; for (k in hb.cc) { var c = out.cc[k] || (out.cc[k] = { n: 0, city: {} }), src = hb.cc[k], ci; c.n += src.n; for (ci in src.city) c.city[ci] = (c.city[ci] || 0) + src.city[ci]; } } } return out; }; P.pct = function (x) { return (x >= 0 ? '+' : '-') + Math.abs(Math.round(x)) + '%'; }; P.setSub = function (card, text, tone) { card.sub.textContent = text; card.sub.title = card.sub.className.indexOf('lv-m-sub') >= 0 && card === this.mM['1h'] && text.indexOf('vs') > 0 ? this.t('live.vsfull') : ''; card.sub.className = 'lv-m-sub' + (tone ? ' lv-' + tone : ''); }; // the headline numbers: they only change when the minute turns (or new data arrives) P.computeMetrics = function (min, fmtN) { var self = this, mm = this.mM; var useBack = this.back && this.ctx && (!this.ctx.host || this.ctx.host === 'all') && !Object.keys(this.offHosts).some(function (k) { return self.offHosts[k]; }); var b = useBack ? this.back : null; // 15 minutes: the last 15 complete minutes, aligned to the clock var a15 = this.agg(min - 15, min - 1, false), bins = [], i; for (i = min - 15; i < min; i++) { var one = this.agg(i, i, false); bins.push(one.n); } var v15 = b && b.m15 ? b.m15.value : a15.n; if (b && b.m15 && b.m15.spark && b.m15.spark.length >= 15) bins = b.m15.spark.slice(-15); mm['15m'].val.textContent = fmtN(v15); this.setSub(mm['15m'], this.t('live.events'), ''); this.drawSpark(bins); // last hour versus the hour before var h1 = this.agg(min - 60, min - 1, false).n, hp = this.agg(min - 120, min - 61, false).n; var cover = this.firstMin && this.firstMin <= min - 119; var v1 = b && b.h1 ? b.h1.value : h1, prev = b && b.h1 && b.h1.prev !== null && b.h1.prev !== undefined ? b.h1.prev : (cover ? hp : null); var dp = b && b.h1 && b.h1.delta !== null && b.h1.delta !== undefined ? b.h1.delta : (prev ? (v1 - prev) / prev * 100 : null); mm['1h'].val.textContent = fmtN(v1); if (dp === null || !isFinite(dp)) this.setSub(mm['1h'], this.t('live.events'), ''); else this.setSub(mm['1h'], (dp >= 0 ? '\u25B2' : '\u25BC') + this.t('live.vs', { p: this.pct(dp).replace(/^[+-]/, '') }), Math.abs(dp) >= 20 ? (dp > 0 ? 'up' : 'down') : ''); // hourly average over 24 h against the normal (7 day average) var avg = b && b.avg ? b.avg.value : null; if (avg === null) { var span = this.firstMin ? Math.min(1440, min - this.firstMin) : 0; if (span >= 60) avg = this.agg(min - span, min - 1, false).n / (span / 60); } if (avg === null) { mm.avg.val.textContent = '-'; this.setSub(mm.avg, this.t('live.perhour'), ''); } else { mm.avg.val.textContent = fmtN(Math.round(avg)); var norm = b && b.norm ? b.norm.value : null; // what the user sees side by side: the last hour against the hourly average if (avg > 0) { var ratio = v1 / avg; this.setSub(mm.avg, this.t(ratio >= 1.5 ? 'live.above' : ratio < 0.8 ? 'live.below' : 'live.normal'), ratio >= 1.5 ? 'up' : ''); } else this.setSub(mm.avg, this.t('live.perhour'), ''); } // addresses: distinct in the last hour, and the ones never seen before var ips = 0, nw = 0; this.ipLast.forEach(function (last) { if (last >= min - 60) ips++; }); this.ipFirst.forEach(function (first, ip) { if (first >= min - 60 && self.firstMin && self.firstMin <= min - 60) nw++; }); mm.ips.val.textContent = fmtN(b && b.ips ? b.ips.value : ips); this.setSub(mm.ips, this.t('live.unit.ips'), ''); if (b && b.nw) mm.new.val.textContent = fmtN(b.nw.value); else mm.new.val.textContent = this.firstMin && this.firstMin <= min - 60 ? fmtN(nw) : '-'; this.setSub(mm.new, this.t('live.unit.ips'), ''); // prune what is no longer needed if (this.ipLast.size > 0) { this.ipLast.forEach(function (last, ip) { if (last < min - 130) { self.ipLast.delete(ip); self.ipFirst.delete(ip); } }); } for (var k in this.bk) if (+k < min - 1500) delete this.bk[k]; }; // legitimate traffic: totals of the last hour from /api/v1/traffic (the server has no 15 min range), // refreshed every 30 s whether or not the "Legitimate traffic" toggle is on (it only controls the drawing) P.loadTraffic = function () { var self = this; if (!this.U.api || this.hidden) return; var h = this.ctx && this.ctx.host, q = { range: '1h' }; if (h && h !== 'all') q.host = h; var key = q.host || 'all', p; try { p = this.U.api('/api/v1/traffic', q); } catch (x) { return; } if (!p || !p.then) return; p.then(function (d) { if (!self.alive || !d || typeof d !== 'object') return; var top = function (l) { return Array.isArray(l) && l[0] && l[0].key ? l[0] : null; }; self.traf = { key: key, visitors: isNum(d.visitors) ? d.visitors : null, pages: isNum(d.pages) ? d.pages : null, requests: isNum(d.requests) ? d.requests : null, dom: top(d.domains), cc: top(d.countries) }; self.minute = -1; self.tick(true); }).catch(function () { /* traffic unavailable */ }); }; P.visitMetrics = function (min, fmtN) { var mm = this.mM, d = this.traf, h = this.ctx && this.ctx.host; if (!d || d.key !== (h && h !== 'all' ? h : 'all')) { mm.vis.val.textContent = '-'; mm.pages.val.textContent = '-'; return; } mm.vis.val.textContent = d.visitors === null ? '-' : fmtN(d.visitors); this.setSub(mm.vis, d.requests === null ? this.t('live.legend.visits') : this.t('live.sub.vis', { n: fmtN(d.requests) }), ''); mm.pages.val.textContent = d.pages === null ? '-' : fmtN(d.pages); var x = d.dom ? str(d.dom.key, 40) : ''; if (d.cc && d.cc.key) x = (x ? x + ' · ' : '') + cc2(d.cc.key); this.setSub(mm.pages, x ? this.t('live.sub.top', { x: x }) : this.t('live.unit.pages'), ''); var pl = this.pathLast; for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk]; pl.forEach(function (last, p) { if (last < min - 30) pl.delete(p); }); }; 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 self = this, nowMs = Date.now(), min = Math.floor(nowMs / 60000); var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String; var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; }; if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); } this.visitMetrics(min, fmtN); // category and server counts, origins: the 15 minute window (partial minute included) var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c; CATS.forEach(function (k) { var n = a.cat[k] || 0; self.catRows[k].num.textContent = fmtN(n); self.catRows[k].bar.style.setProperty('--w', Math.round(n / Math.max(1, a.n) * 100) + '%'); }); Object.keys(this.hostChips).forEach(function (h) { self.hostChips[h].num.textContent = fmtN(a.host[h] || 0); }); var win1h = false; if (!Object.keys(vis.cc).length) { vis = this.agg(min - 59, min, false); win1h = Object.keys(vis.cc).length > 0; } this.ctyTitle.textContent = this.t(win1h ? 'live.countries1h' : 'live.countries'); var rows = Object.keys(vis.cc).filter(function () { return true; }).sort(function (x, y) { return vis.cc[y].n - vis.cc[x].n; }).slice(0, 8); var box = this.ctyList, max = rows.length ? vis.cc[rows[0]].n : 1; while (box.firstChild) box.removeChild(box.firstChild); if (!rows.length) box.appendChild(this.el('li', 'lv-empty', this.t('live.noorigin'))); rows.forEach(function (cc) { var row = vis.cc[cc], city = '', best = 0, k; for (k in row.city) if (row.city[k] > best) { best = row.city[k]; city = k; } var li = self.el('li', 'lv-row lv-cty-i'); var bar = self.el('span', 'lv-row-bar'); bar.style.setProperty('--w', Math.round(row.n / max * 100) + '%'); li.appendChild(bar); var nm = self.el('span', 'lv-row-l', fl(cc) + ' ' + self.regionName(cc)); if (city) nm.appendChild(self.el('span', 'lv-city', ' · ' + city)); li.appendChild(nm); li.appendChild(self.el('span', 'lv-row-n', fmtN(row.n))); box.appendChild(li); }); // last event var last = this.ring.length ? this.ring[this.ring.length - 1] : null; if (last && (!this.lastEv || this.lastEv.key !== last.key || force)) this.lastEv = last; var lm = this.mM.last; if (this.lastEv && this.U.fmt && this.U.fmt.ago) { lm.val.textContent = this.U.fmt.ago(this.lastEv.t); this.setSub(lm, this.lastEv.host, ''); } else { lm.val.textContent = '-'; this.setSub(lm, this.t('live.none'), ''); } var s = Math.floor(nowMs / 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', { n: fmtN(more) }); this.nEst.hidden = !this.map.hasEstimatedDest(); 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.map._map.pal.accent, bw = w / bins.length; for (i = 0; i < bins.length; i++) { var bh = bins[i] ? Math.max(4, bins[i] / max * (h - 2)) : 1.5; g.fillStyle = rgba(col, bins[i] ? 1 : 0.4); g.fillRect(i * bw + 1, h - bh, bw - 2.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); var merged = ring; if (this.visitsOn && this.vring.length) merged = ring.concat(this.vring).sort(function (a, b) { return a.t - b.t; }); for (i = merged.length - 1; i >= 0 && n < 30; i--) { r = merged[i]; if (r.visit) { if (!this.hostOk(r.host) || (r.device && this.offDev[r.device])) continue; n++; var vl = this.el('li', 'lv-ev lv-ev-visit'); vl.appendChild(this.el('time', 'lv-ev-t', new Date(r.t * 1000).toLocaleTimeString(this.ctx.lang || undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }))); vl.appendChild(this.el('span', 'lv-tag lv-k-visit', this.t('live.visit'))); vl.appendChild(this.el('span', 'lv-vtxt', [r.city || this.t('live.vis.empty'), r.domain, r.path, r.device].filter(Boolean).join(' \u00B7 '))); box.appendChild(vl); continue; } if (!this.visible(r)) continue; n++; var li = this.el('li', 'lv-ev'); 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 }); })();