2198 lines
132 KiB
JavaScript
2198 lines
132 KiB
JavaScript
/* 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().
|
|
* ctx also carries { from, to } (unix seconds, set only for a custom window; then
|
|
* range is null) and params = { segments: [...], path: [...], query: {...}, get(name) }:
|
|
* the URL segments after the page id and the query keys the shell does not own
|
|
* (#/ip/1.2.3.4 -> segments ['1.2.3.4']; #/replay?ip=1.2.3.4 -> query.ip).
|
|
* The URL is the source of truth: #/<page>/<segments>?r=6h&host=oracle or
|
|
* ?from=<ISO>&to=<ISO>. Registering { nav: false } keeps a page out of the rail.
|
|
* Urutau.rangeParams() -> { range: '6h' } or { from, to }; pass it to api()
|
|
* Urutau.rangeLabel() -> label of the slice, for buttons and titles ("Last 6 hours", "Últimos 7 dias")
|
|
* Urutau.rangeLabel({article:true}) -> article form without preposition: "the last 7 days", "os últimos 7 dias",
|
|
* "from 12 Nov 10:00 to 14 Nov 18:00" / "de 12 nov 10:00 a 14 nov 18:00" ("Showing the last 7 days")
|
|
* Urutau.rangeLabel({inline:true}) -> lower-case form for the middle of a sentence, with agreement:
|
|
* en "in the last 6 hours" / "in the last hour" / "between 12 Nov 10:00 and 14 Nov 18:00";
|
|
* pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00"
|
|
* Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice
|
|
* Urutau.toast(msg) short confirmation toast
|
|
* Urutau.setNavBadge(pageId, n, title?) counter on the page's rail/tab item (0 removes it)
|
|
* Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby,
|
|
* popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }.
|
|
* Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat.<category>,
|
|
* help.metric.<name> (requests, malicious, unique_ips, attacks_per_hour_24h, moving_avg_7d_per_hour, trend,
|
|
* active_attackers_24h/_1h, new_attackers, returning_rate, sessions_per_day, exposure_rate, exploits_refused_pct,
|
|
* ban_coverage, blocklist_coverage, blocklist_leak, mttb, visitors, pages, bytes, latency, bots) and
|
|
* help.term.<term> (session, stage.recon|probe|exploit|access|banned, campaign, family, mitre, net_type, cadence,
|
|
* score, level, fcrdns, exposure, blocklist, peer, hub, client_type, status_class, attack_profile).
|
|
* Pass the key WITHOUT the "help." prefix: Urutau.help(el, 'metric.mttb'). Metric cards accept {help:'metric.x'},
|
|
* panels accept {help:'term.x'}. Category names: t('cat.<c>') is the long name, t('cat.short.<c>') the short one.
|
|
* Groups: registerPage({..., group:'monitor|investigate|analyze|operate|reports'}); known ids are placed by the built-in
|
|
* order, unknown ids go to the end of their group (default group: analyze).
|
|
* Page scripts load from /pages.json ({"pages":[{"name":"geo","css":true}]}): add your name there when you create <name>.js.
|
|
* Urutau.registerI18n({ en: {...}, 'pt-BR': {...} }) merge keys (existing keys win)
|
|
* Urutau.t(key, vars?) vars: a number (fills {n}) or an object ({name: ...})
|
|
* Urutau.api(path, params) -> Promise<json> GET with query params; 401 goes to
|
|
* /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.charts: own SVG chart library (no dependencies, CSP-safe, theme tokens, ResizeObserver,
|
|
* every chart also renders a visually hidden <table> for screen readers, and an empty
|
|
* state when there is nothing to draw). Every function returns a DOM node; append it.
|
|
* donut(data[{key,label,value}], {title, colors:['--viz-3',...], centerLabel, format})
|
|
* radar(axes[{key,label}], series[{label,values[]}], {max, format, colors, title})
|
|
* stackedArea(series[{key,label,values[]}], stepSeconds, {start (unix), colors, title})
|
|
* bars(rows[{key,label,value,color?:'--token',parts?:[{label,value,color?}]}], {horizontal=true, stacked, format, colors, title})
|
|
* heatmap(matrix[row][col], xLabels[], yLabels[], {format, title}) cells use --seq-1..5
|
|
* sparkline(values[]) gauge(value, max, thresholds[{at,tone:'ok|warn|danger|info'}], {label, format})
|
|
* colors are CSS token names ("--viz-1"); the default palette is --viz-1..8 in order.
|
|
* Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline, pager } 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(/<svg/, '<svg xmlns="' + SVG_NS + '"');
|
|
var doc = new DOMParser().parseFromString(s, 'image/svg+xml');
|
|
var root = doc.documentElement;
|
|
if (!root || root.nodeName.toLowerCase() !== 'svg' || doc.getElementsByTagName('parsererror').length) return fallback();
|
|
var bad = root.querySelectorAll('script, foreignObject, style');
|
|
for (var i = 0; i < bad.length; i++) bad[i].parentNode.removeChild(bad[i]);
|
|
var all = [root].concat(Array.prototype.slice.call(root.querySelectorAll('*')));
|
|
all.forEach(function (n) {
|
|
Array.prototype.slice.call(n.attributes).forEach(function (a) {
|
|
if (/^on/i.test(a.name) || /href/i.test(a.name)) n.removeAttribute(a.name);
|
|
});
|
|
});
|
|
var node = document.importNode(root, true);
|
|
node.setAttribute('aria-hidden', 'true');
|
|
node.removeAttribute('width'); node.removeAttribute('height');
|
|
return node;
|
|
} catch (e) { return fallback(); }
|
|
}
|
|
|
|
// ---------------------------------------------------------------- formatting
|
|
var FLAG_OK = /^[A-Za-z]{2}$/;
|
|
function flag(cc) {
|
|
if (!cc || !FLAG_OK.test(cc)) return '';
|
|
return cc.toUpperCase().replace(/./g, function (c) { return String.fromCodePoint(127397 + c.charCodeAt(0)); });
|
|
}
|
|
var regionNames = null, regionLang = '';
|
|
function countryName(cc) {
|
|
try {
|
|
if (!regionNames || regionLang !== lang) { regionNames = new Intl.DisplayNames([lang], { type: 'region' }); regionLang = lang; }
|
|
return regionNames.of(String(cc).toUpperCase()) || cc;
|
|
} catch (e) { return cc; }
|
|
}
|
|
function fmtBytes(n) {
|
|
var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0;
|
|
while (n >= 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', 'degraded', '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 PRESETS = ['1h', '2h', '3h', '6h', '12h', '24h', '2d', '3d', '5d', '7d', '15d', '30d'];
|
|
var PRESET_GROUPS = [['range.g.hours', ['1h', '2h', '3h', '6h', '12h']], ['range.g.days', ['24h', '2d', '3d', '5d']], ['range.g.weeks', ['7d', '15d', '30d']]];
|
|
var SHORTCUTS = ['1h', '24h', '7d'];
|
|
var MAX_SPAN = 30 * 86400;
|
|
var state = {
|
|
host: lsGet('urutau.host') || 'all', range: lsGet('urutau.range') || '24h', from: null, to: null, domain: 'all',
|
|
live: [], summary: null, hidden: {}, note: '', domains: [], params: { segments: [], path: [], query: {}, get: function () { return null; } }
|
|
};
|
|
if (PRESETS.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 isCustom() { return state.from !== null; }
|
|
function ctx() {
|
|
var c = isCustom();
|
|
return { range: c ? null : state.range, from: c ? state.from : null, to: c ? state.to : null, host: state.host, domain: state.domain, theme: currentTheme(), lang: lang, params: state.params };
|
|
}
|
|
function ctxKey(c) { return [c.range, c.from, c.to, c.host, c.domain].join('|'); }
|
|
function rangeParams() { return isCustom() ? { from: state.from, to: state.to } : { range: state.range }; }
|
|
function presetSecs(p) { var n = parseInt(p, 10); return p.slice(-1) === 'h' ? n * 3600 : n * 86400; }
|
|
function shortDate(ts) {
|
|
var d = new Date(ts * 1000);
|
|
var day = d.toLocaleDateString(lang === 'en' ? 'en-GB' : lang, { day: 'numeric', month: 'short' }).replace(/ de /g, ' ').replace(/\./g, '');
|
|
return day + ' ' + d.toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit', hour12: false });
|
|
}
|
|
// natural, complete label of the slice: "Last 7 days", "Últimas 2 horas", "12 nov 10:00 → 14 nov 18:00"
|
|
function rangeShort() {
|
|
if (isCustom()) return shortDate(state.from) + ' \u2192 ' + shortDate(state.to);
|
|
var n = parseInt(state.range, 10);
|
|
return state.range.slice(-1) === 'h' ? pl('range.nh', n, { n: nf(n) }) : pl('range.nd', n, { n: nf(n) });
|
|
}
|
|
// mid-sentence form: "in the last 7 days", "nas últimas 2 horas", "between 12 Nov 10:00 and 14 Nov 18:00"
|
|
function rangeInline() {
|
|
if (isCustom()) return t('range.in.custom', { a: shortDate(state.from), b: shortDate(state.to) });
|
|
var n = parseInt(state.range, 10);
|
|
return state.range.slice(-1) === 'h' ? pl('range.in.nh', n, { n: nf(n) }) : pl('range.in.nd', n, { n: nf(n) });
|
|
}
|
|
// sentence form with article and no preposition: "the last 7 days", "os últimos 7 dias", "de 12 nov 10:00 a 14 nov 18:00"
|
|
function rangeArticle() {
|
|
if (isCustom()) return t('range.art.custom', { a: shortDate(state.from), b: shortDate(state.to) });
|
|
var n = parseInt(state.range, 10);
|
|
return state.range.slice(-1) === 'h' ? pl('range.art.nh', n, { n: nf(n) }) : pl('range.art.nd', n, { n: nf(n) });
|
|
}
|
|
function rangeLabel(o) { return o && o.inline ? rangeInline() : o && o.article ? rangeArticle() : rangeShort(); }
|
|
function rangeText() { return rangeShort(); }
|
|
function rangeLower() { var x = rangeShort(); return isCustom() ? x : x.charAt(0).toLocaleLowerCase(lang) + x.slice(1); }
|
|
|
|
// ---------------------------------------------------------------- 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 = Object.assign({ host: state.host }, rangeParams());
|
|
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 = ctxKey(c).split('|').slice(0, 4).join('|');
|
|
if (sumCache.key === key && sumCache.p && Date.now() - sumCache.at < 3000) return sumCache.p;
|
|
var q = { host: c.host };
|
|
if (c.from !== null && c.from !== undefined) { q.from = c.from; q.to = c.to; } else q.range = c.range;
|
|
var p = api('/api/v1/summary', q).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;
|
|
}
|
|
// header metrics: the API may not exist yet (older backend), then the callers fall back to the summary
|
|
var metricsMissing = false;
|
|
function getMetrics(c) {
|
|
if (metricsMissing) return Promise.resolve(null);
|
|
c = c || ctx();
|
|
var q = { host: c.host };
|
|
if (c.from !== null && c.from !== undefined) { q.from = c.from; q.to = c.to; } else q.range = c.range;
|
|
return api('/api/v1/metrics', q).then(function (m) { return m && (m.metrics || m); }, function (e) {
|
|
if (e && e.status === 404) metricsMissing = true;
|
|
return null;
|
|
});
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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);
|
|
if (opts.help) help(head.firstChild, opts.help);
|
|
var variant = pick(['list', 'chart', 'map'], opts.variant, '');
|
|
var foot = opts.footer ? h('div', 'panel-f', opts.footer) : null;
|
|
var node = h('section', 'panel' + (variant ? ' card-' + variant : '') + (opts.cls ? ' ' + opts.cls : ''), head, opts.hint ? h('p', 'hint', opts.hint) : null, body, foot);
|
|
if (variant === 'list') body.classList.add('list-body');
|
|
if (opts.loading) body.appendChild(h('div', 'skeleton'));
|
|
node.body = body;
|
|
return node;
|
|
}
|
|
// remove the loading skeleton of a panel once it has content
|
|
function ready(node) { var k = node.body ? node.body.querySelectorAll(':scope > .skeleton') : []; for (var i = 0; i < k.length; i++) k[i].parentNode.removeChild(k[i]); }
|
|
function sparkline(vals) {
|
|
if (!vals || vals.length < 2) return null;
|
|
var max = Math.max.apply(null, vals), min = Math.min.apply(null, vals), span = max - min || 1, n = vals.length;
|
|
var pts = vals.map(function (v, i) { return (i / (n - 1) * 100).toFixed(1) + ',' + (22 - (v - min) / span * 20).toFixed(1); }).join(' ');
|
|
var svg = svgEl('svg', { viewBox: '0 0 100 24', preserveAspectRatio: 'none', 'class': 'cm-spark', 'aria-hidden': 'true' });
|
|
svg.appendChild(svgEl('polyline', { points: pts }));
|
|
return svg;
|
|
}
|
|
// metric card. o: { sub, tone, delta (percent), goodUp (true when an increase is good), spark: [numbers], hint }
|
|
function metric(label, value, o) {
|
|
o = o || {};
|
|
var tn = pick(KNOWN_TONES, o.tone, 'neutral'), dl = null;
|
|
if (typeof o.delta === 'number' && isFinite(o.delta)) {
|
|
var big = Math.abs(o.delta) >= 20, up = o.delta > 0, good = o.goodUp ? up : !up;
|
|
var arrow = o.delta === 0 ? '\u25A0' : up ? '\u25B2' : '\u25BC';
|
|
dl = h('p', 'cm-delta' + (big && o.delta !== 0 ? (good ? ' good' : ' bad') : ''), arrow + ' ' + nfFor({ maximumFractionDigits: 0 }, 'd0').format(Math.abs(o.delta)) + '%');
|
|
}
|
|
var lab = h('p', 'cm-label', label);
|
|
if (o.help) help(lab, o.help);
|
|
var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), lab, h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark));
|
|
if (o.hint) n.title = o.hint;
|
|
return n;
|
|
}
|
|
function stat(label, value, sub, tone, hint, helpKey) { return metric(label, value, { sub: sub, tone: tone, hint: hint, help: helpKey }); }
|
|
function lead(title, body, tone) {
|
|
var tn = pick(['ok', 'danger', 'neutral'], tone, 'ok');
|
|
return h('section', 'lead tone-' + tn, h('div', null, h('h2', null, title), body ? h('p', null, body) : null), h('span', 'pulse', ''));
|
|
}
|
|
var EMPTY_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="12" cy="12" r="9"/><path d="M8 12h8"/></svg>';
|
|
// why it is empty, and what to do about it
|
|
function empty(title, detail, action) {
|
|
return h('div', 'state-empty empty', h('span', 'se-ico', iconNode(EMPTY_ICON)), h('div', 'se-txt', h('strong', null, title), detail ? h('span', null, detail) : null, action || null));
|
|
}
|
|
function widenAction() { var b = el('button', { type: 'button', class: 'btn' }, t('range.widen')); b.addEventListener('click', function () { openRangePicker(); }); return b; }
|
|
function showSkeleton(box, n, cls) { clear(box); for (var i = 0; i < n; i++) box.appendChild(h('div', cls || 'skeleton')); }
|
|
function badge(text, tone) { var tn = pick(KNOWN_TONES, tone, 'neutral'); return h('span', 'badge' + (tn === 'neutral' ? '' : ' tone-' + tn), text); }
|
|
function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return badge(t('level.' + l), LEVEL_TONE[l]); }
|
|
function catShort(c) { var k = pick(KNOWN_CATS, c, 'ok'); return t('cat.short.' + k); }
|
|
function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'), n = h('span', 'cat c-' + k, label || catShort(k)); n.title = t('cat.' + k); return n; }
|
|
|
|
// ---------------------------------------------------------------- help and glossary
|
|
// help.cat.<cat>, help.metric.<name>, help.term.<term> (+ ".do" = what to do) live in the central dictionary
|
|
var glossary = {
|
|
has: function (key) { var k = 'help.' + key; return t(k) !== k; },
|
|
get: function (key) { var k = 'help.' + key, tx = t(k); if (tx === k) return null; var dk = k + '.do', d = t(dk); return { text: tx, action: d === dk ? '' : d }; }
|
|
};
|
|
var helpPop = null, helpBtn = null, helpPinned = false;
|
|
function ensureHelpPop() {
|
|
if (!helpPop) { helpPop = h('div', 'help-pop'); helpPop.id = 'help-pop'; helpPop.setAttribute('role', 'tooltip'); helpPop.hidden = true; document.body.appendChild(helpPop); }
|
|
return helpPop;
|
|
}
|
|
function hideHelp() { if (helpPop) helpPop.hidden = true; helpBtn = null; helpPinned = false; }
|
|
function showHelp(btn, key) {
|
|
var g = glossary.get(key), pop = ensureHelpPop();
|
|
if (!g) return;
|
|
clear(pop);
|
|
pop.appendChild(h('p', 'help-t', g.text));
|
|
if (g.action) pop.appendChild(h('p', 'help-do', h('strong', null, t('help.do') + ': '), g.action));
|
|
pop.hidden = false; helpBtn = btn;
|
|
var r = btn.getBoundingClientRect(), w = pop.offsetWidth, ph = pop.offsetHeight;
|
|
var left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8)), top = r.bottom + 6;
|
|
if (top + ph > window.innerHeight - 8) top = Math.max(8, r.top - ph - 6);
|
|
pop.style.left = left + 'px'; pop.style.top = top + 'px';
|
|
}
|
|
// append an accessible "?" to a node: focusable, aria-describedby, popover with short text + what to do
|
|
function help(node, key) {
|
|
if (!node || !glossary.has(key)) return null;
|
|
var b = el('button', { type: 'button', class: 'help-btn', 'aria-label': t('help.label'), 'aria-describedby': 'help-pop' }, '?');
|
|
ensureHelpPop();
|
|
b.addEventListener('mouseenter', function () { if (!helpPinned) showHelp(b, key); });
|
|
b.addEventListener('focus', function () { if (!helpPinned) showHelp(b, key); });
|
|
b.addEventListener('mouseleave', function () { if (!helpPinned) hideHelp(); });
|
|
b.addEventListener('blur', function () { if (!helpPinned) hideHelp(); });
|
|
b.addEventListener('click', function (e) { e.stopPropagation(); if (helpBtn === b && helpPinned) hideHelp(); else { showHelp(b, key); helpPinned = true; } });
|
|
node.appendChild(b);
|
|
return b;
|
|
}
|
|
|
|
|
|
// ranked list with a proportional bar; rows: [{key, n, label?}]
|
|
function bars(rows, opts) {
|
|
opts = opts || {};
|
|
var box = h('div');
|
|
if (!rows || !rows.length) { box.appendChild(empty(t('top.empty.title'), t('top.empty'), widenAction())); 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 = 220, 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; };
|
|
}
|
|
|
|
// ---------------------------------------------------------------- pager
|
|
// pager({page, pages, total, onPage, hasNext, label}): numbered pages (first/prev/next/last, ellipses) when the
|
|
// page count is known; with only hasNext (cursor lists) just previous/next and "page N". Returns null when
|
|
// there is nothing to page through.
|
|
function pager(o) {
|
|
var page = Math.max(1, o.page || 1), known = typeof o.pages === 'number', pages = known ? Math.max(1, o.pages) : 0;
|
|
if (known && pages <= 1) return null;
|
|
if (!known && page <= 1 && !o.hasNext) return null;
|
|
var nav = el('nav', { class: 'pgr', 'aria-label': o.label || t('pager.nav') });
|
|
function go(n) { return function () { if (o.onPage) o.onPage(n); }; }
|
|
function btn(txt, aria, n, off, cls) {
|
|
var b = el('button', { type: 'button', class: 'btn pgr-b ' + (cls || ''), 'aria-label': aria, title: aria, disabled: off }, txt);
|
|
if (!off) b.addEventListener('click', go(n));
|
|
return b;
|
|
}
|
|
var atEnd = known ? page >= pages : !o.hasNext;
|
|
var list = h('div', 'pgr-l');
|
|
if (known) list.appendChild(btn('\u00ab', t('pager.first'), 1, page <= 1, 'pgr-edge'));
|
|
list.appendChild(btn('\u2039', t('pager.prev'), page - 1, page <= 1));
|
|
if (known) {
|
|
var seq = [], last = 0;
|
|
for (var i = 1; i <= pages; i++) if (i === 1 || i === pages || Math.abs(i - page) <= 1) seq.push(i);
|
|
seq.forEach(function (n) {
|
|
if (last && n - last > 1) list.appendChild(h('span', 'pgr-gap', n - last === 2 ? String(last + 1) : '\u2026'));
|
|
var b = el('button', { type: 'button', class: 'btn pgr-b pgr-n' + (n === page ? ' on' : ''), 'aria-label': t('pager.goto', { n: nf(n) }) }, nf(n));
|
|
if (n === page) b.setAttribute('aria-current', 'page'); else b.addEventListener('click', go(n));
|
|
list.appendChild(b); last = n;
|
|
});
|
|
}
|
|
list.appendChild(btn('\u203a', t('pager.next'), page + 1, atEnd));
|
|
if (known) list.appendChild(btn('\u00bb', t('pager.last'), pages, atEnd, 'pgr-edge'));
|
|
var info = known ? t('pager.page', { n: nf(page), m: nf(pages) }) + (o.total !== undefined && o.total !== null ? ' \u00b7 ' + (o.totalText || nf(o.total)) : '') : t('pager.pageN', { n: nf(page) });
|
|
nav.appendChild(h('span', 'pgr-i', info));
|
|
nav.appendChild(list);
|
|
return nav;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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: 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].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 tbl-cards', thead, tbody);
|
|
var pagerBox = h('div', 'pgr-box');
|
|
var node = h('div', null, toolbar, h('div', 'tbl-wrap', table), pagerBox);
|
|
|
|
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'; }
|
|
reset();
|
|
});
|
|
th.appendChild(b);
|
|
} else th.textContent = colLabel(x.k);
|
|
var hk = { score: 'term.score', level: 'term.level', cats: 'term.categories', origin: 'term.net_type' }[x.k];
|
|
if (hk) help(th, hk);
|
|
tr.appendChild(th);
|
|
});
|
|
thead.appendChild(tr);
|
|
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', null, empty(t('ips.empty.title'), 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', nf(Math.round(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) { { var cp = h('span', 'chip', catShort(k) + ' ' + nf(x.counts[k])); cp.title = t('cat.' + k); chips.appendChild(cp); } });
|
|
if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2)));
|
|
cell('cats', chips); break;
|
|
}
|
|
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);
|
|
});
|
|
drawPager();
|
|
}
|
|
function drawPager() {
|
|
clear(pagerBox);
|
|
var pages = Math.max(1, Math.ceil(st.total / st.per));
|
|
var pg = pager({ page: st.page, pages: pages, total: st.total, totalText: pl('pager.count', st.total, { n: nf(st.total) }), onPage: goPage });
|
|
if (pg) pagerBox.appendChild(pg); else pagerBox.appendChild(h('p', 'note', pl('pager.count', st.total, { n: nf(st.total) })));
|
|
}
|
|
// the full page keeps its page number in the URL (&p=3); the overview widget keeps it locally
|
|
function goPage(n) {
|
|
st.page = n;
|
|
if (full) setParam('p', n);
|
|
load();
|
|
}
|
|
function load() {
|
|
var c = ctx(), key = ctxKey(c);
|
|
if (key !== st.ctxKey) { st.ctxKey = key; if (!full) st.page = 1; }
|
|
if (full) st.page = pageParam();
|
|
buildHead();
|
|
var params = qs({ sort: st.sort, order: st.order, page: st.page, per_page: 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 (st.page > 1 && !r.items.length && r.total) { goPage(Math.max(1, r.pages || 1)); return; } // the list shrank under the page
|
|
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; if (full) setParam('p', 1); return load(); }
|
|
function onHash() { if (full && alive && pageParam() !== st.page) load(); }
|
|
window.addEventListener('hashchange', onHash); // back/forward between pages (route() runs first)
|
|
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(); });
|
|
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); window.removeEventListener('hashchange', onHash); }
|
|
};
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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 spanText(sec) {
|
|
sec = Math.max(0, Math.round(sec));
|
|
if (sec < 90) return t('dur.s', sec);
|
|
if (sec < 5400) return t('dur.m', Math.round(sec / 60));
|
|
if (sec < 172800) return t('dur.h', Math.round(sec / 3600));
|
|
return t('dur.d', Math.round(sec / 86400));
|
|
}
|
|
// the timeline field may arrive as a number array, an array of {n}, or {series:{cat:[...]}}; draw what is numeric
|
|
function numbersOf(tl) {
|
|
if (!tl) return [];
|
|
if (Array.isArray(tl)) return tl.map(function (x) { return typeof x === 'number' ? x : (x && (x.n || x.count || x.v)) || 0; });
|
|
var src = tl.counts || tl.values || tl.total;
|
|
if (Array.isArray(src)) return numbersOf(src);
|
|
if (tl.series && typeof tl.series === 'object') {
|
|
var out = [];
|
|
Object.keys(tl.series).forEach(function (k) { (tl.series[k] || []).forEach(function (v, i) { out[i] = (out[i] || 0) + (typeof v === 'number' ? v : 0); }); });
|
|
return out;
|
|
}
|
|
return [];
|
|
}
|
|
function miniBars(vals, startTs, step) {
|
|
// 6-hour buckets (28 for 7 days) keep every bar readable on a phone
|
|
var g = Math.max(1, Math.round(6 * 3600 / step)), agg = [];
|
|
for (var i = 0; i < vals.length; i += g) { var sm = 0; for (var j = i; j < Math.min(vals.length, i + g); j++) sm += vals[j]; agg.push(sm); }
|
|
var W = 280, H = 56, n = agg.length, max = Math.max.apply(null, agg) || 1, bw = W / n;
|
|
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, 'class': 'mini-bars', role: 'img', 'aria-label': t('drawer.timeline'), preserveAspectRatio: 'none' });
|
|
[0, .5, 1].forEach(function (f) { svg.appendChild(svgEl('line', { x1: 0, x2: W, y1: H - 1 - f * (H - 2), y2: H - 1 - f * (H - 2), 'class': 'gridline' })); });
|
|
agg.forEach(function (v, k) { if (!v) return; var bh = Math.max(2, v / max * (H - 2)); svg.appendChild(svgEl('rect', { x: k * bw + 1, y: H - bh, width: Math.max(2, bw - 2), height: bh })); });
|
|
var days = [], total = Math.round(vals.length * step / 86400), narrow = window.innerWidth < 560, every = narrow ? 2 : 1;
|
|
for (var d = 0; d < total; d += every) days.push(h('span', null, new Date((startTs + d * 86400) * 1000).toLocaleDateString(lang, { day: 'numeric', month: 'short' }).replace(/ de /g, ' ').replace(/\./g, '')));
|
|
return h('div', 'mini-wrap', h('div', 'mini-scale num', h('span', null, nf(max)), h('span', null, nf(Math.round(max / 2))), h('span', null, '0')), h('div', 'mini-plot', svg, h('div', 'mini-days', days)));
|
|
}
|
|
// reasons arrive as an i18n key (intel.reason.<code>) plus params to interpolate
|
|
function reasonText(r) {
|
|
if (typeof r === 'string') return r;
|
|
if (!r) return '';
|
|
var p = r.params && typeof r.params === 'object' ? r.params : {}, code = String(r.code || ''), n = Number(p.n !== undefined ? p.n : r.n) || 0;
|
|
// families: comma separated, trimmed, each translated with the same ip.fam.* keys the IP page uses
|
|
var fams = String(p.families || '').split(',').map(function (x) { return x.trim(); }).filter(Boolean).map(function (f) {
|
|
var k = 'ip.fam.' + f.replace(/[^a-z0-9_-]/gi, ''), v = t(k);
|
|
return v === k ? f : v;
|
|
}).join(', ');
|
|
var vars = { n: nf(n), families: fams || '-', tool: String(p.tool || '-').slice(0, 80), jails: String(p.jails || '-').split(',').map(function (x) { return x.trim(); }).join(', ') };
|
|
var PLURAL = ['exploits_refused', 'multi_category', 'exposure'];
|
|
// the IP page owns the sentences (ip.reason.*, with .one/.other); intel.reason.* is the fallback
|
|
var base = 'ip.reason.' + code, pk = base + (n === 1 ? '.one' : '.other'), tx;
|
|
tx = PLURAL.indexOf(code) >= 0 ? t(pk, vars) : t(base, vars);
|
|
if (tx !== pk && tx !== base) return tx;
|
|
var key = code ? 'intel.reason.' + code : String(r.text || '');
|
|
tx = t(key, vars);
|
|
return tx === key ? code.replace(/[._]/g, ' ') : tx;
|
|
}
|
|
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; }
|
|
box.appendChild(h('div', 'dh', h('h2', null, String(ip)), closeBtn()));
|
|
box.appendChild(h('p', 'note', t('detail.loading')));
|
|
box.querySelector('button').focus();
|
|
api('/api/v1/ip/' + encodeURIComponent(ip)).then(function (d) {
|
|
clear(box);
|
|
var v = d.verdict || {}, tm = d.time || {};
|
|
var level = v.level || d.level, score = Math.round(typeof v.score === 'number' ? v.score : d.score || 0);
|
|
var first = tm.first || d.first, last = tm.last || d.last;
|
|
var cp = el('button', { type: 'button', class: 'btn' }, t('detail.copyIp'));
|
|
cp.addEventListener('click', function () { copyText(d.ip).then(function () { toast(t('toast.copied')); }, function () { /* clipboard blocked */ }); });
|
|
box.appendChild(h('div', 'dh', h('h2', null, d.ip), cp, closeBtn()));
|
|
var origin = [d.cc ? flag(d.cc) + ' ' + countryName(d.cc) : '', d.city || '', d.asn ? 'AS' + d.asn + (d.as_org ? ' ' + d.as_org : '') : ''].filter(Boolean).join(' \u00b7 ');
|
|
var bar = h('div', 'score-bar'), fill = h('i');
|
|
fill.style.width = Math.min(100, Math.max(0, score / 10)) + '%';
|
|
bar.appendChild(fill);
|
|
[[1, 'drawer.cut.susp'], [5, 'drawer.cut.host']].forEach(function (c) { var tk = h('b', 'tick'); tk.style.left = c[0] + '%'; tk.title = t(c[1]); bar.appendChild(tk); });
|
|
var verdict = h('section', 'ip-verdict lv-' + pick(KNOWN_LEVELS, level, 'low'),
|
|
h('div', 'iv-top', (function () { var w = h('span', 'iv-lv', levelBadge(level)); help(w, 'term.level'); return w; })(), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000'), (function () { var w = h('span', 'iv-h'); help(w, 'term.score'); return w; })()), bar,
|
|
h('p', 'note iv-cuts', t('drawer.cuts')),
|
|
origin ? h('p', 'iv-origin', origin) : null,
|
|
first && last ? h('p', 'note', t('drawer.active', { v: spanText(last - first) }) + ' \u00b7 ' + t('detail.last') + ': ' + ago(last)) : null);
|
|
if (pick(KNOWN_LEVELS, level, 'low') === 'hostile' && (v.strong || d.strong) && score < 50) {
|
|
var why = Array.isArray(v.reasons) && v.reasons.length ? reasonText(v.reasons[0]) : '';
|
|
verdict.appendChild(h('p', 'note', t('drawer.byRule', { r: why || t('level.hostile') })));
|
|
}
|
|
if (d.banned || (d.bans && d.bans.length)) verdict.appendChild(h('p', 't-banned', t('detail.jails') + ': ' + ((d.jails || []).join(', ') || t('yes'))));
|
|
box.appendChild(verdict);
|
|
var evs = sumCounts(d.counts || {});
|
|
var days = typeof tm.active_days === 'number' ? nf(tm.active_days) : '\u2014';
|
|
var nbans = (d.bans && d.bans.length) || (d.jails || []).length;
|
|
box.appendChild(h('div', 'drawer-metrics',
|
|
metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans'), help: 'cat.ban' })));
|
|
var tstep = (d.timeline && d.timeline.step) || 3600, all = numbersOf(d.timeline), keep = Math.round(7 * 86400 / tstep), vals = all.slice(-keep);
|
|
if (vals.length > 1 && Math.max.apply(null, vals) > 0) {
|
|
var t0 = ((d.timeline && d.timeline.start) || 0) + (all.length - vals.length) * tstep;
|
|
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.timeline')), miniBars(vals, t0, tstep)));
|
|
}
|
|
if (Array.isArray(d.techniques) && d.techniques.length) {
|
|
var chips = h('div', 'chip-group');
|
|
d.techniques.slice(0, 8).forEach(function (x) { chips.appendChild(h('span', 'chip-mitre', (x.id ? x.id + ' ' : '') + (x.name || '') + (x.n ? ' \u00d7' + nf(x.n) : ''))); });
|
|
var th3 = h('h3', null, t('drawer.techniques')); help(th3, 'term.mitre');
|
|
box.appendChild(h('section', 'drawer-sec', th3, chips));
|
|
}
|
|
var kinds = Object.keys(d.counts || {}).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0 && c !== 'ok' && c !== 'ssh-ok'; });
|
|
if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); var ch3 = h('h3', null, t('drawer.categories')); help(ch3, 'term.categories'); box.appendChild(h('section', 'drawer-sec', ch3, cc)); }
|
|
if (Array.isArray(v.reasons) && v.reasons.length) {
|
|
var ul = h('ul'); v.reasons.slice(0, 3).forEach(function (r) { ul.appendChild(h('li', null, reasonText(r))); });
|
|
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.reasons')), ul));
|
|
}
|
|
var open = el('a', { class: 'btn primary', href: hrefFor('ip', [d.ip]) }, t('drawer.open'));
|
|
open.addEventListener('click', function () { setTimeout(closeDetail, 0); });
|
|
box.appendChild(h('div', 'drawer-actions', open));
|
|
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(empty(t('detail.notfound.title'), t('detail.notfound')));
|
|
box.querySelector('button').focus();
|
|
});
|
|
}
|
|
var toastBox = null;
|
|
function toast(msg) {
|
|
if (!toastBox) toastBox = $('#toasts');
|
|
if (!toastBox) return;
|
|
var n = h('div', 'toast', String(msg));
|
|
toastBox.appendChild(n);
|
|
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
|
|
}
|
|
|
|
// POST/DELETE with a JSON body (same-origin cookie session); resolves with the parsed answer or rejects with its status.
|
|
function apiSend(method, path, body) {
|
|
var o = { method: method, credentials: 'same-origin', headers: { Accept: 'application/json' } };
|
|
if (body !== undefined) { o.body = JSON.stringify(body); o.headers['Content-Type'] = 'application/json'; }
|
|
return fetch(path, o).then(function (r) {
|
|
if (r.status === 401) { location.href = '/login'; throw mkErr('unauthorized', 401); }
|
|
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
|
|
return r.json();
|
|
});
|
|
}
|
|
|
|
// Unban dialog: native <dialog> (focus trap, Esc), a radio group for how long the address stays protected, confirm.
|
|
var UNBAN_CHOICES = [['0', 'unban.keep.none'], ['3600', 'unban.keep.1h'], ['86400', 'unban.keep.24h'], ['604800', 'unban.keep.7d']];
|
|
function unbanDialog(ip, onDone) {
|
|
var prev = document.activeElement;
|
|
var dlg = el('dialog', { class: 'unban-dlg', 'aria-labelledby': 'unban-h', 'aria-describedby': 'unban-p' });
|
|
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
|
|
var fs = el('fieldset', { class: 'unban-opts' }, el('legend', null, t('unban.keep')));
|
|
UNBAN_CHOICES.forEach(function (c, i) {
|
|
var id = 'unban-o' + i;
|
|
var inp = el('input', { type: 'radio', name: 'unban-keep', id: id, value: c[0] });
|
|
if (i === 0) inp.checked = true;
|
|
fs.appendChild(el('div', { class: 'unban-opt' }, inp, el('label', { for: id }, t(c[1]))));
|
|
});
|
|
var ok = el('button', { type: 'button', class: 'btn btn-primary' }, t('unban.confirm'));
|
|
var cancel = el('button', { type: 'button', class: 'btn' }, t('unban.cancel'));
|
|
dlg.appendChild(el('h2', { id: 'unban-h' }, t('unban.title', { ip: ip })));
|
|
dlg.appendChild(el('p', { id: 'unban-p' }, t('unban.explain')));
|
|
dlg.appendChild(fs);
|
|
dlg.appendChild(err);
|
|
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
|
|
function close() { dlg.close(); }
|
|
cancel.addEventListener('click', close);
|
|
dlg.addEventListener('close', function () {
|
|
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
|
|
if (prev && prev.focus && document.contains(prev)) prev.focus();
|
|
});
|
|
ok.addEventListener('click', function () {
|
|
var sel = dlg.querySelector('input[name="unban-keep"]:checked');
|
|
ok.disabled = true;
|
|
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0 }).then(function () {
|
|
close();
|
|
toast(t('unban.done', { ip: ip }));
|
|
if (onDone) onDone();
|
|
}, function (e) {
|
|
ok.disabled = false;
|
|
err.textContent = t(e && e.status === 409 ? 'unban.err.off' : 'unban.err');
|
|
err.hidden = false;
|
|
});
|
|
});
|
|
document.body.appendChild(dlg);
|
|
if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', '');
|
|
ok.focus();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- charts library (own SVG, no dependencies)
|
|
var VIZ = ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-6', '--viz-7', '--viz-8'];
|
|
function vizColor(i, colors) { return 'var(' + ((colors && colors[i % colors.length]) || VIZ[i % VIZ.length]) + ')'; }
|
|
// run fn(width) now and whenever the box is resized
|
|
function watch(node, fn) {
|
|
if (!window.ResizeObserver) { fn(node.clientWidth || 320); return; }
|
|
var last = 0;
|
|
new ResizeObserver(function (es) { var w = Math.round(es[0].contentRect.width); if (w > 0 && w !== last) { last = w; fn(w); } }).observe(node);
|
|
}
|
|
// screen-reader alternative: a real table with the same numbers
|
|
function srTable(caption, head, rows) {
|
|
return h('table', 'sr-only', h('caption', null, caption || ''), h('thead', null, h('tr', null, head.map(function (x) { return el('th', { scope: 'col' }, x); }))),
|
|
h('tbody', null, rows.map(function (r) { return h('tr', null, r.map(function (c) { return h('td', null, String(c)); })); })));
|
|
}
|
|
function sumOf(a) { var s = 0; a.forEach(function (x) { s += x; }); return s; }
|
|
function legendList(items, colors, fmt, onHover) {
|
|
var ul = h('ul', 'vz-legend');
|
|
items.forEach(function (d, i) {
|
|
var li = h('li', null, h('span', 'sw'), h('span', 'vz-l', d.label), h('span', 'vz-v num', fmt(d)));
|
|
li.firstChild.style.background = vizColor(i, colors);
|
|
if (onHover) { li.addEventListener('mouseenter', function () { onHover(i); }); li.addEventListener('mouseleave', function () { onHover(-1); }); }
|
|
ul.appendChild(li);
|
|
});
|
|
return ul;
|
|
}
|
|
// donut(data [{key,label,value}], {title, colors:[token], centerLabel, format})
|
|
function donut(data, o) {
|
|
o = o || {};
|
|
data = (data || []).filter(function (x) { return x && x.value > 0; });
|
|
var total = sumOf(data.map(function (x) { return x.value; })), fmt = o.format || nf;
|
|
if (!total) return empty(t('charts.empty'));
|
|
var R = 70, C = 2 * Math.PI * R, acc = 0, segs = [];
|
|
var svg = svgEl('svg', { viewBox: '0 0 200 200', 'class': 'vz-donut', role: 'img', 'aria-label': o.title || '' });
|
|
var cv = svgEl('text', { x: 100, y: 102, 'text-anchor': 'middle', 'class': 'vz-c-v' }), cl = svgEl('text', { x: 100, y: 124, 'text-anchor': 'middle', 'class': 'vz-c-l' });
|
|
function center(i) {
|
|
if (i < 0) { cv.textContent = fmt(total); cl.textContent = o.centerLabel || t('charts.total'); return; }
|
|
cv.textContent = pct(data[i].value, total); cl.textContent = data[i].label;
|
|
}
|
|
data.forEach(function (d, i) {
|
|
var len = d.value / total * C, vis = Math.max(0.5, len - (data.length > 1 ? 1.5 : 0));
|
|
var c = svgEl('circle', { cx: 100, cy: 100, r: R, fill: 'none', 'stroke-width': 26, 'stroke-dasharray': vis + ' ' + (C - vis), 'stroke-dashoffset': -acc, transform: 'rotate(-90 100 100)', 'class': 'vz-seg', tabindex: 0, 'aria-label': d.label + ': ' + fmt(d.value) + ' (' + pct(d.value, total) + ')' });
|
|
c.style.stroke = vizColor(i, o.colors);
|
|
c.addEventListener('mouseenter', function () { center(i); }); c.addEventListener('focus', function () { center(i); });
|
|
c.addEventListener('mouseleave', function () { center(-1); }); c.addEventListener('blur', function () { center(-1); });
|
|
segs.push(c); svg.appendChild(c); acc += len;
|
|
});
|
|
svg.appendChild(cv); svg.appendChild(cl); center(-1);
|
|
var legend = legendList(data, o.colors, function (d) { return fmt(d.value) + ' · ' + pct(d.value, total); }, function (i) { center(i); segs.forEach(function (s, k) { s.classList.toggle('dim', i >= 0 && k !== i); }); });
|
|
return h('div', 'vz vz-donut-wrap', h('div', 'vz-donut-svg', svg), legend, srTable(o.title, [t('charts.item'), t('charts.value')], data.map(function (d) { return [d.label, fmt(d.value) + ' (' + pct(d.value, total) + ')']; })));
|
|
}
|
|
// radar(axes [{key,label}], series [{label, values[]}], {max, format, colors})
|
|
function radar(axes, series, o) {
|
|
o = o || {};
|
|
var n = axes.length;
|
|
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
|
|
var mx = o.max || Math.max.apply(null, [0].concat.apply([], series.map(function (s) { return s.values; })));
|
|
if (n < 3 || !series.length || !(mx > 0)) return empty(t('charts.empty'));
|
|
var fmt = o.format || nf, W = 360, H = 290, cx = 180, cy = 145, R = 82;
|
|
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, 'class': 'vz-radar', role: 'img', 'aria-label': o.title || '' });
|
|
function pt(i, f) { var a = -Math.PI / 2 + i * 2 * Math.PI / n; return [cx + Math.cos(a) * R * f, cy + Math.sin(a) * R * f, Math.cos(a), Math.sin(a)]; }
|
|
[.25, .5, .75, 1].forEach(function (f) {
|
|
svg.appendChild(svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, f); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-ring' }));
|
|
});
|
|
var rl = svgEl('text', { x: cx + 4, y: cy - R + 12, 'class': 'axis' }); rl.textContent = fmt(mx); svg.appendChild(rl);
|
|
axes.forEach(function (a, i) {
|
|
var p = pt(i, 1), q = pt(i, 1.14);
|
|
svg.appendChild(svgEl('line', { x1: cx, y1: cy, x2: p[0], y2: p[1], 'class': 'gridline' }));
|
|
var tx = svgEl('text', { x: q[0], y: q[1] + 4, 'text-anchor': q[2] > .3 ? 'start' : q[2] < -.3 ? 'end' : 'middle', 'class': 'vz-axl' });
|
|
tx.textContent = a.label; svg.appendChild(tx);
|
|
});
|
|
series.forEach(function (s, k) {
|
|
var col = vizColor(k, o.colors);
|
|
var poly = svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-rs' });
|
|
poly.style.stroke = col; poly.style.fill = col; svg.appendChild(poly);
|
|
axes.forEach(function (a, i) {
|
|
var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)), c = svgEl('circle', { cx: p[0], cy: p[1], r: 3, 'class': 'vz-dot', tabindex: 0, 'aria-label': s.label + ', ' + a.label + ': ' + fmt(s.values[i] || 0) });
|
|
c.style.fill = col; var ti = svgEl('title', {}); ti.textContent = s.label + ' · ' + a.label + ': ' + fmt(s.values[i] || 0); c.appendChild(ti); svg.appendChild(c);
|
|
});
|
|
});
|
|
var legend = legendList(series.map(function (s) { return { label: s.label }; }), o.colors, function () { return ''; });
|
|
return h('div', 'vz vz-radar-wrap', svg, legend, srTable(o.title, [t('charts.item')].concat(series.map(function (s) { return s.label; })), axes.map(function (a, i) { return [a.label].concat(series.map(function (s) { return fmt(s.values[i] || 0); })); })));
|
|
}
|
|
// stackedArea(series [{key,label,values[]}], step seconds, {start, colors, title})
|
|
function stackedArea(series, step, o) {
|
|
o = o || {};
|
|
series = (series || []).filter(function (s) { return s && s.values && s.values.length; });
|
|
var n = series.length ? series[0].values.length : 0, tot = [], mx = 0, i;
|
|
if (n < 2) return empty(t('charts.empty'));
|
|
for (i = 0; i < n; i++) { var v = 0; series.forEach(function (s) { v += s.values[i] || 0; }); tot.push(v); if (v > mx) mx = v; }
|
|
var wrap = h('div', 'chart-wrap vz-area'), box = h('div', 'vz');
|
|
var colors = o.colors;
|
|
function draw(Wpx) {
|
|
clear(wrap);
|
|
var W = Math.max(280, Wpx), H = 220, L = 40, R = 6, Tp = 8, B = 22, top = niceMax(mx), ph = H - Tp - B, dx = (W - L - R) / (n - 1);
|
|
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), k;
|
|
for (k = 0; k <= 4; k++) {
|
|
var y = Tp + ph - ph * k / 4;
|
|
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
|
|
var lb = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); lb.textContent = top >= 10000 ? nfCompact(Math.round(top * k / 4)) : nf(Math.round(top * k / 4)); svg.appendChild(lb);
|
|
}
|
|
var nt = W < 520 ? 3 : 5, longSpan = step * n > 2 * 86400;
|
|
for (k = 0; k < nt; k++) {
|
|
var ix = Math.round((n - 1) * k / (nt - 1)), xl = svgEl('text', { x: L + dx * ix, y: H - 6, 'text-anchor': k === 0 ? 'start' : k === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
|
|
xl.textContent = tickLabel((o.start || 0) + ix * step, longSpan); svg.appendChild(xl);
|
|
}
|
|
var base = []; for (i = 0; i < n; i++) base.push(0);
|
|
series.forEach(function (s, si) {
|
|
var up = [], down = [];
|
|
for (i = 0; i < n; i++) { var lo = base[i], hi = lo + (s.values[i] || 0); up.push((L + dx * i).toFixed(1) + ',' + (Tp + ph - hi / top * ph).toFixed(1)); down.unshift((L + dx * i).toFixed(1) + ',' + (Tp + ph - lo / top * ph).toFixed(1)); base[i] = hi; }
|
|
var p = svgEl('polygon', { points: up.concat(down).join(' '), 'class': 'vz-area-s' }); p.style.fill = vizColor(si, colors); svg.appendChild(p);
|
|
});
|
|
var tip = h('div', 'tip'); tip.hidden = true;
|
|
var guide = svgEl('line', { y1: Tp, y2: Tp + ph, 'class': 'vz-guide' }); guide.style.display = 'none'; svg.appendChild(guide);
|
|
var hit = svgEl('rect', { x: L, y: Tp, width: W - L - R, height: ph, fill: 'transparent' });
|
|
function at(ev) {
|
|
var r = svg.getBoundingClientRect(), px = (ev.clientX - r.left) * W / r.width, ix = Math.max(0, Math.min(n - 1, Math.round((px - L) / dx)));
|
|
clear(tip); tip.appendChild(h('strong', null, new Date(((o.start || 0) + ix * step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
|
series.forEach(function (s) { tip.appendChild(h('div', null, h('span', null, s.label), h('span', 'num', nf(s.values[ix] || 0)))); });
|
|
tip.hidden = false; tip.style.left = Math.max(0, Math.min(L + dx * ix + 12, W - 170)) + 'px'; tip.style.top = '4px';
|
|
guide.setAttribute('x1', L + dx * ix); guide.setAttribute('x2', L + dx * ix); guide.style.display = '';
|
|
}
|
|
hit.addEventListener('mousemove', at); hit.addEventListener('click', at);
|
|
hit.addEventListener('mouseleave', function () { tip.hidden = true; guide.style.display = 'none'; });
|
|
svg.appendChild(hit); wrap.appendChild(svg); wrap.appendChild(tip);
|
|
}
|
|
box.appendChild(wrap);
|
|
box.appendChild(legendList(series.map(function (s) { return { label: s.label }; }), colors, function (d, j) { return ''; }));
|
|
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], series.map(function (s) { return [s.label, nf(sumOf(s.values))]; })));
|
|
watch(wrap, draw);
|
|
return box;
|
|
}
|
|
// bars(rows [{key,label,value,color?,parts?:[{label,value,color?}]}], {horizontal (default true), stacked, format, colors})
|
|
function barChart(rows, o) {
|
|
o = o || {};
|
|
rows = (rows || []).filter(function (r) { return r; });
|
|
var fmt = o.format || nf, hor = o.horizontal !== false;
|
|
function rowTotal(r) { return r.parts ? sumOf(r.parts.map(function (p) { return p.value; })) : r.value; }
|
|
var mx = Math.max.apply(null, [0].concat(rows.map(rowTotal)));
|
|
if (!mx) return empty(t('charts.empty'));
|
|
var box = h('div', 'vz vz-bars' + (hor ? '' : ' vz-cols'));
|
|
rows.forEach(function (r, i) {
|
|
var tot = rowTotal(r), track = h('div', 'vz-track');
|
|
var parts = r.parts && o.stacked !== false ? r.parts : [{ label: r.label, value: r.value, color: r.color }];
|
|
parts.forEach(function (p, j) {
|
|
var seg = h('i'); seg.style[hor ? 'width' : 'height'] = Math.max(p.value ? 1 : 0, p.value / mx * 100) + '%';
|
|
seg.style.background = p.color ? 'var(' + p.color + ')' : vizColor(r.parts ? j : (r.color ? 0 : i), r.color ? [r.color] : o.colors);
|
|
seg.title = p.label + ': ' + fmt(p.value); track.appendChild(seg);
|
|
});
|
|
box.appendChild(h('div', 'vz-row', h('span', 'vz-l', r.label), track, h('span', 'vz-v num', fmt(tot))));
|
|
});
|
|
box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], rows.map(function (r) { return [r.label, fmt(rowTotal(r))]; })));
|
|
return box;
|
|
}
|
|
// heatmap(matrix [row][col] numbers, xLabels, yLabels, {format, title}); cell colour from --seq-1..5
|
|
function heatmap(matrix, xl, yl, o) {
|
|
o = o || {};
|
|
var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); });
|
|
if (!mx) return empty(t('charts.empty'));
|
|
var fmt = o.format || nf, wrap = h('div', 'vz vz-heat');
|
|
function draw(Wpx) {
|
|
clear(wrap);
|
|
var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22;
|
|
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw);
|
|
matrix.forEach(function (row, y) {
|
|
var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt);
|
|
row.forEach(function (v, x) {
|
|
var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0;
|
|
var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) });
|
|
var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r);
|
|
});
|
|
});
|
|
for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); }
|
|
wrap.appendChild(svg);
|
|
}
|
|
var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); })));
|
|
watch(wrap, draw);
|
|
return box;
|
|
}
|
|
// gauge(value, max, thresholds [{at, tone: ok|warn|danger|info}], {label, format})
|
|
function gauge(value, max, thr, o) {
|
|
o = o || {};
|
|
max = max > 0 ? max : 1;
|
|
var fmt = o.format || nf, v = Math.max(0, Math.min(max, Number(value) || 0));
|
|
thr = thr && thr.length ? thr : [{ at: 0, tone: 'ok' }, { at: max * .5, tone: 'warn' }, { at: max * .8, tone: 'danger' }];
|
|
var tone = 'ok'; thr.forEach(function (x) { if (v >= x.at) tone = pick(['ok', 'warn', 'danger', 'info'], x.tone, 'ok'); });
|
|
var d = 'M20 100 A80 80 0 0 1 180 100';
|
|
var svg = svgEl('svg', { viewBox: '0 0 200 120', 'class': 'vz-gauge', role: 'img', 'aria-label': (o.label || '') + ' ' + fmt(v) + ' / ' + fmt(max) });
|
|
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-bg' }));
|
|
svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-fg tone-' + tone, 'stroke-dasharray': (v / max * 100) + ' 100' }));
|
|
var tv = svgEl('text', { x: 100, y: 92, 'text-anchor': 'middle', 'class': 'vz-c-v' }); tv.textContent = fmt(v); svg.appendChild(tv);
|
|
var lo = svgEl('text', { x: 20, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); lo.textContent = '0'; svg.appendChild(lo);
|
|
var hi = svgEl('text', { x: 180, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); hi.textContent = fmt(max); svg.appendChild(hi);
|
|
return h('div', 'vz vz-gauge-wrap', svg, o.label ? h('div', 'vz-c-l', o.label) : null);
|
|
}
|
|
var charts = { donut: donut, radar: radar, stackedArea: stackedArea, bars: barChart, heatmap: heatmap, sparkline: sparkline, gauge: gauge };
|
|
|
|
// ---------------------------------------------------------------- page registry
|
|
var 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(); }
|
|
}
|
|
// rail groups; ids not listed go to the end of their group (page.group, else Analyze)
|
|
var GROUPS = [
|
|
['monitor', ['overview', 'live', 'slo']],
|
|
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search', 'incidents']],
|
|
['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']],
|
|
['operate', ['defense', 'sources', 'integrity']],
|
|
['reports', ['reports']]
|
|
];
|
|
function groupOf(p) {
|
|
if (p.group) for (var i = 0; i < GROUPS.length; i++) if (GROUPS[i][0] === p.group) return p.group;
|
|
for (var j = 0; j < GROUPS.length; j++) if (GROUPS[j][1].indexOf(p.id) >= 0) return GROUPS[j][0];
|
|
return 'analyze';
|
|
}
|
|
function orderedPages() {
|
|
var visible = Object.keys(pages).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; }), out = [];
|
|
GROUPS.forEach(function (g) {
|
|
var mine = visible.filter(function (p) { return groupOf(p) === g[0]; });
|
|
g[1].forEach(function (id) { mine.filter(function (p) { return p.id === id; }).forEach(function (p) { out.push(p); }); });
|
|
mine.filter(function (p) { return g[1].indexOf(p.id) < 0; }).sort(function (a, b) { return a.id < b.id ? -1 : 1; }).forEach(function (p) { out.push(p); });
|
|
});
|
|
return out;
|
|
}
|
|
function sp(n, node) { node.classList.add('span-' + n); return node; }
|
|
function grid12() { return h('div', 'grid-12'); }
|
|
function skeletonCards(box, n) { clear(box); for (var i = 0; i < n; i++) box.appendChild(h('div', 'card-metric skeleton')); }
|
|
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); } } }
|
|
var errBox = null;
|
|
function load() {
|
|
var my = ++seq;
|
|
return spec.load(c, view).then(function (d) {
|
|
if (!alive || my !== seq) return;
|
|
if (errBox && errBox.parentNode) errBox.parentNode.removeChild(errBox);
|
|
errBox = null; data = d; paint();
|
|
}).catch(function () {
|
|
if (!alive || my !== seq || data || errBox) return;
|
|
var retry = el('button', { type: 'button', class: 'btn' }, t('state.retry'));
|
|
retry.addEventListener('click', load);
|
|
errBox = h('div', 'state-error', h('strong', null, t('error.load')), retry);
|
|
root.insertBefore(errBox, root.firstChild);
|
|
});
|
|
}
|
|
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 (ctxKey(prev) !== ctxKey(cx)) { data = null; load(); }
|
|
},
|
|
refresh: function () { load(); },
|
|
unmount: function () { alive = false; seq++; if (view && spec.dispose) spec.dispose(view); view = null; clear(root); }
|
|
};
|
|
}
|
|
|
|
var ICONS = {
|
|
overview: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/></svg>',
|
|
threats: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"/><path d="M12 8v5M12 16h.01"/></svg>',
|
|
traffic: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M3 20h18"/><path d="M6 20v-7M11 20V6M16 20v-10M21 20v-5"/></svg>',
|
|
ips: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="4" width="18" height="6" rx="1.5"/><rect x="3" y="14" width="18" height="6" rx="1.5"/><path d="M7 7h.01M7 17h.01"/></svg>',
|
|
sources: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><ellipse cx="12" cy="6" rx="8" ry="3"/><path d="M4 6v6c0 1.7 3.6 3 8 3s8-1.3 8-3V6"/><path d="M4 12v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6"/></svg>'
|
|
};
|
|
|
|
// ---------------------------------------------------------------- shared blocks
|
|
function bucketNote(step) { return step ? t('timeline.bucket', { n: nf(Math.max(1, Math.round(step / 60))) }) : ''; }
|
|
function timelinePanel() {
|
|
var wrap = h('div', 'chart-wrap'), legend = h('div', 'legend'), note = h('span', 'note bucket-note');
|
|
var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true, help: 'metric.attacks_per_hour_24h' }, 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);
|
|
b.title = t('cat.' + c);
|
|
});
|
|
help(legend, 'term.categories');
|
|
legend.appendChild(note);
|
|
}
|
|
function draw() {
|
|
if (!data) return;
|
|
ready(node);
|
|
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 }];
|
|
note.textContent = bucketNote(tl.step);
|
|
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 };
|
|
}
|
|
var METRIC_ORDER = {
|
|
overview: ['attacks_per_hour_24h', 'active_attackers_24h', 'new_attackers', 'mttb', 'ban_coverage', 'exposure_rate'],
|
|
threats: ['attacks_per_hour_24h', 'moving_avg_7d_per_hour', 'active_attackers_24h', 'new_attackers', 'blocklist_coverage', 'exposure_rate']
|
|
};
|
|
var GOOD_UP = { ban_coverage: 1, blocklist_coverage: 1 };
|
|
var RATIO = { ban_coverage: 1, blocklist_coverage: 1, exposure_rate: 1 };
|
|
function durationText(sec) {
|
|
sec = Math.max(0, Math.round(sec));
|
|
if (sec < 60) return t('dur.s', sec);
|
|
if (sec < 3600) return t('dur.m', Math.round(sec / 60));
|
|
if (sec < 86400) return t('dur.h', nfFor({ maximumFractionDigits: 1 }, 'd1').format(sec / 3600));
|
|
return t('dur.d', nfFor({ maximumFractionDigits: 1 }, 'd1').format(sec / 86400));
|
|
}
|
|
function metricValue(key, v) {
|
|
if (typeof v !== 'number' || !isFinite(v)) return '\u2014';
|
|
if (key === 'mttb') return durationText(v);
|
|
if (RATIO[key]) return pct(v / 100); // the API reports percentages
|
|
return nfFor({ maximumFractionDigits: v < 100 && v % 1 ? 1 : 0 }, 'm').format(v);
|
|
}
|
|
function metricSub(k, x) {
|
|
if (typeof x.value !== 'number' || !isFinite(x.value)) return k === 'mttb' ? t('metric.noBan') : null;
|
|
if (typeof x.prev === 'number' && x.prev > 0) return t('metric.prev', { v: metricValue(k, x.prev) });
|
|
return t('metric.noBase');
|
|
}
|
|
function metricLabel(key) {
|
|
var k = 'metric.' + key;
|
|
return ((D[lang] && D[lang][k]) || D.en[k]) ? t(k) : key.replace(/_/g, ' ');
|
|
}
|
|
// header cards from /api/v1/metrics; returns false when the API gave nothing usable
|
|
function metricRow(m, which, box) {
|
|
if (!m || typeof m !== 'object') return false;
|
|
var mm = Object.assign({}, m);
|
|
if (m.mttb && typeof m.mttb.median_s === 'number') {
|
|
var pv = m.mttb.prev_median_s;
|
|
mm.mttb = { value: m.mttb.n ? m.mttb.median_s : NaN, prev: m.mttb.n ? pv : undefined, delta_pct: m.mttb.n && pv > 0 ? (m.mttb.median_s - pv) / pv * 100 : undefined, n: m.mttb.n };
|
|
}
|
|
m = mm;
|
|
var keys = METRIC_ORDER[which].filter(function (k) { return m[k] && typeof m[k] === 'object' && ('value' in m[k]); });
|
|
if (keys.length < 3) return false;
|
|
clear(box);
|
|
keys.forEach(function (k) {
|
|
var x = m[k];
|
|
box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x), help: 'metric.' + k }));
|
|
});
|
|
return true;
|
|
}
|
|
function kpiRow(s, box, m, which) {
|
|
if (metricRow(m, which, box)) return;
|
|
var T = s.totals, hosts = s.hosts || [], on = hosts.filter(function (x) { return x.online; }).length;
|
|
var range = rangeLower();
|
|
clear(box);
|
|
box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.requests'));
|
|
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral', null, 'metric.malicious'));
|
|
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral', null, 'term.level'));
|
|
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral', null, 'term.level'));
|
|
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'), 'neutral', null, 'cat.ban'));
|
|
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.unique_ips'));
|
|
}
|
|
function overviewLead(s) {
|
|
var T = s.totals;
|
|
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 num', nf(Math.round(x.score))), sub, bar));
|
|
});
|
|
return box;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- page: overview
|
|
var RADAR_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe'];
|
|
var pOverview = corePage({
|
|
id: 'overview', icon: ICONS.overview, titleKey: 'nav.overview',
|
|
build: function (root) {
|
|
var v = {}, g = grid12();
|
|
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
|
|
v.timeline = timelinePanel();
|
|
v.radar = panel({ title: t('ov.radar'), hint: t('ov.radar.hint'), loading: true, help: 'term.attack_profile' });
|
|
v.countries = panel({ title: t('ov.countries'), hint: t('ov.countries.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/geo' }, t('ov.all')) });
|
|
v.topips = panel({ title: t('ov.topips'), hint: t('ov.topips.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/ips' }, t('ov.all')) });
|
|
v.feedList = feedList(30);
|
|
v.feed = panel({ title: t('ov.feed'), hint: t('ov.feed.hint'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
|
|
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(8, v.timeline.node)); g.appendChild(sp(4, v.radar));
|
|
g.appendChild(sp(4, v.countries)); g.appendChild(sp(4, v.topips)); g.appendChild(sp(4, v.feed));
|
|
root.appendChild(g);
|
|
v.offResize = onResize(function () { v.timeline.draw(); });
|
|
v.offFeed = liveFeedBinding(v.feedList);
|
|
v.feedList.render();
|
|
return v;
|
|
},
|
|
load: function (c) {
|
|
return getSummary(c).then(function (s) {
|
|
var hosts = (s.hosts || []).filter(function (x) { return x.online !== false; }).slice(0, 4);
|
|
var rq = c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range };
|
|
var jobs = hosts.length > 1 ? hosts.map(function (x) { return api('/api/v1/summary', Object.assign({ host: x.name }, rq)).then(function (r) { return { label: x.name, s: r }; }, function () { return null; }); }) : [Promise.resolve({ label: (hosts[0] && hosts[0].name) || t('host.all'), s: s })];
|
|
return Promise.all(jobs).then(function (rs) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m, radar: rs.filter(Boolean) }); }); });
|
|
});
|
|
},
|
|
render: function (v, s) {
|
|
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel'); v.lead.appendChild(overviewLead(s));
|
|
ready(v.radar); clear(v.radar.body);
|
|
v.radar.body.appendChild(charts.radar(RADAR_CATS.map(function (c) { return { key: c, label: catShort(c) }; }), (s.radar || []).map(function (r) {
|
|
var vals = RADAR_CATS.map(function (c) { var n = 0; ((r.s.timeline.series || {})[c] || []).forEach(function (x) { n += x; }); return n; }), tot = sumOf(vals) || 1;
|
|
return { label: r.label, values: vals.map(function (x) { return Math.round(x / tot * 1000) / 10; }) };
|
|
}), { title: t('ov.radar'), format: function (x) { return nf(x) + '%' } }));
|
|
kpiRow(s, v.kpis, s.metrics, 'overview');
|
|
v.timeline.set(s);
|
|
clear(v.countries.body); v.countries.body.appendChild(bars(s.countries, { label: function (r) { return countryLabel(r.key); } }));
|
|
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 = {}, g = grid12();
|
|
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); v.mon = sp(12, h('p', 'note'));
|
|
v.timeline = timelinePanel();
|
|
v.mapbox = mapBox();
|
|
v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true, help: 'term.categories' }, v.mapbox);
|
|
v.tbl = ipTable(false);
|
|
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score', actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node);
|
|
v.feedList = feedList(100);
|
|
v.feed = panel({ title: t('feed.title'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node);
|
|
v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true, help: 'cat.scanner' }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true, help: 'metric.requests' });
|
|
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true, help: 'term.family' }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true, help: 'cat.ssh-fail' });
|
|
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(v.mon); g.appendChild(sp(12, v.timeline.node)); g.appendChild(sp(8, v.map)); g.appendChild(sp(4, v.feed));
|
|
g.appendChild(sp(12, v.ips));
|
|
[v.paths, v.domains, v.uas, v.users].forEach(function (x) { g.appendChild(sp(3, x)); });
|
|
root.appendChild(g);
|
|
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 getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m }); });
|
|
});
|
|
},
|
|
render: function (v, s) {
|
|
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel'); v.lead.appendChild(threatsLead(s));
|
|
kpiRow(s, v.kpis, s.metrics, 'threats');
|
|
v.mon.textContent = s.totals.monitoring ? t('kpi.monitoring', nf(s.totals.monitoring)) : '';
|
|
v.mon.hidden = !s.totals.monitoring;
|
|
v.timeline.set(s);
|
|
ready(v.map);
|
|
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 CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
|
|
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
|
|
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
|
|
var pTraffic = corePage({
|
|
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
|
|
build: function (root) {
|
|
var v = {}, g = grid12();
|
|
v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6);
|
|
v.wrap = h('div'); v.note = h('span', 'note bucket-note');
|
|
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.area.hint'), variant: 'chart', loading: true, help: 'metric.pages' }, v.wrap, h('div', 'legend', v.note));
|
|
v.mapbox = mapBox();
|
|
v.map = panel({ title: t('map.visitors'), hint: t('map.visitors.hint'), variant: 'map', loading: true }, v.mapbox);
|
|
var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['bots', 'traffic.bots']];
|
|
ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]), variant: 'list', loading: true }); });
|
|
v.client = panel({ title: t('traffic.client'), hint: t('traffic.client.hint'), loading: true, help: 'term.client_type' });
|
|
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
|
|
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
|
|
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
|
|
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
|
|
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
|
|
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
|
|
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
|
|
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
|
|
g.appendChild(v.privacy);
|
|
root.appendChild(g);
|
|
return v;
|
|
},
|
|
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
|
|
render: function (v, d) {
|
|
v.data = d;
|
|
setDomains(d.domains || []);
|
|
var hasData = d.requests > 0;
|
|
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel');
|
|
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);
|
|
var rg = rangeLower();
|
|
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'), 'neutral', null, 'metric.requests'));
|
|
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }), 'neutral', null, 'metric.pages'));
|
|
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'), 'neutral', null, 'metric.visitors'));
|
|
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.bytes'));
|
|
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms), 'ms \u00b7 ' + t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.latency'));
|
|
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }), 'neutral', null, 'metric.bots'));
|
|
// time series: page views and the rest of the requests
|
|
var tl = d.timeline, pg = tl.pages || [], other = (tl.req || []).map(function (x, i) { return Math.max(0, x - (pg[i] || 0)); });
|
|
ready(v.timeline); clear(v.wrap);
|
|
v.note.textContent = bucketNote(tl.step);
|
|
v.wrap.appendChild(charts.stackedArea([{ key: 'pages', label: t('traffic.pages'), values: pg }, { key: 'other', label: t('traffic.otherReq'), values: other }], tl.step, { start: tl.start, colors: ['--accent', '--viz-8'], title: t('traffic.timeline') }));
|
|
ready(v.map);
|
|
renderMap(v.mapbox, d.countries, true, t('map.visitors'));
|
|
function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); }
|
|
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); fill('bots', d.bot_names, false);
|
|
// client type: devices as reported, plus bots when the devices list has no bot entry
|
|
var dev = (d.devices || []).map(function (x) { return { k: pick(CLIENT_ORDER, x.key, 'misc'), n: x.n }; });
|
|
dev.sort(function (a, b) { return CLIENT_ORDER.indexOf(a.k) - CLIENT_ORDER.indexOf(b.k); });
|
|
function donutOf(box, data, colors, title) { ready(box); clear(box.body); box.body.appendChild(charts.donut(data, { title: title, colors: colors })); }
|
|
donutOf(v.client, dev.map(function (x) { return { key: x.k, label: t('device.' + x.k), value: x.n }; }), dev.map(function (x) { return CLIENT_COLORS[x.k]; }), t('traffic.client'));
|
|
donutOf(v.browsers, (d.browsers || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.browsers'));
|
|
donutOf(v.oses, (d.oses || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.oses'));
|
|
var cls = ['2xx', '3xx', '4xx', '5xx'];
|
|
ready(v.status); clear(v.status.body);
|
|
v.status.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (d.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
|
|
},
|
|
dispose: function () { }
|
|
});
|
|
|
|
// ---------------------------------------------------------------- page: ips
|
|
var pIPs = corePage({
|
|
id: 'ips', icon: ICONS.ips, titleKey: 'nav.ips',
|
|
build: function (root) {
|
|
var v = {}, g = grid12();
|
|
v.lead = sp(12, h('div'));
|
|
v.tbl = ipTable(true);
|
|
v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); });
|
|
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score' }, v.tbl.node);
|
|
g.appendChild(v.lead); g.appendChild(sp(12, v.ips)); root.appendChild(g);
|
|
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'), help: 'term.blocklist' },
|
|
h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg);
|
|
var timer = 0, alive = true;
|
|
function query(extra) {
|
|
var o = Object.assign({ host: state.host, min_score: minScore.value || '50', family: fam.value }, rangeParams());
|
|
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', Object.assign({ host: state.host, min_score: minScore.value || '50', family: fam.value }, rangeParams())).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 = {}, g = grid12();
|
|
v.lead = sp(12, h('div'));
|
|
v.hostsBox = h('div', 'hosts');
|
|
v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox);
|
|
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
|
|
v.tbody = h('tbody');
|
|
v.srcEmpty = h('div');
|
|
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint'), help: 'term.integrity_gap' }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty);
|
|
v.geoBox = h('div');
|
|
v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox);
|
|
v.bl = blocklistPanel();
|
|
g.appendChild(v.lead); g.appendChild(sp(12, v.hosts)); g.appendChild(sp(12, v.sources)); g.appendChild(sp(6, v.geo)); g.appendChild(sp(6, v.bl.node)); root.appendChild(g);
|
|
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; });
|
|
|
|
// ---------------------------------------------------------------- url (the source of truth)
|
|
function parseHash() {
|
|
var raw = location.hash.replace(/^#\/?/, ''), q = '', i = raw.indexOf('?');
|
|
if (i >= 0) { q = raw.slice(i + 1); raw = raw.slice(0, i); }
|
|
var segs = raw.split('/').filter(Boolean).map(function (x) { try { return decodeURIComponent(x); } catch (e) { return x; } });
|
|
return { page: segs.shift() || '', segments: segs, query: new URLSearchParams(q) };
|
|
}
|
|
// shell query for a slice: ?r=6h&host=x or ?from=<ISO>&to=<ISO>
|
|
function shellQuery(sl) {
|
|
var p = [];
|
|
if (sl.from !== null && sl.from !== undefined) p.push('from=' + encodeURIComponent(new Date(sl.from * 1000).toISOString()), 'to=' + encodeURIComponent(new Date(sl.to * 1000).toISOString()));
|
|
else p.push('r=' + sl.range);
|
|
if (sl.host && sl.host !== 'all') p.push('host=' + encodeURIComponent(sl.host));
|
|
return p;
|
|
}
|
|
function buildHash(id, segments, extra, sl) {
|
|
var parts = shellQuery(sl || state);
|
|
Object.keys(extra || {}).forEach(function (k) { parts.push(encodeURIComponent(k) + '=' + encodeURIComponent(extra[k])); });
|
|
return '#/' + [id].concat((segments || []).map(encodeURIComponent)).join('/') + '?' + parts.join('&');
|
|
}
|
|
function hrefFor(id, segments, extra) { return buildHash(id, segments || [], extra || {}); }
|
|
// read r/from/to/host from the URL; absent keys keep the current slice
|
|
function readSlice(q) {
|
|
var f = q.get('from'), to = q.get('to'), r = q.get('r') || q.get('range'), ok = false;
|
|
if (f && to) {
|
|
var a = Date.parse(f), b = Date.parse(to);
|
|
if (isFinite(a) && isFinite(b) && b > a && (b - a) / 1000 <= MAX_SPAN) { state.from = Math.floor(a / 1000); state.to = Math.floor(b / 1000); ok = true; }
|
|
}
|
|
if (!ok && r && PRESETS.indexOf(r) >= 0) { state.range = r; state.from = state.to = null; lsSet('urutau.range', r); }
|
|
if (q.has('host')) { state.host = q.get('host') || 'all'; lsSet('urutau.host', state.host); }
|
|
}
|
|
// change the slice: the URL changes, the router does the rest
|
|
function setShell(over) {
|
|
var sl = { range: state.range, from: state.from, to: state.to, host: state.host };
|
|
Object.keys(over).forEach(function (k) { sl[k] = over[k]; });
|
|
var q = Object.assign({}, state.params.query); delete q.p; // a new period or host starts at page 1
|
|
var id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, q, sl);
|
|
if (hash !== location.hash) history.pushState(null, '', hash);
|
|
route();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- range picker
|
|
var rp = { open: false, pop: null, btn: null, from: null, to: null, err: null };
|
|
function localInput(ts) {
|
|
var d = new Date(ts * 1000), p = function (n) { return String(n).padStart(2, '0'); };
|
|
return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + 'T' + p(d.getHours()) + ':' + p(d.getMinutes());
|
|
}
|
|
function presetButtons() { return rp.pop ? Array.prototype.slice.call(rp.pop.querySelectorAll('.chip-btn')) : []; }
|
|
function renderRangePicker() {
|
|
if (!rp.btn) return;
|
|
rp.label.textContent = rangeShort();
|
|
var custom = isCustom();
|
|
document.querySelectorAll('#range-picker [data-range]').forEach(function (b) { b.setAttribute('aria-pressed', !custom && b.getAttribute('data-range') === state.range ? 'true' : 'false'); });
|
|
if (rp.from) { var now = Math.floor(Date.now() / 1000); rp.from.value = localInput(custom ? state.from : now - presetSecs(state.range)); rp.to.value = localInput(custom ? state.to : now); }
|
|
}
|
|
function closeRangePicker(refocus) {
|
|
if (!rp.open) return;
|
|
rp.open = false; rp.pop.hidden = true; rp.scrim.hidden = true; rp.btn.setAttribute('aria-expanded', 'false');
|
|
if (refocus) rp.btn.focus();
|
|
}
|
|
function openRangePicker() {
|
|
if (!rp.pop) return;
|
|
renderRangePicker();
|
|
rp.err.textContent = '';
|
|
rp.open = true; rp.pop.hidden = false; rp.scrim.hidden = false; rp.btn.setAttribute('aria-expanded', 'true');
|
|
var cur = rp.pop.querySelector('.chip-btn[aria-pressed="true"]') || rp.pop.querySelector('.chip-btn');
|
|
if (cur) cur.focus();
|
|
}
|
|
function stepPreset(dir) {
|
|
var i = PRESETS.indexOf(state.range);
|
|
if (isCustom() || i < 0) return;
|
|
var n = Math.min(PRESETS.length - 1, Math.max(0, i + dir));
|
|
if (n !== i) setShell({ range: PRESETS[n], from: null, to: null });
|
|
}
|
|
function shiftWindow(dir) {
|
|
if (!isCustom()) return;
|
|
var span = state.to - state.from, now = Math.floor(Date.now() / 1000), nf2 = state.from + dir * span, nt = state.to + dir * span;
|
|
if (nt > now) { nt = now; nf2 = now - span; }
|
|
setShell({ from: nf2, to: nt });
|
|
}
|
|
function applyCustom() {
|
|
var a = Date.parse(rp.from.value), b = Date.parse(rp.to.value);
|
|
var msg = '';
|
|
if (!isFinite(a) || !isFinite(b)) msg = t('range.err.missing');
|
|
else if (b <= a) msg = t('range.err.order');
|
|
else if ((b - a) / 1000 > MAX_SPAN) msg = t('range.err.span');
|
|
rp.err.textContent = msg;
|
|
if (msg) return;
|
|
closeRangePicker(true);
|
|
setShell({ from: Math.floor(a / 1000), to: Math.floor(b / 1000) });
|
|
}
|
|
function buildRangePicker() {
|
|
var box = $('#range-picker');
|
|
clear(box);
|
|
rp.btn = el('button', { type: 'button', class: 'btn rp-btn', 'aria-haspopup': 'dialog', 'aria-expanded': 'false', 'aria-controls': 'rp-pop', 'aria-label': t('range.picker'), title: t('range.keys') });
|
|
rp.label = h('span', 'rp-label');
|
|
rp.btn.appendChild(rp.label);
|
|
rp.btn.appendChild(h('span', 'rp-caret', '\u25BE'));
|
|
rp.btn.lastChild.setAttribute('aria-hidden', 'true');
|
|
rp.btn.addEventListener('click', function () { rp.open ? closeRangePicker(true) : openRangePicker(); });
|
|
var sc = h('div', 'seg rp-shortcuts');
|
|
sc.setAttribute('role', 'group'); sc.setAttribute('aria-label', t('range.label'));
|
|
SHORTCUTS.forEach(function (p) {
|
|
var b = el('button', { type: 'button', 'data-range': p }, parseInt(p, 10) + ' ' + p.slice(-1));
|
|
b.addEventListener('click', function () { setShell({ range: p, from: null, to: null }); });
|
|
sc.appendChild(b);
|
|
});
|
|
rp.pop = h('div', 'popover rp-pop');
|
|
rp.pop.id = 'rp-pop'; rp.pop.setAttribute('role', 'dialog'); rp.pop.setAttribute('aria-label', t('range.picker')); rp.pop.hidden = true;
|
|
PRESET_GROUPS.forEach(function (g) {
|
|
var grp = h('div', 'chip-group');
|
|
g[1].forEach(function (p) {
|
|
var b = el('button', { type: 'button', class: 'chip-btn', 'data-range': p, 'aria-pressed': 'false' }, parseInt(p, 10) + ' ' + p.slice(-1));
|
|
b.addEventListener('click', function () { closeRangePicker(true); setShell({ range: p, from: null, to: null }); });
|
|
grp.appendChild(b);
|
|
});
|
|
rp.pop.appendChild(h('div', 'rp-group', h('div', 'rp-title', t(g[0])), grp));
|
|
});
|
|
rp.from = el('input', { type: 'datetime-local', id: 'rp-from' }); rp.to = el('input', { type: 'datetime-local', id: 'rp-to' });
|
|
rp.err = h('p', 'rp-err'); rp.err.setAttribute('role', 'alert');
|
|
var apply = el('button', { type: 'button', class: 'btn primary' }, t('range.apply'));
|
|
apply.addEventListener('click', applyCustom);
|
|
rp.pop.appendChild(h('div', 'rp-group rp-custom', h('div', 'rp-title', t('range.custom')),
|
|
h('label', null, h('span', null, t('range.from')), rp.from), h('label', null, h('span', null, t('range.to')), rp.to), rp.err, apply));
|
|
rp.pop.appendChild(h('p', 'note rp-keys', t('range.keys')));
|
|
rp.pop.addEventListener('keydown', function (e) {
|
|
var tg = e.target;
|
|
if (e.key === 'Escape') { e.stopPropagation(); closeRangePicker(true); return; }
|
|
if (tg.classList && tg.classList.contains('chip-btn') && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].indexOf(e.key) >= 0) {
|
|
var list = presetButtons(), i = list.indexOf(tg), d = (e.key === 'ArrowLeft' || e.key === 'ArrowUp') ? -1 : 1;
|
|
e.preventDefault(); list[(i + d + list.length) % list.length].focus();
|
|
}
|
|
});
|
|
rp.scrim = h('div', 'scrim rp-scrim'); rp.scrim.hidden = true;
|
|
rp.scrim.addEventListener('click', function () { closeRangePicker(true); });
|
|
box.appendChild(rp.btn); box.appendChild(sc); box.appendChild(rp.pop); box.appendChild(rp.scrim);
|
|
rp.open = false;
|
|
renderRangePicker();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- 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, rangeArticle()));
|
|
p.appendChild(document.createTextNode(' · ' + parts.join(' · ')));
|
|
$('#domain').hidden = !(current && pages[current.id] && pages[current.id].domain);
|
|
renderRangePicker();
|
|
}
|
|
|
|
function navId() { return current ? (current.id === 'ip' ? 'ips' : current.id) : null; }
|
|
// small counter on a rail/tab item (e.g. open incidents); n <= 0 removes it. Set by page scripts.
|
|
var navBadges = {};
|
|
function setNavBadge(id, n, label) {
|
|
n = Math.max(0, Math.floor(Number(n) || 0));
|
|
var old = navBadges[id];
|
|
if (old ? old.n === n && old.label === label : n === 0) return;
|
|
if (n) navBadges[id] = { n: n, label: label || '' }; else delete navBadges[id];
|
|
if (booted) renderNav();
|
|
}
|
|
function navBadgeNode(id) {
|
|
var b = navBadges[id];
|
|
if (!b) return null;
|
|
var n = h('span', 'nav-badge', b.n > 99 ? '99+' : String(b.n));
|
|
if (b.label) n.title = b.label;
|
|
return n;
|
|
}
|
|
function renderNav() {
|
|
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
|
|
clear(nav); clear(bar); clear(more);
|
|
var lastGroup = null;
|
|
list.forEach(function (p) {
|
|
var label = t(p.titleKey), gr = groupOf(p);
|
|
if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; }
|
|
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label), navBadgeNode(p.id));
|
|
if (cur === p.id) 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: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
|
if (cur === 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('<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><circle cx="5" cy="12" r="1.2"/><circle cx="12" cy="12" r="1.2"/><circle cx="19" cy="12" r="1.2"/></svg>')), h('span', null, t('nav.more')));
|
|
if (rest.some(function (p) { return p.id === cur; })) mb.setAttribute('aria-current', 'page');
|
|
mb.addEventListener('click', function () { setMore(more.hidden); });
|
|
bar.appendChild(mb);
|
|
var rg = null;
|
|
rest.forEach(function (p) {
|
|
var g2 = groupOf(p);
|
|
if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; }
|
|
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
|
if (cur === 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 mkParams(segments, extra) {
|
|
return { segments: segments, path: segments, query: extra, get: function (n) { return Object.prototype.hasOwnProperty.call(extra, n) ? extra[n] : null; } };
|
|
}
|
|
// one query parameter of the current page (e.g. p, the page number); null when absent
|
|
function param(name) { return state.params.get(name); }
|
|
// set or drop one query parameter in the hash without re-routing: the caller reloads its own data.
|
|
// p=1 is the default and never written, so the first page keeps a clean link.
|
|
function setParam(name, val) {
|
|
var q = Object.assign({}, state.params.query);
|
|
if (val === '' || val === null || val === undefined || (name === 'p' && String(val) === '1')) delete q[name]; else q[name] = String(val);
|
|
state.params = mkParams(state.params.segments, q);
|
|
var hash = buildHash(current ? current.id : 'overview', state.params.segments, q);
|
|
if (hash !== location.hash) history.pushState(null, '', hash);
|
|
if (current) current.sig = pageSig();
|
|
}
|
|
// page number of the URL (>= 1)
|
|
function pageParam() { var n = parseInt(param('p'), 10); return n >= 1 ? Math.min(n, 100000) : 1; }
|
|
function pageSig() { var c = ctx(); return ctxKey(c) + '|' + JSON.stringify(state.params.segments) + '|' + JSON.stringify(state.params.query); }
|
|
function route() {
|
|
var u = parseHash(), id = u.page;
|
|
if (!id || !pages[id]) {
|
|
var saved = lsGet('urutau.page');
|
|
id = pages[saved] && saved !== 'ip' ? saved : pages.overview ? 'overview' : orderedPages()[0].id;
|
|
u = { page: id, segments: [], query: u.query };
|
|
}
|
|
readSlice(u.query);
|
|
var extra = {};
|
|
u.query.forEach(function (v, k) { if (['r', 'range', 'from', 'to', 'host'].indexOf(k) < 0) extra[k] = v; });
|
|
state.params = mkParams(u.segments, extra);
|
|
var norm = buildHash(id, u.segments, extra);
|
|
if (norm !== location.hash) history.replaceState(null, '', norm);
|
|
setMore(false); closeRangePicker(false);
|
|
var sig = pageSig();
|
|
if (current && current.id === id) {
|
|
if (current.sig === sig) return;
|
|
current.sig = sig;
|
|
renderSlice(); renderNav(); notifyPage();
|
|
shellSummary().catch(function () { /* banner already shown */ });
|
|
return;
|
|
}
|
|
if (current) { try { current.page.unmount(); } catch (e) { console.error(e); } }
|
|
var view = $('#view');
|
|
// Mobile tables: every plain data table of a page gets data-label on its cells (from the header)
|
|
// and the class "mc"; style.css turns those rows into stacked cards under 768 px. Tables that
|
|
// already handle phones (stack, tbl-cards, eg-table, ipx-tbl, no-mc) and the sr-only chart tables are skipped.
|
|
function cardTables() {
|
|
var tabs = view.querySelectorAll('table:not(.sr-only):not(.stack):not(.tbl-cards):not(.eg-table):not(.ipx-tbl):not(.no-mc):not(.mc)');
|
|
for (var i = 0; i < tabs.length; i++) {
|
|
var tb = tabs[i], hr = tb.querySelector('thead tr');
|
|
if (!hr) continue;
|
|
var labels = [].map.call(hr.children, function (c) { return (c.textContent || '').trim(); });
|
|
[].forEach.call(tb.tBodies, function (body) {
|
|
[].forEach.call(body.rows, function (r) {
|
|
var k = 0;
|
|
[].forEach.call(r.cells, function (c) {
|
|
if (!c.hasAttribute('data-label')) c.setAttribute('data-label', labels[k] || '');
|
|
if (c.childNodes.length > 1) { // one flex item per cell, so mixed content flows as text
|
|
var w = document.createElement('span');
|
|
w.className = 'mc-v';
|
|
while (c.firstChild) w.appendChild(c.firstChild);
|
|
c.appendChild(w);
|
|
}
|
|
k += c.colSpan || 1;
|
|
});
|
|
});
|
|
});
|
|
tb.classList.add('mc');
|
|
}
|
|
}
|
|
var cardQueued = false;
|
|
new MutationObserver(function () {
|
|
if (cardQueued) return;
|
|
cardQueued = true;
|
|
requestAnimationFrame(function () { cardQueued = false; cardTables(); });
|
|
}).observe(view, { childList: true, subtree: true });
|
|
clear(view);
|
|
state.note = '';
|
|
var page = pages[id];
|
|
current = { id: id, page: page, sig: sig };
|
|
if (id !== 'ip') 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 typing(e) {
|
|
var tg = e.target, tag = tg && tg.tagName;
|
|
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (tg && tg.isContentEditable);
|
|
}
|
|
|
|
function boot() {
|
|
booted = true;
|
|
applyI18n();
|
|
buildRangePicker();
|
|
readSlice(parseHash().query);
|
|
renderRangePicker();
|
|
$('#host').addEventListener('change', function (e) { setShell({ host: e.target.value }); });
|
|
$('#domain').addEventListener('change', function (e) { state.domain = e.target.value; renderSlice(); notifyPage(); });
|
|
$('#lang').addEventListener('click', function () {
|
|
lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang);
|
|
applyI18n(); renderNav(); buildRangePicker();
|
|
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') { hideHelp(); closeDetail(); setMore(false); closeRangePicker(true); return; }
|
|
var box = $('#detail');
|
|
if (e.key === 'Tab' && !box.hidden) {
|
|
var f = Array.prototype.slice.call(box.querySelectorAll('button, a[href], [tabindex="0"]'));
|
|
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(); }
|
|
return;
|
|
}
|
|
if (e.ctrlKey || e.metaKey || e.altKey || typing(e) || !box.hidden) return;
|
|
if (e.key === 't') { e.preventDefault(); rp.open ? closeRangePicker(true) : openRangePicker(); }
|
|
else if (e.key === '[') stepPreset(-1);
|
|
else if (e.key === ']') stepPreset(1);
|
|
else if ((e.key === 'ArrowLeft' || e.key === 'ArrowRight') && e.target === document.body && isCustom()) { e.preventDefault(); shiftWindow(e.key === 'ArrowLeft' ? -1 : 1); }
|
|
});
|
|
document.addEventListener('click', function (e) {
|
|
var more = $('#more');
|
|
if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false);
|
|
if (rp.open && !$('#range-picker').contains(e.target)) closeRangePicker(false);
|
|
if (helpPinned) hideHelp();
|
|
});
|
|
window.addEventListener('hashchange', route);
|
|
window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage);
|
|
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,
|
|
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast, apiSend: apiSend, unbanDialog: unbanDialog, setNavBadge: setNavBadge,
|
|
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
|
|
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
|
|
charts: charts, help: help, glossary: glossary,
|
|
param: param, setParam: setParam, pageParam: pageParam,
|
|
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline, pager: pager }
|
|
};
|
|
|
|
// page scripts are listed in /pages.json ({"pages":[{"name":"geo","css":true}, ...]}); only files that exist
|
|
// are listed, so nothing 404s. Each name loads /<name>.js (and /<name>.css) in order, then the app boots.
|
|
var DEFAULT_PAGES = [{ name: 'geo', css: true }, { name: 'live', css: true }, { name: 'ip', css: true }, { name: 'replay', css: true }];
|
|
function loadScript(src) {
|
|
return new Promise(function (ok) {
|
|
var sc = document.createElement('script');
|
|
sc.src = src; sc.async = false;
|
|
sc.onload = ok; sc.onerror = function () { console.warn('page script failed: ' + src); ok(); };
|
|
document.head.appendChild(sc);
|
|
});
|
|
}
|
|
function loadPages() {
|
|
return fetch('/pages.json', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }, function () { return null; }).then(function (m) {
|
|
var list = m && Array.isArray(m.pages) ? m.pages : DEFAULT_PAGES, chain = Promise.resolve();
|
|
list.forEach(function (p) {
|
|
var name = p && String(p.name || '');
|
|
if (!/^[a-z][a-z0-9-]*$/.test(name)) return;
|
|
if (p.css) { var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/' + name + '.css'; document.head.appendChild(l); }
|
|
chain = chain.then(function () { return loadScript('/' + name + '.js'); });
|
|
});
|
|
return chain;
|
|
});
|
|
}
|
|
function start() { loadPages().then(boot, boot); }
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else setTimeout(start, 0);
|
|
})();
|