/* Urutau dashboard shell, design-system primitives and core pages. * * Public API for page scripts loaded after this file (geo.js, live.js...). * Everything hangs from window.Urutau: * * Urutau.registerPage({ id, icon, titleKey, mount(el, ctx), update(ctx), unmount(), refresh? }) * Adds a page to the rail. Pages appear in this order: overview, threats, * geo, live, traffic, ips, sources (unknown ids go last). `icon` is an SVG * string (24x24 viewBox, stroke="currentColor"). `ctx` is * { range: '1h'|'24h'|'7d', host: 'all'|name, domain: 'all'|name, * theme: 'dark'|'light', lang: 'en'|'pt-BR' }. * update(ctx) runs when range, host, domain, theme or language change. * refresh() (optional) runs every 10 s while the page is open and the tab * is visible; do the cheap polling there, not in update. * The page renders inside `el` and must clean up in unmount(). * Urutau.registerI18n({ en: {...}, 'pt-BR': {...} }) merge keys (existing keys win) * Urutau.t(key, vars?) vars: a number (fills {n}) or an object ({name: ...}) * Urutau.api(path, params) -> Promise GET with query params; 401 goes to * /login, 429 and 5xx show the error banner and reject (err.status is set) * Urutau.onEvent(cb) -> unsubscribe one JSON event per SSE frame of * /api/v1/events/stream (the connection reconnects by itself) * Urutau.openIP(ip) opens the IP detail drawer * Urutau.fmt = { num(n), pct(x[, total]), ago(unixSeconds), bytes(n), flag(cc), * country(cc), clock(unixSeconds), date(unixSeconds) } * pct(x) takes a ratio (0.12 -> "12%"); pct(part, total) divides. * Urutau.world = { w, h, paths: {CC: 'svg path d'}, centroids: {CC: [x, y]} } * Urutau.el(tag, attrs, ...children) DOM builder that only ever uses * textContent / setAttribute (never innerHTML). attrs: class, text, style * (object, applied through CSSOM), dataset (object), onclick-style * function handlers, any other attribute as a string. SVG tags work. * Urutau.css(name) reads a design token, e.g. css('accent') or css('--cat-exploit') * Urutau.setSliceNote(text) optional extra words appended to the slice sentence * Urutau.ui = { panel, stat, lead, empty, badge, bars, chart } shared primitives * (the same ones the core pages use; see their definitions below) * * Security rule of this file: log data is hostile. Dynamic text goes through * textContent only, and class names come from whitelists. */ (function () { 'use strict'; var D = window.URUTAU_I18N; var $ = function (s, r) { return (r || document).querySelector(s); }; function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } } function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } } var lang = lsGet('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en'); if (!D[lang]) lang = 'en'; var themeSaved = lsGet('urutau.theme'); if (themeSaved === 'light' || themeSaved === 'dark') document.documentElement.setAttribute('data-theme', themeSaved); function t(key, vars) { var s = (D[lang] && D[lang][key]) || D.en[key] || key; if (vars === undefined || vars === null) return s; if (typeof vars !== 'object') vars = { n: vars }; return s.replace(/\{(\w+)\}/g, function (m, k) { return Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m; }); } // plural: picks key.one when count is 1, key.other otherwise function pl(key, count, vars) { vars = vars || {}; if (vars.n === undefined) vars.n = nf(count); return t(key + (count === 1 ? '.one' : '.other'), vars); } function registerI18n(dict) { Object.keys(dict || {}).forEach(function (l) { if (!D[l]) D[l] = {}; Object.keys(dict[l]).forEach(function (k) { if (!(k in D[l])) D[l][k] = dict[l][k]; }); }); } var nfCache = {}; function nfFor(opts, key) { var k = lang + '|' + key; if (!nfCache[k]) nfCache[k] = new Intl.NumberFormat(lang, opts); return nfCache[k]; } function nf(n) { return nfFor({}, 'plain').format(n); } function nfCompact(n) { return nfFor({ notation: 'compact', maximumFractionDigits: 1 }, 'compact').format(n); } function pct(a, b) { var r = b === undefined ? a : (b ? a / b : 0); if (!isFinite(r)) r = 0; return nfFor({ style: 'percent', maximumFractionDigits: r > 0 && r < 0.1 ? 1 : 0 }, 'pct' + (r > 0 && r < 0.1 ? 1 : 0)).format(r); } // ---------------------------------------------------------------- DOM builder var SVG_NS = 'http://www.w3.org/2000/svg'; var SVG_TAGS = {}; ['svg', 'g', 'path', 'line', 'rect', 'circle', 'ellipse', 'polyline', 'polygon', 'text', 'tspan', 'title', 'desc', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'use'].forEach(function (n) { SVG_TAGS[n] = 1; }); var PROPS = { value: 1, checked: 1, selected: 1, disabled: 1, hidden: 1, indeterminate: 1 }; function appendKids(node, kids) { for (var i = 0; i < kids.length; i++) { var c = kids[i]; if (c === null || c === undefined || c === false) continue; if (Array.isArray(c)) appendKids(node, c); else if (c instanceof Node) node.appendChild(c); else node.appendChild(document.createTextNode(String(c))); } } function el(tag, attrs) { var node = SVG_TAGS[tag] ? document.createElementNS(SVG_NS, tag) : document.createElement(tag); if (attrs) { Object.keys(attrs).forEach(function (k) { var v = attrs[k]; if (v === undefined || v === null || v === false) return; if (k === 'class' || k === 'className') node.setAttribute('class', String(v)); else if (k === 'text') node.textContent = String(v); else if (k === 'style') { if (typeof v === 'object') Object.keys(v).forEach(function (p) { if (p.indexOf('-') >= 0) node.style.setProperty(p, String(v[p])); else node.style[p] = v[p]; }); } else if (k === 'dataset') { if (typeof v === 'object') Object.keys(v).forEach(function (p) { node.setAttribute('data-' + p.replace(/[A-Z]/g, function (m) { return '-' + m.toLowerCase(); }), String(v[p])); }); } else if (k.slice(0, 2) === 'on') { if (typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v); } else if (/^(innerhtml|outerhtml|srcdoc)$/i.test(k)) { return; } else if (PROPS[k]) node[k] = v; else if ((k === 'href' || k === 'src' || k === 'xlink:href') && !/^(#|\/|https?:)/i.test(String(v))) return; else if (v === true) node.setAttribute(k, ''); else node.setAttribute(k, String(v)); }); } appendKids(node, Array.prototype.slice.call(arguments, 2)); return node; } function h(tag, cls) { return el.apply(null, [tag, cls ? { class: cls } : null].concat(Array.prototype.slice.call(arguments, 2))); } function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } function svgEl(tag, attrs) { var e = document.createElementNS(SVG_NS, tag); for (var k in attrs) e.setAttribute(k, attrs[k]); return e; } function pick(list, v, fallback) { return list.indexOf(v) >= 0 ? v : fallback; } function cssVar(name) { var n = String(name); return getComputedStyle(document.documentElement).getPropertyValue(n.indexOf('--') === 0 ? n : '--' + n).trim(); } // icon strings come from first-party scripts, but are still parsed, not injected function iconNode(str) { var fallback = function () { return svgEl('svg', { viewBox: '0 0 24 24', 'aria-hidden': 'true' }); }; try { var s = String(str || ''); if (!/xmlns=/.test(s)) s = s.replace(/= 1024 && i < u.length - 1) { n /= 1024; i++; } return new Intl.NumberFormat(lang, { maximumFractionDigits: n < 10 && i > 0 ? 1 : 0 }).format(n) + ' ' + u[i]; } function ago(ts) { if (!ts) return t('never'); var s = Math.max(0, Math.floor(Date.now() / 1000 - ts)); if (s < 5) return t('ago.now'); if (s < 60) return t('ago.s', s); if (s < 3600) return t('ago.m', Math.floor(s / 60)); if (s < 86400) return t('ago.h', Math.floor(s / 3600)); return t('ago.d', Math.floor(s / 86400)); } function clock(ts) { return new Date(ts * 1000).toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); } function dateTime(ts) { return new Date(ts * 1000).toLocaleString(lang); } function countryLabel(cc) { return (flag(cc) + ' ' + countryName(cc)).trim(); } var KNOWN_CATS = ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban']; var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'disabled']; var KNOWN_LEVELS = ['hostile', 'suspicious', 'low']; var KNOWN_TONES = ['neutral', 'ok', 'warn', 'danger', 'info']; var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban']; var LEVEL_TONE = { hostile: 'danger', suspicious: 'warn', low: 'neutral' }; var STATE_TONE = { following: 'ok', waiting: 'warn', backfill: 'warn', error: 'danger', disabled: 'neutral' }; // ---------------------------------------------------------------- state var state = { host: lsGet('urutau.host') || 'all', range: lsGet('urutau.range') || '24h', domain: 'all', live: [], summary: null, hidden: {}, note: '', domains: [] }; if (['1h', '24h', '7d'].indexOf(state.range) < 0) state.range = '24h'; function currentTheme() { var a = document.documentElement.getAttribute('data-theme'); if (a === 'light' || a === 'dark') return a; return window.matchMedia && matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; } function ctx() { return { range: state.range, host: state.host, domain: state.domain, theme: currentTheme(), lang: lang }; } // ---------------------------------------------------------------- api + events function showError(msg) { var b = $('#err'); if (b) { b.textContent = msg; b.hidden = false; } } function hideError() { var b = $('#err'); if (b) b.hidden = true; } function mkErr(msg, status) { var e = new Error(msg); e.status = status; return e; } function api(path, params) { var url = path; if (params) { var p = new URLSearchParams(); Object.keys(params).forEach(function (k) { if (params[k] !== undefined && params[k] !== null) p.set(k, String(params[k])); }); var q = p.toString(); if (q) url += (path.indexOf('?') < 0 ? '?' : '&') + q; } return fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } }).then(function (r) { if (r.status === 401) { location.href = '/login'; throw mkErr('unauthorized', 401); } if (r.status === 429) { showError(t('error.rate')); throw mkErr('rate limited', 429); } if (r.status >= 500) { showError(t('error.load')); throw mkErr('HTTP ' + r.status, r.status); } if (!r.ok) throw mkErr('HTTP ' + r.status, r.status); hideError(); return r.json(); }, function (e) { showError(t('error.load')); throw e; }); } function qs(extra) { var o = { host: state.host, range: state.range }; for (var k in extra) o[k] = extra[k]; return o; } var listeners = []; function onEvent(cb) { listeners.push(cb); return function () { var i = listeners.indexOf(cb); if (i >= 0) listeners.splice(i, 1); }; } function connectLive() { if (!window.EventSource) return; var es = new EventSource('/api/v1/events/stream'); function setLive(on) { $('#live-dot').className = 'dot ' + (on ? 'on' : 'off'); var tx = $('#live-text'); tx.textContent = t(on ? 'conn.on' : 'conn.off'); tx.setAttribute('data-i18n', on ? 'conn.on' : 'conn.off'); } es.onopen = function () { setLive(true); }; es.onerror = function () { setLive(false); }; es.addEventListener('ev', function (m) { var e; try { e = JSON.parse(m.data); } catch (x) { return; } state.live.unshift(e); if (state.live.length > 100) state.live.length = 100; listeners.slice().forEach(function (cb) { try { cb(e); } catch (x) { /* a page must not break the stream */ } }); }); } // one summary request shared by every page and the shell var sumCache = { key: '', at: 0, p: null }; function getSummary(c) { c = c || ctx(); var key = c.host + '|' + c.range; if (sumCache.key === key && sumCache.p && Date.now() - sumCache.at < 3000) return sumCache.p; var p = api('/api/v1/summary', { host: c.host, range: c.range }).then(function (s) { state.summary = s; return s; }); sumCache = { key: key, at: Date.now(), p: p }; p.catch(function () { if (sumCache.p === p) sumCache.p = null; }); return p; } // ---------------------------------------------------------------- resize var resizeSubs = [], rzTimer; function onResize(cb) { resizeSubs.push(cb); return function () { var i = resizeSubs.indexOf(cb); if (i >= 0) resizeSubs.splice(i, 1); }; } var lastW = window.innerWidth; window.addEventListener('resize', function () { if (window.innerWidth === lastW) return; lastW = window.innerWidth; clearTimeout(rzTimer); rzTimer = setTimeout(function () { resizeSubs.slice().forEach(function (cb) { cb(); }); }, 150); }); // ---------------------------------------------------------------- primitives function panel(opts) { var kids = Array.prototype.slice.call(arguments, 1); var acts = opts.actions ? [].concat(opts.actions) : null; var head = h('div', 'panel-h', h('h2', null, opts.title), acts ? h('div', 'acts', acts) : null); var body = h('div', 'panel-b', kids); var node = h('section', 'panel' + (opts.cls ? ' ' + opts.cls : ''), head, opts.hint ? h('p', 'hint', opts.hint) : null, body); node.body = body; return node; } function stat(label, value, sub, tone, hint) { var tn = pick(KNOWN_TONES, tone, 'neutral'); var n = h('div', 'stat' + (tn === 'neutral' ? '' : ' tone-' + tn), h('p', 'l', label), h('p', 'v', value), sub ? h('p', 's', sub) : null); if (hint) n.title = hint; return n; } function lead(title, body, tone) { var tn = pick(['ok', 'danger', 'neutral'], tone, 'ok'); return h('section', 'lead tone-' + tn, h('div', null, h('h2', null, title), body ? h('p', null, body) : null), h('span', 'pulse', '')); } function empty(title, detail) { return h('div', 'empty', h('strong', null, title), detail || null); } function badge(text, tone) { var tn = pick(KNOWN_TONES, tone, 'neutral'); return h('span', 'badge' + (tn === 'neutral' ? '' : ' tone-' + tn), text); } function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return badge(t('level.' + l), LEVEL_TONE[l]); } function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'); return h('span', 'cat c-' + k, label || t('cat.' + k)); } // ranked list with a proportional bar; rows: [{key, n, label?}] function bars(rows, opts) { opts = opts || {}; var box = h('div'); if (!rows || !rows.length) { box.appendChild(empty(t('top.empty'))); return box; } var max = rows[0].n || 1; rows.slice(0, opts.limit || 10).forEach(function (r) { var d = h('div', 'bar-row'); var label = opts.label ? opts.label(r) : r.key; d.appendChild(h('span', 'k' + (opts.mono ? ' mono' : ''), label)); d.appendChild(h('span', 'n', nf(r.n))); if (r.label) d.appendChild(h('span', 'sub', r.label)); var bar = h('div', 'bar'), i = h('i'); i.style.width = Math.max(2, r.n / max * 100) + '%'; bar.appendChild(i); d.appendChild(bar); box.appendChild(d); }); return box; } // ---------------------------------------------------------------- charts function niceMax(v) { var raw = Math.max(v, 4) / 4, p = Math.pow(10, Math.floor(Math.log10(raw))), m = raw / p; return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p * 4; } function tickLabel(ts, longSpan) { var d = new Date(ts * 1000); if (longSpan) return d.toLocaleDateString(lang, { month: 'short', day: 'numeric' }); return d.toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit' }); } // spec: { start, step, layers: [{cls, label, vals}], stacked, aria, emptyText } function chart(wrap, spec) { clear(wrap); var layers = spec.layers, n = layers.length ? layers[0].vals.length : 0; if (!n) return; var W = Math.max(280, wrap.clientWidth), H = 230, L = 40, R = 6, Tp = 8, B = 22, i, k; var tot = [], max = 0; for (i = 0; i < n; i++) { var v = 0; layers.forEach(function (l) { v = spec.stacked ? v + (l.vals[i] || 0) : Math.max(v, l.vals[i] || 0); }); tot.push(v); if (v > max) max = v; } var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n; var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': spec.aria || '' }); for (i = 0; i <= 4; i++) { var y = Tp + ph - (ph * i / 4); svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' })); var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); lab.textContent = top >= 10000 ? nfCompact(Math.round(top * i / 4)) : nf(Math.round(top * i / 4)); svg.appendChild(lab); } var longSpan = spec.step * n > 2 * 86400; var nt = W < 520 ? 3 : 5; for (i = 0; i < nt; i++) { var idx = Math.round((n - 1) * i / (nt - 1)); var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' }); xl.textContent = tickLabel(spec.start + idx * spec.step, longSpan); svg.appendChild(xl); } for (i = 0; i < n; i++) { var yb = Tp + ph, x = L + bw * i + (bw > 3 ? 0.5 : 0), w = Math.max(1, bw - (bw > 3 ? 1 : 0)); for (k = 0; k < layers.length; k++) { var val = layers[k].vals[i]; if (!val) continue; var bh = Math.max(1, val / top * ph); if (spec.stacked) yb -= bh; else yb = Tp + ph - bh; svg.appendChild(svgEl('rect', { x: x, y: yb, width: w, height: bh, 'class': layers[k].cls })); } } var tip = h('div', 'tip'); tip.hidden = true; function showTip(ix, x0) { clear(tip); tip.appendChild(h('strong', null, new Date((spec.start + ix * spec.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }))); layers.slice().sort(function (a, b) { return (b.vals[ix] || 0) - (a.vals[ix] || 0); }).forEach(function (l) { if (!l.vals[ix]) return; tip.appendChild(h('div', null, h('span', null, l.label), h('span', 'num', nf(l.vals[ix])))); }); tip.hidden = false; tip.style.left = Math.max(0, Math.min(x0, W - 170)) + 'px'; tip.style.top = '4px'; } for (i = 0; i < n; i++) { (function (j) { var r = svgEl('rect', { x: L + bw * j, y: Tp, width: bw, height: ph, 'class': 'hover-col' }); r.addEventListener('mouseenter', function () { showTip(j, L + bw * j + 14); }); r.addEventListener('click', function () { showTip(j, L + bw * j + 14); }); svg.appendChild(r); })(i); } svg.addEventListener('mouseleave', function () { tip.hidden = true; }); wrap.appendChild(svg); wrap.appendChild(tip); if (max === 0) { var e = svgEl('text', { x: W / 2, y: H / 2, 'text-anchor': 'middle', 'class': 'axis' }); e.textContent = spec.emptyText || t('timeline.empty'); svg.appendChild(e); } } // ---------------------------------------------------------------- map var world = window.URUTAU_WORLD; function mapBox(rowsHolder) { return h('div', 'mapbox', h('div', 'map'), h('div', 'maplist')); } function renderMap(box, rows, good, aria) { var map = box.querySelector('.map'), list = box.querySelector('.maplist'); clear(map); clear(list); map.className = 'map' + (good ? ' good' : ''); rows = rows || []; var by = {}, max = 1; rows.forEach(function (r) { by[String(r.key).toUpperCase()] = r.n; if (r.n > max) max = r.n; }); if (world) { var svg = svgEl('svg', { viewBox: '0 0 ' + world.w + ' ' + world.h, role: 'img', 'aria-label': aria }); Object.keys(world.paths).forEach(function (cc) { var p = svgEl('path', { d: world.paths[cc], 'class': 'mapc' + (by[cc] ? ' hit' : '') }); if (by[cc]) { p.setAttribute('fill-opacity', String(0.25 + 0.75 * Math.sqrt(by[cc] / max))); var ti = svgEl('title', {}); ti.textContent = countryLabel(cc) + ': ' + nf(by[cc]); p.appendChild(ti); } svg.appendChild(p); }); map.appendChild(svg); } list.appendChild(bars(rows, { limit: 8, label: function (r) { return countryLabel(r.key); } })); } // ---------------------------------------------------------------- feed function eventText(e) { if (e.source === 'traefik') return (e.method || '') + ' ' + (e.domain || '') + (e.path || '') + (e.forged ? ' [' + t('feed.forged') + ']' : ''); if (e.source === 'ssh') return e.user ? 'ssh user ' + e.user : 'ssh'; if (e.source === 'fail2ban') return 'fail2ban [' + (e.jail || '') + ']'; return ''; } function feedList(limit) { var ul = h('ul', 'feed'); function render() { clear(ul); var seen = {}, list = []; var rec = state.summary ? state.summary.recent || [] : []; state.live.concat(rec).forEach(function (e) { if (state.host !== 'all' && e.host !== state.host) return; var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || ''); if (seen[key]) return; seen[key] = 1; list.push(e); }); list.sort(function (a, b) { return b.t - a.t; }); list = list.slice(0, limit); if (!list.length) { ul.appendChild(h('li', 'empty', t('feed.empty'))); return; } list.forEach(function (e) { var li = h('li'); li.appendChild(h('span', 't', clock(e.t))); if (e.forged) li.title = t('feed.forged'); li.appendChild(catPill(e.cat, e.unban ? t('feed.unban') : null)); var b = h('button', 'linkish mono', (e.cc ? flag(e.cc) + ' ' : '') + e.ip); b.type = 'button'; b.addEventListener('click', function () { openIP(e.ip); }); li.appendChild(b); li.appendChild(h('span', 'what', (e.host ? '[' + e.host + '] ' : '') + eventText(e))); ul.appendChild(li); }); } return { node: ul, render: render }; } // re-render a feed when events arrive, at most a few times per second function liveFeedBinding(feed) { var timer = 0; var off = onEvent(function () { if (timer) return; timer = setTimeout(function () { timer = 0; feed.render(); }, 400); }); return function () { off(); clearTimeout(timer); timer = 0; }; } // ---------------------------------------------------------------- IP table function sumCounts(c) { var s = 0; for (var k in c) s += c[k]; return s; } function ipTable(full) { var st = { sort: 'score', order: 'desc', page: 1, per: window.innerWidth <= 720 ? 25 : (full ? 50 : 25), q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' }; var timer = 0, alive = true, onTotal = null; var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('ips.search'), 'aria-label': t('ips.search') }); var levelSel = el('select', { 'aria-label': t('ips.level') }); ['', 'hostile', 'suspicious', 'low'].forEach(function (l) { levelSel.appendChild(el('option', { value: l }, l ? t('level.' + l) : t('level.all'))); }); var bannedChk = el('input', { type: 'checkbox' }); var toolbar = h('div', 'toolbar', search, levelSel, h('label', 'check', bannedChk, h('span', null, t('ips.bannedOnly')))); var perSel = null; if (full) { perSel = el('select', { 'aria-label': t('ips.perPage') }); [25, 50, 100, 200].forEach(function (n) { perSel.appendChild(el('option', { value: String(n) }, String(n))); }); perSel.value = String(st.per); toolbar.appendChild(perSel); } var thead = h('thead'), tbody = h('tbody'); var table = h('table', 'stack', thead, tbody); var count = h('span'), page = h('span'), prev = el('button', { type: 'button', class: 'btn' }, t('pager.prev')), next = el('button', { type: 'button', class: 'btn' }, t('pager.next')); var pager = h('div', 'pager', count, h('div', 'btns', page, prev, next)); var node = h('div', null, toolbar, h('div', 'tbl-wrap', table), pager); function cols() { var c = [{ k: 'ip', s: 'ip' }, { k: 'score', s: 'score' }, { k: 'level' }, { k: 'cats' }, { k: 'origin' }]; if (full && st.multi) c.push({ k: 'hosts' }); if (full) c.push({ k: 'first', s: 'first' }); c.push({ k: 'last', s: 'last' }); if (full) c.push({ k: 'events', s: 'events' }); c.push({ k: 'banned' }); return c; } function colLabel(k) { return t(k === 'cats' ? 'col.cats' : 'col.' + k); } function buildHead() { var c = cols(); var sig = c.map(function (x) { return x.k; }).join(',') + '|' + lang; if (sig === st.headSig) { markSort(); return; } st.headSig = sig; clear(thead); var tr = h('tr'); c.forEach(function (x) { var th = el('th', { scope: 'col', 'data-key': x.s || '' }); if (x.s) { var b = el('button', { type: 'button' }, colLabel(x.k)); b.addEventListener('click', function () { if (st.sort === x.s) st.order = st.order === 'desc' ? 'asc' : 'desc'; else { st.sort = x.s; st.order = 'desc'; } st.page = 1; load(); }); th.appendChild(b); } else th.textContent = colLabel(x.k); tr.appendChild(th); }); thead.appendChild(tr); markSort(); } function markSort() { thead.querySelectorAll('th').forEach(function (th) { var k = th.getAttribute('data-key'); if (k && k === st.sort) th.setAttribute('aria-sort', st.order === 'asc' ? 'ascending' : 'descending'); else th.removeAttribute('aria-sort'); }); } function renderRows(items) { clear(tbody); var c = cols(); if (!items.length) { var td0 = h('td', 'empty', t('ips.empty')); td0.colSpan = c.length; tbody.appendChild(h('tr', null, td0)); } items.forEach(function (x) { var tr = h('tr', 'row'); tr.tabIndex = 0; tr.setAttribute('role', 'button'); function cell(key, nodeOrText, cls) { var td = h('td', cls || ''); td.setAttribute('data-label', colLabel(key)); td.appendChild(typeof nodeOrText === 'string' ? document.createTextNode(nodeOrText) : nodeOrText); tr.appendChild(td); } c.forEach(function (col) { switch (col.k) { case 'ip': { var ipc = h('span', null, h('span', 'mono', x.ip)); if (!full && st.multi) ipc.appendChild(h('small', null, (x.hosts || []).join(', '))); cell('ip', ipc, 'nw'); break; } case 'score': cell('score', h('span', 'num', String(x.score)), 'nw'); break; case 'level': cell('level', levelBadge(x.level)); break; case 'cats': { var chips = h('span'); var kinds = Object.keys(x.counts || {}).filter(function (k) { return k !== 'ok' && k !== 'ssh-ok' && KNOWN_CATS.indexOf(k) >= 0; }) .sort(function (a, b) { return x.counts[b] - x.counts[a]; }); kinds.slice(0, 2).forEach(function (k) { chips.appendChild(h('span', 'chip', t('cat.' + k) + ' ' + nf(x.counts[k]))); }); if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2))); cell('cats', chips, 'nw'); break; } case 'origin': { var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + countryName(x.cc)) : '-'); var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean); if (x.cc) tip.unshift(org.textContent); if (tip.length) org.title = tip.join('\n'); cell('origin', org); break; } case 'hosts': cell('hosts', (x.hosts || []).join(', ') || '-'); break; case 'first': cell('first', ago(x.first), 'nw'); break; case 'last': cell('last', ago(x.last), 'nw'); break; case 'events': cell('events', h('span', 'num', nf(sumCounts(x.counts || {}))), 'nw'); break; case 'banned': cell('banned', x.banned ? h('span', 't-banned', (x.jails || []).join(', ') || t('yes')) : '-', 'nw'); break; } }); tr.addEventListener('click', function () { openIP(x.ip); }); tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openIP(x.ip); } }); tbody.appendChild(tr); }); var pages = Math.max(1, Math.ceil(st.total / st.per)); count.textContent = pl('pager.count', st.total, { n: nf(st.total) }); page.textContent = full ? t('pager.page', { n: nf(st.page), m: nf(pages) }) : ''; prev.disabled = st.page <= 1; next.disabled = st.page >= pages; } function load() { var c = ctx(), key = c.host + '|' + c.range; if (key !== st.ctxKey) { st.ctxKey = key; st.page = 1; } buildHead(); var params = qs({ sort: st.sort, order: st.order, page: st.page, per: st.per, q: st.q, level: st.level, banned: st.banned ? '1' : '0' }); return api('/api/v1/ips', params).then(function (r) { if (!alive) return; st.total = r.total; if (onTotal) onTotal(r.total); var sig = JSON.stringify([lang, st.multi, st.page, st.per, r.items.map(function (x) { return [x.ip, x.score, x.last, x.banned, x.level]; })]); if (sig === st.sig) return; st.sig = sig; renderRows(r.items); }).catch(function () { /* banner already shown by api() */ }); } function reset() { st.page = 1; return load(); } search.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(function () { st.q = search.value.trim(); reset(); }, 300); }); levelSel.addEventListener('change', function () { st.level = levelSel.value; reset(); }); bannedChk.addEventListener('change', function () { st.banned = bannedChk.checked; reset(); }); if (perSel) perSel.addEventListener('change', function () { st.per = parseInt(perSel.value, 10) || 50; reset(); }); prev.addEventListener('click', function () { if (st.page > 1) { st.page--; load(); } }); next.addEventListener('click', function () { st.page++; load(); }); return { node: node, load: load, reset: reset, setMulti: function (b) { if (st.multi !== b) { st.multi = b; st.sig = ''; } }, onTotal: function (cb) { onTotal = cb; }, dispose: function () { alive = false; clearTimeout(timer); } }; } // ---------------------------------------------------------------- drawer var drawerOpener = null; function copyText(text) { if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text); return new Promise(function (ok, fail) { var ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); var done = false; try { done = document.execCommand('copy'); } catch (e) { done = false; } document.body.removeChild(ta); done ? ok() : fail(new Error('copy')); }); } function closeDetail() { var box = $('#detail'); if (box.hidden) return; box.hidden = true; $('#scrim').hidden = true; if (drawerOpener && document.contains(drawerOpener)) drawerOpener.focus(); drawerOpener = null; } function listOf(items, mono) { if (!items || !items.length) return h('span', null, '-'); var ul = h('ul'); items.forEach(function (i) { ul.appendChild(h('li', mono ? 'mono' : '', i)); }); return ul; } function openIP(ip) { var box = $('#detail'); if (box.hidden) drawerOpener = document.activeElement; clear(box); box.hidden = false; $('#scrim').hidden = false; function closeBtn() { var b = el('button', { type: 'button', class: 'btn', 'data-first': '1' }, t('detail.close')); b.addEventListener('click', closeDetail); return b; } var loading = h('div', 'dh', h('h2', null, String(ip)), closeBtn()); box.appendChild(loading); box.appendChild(h('p', 'note', t('detail.loading'))); box.querySelector('button').focus(); api('/api/v1/ip/' + encodeURIComponent(ip)).then(function (d) { clear(box); var cp = el('button', { type: 'button', class: 'btn' }, t('detail.copyIp')); cp.addEventListener('click', function () { copyText(d.ip); }); box.appendChild(h('div', 'dh', h('h2', null, d.ip), cp, closeBtn())); var dl = h('dl', 'kv'); function row(label, nodeOrText) { dl.appendChild(h('dt', null, label)); dl.appendChild(h('dd', null, nodeOrText)); } row(t('detail.level'), levelBadge(d.level)); row(t('detail.score'), h('span', 'num', String(d.score))); row(t('detail.rdns'), h('span', 'mono', d.rdns || '-')); if (d.cc) row(t('detail.country'), (flag(d.cc) + ' ' + countryName(d.cc)).trim()); if (d.city) row(t('detail.city'), d.city); if (d.asn) row(t('detail.network'), 'AS' + d.asn + (d.as_org ? ' ' + d.as_org : '')); row(t('detail.first'), dateTime(d.first)); row(t('detail.last'), dateTime(d.last) + ' (' + ago(d.last) + ')'); row(t('detail.hosts'), (d.hosts || []).join(', ') || '-'); if (d.banned) row(t('detail.jails'), h('span', 't-banned', (d.jails || []).join(', ') || t('yes'))); var counts = h('span'); Object.keys(d.counts || {}).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0; }).forEach(function (c) { counts.appendChild(h('span', 'chip', t('cat.' + c) + ' ' + nf(d.counts[c]))); }); row(t('detail.counts'), counts); row(t('detail.domains'), listOf(d.domains, true)); row(t('detail.uas'), listOf(d.uas, false)); if (d.ua_labels && d.ua_labels.length) row(t('detail.uaparsed'), listOf(d.ua_labels, false)); row(t('detail.samples'), listOf(d.samples, true)); box.appendChild(dl); box.querySelector('button[data-first], button').focus(); }).catch(function (e) { if (e && e.message === 'unauthorized') return; clear(box); box.appendChild(h('div', 'dh', h('h2', null, String(ip)), closeBtn())); box.appendChild(h('p', 'empty', t('detail.notfound'))); box.querySelector('button').focus(); }); } // ---------------------------------------------------------------- page registry var ORDER = ['overview', 'threats', 'geo', 'live', 'traffic', 'ips', 'sources']; var pages = {}; var current = null; // { page, el } function registerPage(p) { if (!p || typeof p.id !== 'string' || !/^[a-z][a-z0-9-]*$/.test(p.id) || pages[p.id]) return; pages[p.id] = p; if (booted) { renderNav(); route(); } } function orderedPages() { var ids = Object.keys(pages); return ORDER.filter(function (id) { return pages[id]; }).concat(ids.filter(function (id) { return ORDER.indexOf(id) < 0; }).sort()).map(function (id) { return pages[id]; }); } var booted = false; // core page wrapper: loads data, ignores stale answers, rebuilds on language change function corePage(spec) { var root, view, data = null, c, lastLang, seq = 0, alive = false; function paint() { if (data) { try { spec.render(view, data, c); } catch (e) { console.error(e); } } } function load() { var my = ++seq; return spec.load(c, view).then(function (d) { if (!alive || my !== seq) return; data = d; paint(); }).catch(function () { /* the api layer already reported it */ }); } function build() { if (view && spec.dispose) spec.dispose(view); clear(root); view = spec.build(root, c); } return { id: spec.id, icon: spec.icon, titleKey: spec.titleKey, domain: !!spec.domain, mount: function (elx, cx) { root = elx; c = cx; lastLang = cx.lang; alive = true; data = null; build(); load(); }, update: function (cx) { var prev = c; c = cx; if (cx.lang !== lastLang) { lastLang = cx.lang; build(); paint(); load(); return; } if (prev.range !== cx.range || prev.host !== cx.host || prev.domain !== cx.domain) load(); }, refresh: function () { load(); }, unmount: function () { alive = false; seq++; if (view && spec.dispose) spec.dispose(view); view = null; clear(root); } }; } var ICONS = { overview: '', threats: '', traffic: '', ips: '', sources: '' }; // ---------------------------------------------------------------- shared blocks function timelinePanel() { var wrap = h('div', 'chart-wrap'), legend = h('div', 'legend'); var node = panel({ title: t('timeline.title'), hint: t('timeline.hint') }, wrap, legend); var data = null; function renderLegend() { clear(legend); CHART_CATS.forEach(function (c) { var b = el('button', { type: 'button', 'aria-pressed': state.hidden[c] ? 'false' : 'true' }, h('span', 'sw b-' + c), h('span', null, t('cat.' + c))); b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); draw(); }); legend.appendChild(b); }); } function draw() { if (!data) return; var tl = data.timeline, n = ((tl.series.ok || tl.series.notfound || []).length), zeros = [], i; for (i = 0; i < n; i++) zeros.push(0); var layers = CHART_CATS.filter(function (c) { return !state.hidden[c]; }).map(function (c) { return { cls: 'b-' + c, label: t('cat.' + c), vals: tl.series[c] || zeros }; }); if (!layers.length) layers = [{ cls: 'b-notfound', label: '', vals: zeros }]; chart(wrap, { start: tl.start, step: tl.step, stacked: true, layers: layers, aria: t('timeline.title') }); } renderLegend(); return { node: node, set: function (s) { data = s; draw(); }, draw: draw }; } function kpiRow(s, box) { var T = s.totals, hosts = s.hosts || [], on = hosts.filter(function (x) { return x.online; }).length; var range = t('range.long.' + state.range); clear(box); box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }))); box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral')); box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral')); box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral')); box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'))); box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }))); } function overviewLead(s) { var T = s.totals; if (!T.requests && !T.malicious && !T.unique_ips) return lead(t('ov.lead.empty'), t('ov.lead.bodyEmpty'), 'neutral'); var title = T.hostile_ips > 1 ? t('ov.lead.hostile', { n: nf(T.hostile_ips) }) : T.hostile_ips === 1 ? t('ov.lead.hostile.one') : t('ov.lead.calm'); return lead(title, t('ov.lead.body', { m: nf(T.malicious), r: nf(T.requests), ips: nf(T.unique_ips), b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : 'ok'); } function topIpList(list) { var box = h('div'); if (!list.length) { box.appendChild(empty(t('top.empty'))); return box; } var max = Math.max.apply(null, list.map(function (x) { return x.score; })) || 1; list.forEach(function (x) { var b = el('button', { type: 'button', class: 'linkish mono' }, x.ip); b.addEventListener('click', function () { openIP(x.ip); }); var org = x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc))) : ''; var sub = h('span', 'sub', levelBadge(x.level), org ? ' ' + org : ''); var bar = h('div', 'bar'), i = h('i'); i.style.width = Math.max(2, x.score / max * 100) + '%'; bar.appendChild(i); box.appendChild(h('div', 'bar-row', h('span', 'k', b), h('span', 'n', String(x.score)), sub, bar)); }); return box; } // ---------------------------------------------------------------- page: overview var pOverview = corePage({ id: 'overview', icon: ICONS.overview, titleKey: 'nav.overview', build: function (root) { var v = {}; v.lead = h('div'); v.kpis = h('section', 'grid kpis'); v.timeline = timelinePanel(); v.countries = panel({ title: t('ov.countries'), hint: t('ov.countries.hint') }); v.topips = panel({ title: t('ov.topips'), hint: t('ov.topips.hint'), actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }); v.feedList = feedList(12); v.feed = panel({ title: t('ov.feed'), hint: t('ov.feed.hint') }, v.feedList.node); root.appendChild(v.lead); root.appendChild(v.kpis); root.appendChild(v.timeline.node); root.appendChild(h('div', 'grid g3', v.countries, v.topips, v.feed)); v.offResize = onResize(function () { v.timeline.draw(); }); v.offFeed = liveFeedBinding(v.feedList); v.feedList.render(); return v; }, load: function (c) { return getSummary(c); }, render: function (v, s) { clear(v.lead); v.lead.appendChild(overviewLead(s)); kpiRow(s, v.kpis); v.timeline.set(s); clear(v.countries.body); v.countries.body.appendChild(bars(s.countries, { label: function (r) { return countryLabel(r.key); } })); clear(v.topips.body); v.topips.body.appendChild(topIpList((s.ips || []).slice().sort(function (a, b) { return b.score - a.score; }).slice(0, 8))); v.feedList.render(); }, dispose: function (v) { v.offResize(); v.offFeed(); } }); // ---------------------------------------------------------------- page: threats function threatsLead(s) { var tl = s.timeline, best = null, total = 0, bestN = 0; CHART_CATS.forEach(function (c) { if (c === 'ban') return; var n = 0; (tl.series[c] || []).forEach(function (x) { n += x; }); total += n; if (n > bestN) { bestN = n; best = c; } }); if (!best) return lead(t('th.lead.none'), t('th.lead.noneBody'), 'neutral'); var body = [pl('th.lead.body', total, { n: nf(bestN), m: nf(total), p: pct(bestN, total) })]; if (s.top_domains && s.top_domains.length) body.push(t('th.lead.domain', { name: s.top_domains[0].key })); if (s.countries && s.countries.length) body.push(t('th.lead.origin', { name: countryLabel(s.countries[0].key) })); return lead(t('th.lead.top', { cat: t('cat.' + best) }), body.join(' '), s.totals.hostile_ips > 0 ? 'danger' : 'ok'); } var pThreats = corePage({ id: 'threats', icon: ICONS.threats, titleKey: 'nav.threats', build: function (root) { var v = {}; v.lead = h('div'); v.kpis = h('section', 'grid kpis'); v.mon = h('p', 'note'); v.timeline = timelinePanel(); v.mapbox = mapBox(); v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint') }, v.mapbox); v.tbl = ipTable(false); v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), actions: el('a', { class: 'btn', href: '#/sources' }, t('blocklist.title')) }, v.tbl.node); v.feedList = feedList(100); v.feed = panel({ title: t('feed.title') }, v.feedList.node); v.paths = panel({ title: t('top.paths') }); v.domains = panel({ title: t('top.domains') }); v.uas = panel({ title: t('top.uas') }); v.users = panel({ title: t('top.users') }); root.appendChild(v.lead); root.appendChild(v.kpis); root.appendChild(v.mon); root.appendChild(v.timeline.node); root.appendChild(v.map); root.appendChild(h('div', 'grid main-side', v.ips, v.feed)); root.appendChild(h('div', 'grid g2', v.paths, v.domains, v.uas, v.users)); v.offResize = onResize(function () { v.timeline.draw(); }); v.offFeed = liveFeedBinding(v.feedList); v.feedList.render(); return v; }, load: function (c, v) { return getSummary(c).then(function (s) { v.tbl.setMulti((s.hosts || []).length > 1); v.tbl.load(); return s; }); }, render: function (v, s) { clear(v.lead); v.lead.appendChild(threatsLead(s)); kpiRow(s, v.kpis); v.mon.textContent = s.totals.monitoring ? t('kpi.monitoring', nf(s.totals.monitoring)) : ''; v.mon.hidden = !s.totals.monitoring; v.timeline.set(s); renderMap(v.mapbox, s.countries, false, t('map.attacks')); [['paths', s.top_paths, true], ['domains', s.top_domains, true], ['uas', s.top_uas, false], ['users', s.top_users, true]].forEach(function (p) { clear(v[p[0]].body); v[p[0]].body.appendChild(bars(p[1], { mono: p[2] })); }); v.feedList.render(); }, dispose: function (v) { v.offResize(); v.offFeed(); v.tbl.dispose(); } }); // ---------------------------------------------------------------- page: traffic function setDomains(list) { var sel = $('#domain'), want = list.map(function (x) { return x.key; }).join('|') + '|' + lang; state.domains = list; if (sel.getAttribute('data-doms') !== want) { clear(sel); sel.appendChild(el('option', { value: 'all' }, t('traffic.allDomains'))); list.forEach(function (x) { sel.appendChild(el('option', { value: x.key }, x.key + ' (' + nf(x.n) + ')')); }); sel.setAttribute('data-doms', want); } sel.value = state.domain; if (sel.value !== state.domain) sel.value = 'all'; } var pTraffic = corePage({ id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true, build: function (root) { var v = {}; v.lead = h('div'); v.kpis = h('section', 'grid kpis'); v.wrap = h('div', 'chart-wrap'); v.legend = h('div', 'legend', h('span', 'li', h('span', 'sw b-treq'), t('traffic.requests')), h('span', 'li', h('span', 'sw b-tpages'), t('traffic.pages'))); v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.timeline.hint') }, v.wrap, v.legend); v.mapbox = mapBox(); v.map = panel({ title: t('map.visitors'), hint: t('map.visitors.hint') }, v.mapbox); var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['browsers', 'traffic.browsers'], ['oses', 'traffic.oses'], ['devices', 'traffic.devices'], ['bots', 'traffic.bots'], ['status', 'traffic.status']]; ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]) }); }); v.privacy = h('p', 'note', t('traffic.privacy')); root.appendChild(v.lead); root.appendChild(v.kpis); root.appendChild(v.timeline); root.appendChild(v.map); root.appendChild(h('div', 'grid g3', v.pages, v.refs, v.cities)); root.appendChild(h('div', 'grid g3', v.browsers, v.oses, v.devices)); root.appendChild(h('div', 'grid g2', v.bots, v.status)); root.appendChild(v.privacy); v.offResize = onResize(function () { if (v.data) drawTraffic(v, v.data); }); return v; }, load: function (c) { return api('/api/v1/traffic', { host: c.host, range: c.range, domain: c.domain }); }, render: function (v, d) { v.data = d; setDomains(d.domains || []); var hasData = d.requests > 0; clear(v.lead); v.lead.appendChild(hasData ? lead(t('tr.lead.some', { n: nf(d.visitors), p: nf(d.pages) }), t('tr.lead.body', { r: nf(d.requests), b: nf(d.bots), a: nf(Math.round(d.p50_ms)), c: nf(Math.round(d.p95_ms)) }), 'ok') : lead(t('tr.lead.none'), t('tr.lead.noneBody'), 'neutral')); clear(v.kpis); v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'))); v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }))); v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'))); v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: t('range.long.' + state.range) }))); v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms', t('kpi.sub.range', { range: t('range.long.' + state.range) }))); v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }))); drawTraffic(v, d); renderMap(v.mapbox, d.countries, true, t('map.visitors')); function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); } fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); fill('browsers', d.browsers, false); fill('oses', d.oses, false); fill('devices', (d.devices || []).map(function (x) { return { key: t('device.' + pick(['desktop', 'mobile', 'tablet', 'bot', 'tool'], x.key, 'unknown')), n: x.n }; }), false); fill('bots', d.bot_names, false); fill('status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true); }, dispose: function (v) { v.offResize(); } }); function drawTraffic(v, d) { var tl = d.timeline; chart(v.wrap, { start: tl.start, step: tl.step, stacked: false, aria: t('traffic.timeline'), layers: [ { cls: 'b-treq', label: t('traffic.requests'), vals: tl.req }, { cls: 'b-tpages', label: t('traffic.pages'), vals: tl.pages } ] }); } // ---------------------------------------------------------------- page: ips var pIPs = corePage({ id: 'ips', icon: ICONS.ips, titleKey: 'nav.ips', build: function (root) { var v = {}; v.lead = h('div'); v.tbl = ipTable(true); v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); }); v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node); root.appendChild(v.lead); root.appendChild(v.ips); return v; }, load: function (c, v) { return getSummary(c).then(function (s) { v.tbl.setMulti((s.hosts || []).length > 1); v.tbl.load(); return s; }); }, render: function (v, s) { var T = s.totals; clear(v.lead); v.lead.appendChild(lead(pl('ips.lead', T.unique_ips, { n: nf(T.unique_ips), h: nf(T.hostile_ips), s: nf(T.suspicious_ips) }), t('ips.lead.body', { b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : T.unique_ips ? 'ok' : 'neutral')); }, dispose: function (v) { v.tbl.dispose(); setSliceNote(''); } }); // ---------------------------------------------------------------- page: sources and hosts function blocklistPanel() { var minScore = el('input', { type: 'number', value: '50', min: '0', step: '1', 'aria-label': t('blocklist.minScore') }); var fam = el('select', { 'aria-label': t('blocklist.family') }); ['all', '4', '6'].forEach(function (f) { fam.appendChild(el('option', { value: f }, t('blocklist.family.' + f))); }); var msg = h('div', 'note'); msg.setAttribute('role', 'status'); var count = h('div', 'note'); var copy = el('button', { type: 'button', class: 'btn primary' }, t('blocklist.copy')); var dlTxt = el('a', { class: 'btn', href: '/api/v1/blocklist.txt' }, t('blocklist.download')); var dlJson = el('a', { class: 'btn', href: '/api/v1/blocklist.json' }, t('blocklist.downloadJson')); var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help') }, h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg); var timer = 0, alive = true; function query(extra) { var o = { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value }; for (var k in extra) o[k] = extra[k]; return new URLSearchParams(o).toString(); } function sync() { dlTxt.setAttribute('href', '/api/v1/blocklist.txt?' + query({ download: '1' })); dlJson.setAttribute('href', '/api/v1/blocklist.json?' + query({ download: '1' })); clearTimeout(timer); timer = setTimeout(function () { api('/api/v1/blocklist.json', { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value }).then(function (j) { if (!alive) return; var arr = Array.isArray(j) ? j : (j.items || j.ips || []); count.textContent = pl('blocklist.count', typeof j.count === 'number' ? j.count : arr.length, { n: nf(typeof j.count === 'number' ? j.count : arr.length) }); }).catch(function () { /* optional preview */ }); }, 250); } minScore.addEventListener('input', sync); fam.addEventListener('change', sync); copy.addEventListener('click', function () { fetch('/api/v1/blocklist.txt?' + query({}), { credentials: 'same-origin' }).then(function (r) { if (r.status === 401) { location.href = '/login'; throw new Error('unauthorized'); } return r.text(); }).then(function (txt) { var n = txt.split('\n').filter(Boolean).length; return copyText(txt).then(function () { msg.textContent = pl('blocklist.copied', n, { n: nf(n) }); }); }).catch(function () { msg.textContent = t('blocklist.failed'); }); }); return { node: node, sync: sync, dispose: function () { alive = false; clearTimeout(timer); } }; } function hostCard(hh) { var c = h('div', 'host'); c.appendChild(h('h3', null, h('span', 'dot ' + (hh.online ? 'on' : 'off')), h('span', null, hh.name), hh.self ? badge(t('host.self'), 'info') : null)); c.appendChild(h('div', 'meta', hh.online ? t('host.online') + (hh.version ? ' · ' + hh.version : '') : t('host.offline') + (hh.error ? ' · ' + hh.error : ''))); var dl = h('dl'); [['host.requests', nf(hh.requests || 0)], ['host.malicious', nf(hh.malicious || 0)], ['host.hostile', nf(hh.hostile_ips || 0)], ['host.bans', nf(hh.active_bans || 0)]].forEach(function (p) { dl.appendChild(h('dt', null, t(p[0]))); dl.appendChild(h('dd', null, p[1])); }); if (hh.latency_ms) { dl.appendChild(h('dt', null, t('host.latency'))); dl.appendChild(h('dd', null, hh.latency_ms + ' ms')); } if (!hh.self && hh.last_seen) { dl.appendChild(h('dt', null, t('host.seen'))); dl.appendChild(h('dd', null, ago(hh.last_seen))); } c.appendChild(dl); return c; } var pSources = corePage({ id: 'sources', icon: ICONS.sources, titleKey: 'nav.sources', build: function (root) { var v = {}; v.lead = h('div'); v.hostsBox = h('div', 'hosts'); v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint') }, v.hostsBox); var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); }))); v.tbody = h('tbody'); v.srcEmpty = h('div'); v.sources = panel({ title: t('sources.title'), hint: t('sources.hint') }, h('div', 'tbl-wrap', h('table', 'stack', thead, v.tbody)), v.srcEmpty); v.geoBox = h('div'); v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox); v.bl = blocklistPanel(); root.appendChild(v.lead); root.appendChild(v.hosts); root.appendChild(v.sources); root.appendChild(h('div', 'grid g2', v.geo, v.bl.node)); v.bl.sync(); return v; }, load: function (c, v) { v.bl.sync(); return getSummary(c); }, render: function (v, s) { var srcs = s.sources || [], hosts = s.hosts || []; var following = srcs.filter(function (r) { return r.state === 'following'; }).length; var lines = 0, bad = 0; srcs.forEach(function (r) { lines += r.lines || 0; bad += r.malformed || 0; }); var online = hosts.filter(function (x) { return x.online; }).length; var title = !srcs.length ? t('src.lead.none') : following === srcs.length ? pl('src.lead.all', srcs.length, { n: nf(srcs.length) }) : t('src.lead.some', { a: nf(following), n: nf(srcs.length), x: nf(srcs.length - following) }); clear(v.lead); v.lead.appendChild(lead(title, t('src.lead.body', { h: nf(online), m: nf(hosts.length), l: nf(lines), f: nf(bad) }), !srcs.length ? 'neutral' : following === srcs.length && online === hosts.length ? 'ok' : 'danger')); clear(v.hostsBox); hosts.forEach(function (hh) { v.hostsBox.appendChild(hostCard(hh)); }); clear(v.tbody); clear(v.srcEmpty); if (!srcs.length) v.srcEmpty.appendChild(empty(t('sources.empty'))); srcs.forEach(function (r) { var tr = h('tr'); function cell(key, node, cls) { var td = h('td', cls || ''); td.setAttribute('data-label', t(key)); td.appendChild(typeof node === 'string' ? document.createTextNode(node) : node); tr.appendChild(td); } var rs = pick(KNOWN_STATES, r.state, 'error'); cell('col.host', r.host || ''); cell('col.source', h('span', null, r.name, r.path ? h('small', 'mono', r.path) : null)); cell('col.state', h('span', 'st-' + rs, t('state.' + rs) + (r.error ? ' (' + r.error + ')' : ''))); cell('col.lines', h('span', 'num', nf(r.lines)), 'nw'); cell('col.malformed', h('span', 'num', nf(r.malformed)), 'nw'); cell('col.lastEvent', ago(r.last_event), 'nw'); v.tbody.appendChild(tr); }); var ips = s.ips || [], known = ips.filter(function (x) { return x.cc; }).length; clear(v.geoBox); var dl = h('dl', 'kv'); dl.appendChild(h('dt', null, t('src.geo.title'))); dl.appendChild(h('dd', null, t('src.geo.known', { n: nf(known), m: nf(ips.length) }))); dl.appendChild(h('dt', null, t('ov.countries'))); dl.appendChild(h('dd', null, t('src.geo.countries', { n: nf((s.countries || []).length) }))); dl.appendChild(h('dt', null, t('src.geo.attrib'))); dl.appendChild(h('dd', null, s.attribution || t('src.geo.none'))); v.geoBox.appendChild(dl); }, dispose: function (v) { v.bl.dispose(); } }); [pOverview, pThreats, pTraffic, pIPs, pSources].forEach(function (p) { pages[p.id] = p; }); // ---------------------------------------------------------------- shell function setSliceNote(text) { state.note = text || ''; renderSlice(); } function renderSlice() { var p = $('#slice-text'); if (!p) return; clear(p); var parts = [state.host === 'all' ? t('slice.allHosts') : t('slice.host', { name: state.host })]; if (current && pages[current.id] && pages[current.id].domain) parts.push(state.domain === 'all' ? t('slice.allDomains') : t('slice.domain', { name: state.domain })); if (state.note) parts.push(state.note); p.appendChild(document.createTextNode(t('slice.showing') + ' ')); p.appendChild(h('strong', null, t('range.long.' + state.range))); p.appendChild(document.createTextNode(' · ' + parts.join(' · '))); $('#domain').hidden = !(current && pages[current.id] && pages[current.id].domain); document.querySelectorAll('#range button').forEach(function (b) { b.setAttribute('aria-pressed', b.getAttribute('data-range') === state.range ? 'true' : 'false'); }); } function renderNav() { var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'); clear(nav); clear(bar); clear(more); list.forEach(function (p) { var label = t(p.titleKey), cur = current && current.id === p.id; var a = el('a', { class: 'nav-item', href: '#/' + p.id, title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label)); if (cur) a.setAttribute('aria-current', 'page'); nav.appendChild(a); }); var direct = list.length <= 5 ? list : list.slice(0, 4), rest = list.length <= 5 ? [] : list.slice(4); direct.forEach(function (p) { var a = el('a', { class: 'tab', href: '#/' + p.id }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey))); if (current && current.id === p.id) a.setAttribute('aria-current', 'page'); bar.appendChild(a); }); if (rest.length) { var mb = el('button', { type: 'button', class: 'tab', 'aria-expanded': 'false', 'aria-controls': 'more' }, h('span', 'nav-ico', iconNode('')), h('span', null, t('nav.more'))); if (current && rest.some(function (p) { return p.id === current.id; })) mb.setAttribute('aria-current', 'page'); mb.addEventListener('click', function () { setMore(more.hidden); }); bar.appendChild(mb); rest.forEach(function (p) { var a = el('a', { href: '#/' + p.id }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey))); if (current && current.id === p.id) a.setAttribute('aria-current', 'page'); more.appendChild(a); }); } } function setMore(open) { var more = $('#more'); more.hidden = !open; var b = $('#tabbar button.tab'); if (b) b.setAttribute('aria-expanded', open ? 'true' : 'false'); } function route() { var m = /^#\/([a-z][a-z0-9-]*)/.exec(location.hash), id = m ? m[1] : null; if (!id || !pages[id]) { var saved = lsGet('urutau.page'); id = pages[saved] ? saved : pages.overview ? 'overview' : orderedPages()[0].id; history.replaceState(null, '', '#/' + id); } setMore(false); if (current && current.id === id) return; if (current) { try { current.page.unmount(); } catch (e) { console.error(e); } } var view = $('#view'); clear(view); state.note = ''; var page = pages[id]; current = { id: id, page: page }; lsSet('urutau.page', id); $('#page-title').textContent = t(page.titleKey); document.title = t(page.titleKey) + ' · Urutau'; renderNav(); renderSlice(); try { page.mount(view, ctx()); } catch (e) { console.error(e); view.appendChild(empty(t('error.load'))); } window.scrollTo(0, 0); } function notifyPage() { if (!current) return; try { if (current.page.update) current.page.update(ctx()); } catch (e) { console.error(e); } } function applyI18n() { document.documentElement.lang = lang; document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); }); document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); }); document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); }); document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); }); $('#lang').textContent = lang === 'en' ? 'PT' : 'EN'; } function updateHostSelect(s) { var sel = $('#host'), hosts = s.hosts || []; var want = hosts.map(function (x) { return x.name; }).join('|') + '|' + lang; if (sel.getAttribute('data-hosts') !== want) { clear(sel); sel.appendChild(el('option', { value: 'all' }, t('host.all'))); hosts.forEach(function (x) { sel.appendChild(el('option', { value: x.name }, x.name)); }); sel.setAttribute('data-hosts', want); } if (state.host !== 'all' && !hosts.some(function (x) { return x.name === state.host; })) { state.host = 'all'; lsSet('urutau.host', 'all'); } sel.value = state.host; sel.hidden = hosts.length < 2; } function shellSummary() { return getSummary(ctx()).then(function (s) { updateHostSelect(s); $('#ver').textContent = s.version ? 'v' + s.version : ''; $('#attrib').textContent = (s.version ? 'v' + s.version + ' · ' : '') + (s.attribution || ''); renderSlice(); return s; }); } function ctxChanged() { renderSlice(); notifyPage(); shellSummary().catch(function () { /* banner already shown */ }); } function boot() { booted = true; applyI18n(); $('#range').addEventListener('click', function (e) { var r = e.target.getAttribute && e.target.getAttribute('data-range'); if (!r || r === state.range) return; state.range = r; lsSet('urutau.range', r); ctxChanged(); }); $('#host').addEventListener('change', function (e) { state.host = e.target.value; lsSet('urutau.host', state.host); ctxChanged(); }); $('#domain').addEventListener('change', function (e) { state.domain = e.target.value; ctxChanged(); }); $('#lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang); applyI18n(); renderNav(); if (current) { $('#page-title').textContent = t(current.page.titleKey); document.title = t(current.page.titleKey) + ' · Urutau'; } if (state.summary) updateHostSelect(state.summary); if (state.domains.length) setDomains(state.domains); renderSlice(); notifyPage(); }); $('#theme').addEventListener('click', function () { var next = currentTheme() === 'dark' ? 'light' : 'dark'; document.documentElement.setAttribute('data-theme', next); lsSet('urutau.theme', next); notifyPage(); }); $('#scrim').addEventListener('click', closeDetail); document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { closeDetail(); setMore(false); return; } var box = $('#detail'); if (e.key === 'Tab' && !box.hidden) { var f = Array.prototype.slice.call(box.querySelectorAll('button, a[href], [tabindex="0"]')); if (!f.length) return; var first = f[0], last = f[f.length - 1]; if (!box.contains(document.activeElement)) { e.preventDefault(); first.focus(); } else if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); } } }); document.addEventListener('click', function (e) { var more = $('#more'); if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false); }); window.addEventListener('hashchange', route); window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage); connectLive(); // the host must be validated before a page asks for data with a stale one shellSummary().catch(function (e) { if (e && e.status === 404 && state.host !== 'all') { state.host = 'all'; lsSet('urutau.host', 'all'); } }).then(function () { renderNav(); route(); }); setInterval(function () { if (document.hidden) return; shellSummary().catch(function () { /* banner already shown */ }); if (current && current.page.refresh) { try { current.page.refresh(); } catch (e) { console.error(e); } } }, 10000); } window.Urutau = { registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP, fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime }, world: world, el: el, css: cssVar, setSliceNote: setSliceNote, ui: { panel: panel, stat: stat, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart } }; if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0); })();