Files
urutau/internal/server/web/app.js
T
Lucas RayanandClaude Opus 5.5 b7462c14fa
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.

Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.

Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.

Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 21:45:59 -03:00

1688 lines
97 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.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.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline } 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', '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);
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 n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), h('p', 'cm-label', label), 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) { return metric(label, value, { sub: sub, tone: tone, hint: hint }); }
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 catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'); return h('span', 'cat c-' + k, label || t('cat.' + k)); }
// ranked list with a proportional bar; rows: [{key, n, label?}]
function bars(rows, opts) {
opts = opts || {};
var box = h('div');
if (!rows || !rows.length) { box.appendChild(empty(t('top.empty.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; };
}
// ---------------------------------------------------------------- IP table
function sumCounts(c) { var s = 0; for (var k in c) s += c[k]; return s; }
function ipTable(full) {
var st = { sort: 'score', order: 'desc', page: 1, per: window.innerWidth < 768 ? 25 : (full ? 50 : 25), q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
var timer = 0, alive = true, onTotal = null;
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('ips.search'), 'aria-label': t('ips.search') });
var levelSel = el('select', { 'aria-label': t('ips.level') });
['', 'hostile', 'suspicious', 'low'].forEach(function (l) { levelSel.appendChild(el('option', { value: l }, l ? t('level.' + l) : t('level.all'))); });
var bannedChk = el('input', { type: 'checkbox' });
var toolbar = h('div', 'toolbar', search, levelSel, h('label', 'check', bannedChk, h('span', null, t('ips.bannedOnly'))));
var perSel = null;
if (full) {
perSel = el('select', { 'aria-label': t('ips.perPage') });
[25, 50, 100, 200].forEach(function (n) { perSel.appendChild(el('option', { value: String(n) }, String(n))); });
perSel.value = String(st.per);
toolbar.appendChild(perSel);
}
var thead = h('thead'), tbody = h('tbody');
var table = h('table', 'stack tbl-cards', thead, tbody);
var count = h('span'), page = h('span'), prev = el('button', { type: 'button', class: 'btn' }, t('pager.prev')), next = el('button', { type: 'button', class: 'btn' }, t('pager.next'));
var pager = h('div', 'pager', count, h('div', 'btns', page, prev, next));
var node = h('div', null, toolbar, h('div', 'tbl-wrap', table), pager);
function cols() {
var c = [{ k: 'ip', s: 'ip' }, { k: 'score', s: 'score' }, { k: 'level' }, { k: 'cats' }, { k: 'origin' }];
if (full && st.multi) c.push({ k: 'hosts' });
if (full) c.push({ k: 'first', s: 'first' });
c.push({ k: 'last', s: 'last' });
if (full) c.push({ k: 'events', s: 'events' });
c.push({ k: 'banned' });
return c;
}
function colLabel(k) { return t(k === 'cats' ? 'col.cats' : 'col.' + k); }
function buildHead() {
var c = cols();
var sig = c.map(function (x) { return x.k; }).join(',') + '|' + lang;
if (sig === st.headSig) { markSort(); return; }
st.headSig = sig;
clear(thead);
var tr = h('tr');
c.forEach(function (x) {
var th = el('th', { scope: 'col', 'data-key': x.s || '' });
if (x.s) {
var b = el('button', { type: 'button' }, colLabel(x.k));
b.addEventListener('click', function () {
if (st.sort === x.s) st.order = st.order === 'desc' ? 'asc' : 'desc'; else { st.sort = x.s; st.order = 'desc'; }
st.page = 1; load();
});
th.appendChild(b);
} else th.textContent = colLabel(x.k);
tr.appendChild(th);
});
thead.appendChild(tr);
markSort();
}
function markSort() {
thead.querySelectorAll('th').forEach(function (th) {
var k = th.getAttribute('data-key');
if (k && k === st.sort) th.setAttribute('aria-sort', st.order === 'asc' ? 'ascending' : 'descending'); else th.removeAttribute('aria-sort');
});
}
function renderRows(items) {
clear(tbody);
var c = cols();
if (!items.length) {
var td0 = h('td', 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) { chips.appendChild(h('span', 'chip', t('cat.' + k) + ' ' + nf(x.counts[k]))); });
if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2)));
cell('cats', chips); break;
}
case 'origin': {
var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + countryName(x.cc)) : '-');
var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean);
if (x.cc) tip.unshift(org.textContent);
if (tip.length) org.title = tip.join('\n');
cell('origin', org); break;
}
case 'hosts': cell('hosts', (x.hosts || []).join(', ') || '-'); break;
case 'first': cell('first', ago(x.first), 'nw'); break;
case 'last': cell('last', ago(x.last), 'nw'); break;
case 'events': cell('events', h('span', 'num', nf(sumCounts(x.counts || {}))), 'nw'); break;
case 'banned': cell('banned', x.banned ? h('span', 't-banned', (x.jails || []).join(', ') || t('yes')) : '-', 'nw'); break;
}
});
tr.addEventListener('click', function () { openIP(x.ip); });
tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openIP(x.ip); } });
tbody.appendChild(tr);
});
var pages = Math.max(1, Math.ceil(st.total / st.per));
count.textContent = pl('pager.count', st.total, { n: nf(st.total) });
page.textContent = full ? t('pager.page', { n: nf(st.page), m: nf(pages) }) : '';
prev.disabled = st.page <= 1;
next.disabled = st.page >= pages;
}
function load() {
var c = ctx(), key = ctxKey(c);
if (key !== st.ctxKey) { st.ctxKey = key; st.page = 1; }
buildHead();
var params = qs({ sort: st.sort, order: st.order, page: st.page, per: st.per, q: st.q, level: st.level, banned: st.banned ? '1' : '0' });
return api('/api/v1/ips', params).then(function (r) {
if (!alive) return;
st.total = r.total;
if (onTotal) onTotal(r.total);
var sig = JSON.stringify([lang, st.multi, st.page, st.per, r.items.map(function (x) { return [x.ip, x.score, x.last, x.banned, x.level]; })]);
if (sig === st.sig) return;
st.sig = sig;
renderRows(r.items);
}).catch(function () { /* banner already shown by api() */ });
}
function reset() { st.page = 1; return load(); }
search.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(function () { st.q = search.value.trim(); reset(); }, 300); });
levelSel.addEventListener('change', function () { st.level = levelSel.value; reset(); });
bannedChk.addEventListener('change', function () { st.banned = bannedChk.checked; reset(); });
if (perSel) perSel.addEventListener('change', function () { st.per = parseInt(perSel.value, 10) || 50; reset(); });
prev.addEventListener('click', function () { if (st.page > 1) { st.page--; load(); } });
next.addEventListener('click', function () { st.page++; load(); });
return {
node: node, load: load, reset: reset,
setMulti: function (b) { if (st.multi !== b) { st.multi = b; st.sig = ''; } },
onTotal: function (cb) { onTotal = cb; },
dispose: function () { alive = false; clearTimeout(timer); }
};
}
// ---------------------------------------------------------------- drawer
var drawerOpener = null;
function copyText(text) {
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
return new Promise(function (ok, fail) {
var ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
var done = false;
try { done = document.execCommand('copy'); } catch (e) { done = false; }
document.body.removeChild(ta);
done ? ok() : fail(new Error('copy'));
});
}
function closeDetail() {
var box = $('#detail');
if (box.hidden) return;
box.hidden = true;
$('#scrim').hidden = true;
if (drawerOpener && document.contains(drawerOpener)) drawerOpener.focus();
drawerOpener = null;
}
function 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', levelBadge(level), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000')), 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') })));
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) : ''))); });
box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.techniques')), 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]))); }); box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.categories')), 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);
}
// ---------------------------------------------------------------- page registry
var ORDER = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources'];
var pages = {};
var current = null; // { page, el }
function registerPage(p) {
if (!p || typeof p.id !== 'string' || !/^[a-z][a-z0-9-]*$/.test(p.id) || pages[p.id]) return;
pages[p.id] = p;
if (booted) { renderNav(); route(); }
}
function orderedPages() {
var ids = Object.keys(pages);
return ORDER.filter(function (id) { return pages[id]; }).concat(ids.filter(function (id) { return ORDER.indexOf(id) < 0; }).sort()).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; });
}
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 }, 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);
});
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) }));
});
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 })));
box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral'));
box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral'));
box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans')));
box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range })));
}
function overviewLead(s) {
var T = s.totals;
if (!T.requests && !T.malicious && !T.unique_ips) return lead(t('ov.lead.empty'), t('ov.lead.bodyEmpty'), 'neutral');
var title = T.hostile_ips > 1 ? t('ov.lead.hostile', { n: nf(T.hostile_ips) }) : T.hostile_ips === 1 ? t('ov.lead.hostile.one') : t('ov.lead.calm');
return lead(title, t('ov.lead.body', { m: nf(T.malicious), r: nf(T.requests), ips: nf(T.unique_ips), b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : 'ok');
}
function topIpList(list) {
var box = h('div');
if (!list.length) { box.appendChild(empty(t('top.empty'))); return box; }
var max = Math.max.apply(null, list.map(function (x) { return x.score; })) || 1;
list.forEach(function (x) {
var b = el('button', { type: 'button', class: 'linkish mono' }, x.ip);
b.addEventListener('click', function () { openIP(x.ip); });
var org = x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc))) : '';
var sub = h('span', 'sub', levelBadge(x.level), org ? ' ' + org : '');
var bar = h('div', 'bar'), i = h('i');
i.style.width = Math.max(2, x.score / max * 100) + '%';
bar.appendChild(i);
box.appendChild(h('div', 'bar-row', h('span', 'k', b), h('span', 'n num', nf(Math.round(x.score))), sub, bar));
});
return box;
}
// ---------------------------------------------------------------- page: overview
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.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(12, v.timeline.node));
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) { 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(overviewLead(s));
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 }, v.mapbox);
v.tbl = ipTable(false);
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), 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 }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true });
v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true });
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 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', 'chart-wrap'); v.note = h('span', 'note bucket-note');
v.legend = h('div', 'legend', h('span', 'li', h('span', 'sw b-treq'), t('traffic.requests')), h('span', 'li', h('span', 'sw b-tpages'), t('traffic.pages')), v.note);
v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.timeline.hint'), variant: 'chart', loading: true }, v.wrap, v.legend);
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'], ['browsers', 'traffic.browsers'], ['oses', 'traffic.oses'], ['devices', 'traffic.devices'], ['bots', 'traffic.bots'], ['status', 'traffic.status']];
ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]), variant: 'list', loading: true }); });
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));
['pages', 'refs', 'cities', 'browsers', 'oses', 'devices'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
g.appendChild(sp(6, v.bots)); g.appendChild(sp(6, v.status)); g.appendChild(v.privacy);
root.appendChild(g);
v.offResize = onResize(function () { if (v.data) drawTraffic(v, v.data); });
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);
v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests')));
v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) })));
v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors')));
v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms', t('kpi.sub.range', { range: rangeLower() })));
v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) })));
ready(v.timeline); ready(v.map);
drawTraffic(v, d);
renderMap(v.mapbox, d.countries, true, t('map.visitors'));
function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); }
fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false);
fill('browsers', d.browsers, false); fill('oses', d.oses, false);
fill('devices', (d.devices || []).map(function (x) { return { key: t('device.' + pick(['desktop', 'mobile', 'tablet', 'bot', 'tool'], x.key, 'unknown')), n: x.n }; }), false);
fill('bots', d.bot_names, false);
fill('status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true);
},
dispose: function (v) { v.offResize(); }
});
function drawTraffic(v, d) {
var tl = d.timeline;
v.note.textContent = bucketNote(tl.step);
chart(v.wrap, { start: tl.start, step: tl.step, stacked: false, aria: t('traffic.timeline'), layers: [
{ cls: 'b-treq', label: t('traffic.requests'), vals: tl.req }, { cls: 'b-tpages', label: t('traffic.pages'), vals: tl.pages }
] });
}
// ---------------------------------------------------------------- page: ips
var pIPs = corePage({
id: 'ips', icon: ICONS.ips, titleKey: 'nav.ips',
build: function (root) {
var v = {}, 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') }, 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') },
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') }, v.hostsBox);
var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); })));
v.tbody = h('tbody');
v.srcEmpty = h('div');
v.sources = panel({ title: t('sources.title'), hint: t('sources.hint') }, h('div', 'tbl-wrap', h('table', 'stack 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 id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, state.params.query, 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; }
function renderNav() {
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
clear(nav); clear(bar); clear(more);
list.forEach(function (p) {
var label = t(p.titleKey);
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));
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)));
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);
rest.forEach(function (p) {
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
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 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 = { segments: u.segments, path: u.segments, query: extra, get: function (n) { return Object.prototype.hasOwnProperty.call(extra, n) ? extra[n] : null; } };
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');
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') { 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);
});
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,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline }
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0);
})();