Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI): - Network health: live probe/target matrix, status strips, incidents - Probes: add (with install command), rename, remove, latency and throughput charts - Clients merged from AdGuard, DHCP, query log and probe ARP tables; names, categories, suspicious flag, notes, per-client DNS requests - Query log, domain detail (clients, related subdomains), blocked domains via the AdGuard Home /control API Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS, internet URLs and an optional VPS; buffers results while the hub is down. Gateway and ARP from /proc/net on Linux, route/arp on macOS. Install: install.sh (hub) and install-probe.sh (generated from it), each in docker mode (compose; default on Linux hosts) or native mode (venv + systemd or launchd; default on macOS and in LXC). Both modes deploy with an update command that checks the new commit and rolls back on failure. CLAUDE.md carries shared context for Claude Code sessions on each machine. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
54a765510a
63 changed files with 6464 additions and 0 deletions
24
app/static/js/api.js
Normal file
24
app/static/js/api.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
|
||||
export async function request(path, { method = 'GET', body, params } = {}) {
|
||||
const url = new URL(path, location.origin);
|
||||
for (const [k, v] of Object.entries(params || {})) if (v !== undefined && v !== null && v !== '') url.searchParams.set(k, v);
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
headers: { Accept: 'application/json', ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
if (!res.ok) {
|
||||
let detail = res.statusText;
|
||||
try { const j = await res.json(); detail = typeof j.detail === 'string' ? j.detail : JSON.stringify(j.detail ?? j); } catch {}
|
||||
const err = new Error(detail || `HTTP ${res.status}`);
|
||||
err.status = res.status;
|
||||
throw err;
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const get = (path, params) => request(path, { params });
|
||||
export const post = (path, body) => request(path, { method: 'POST', body });
|
||||
export const put = (path, body) => request(path, { method: 'PUT', body });
|
||||
export const patch = (path, body) => request(path, { method: 'PATCH', body });
|
||||
export const del = (path, params) => request(path, { method: 'DELETE', params });
|
||||
214
app/static/js/charts.js
Normal file
214
app/static/js/charts.js
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
// Inline SVG / HTML charts on the house tokens: status strips, line charts, stacked bars,
|
||||
// plus one shared tooltip. Labels go in with textContent only.
|
||||
import { el } from './ui.js';
|
||||
|
||||
const NS = 'http://www.w3.org/2000/svg';
|
||||
export function s(tag, attrs = {}, ...kids) {
|
||||
const n = document.createElementNS(NS, tag);
|
||||
for (const [k, v] of Object.entries(attrs)) if (v != null) n.setAttribute(k, v);
|
||||
for (const c of kids.flat()) if (c != null) n.append(c);
|
||||
return n;
|
||||
}
|
||||
|
||||
// ---------- status ----------
|
||||
|
||||
export const STATUS = {
|
||||
ok: { label: 'OK', chip: 'ok' },
|
||||
degraded: { label: 'Degraded', chip: 'warn' },
|
||||
down: { label: 'Down', chip: 'danger' },
|
||||
nodata: { label: 'No data', chip: '' },
|
||||
};
|
||||
|
||||
export function statusChip(st, text) {
|
||||
const x = STATUS[st] || STATUS.nodata;
|
||||
return el(`span.chip${x.chip ? `.${x.chip}` : ''}`, {}, text || x.label);
|
||||
}
|
||||
|
||||
export function statusLegend() {
|
||||
return el('div.viz-legend', { 'aria-label': 'Legend' },
|
||||
...['ok', 'degraded', 'down', 'nodata'].map((k) => el('span.viz-legend-item', {}, el(`span.viz-swatch.s-${k}`), STATUS[k].label)));
|
||||
}
|
||||
|
||||
export function seriesLegend(items, kind = 'line') {
|
||||
return el('div.viz-legend', {},
|
||||
...items.map((it) => el('span.viz-legend-item', {}, el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${it.color}` }), it.name)));
|
||||
}
|
||||
|
||||
// ---------- tooltip ----------
|
||||
|
||||
let tip;
|
||||
export function showTip(x, y, content) {
|
||||
if (!tip) {
|
||||
tip = el('div.viz-tip', { role: 'tooltip', hidden: true });
|
||||
document.body.append(tip);
|
||||
}
|
||||
tip.replaceChildren(...content.filter(Boolean));
|
||||
tip.hidden = false;
|
||||
const r = tip.getBoundingClientRect();
|
||||
let left = x + 14;
|
||||
if (left + r.width > innerWidth - 8) left = x - 14 - r.width;
|
||||
let top = y + 14;
|
||||
if (top + r.height > innerHeight - 8) top = y - 14 - r.height;
|
||||
tip.style.left = `${Math.max(8, left)}px`;
|
||||
tip.style.top = `${Math.max(8, top)}px`;
|
||||
}
|
||||
export function hideTip() { if (tip) tip.hidden = true; }
|
||||
export const tipTitle = (t) => el('div.viz-tip-title', {}, t);
|
||||
export const tipRow = (value, label, color, kind = 'line') =>
|
||||
el('div.viz-tip-row', {}, color ? el(`span.${kind === 'line' ? 'viz-linekey' : 'viz-swatch'}`, { style: `background:${color}` }) : null,
|
||||
el('strong', {}, value), label ? el('span.muted', {}, label) : null);
|
||||
|
||||
function hover(target, describe) {
|
||||
target.addEventListener('pointermove', (e) => { const c = describe(e); if (c) showTip(e.clientX, e.clientY, c); else hideTip(); });
|
||||
target.addEventListener('pointerleave', hideTip);
|
||||
}
|
||||
|
||||
// ---------- status strip: one cell per time bucket ----------
|
||||
|
||||
/** buckets: [{s, n, down, slow, latency} | null]; describe(i, bucket) -> tooltip nodes */
|
||||
export function strip(buckets, describe) {
|
||||
const n = buckets.length;
|
||||
const wrap = el('div.strip', { style: `--n:${n}` });
|
||||
for (const b of buckets) wrap.append(el(`span.s-${b ? b.s : 'nodata'}`));
|
||||
hover(wrap, (e) => {
|
||||
const r = wrap.getBoundingClientRect();
|
||||
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||
return describe(i, buckets[i]);
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// ---------- responsive SVG helper ----------
|
||||
|
||||
function responsive(draw, height) {
|
||||
const box = el('div.chart', { style: `height:${height}px` });
|
||||
let last = 0;
|
||||
const ro = new ResizeObserver(() => {
|
||||
const w = Math.floor(box.clientWidth);
|
||||
if (w && w !== last) { last = w; box.replaceChildren(draw(w)); }
|
||||
});
|
||||
ro.observe(box);
|
||||
return box;
|
||||
}
|
||||
|
||||
function niceMax(v) {
|
||||
if (!(v > 0)) return 1;
|
||||
const p = 10 ** Math.floor(Math.log10(v));
|
||||
for (const m of [1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10]) if (v <= m * p) return m * p;
|
||||
return 10 * p;
|
||||
}
|
||||
|
||||
// ---------- line chart ----------
|
||||
|
||||
/**
|
||||
* lineChart({ n, xLabel(i), series: [{name, color, values}], marks: [count per bucket],
|
||||
* fmt(v), height, describe(i) -> extra tooltip nodes })
|
||||
* Gaps (null) break the line. `marks` draws failure ticks along the baseline.
|
||||
*/
|
||||
export function lineChart(o) {
|
||||
const H = o.height || 150;
|
||||
return responsive((W) => {
|
||||
const padL = 48, padR = o.series.length > 1 ? 64 : 14, padT = 10, padB = 24;
|
||||
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||
const n = o.n;
|
||||
const all = o.series.flatMap((x) => x.values).filter((v) => v != null);
|
||||
const max = niceMax(Math.max(0, ...all));
|
||||
const x = (i) => padL + ((i + 0.5) / n) * iw;
|
||||
const y = (v) => padT + ih - (v / max) * ih;
|
||||
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||
|
||||
for (const t of [0, max / 2, max]) {
|
||||
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, o.fmt(t)));
|
||||
}
|
||||
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||
g.append(s('text', { x: x(i), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||
}
|
||||
(o.marks || []).forEach((m, i) => {
|
||||
if (m) g.append(s('rect', { x: x(i) - 1.5, y: padT + ih - 7, width: 3, height: 7, rx: 1, class: 'viz-fail' }));
|
||||
});
|
||||
|
||||
const labels = [];
|
||||
for (const ser of o.series) {
|
||||
let d = '';
|
||||
ser.values.forEach((v, i) => {
|
||||
if (v == null) return;
|
||||
const prev = ser.values[i - 1];
|
||||
d += `${prev == null ? 'M' : 'L'}${x(i).toFixed(1)},${y(v).toFixed(1)}`;
|
||||
const next = ser.values[i + 1];
|
||||
if (prev == null && next == null) g.append(s('circle', { cx: x(i), cy: y(v), r: 2.5, fill: ser.color }));
|
||||
});
|
||||
if (d) g.append(s('path', { d, fill: 'none', stroke: ser.color, 'stroke-width': 2, 'stroke-linejoin': 'round', 'stroke-linecap': 'round' }));
|
||||
const li = ser.values.findLastIndex((v) => v != null);
|
||||
if (o.series.length > 1 && li >= 0) labels.push({ y: y(ser.values[li]), text: ser.name, x: x(li) });
|
||||
}
|
||||
// Direct end labels; skip any that would collide (the legend still names it).
|
||||
labels.sort((a, b) => a.y - b.y);
|
||||
let lastY = -99;
|
||||
for (const l of labels) {
|
||||
if (l.y - lastY < 13) continue;
|
||||
lastY = l.y;
|
||||
g.append(s('text', { x: padL + iw + 6, y: l.y, dy: '0.32em', class: 'viz-label' }, l.text));
|
||||
}
|
||||
|
||||
const cross = s('line', { y1: padT, y2: padT + ih, class: 'viz-cross', visibility: 'hidden' });
|
||||
const hit = s('rect', { x: padL, y: 0, width: iw, height: H, fill: 'transparent' });
|
||||
g.append(cross, hit);
|
||||
hit.addEventListener('pointermove', (e) => {
|
||||
const r = hit.getBoundingClientRect();
|
||||
const i = Math.min(n - 1, Math.max(0, Math.floor(((e.clientX - r.left) / r.width) * n)));
|
||||
cross.setAttribute('x1', x(i)); cross.setAttribute('x2', x(i)); cross.setAttribute('visibility', 'visible');
|
||||
showTip(e.clientX, e.clientY, [tipTitle(o.xLabel(i, true)),
|
||||
...o.series.map((ser) => tipRow(ser.values[i] == null ? 'no data' : o.fmt(ser.values[i]), o.series.length > 1 ? ser.name : '', ser.color)),
|
||||
...(o.describe ? o.describe(i) : [])]);
|
||||
});
|
||||
hit.addEventListener('pointerleave', () => { cross.setAttribute('visibility', 'hidden'); hideTip(); });
|
||||
return g;
|
||||
}, H);
|
||||
}
|
||||
|
||||
// ---------- stacked bars ----------
|
||||
|
||||
function topRounded(x, y, w, h, r) {
|
||||
r = Math.min(r, h, w / 2);
|
||||
return `M${x},${y + h}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + h}Z`;
|
||||
}
|
||||
|
||||
/** stackedBars({ n, xLabel(i), series: [{name, color, values}], height }) – bottom series first. */
|
||||
export function stackedBars(o) {
|
||||
const H = o.height || 150;
|
||||
return responsive((W) => {
|
||||
const padL = 40, padR = 10, padT = 10, padB = 24;
|
||||
const iw = Math.max(10, W - padL - padR), ih = H - padT - padB;
|
||||
const n = o.n;
|
||||
const totals = Array.from({ length: n }, (_, i) => o.series.reduce((a, ser) => a + (ser.values[i] || 0), 0));
|
||||
const max = niceMax(Math.max(1, ...totals));
|
||||
const slot = iw / n, bw = Math.min(24, slot * 0.7);
|
||||
const y = (v) => padT + ih - (v / max) * ih;
|
||||
const g = s('svg', { width: W, height: H, viewBox: `0 0 ${W} ${H}`, class: 'viz', role: 'img', 'aria-label': o.label || 'Chart' });
|
||||
for (const t of [0, max / 2, max]) {
|
||||
g.append(s('line', { x1: padL, x2: padL + iw, y1: y(t), y2: y(t), class: t === 0 ? 'viz-axis' : 'viz-grid' }));
|
||||
g.append(s('text', { x: padL - 6, y: y(t), dy: '0.32em', 'text-anchor': 'end', class: 'viz-tick' }, Math.round(t).toLocaleString()));
|
||||
}
|
||||
for (const i of [0, Math.floor((n - 1) / 2), n - 1]) {
|
||||
g.append(s('text', { x: padL + slot * (i + 0.5), y: H - 6, 'text-anchor': i === 0 ? 'start' : i === n - 1 ? 'end' : 'middle', class: 'viz-tick' }, o.xLabel(i)));
|
||||
}
|
||||
for (let i = 0; i < n; i++) {
|
||||
const bx = padL + slot * i + (slot - bw) / 2;
|
||||
let acc = 0;
|
||||
const segs = o.series.map((ser) => ({ ser, v: ser.values[i] || 0 })).filter((x) => x.v > 0);
|
||||
segs.forEach((seg, k) => {
|
||||
const y0 = y(acc), y1 = y(acc + seg.v);
|
||||
const gap = k > 0 ? 2 : 0;
|
||||
const h = Math.max(0, y0 - y1 - gap);
|
||||
const top = k === segs.length - 1;
|
||||
g.append(top ? s('path', { d: topRounded(bx, y1, bw, h, 4), fill: seg.ser.color }) : s('rect', { x: bx, y: y1, width: bw, height: h, fill: seg.ser.color }));
|
||||
acc += seg.v;
|
||||
});
|
||||
const hit = s('rect', { x: padL + slot * i, y: padT, width: slot, height: ih, fill: 'transparent', class: 'viz-hit' });
|
||||
hover(hit, () => [tipTitle(o.xLabel(i, true)), ...o.series.map((ser) => tipRow((ser.values[i] || 0).toLocaleString(), ser.name, ser.color, 'box'))]);
|
||||
g.append(hit);
|
||||
}
|
||||
return g;
|
||||
}, H);
|
||||
}
|
||||
75
app/static/js/common.js
Normal file
75
app/static/js/common.js
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
// Shared bits for the views.
|
||||
import { el } from './ui.js';
|
||||
|
||||
/** The screen frame: toolbar, scrolling pane, status bar. Returns the parts. */
|
||||
export function screen(root, toolbarItems) {
|
||||
const toolbar = el('div.toolbar', {}, ...toolbarItems);
|
||||
const body = el('div.content');
|
||||
const pane = el('div.pane.fill', {}, body);
|
||||
const status = el('div.statusbar', {}, 'Loading…');
|
||||
root.append(el('div.screen', {}, toolbar, pane, status));
|
||||
return {
|
||||
toolbar, body, pane, status,
|
||||
setStatus(text, kind = '') { status.textContent = text; status.className = `statusbar${kind ? ` ${kind}` : ''}`; },
|
||||
};
|
||||
}
|
||||
|
||||
/** replaceChildren without the "null" text nodes the DOM makes from empty slots. */
|
||||
export function fill(node, ...children) {
|
||||
node.replaceChildren(...children.flat().filter((c) => c != null && c !== false));
|
||||
return node;
|
||||
}
|
||||
|
||||
export const section = (title, hint, ...extra) =>
|
||||
el('div.section-head', {}, el('h2.section-title', {}, title), hint ? el('span.hint', {}, hint) : null, ...extra);
|
||||
|
||||
export function table(headers, rows, { empty = 'Nothing to show.' } = {}) {
|
||||
if (!rows.length) return el('div.callout', {}, empty);
|
||||
return el('div.table-wrap', {},
|
||||
el('table.table', {},
|
||||
el('thead', {}, el('tr', {}, ...headers.map((h) => (typeof h === 'string' ? el('th', {}, h) : el('th', h.props || {}, h.text))))),
|
||||
el('tbody', {}, ...rows)));
|
||||
}
|
||||
|
||||
export function errorBox(err, hint) {
|
||||
return el('div.callout.error', { role: 'alert' }, err.message || String(err), hint ? el('div.small.muted', {}, hint) : null);
|
||||
}
|
||||
|
||||
/** A notice for AdGuard-backed views when it isn't set up or reachable. */
|
||||
export function adguardProblem(err) {
|
||||
if (err.status === 503) {
|
||||
return el('div.empty', {},
|
||||
el('p', {}, 'AdGuard Home isn’t connected yet.'),
|
||||
el('p.small', {}, 'Set ADGUARD_URL, ADGUARD_USERNAME and ADGUARD_PASSWORD in the hub’s .env, then restart the hub. Settings shows where that file is.'),
|
||||
el('a.btn', { href: '/settings' }, 'Open settings'));
|
||||
}
|
||||
return errorBox(err, err.status === 502 ? 'Check that AdGuard Home is running and the hub’s .env points at its web address.' : '');
|
||||
}
|
||||
|
||||
export const domainLink = (d) => el('a.domain', { href: `/domains/${encodeURIComponent(d)}` }, d);
|
||||
|
||||
export function clientLink(ip, device, fallbackName) {
|
||||
const name = device?.name || fallbackName || ip;
|
||||
const href = device ? `/clients/${encodeURIComponent(device.key)}` : `/queries?ip=${encodeURIComponent(ip)}`;
|
||||
return el('span.chips', {},
|
||||
el('a', { href, title: ip }, name),
|
||||
name !== ip ? el('span.muted.small', {}, ip) : null,
|
||||
device?.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null);
|
||||
}
|
||||
|
||||
export function resultChip(r) {
|
||||
if (r.blocked) return el('span.chip.danger', { title: r.rule || r.reason }, 'Blocked');
|
||||
if (r.reason?.startsWith('Rewrite') || r.reason === 'FilteredSafeSearch') return el('span.chip.accent', { title: r.reason }, 'Rewritten');
|
||||
if (r.reason === 'NotFilteredWhiteList') return el('span.chip.ok', { title: r.rule }, 'Allowed by rule');
|
||||
if (r.status && r.status !== 'NOERROR') return el('span.chip.warn', {}, r.status);
|
||||
return el('span.chip', {}, 'OK');
|
||||
}
|
||||
|
||||
export const RANGES = [['1h', '1 h'], ['6h', '6 h'], ['24h', '24 h'], ['7d', '7 d'], ['30d', '30 d']];
|
||||
export const SPANS = { '1h': 3600, '6h': 21600, '24h': 86400, '7d': 604800, '30d': 2592000 };
|
||||
|
||||
/** Re-run fn every `ms` while the tab is visible; returns a stop function. */
|
||||
export function every(ms, fn) {
|
||||
const t = setInterval(() => { if (!document.hidden) fn(); }, ms);
|
||||
return () => clearInterval(t);
|
||||
}
|
||||
32
app/static/js/fmt.js
Normal file
32
app/static/js/fmt.js
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// Formatting for times, durations and measurements.
|
||||
export const dash = '—';
|
||||
|
||||
export function ago(ts) {
|
||||
if (!ts) return dash;
|
||||
const s = Date.now() / 1000 - ts;
|
||||
if (s < 45) return 'just now';
|
||||
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
||||
if (s < 86400) return `${Math.round(s / 3600)} h ago`;
|
||||
return `${Math.round(s / 86400)} d ago`;
|
||||
}
|
||||
|
||||
export const clock = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
export const hm = (ts) => new Date(ts * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
export const when = (ts) => (ts ? new Date(ts * 1000).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : dash);
|
||||
export const day = (ts) => new Date(ts * 1000).toLocaleDateString([], { month: 'short', day: 'numeric' });
|
||||
|
||||
export function dur(s) {
|
||||
if (s == null) return dash;
|
||||
if (s < 60) return `${Math.round(s)} s`;
|
||||
if (s < 3600) return `${Math.round(s / 60)} min`;
|
||||
if (s < 86400) return `${(s / 3600).toFixed(1)} h`;
|
||||
return `${(s / 86400).toFixed(1)} d`;
|
||||
}
|
||||
|
||||
export const ms = (v) => (v == null ? dash : v < 10 ? `${v.toFixed(1)} ms` : `${Math.round(v).toLocaleString()} ms`);
|
||||
export const pct = (v, digits = 0) => (v == null ? dash : `${(v * 100).toFixed(digits)}%`);
|
||||
export const num = (n) => (n == null ? dash : Number(n).toLocaleString());
|
||||
export const mbps = (v) => (v == null ? dash : `${v < 10 ? v.toFixed(1) : Math.round(v)} Mbps`);
|
||||
|
||||
/** A time label fitting the span: clock for short ranges, date + hour for long ones. */
|
||||
export const axisTime = (span) => (ts) => (span > 2 * 86400 ? `${day(ts)} ${hm(ts)}` : hm(ts));
|
||||
38
app/static/js/main.js
Normal file
38
app/static/js/main.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Plain ES modules, no bundler.
|
||||
import { startShell } from './shell.js';
|
||||
import { get } from './api.js';
|
||||
|
||||
let offline = 0;
|
||||
|
||||
startShell({
|
||||
name: 'network monitor',
|
||||
categories: ['Network', 'DNS', 'Hub'],
|
||||
views: [
|
||||
{ id: 'health', name: 'Network health', path: '/', category: 'Network', icon: '◎',
|
||||
description: 'Mesh and internet health as the probes see it: now, over time, and every outage.', load: () => import('./views/health.js') },
|
||||
{ id: 'probes', name: 'Probes', path: '/probes', category: 'Network', icon: 'P',
|
||||
description: 'Add, place and remove the machines that test the network.', load: () => import('./views/probes.js'),
|
||||
badge: () => offline },
|
||||
{ id: 'clients', name: 'Clients', path: '/clients', category: 'DNS', icon: '▣',
|
||||
description: 'Every device seen on the network, with your names, categories and flags.', load: () => import('./views/clients.js') },
|
||||
{ id: 'queries', name: 'Query log', path: '/queries', category: 'DNS', icon: 'Q?',
|
||||
description: 'Sift through DNS requests from AdGuard Home.', load: () => import('./views/queries.js') },
|
||||
{ id: 'domains', name: 'Domains', path: '/domains', category: 'DNS', icon: '.com',
|
||||
description: 'Most requested domains, and who asks for each one.', load: () => import('./views/domains.js') },
|
||||
{ id: 'blocked', name: 'Blocked domains', path: '/blocked', category: 'DNS', icon: '⊘',
|
||||
description: 'What AdGuard Home blocked, how often, and for whom.', load: () => import('./views/blocked.js') },
|
||||
{ id: 'settings', name: 'Settings', path: '/settings', category: 'Hub', icon: '⚙',
|
||||
description: 'What the hub tests, its thresholds and its AdGuard connection.', load: () => import('./views/settings.js') },
|
||||
],
|
||||
});
|
||||
|
||||
// Offline probes show as a count on the Probes nav item.
|
||||
async function pollProbes() {
|
||||
try {
|
||||
const { probes } = await get('/api/probes');
|
||||
offline = probes.filter((p) => !p.online).length;
|
||||
window.dispatchEvent(new Event('app:badges'));
|
||||
} catch {}
|
||||
}
|
||||
pollProbes();
|
||||
setInterval(pollProbes, 60000);
|
||||
278
app/static/js/shell.js
Normal file
278
app/static/js/shell.js
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
// House app shell: top bar, sidebar nav (a drawer on phones), theme toggle,
|
||||
// "/" to find a view, client-side routing and a home grid, all built from one
|
||||
// list of views. Copy into the project (e.g. static/js/shell.js) unchanged and
|
||||
// call startShell() from the project's own main.js. Expects the markup in
|
||||
// index.html (ids: view, nav-list, nav-filter, topbar-title, theme-btn,
|
||||
// menu-btn, scrim, sidebar).
|
||||
//
|
||||
// A view: {
|
||||
// id, name, path, // path '/x' owns /x and everything under /x/
|
||||
// category, icon, // sidebar group; 1-3 character monogram ('{ }', 'M↓', '⎘')
|
||||
// description, // home card text and nav search
|
||||
// load: () => import('./views/x.js'), // module exports mount(root, ctx)
|
||||
// badge?: () => number, // count on the nav item; dispatch 'app:badges' on window when it changes
|
||||
// }
|
||||
// mount(root, ctx) may return a cleanup function. ctx = {
|
||||
// rest, // path after the view's own, e.g. "abc123" for /paste/abc123
|
||||
// query, // URLSearchParams of the current URL
|
||||
// navigate, // navigate('/x/abc'): client-side navigation
|
||||
// setTitle, // setTitle('abc123'): extra text in the top bar and tab title
|
||||
// }
|
||||
// A view with path '/' replaces the home grid.
|
||||
import { el, store } from './ui.js';
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let cfg, cleanup = null, routeSeq = 0;
|
||||
|
||||
/**
|
||||
* startShell({
|
||||
* name: 'tools', // shown in the tab title
|
||||
* views: [...],
|
||||
* categories: ['Text', 'Data'], // sidebar order; unknown ones go last, alphabetically
|
||||
* home: { title, intro }, // the home page heading and one-line description
|
||||
* sidebar: true, // false: top bar only (single-screen apps)
|
||||
* passthrough: ['/api/', '/static/'], // same-origin links the router must leave alone
|
||||
* })
|
||||
*/
|
||||
export function startShell(options) {
|
||||
cfg = { categories: [], sidebar: true, passthrough: ['/api/', '/static/'], home: {}, ...options };
|
||||
setupTheme();
|
||||
if (cfg.sidebar) setupNav();
|
||||
else document.querySelector('.shell')?.classList.add('bare');
|
||||
setupLinks();
|
||||
route();
|
||||
}
|
||||
|
||||
// ---------- theme: auto → light → dark, remembered per browser ----------
|
||||
|
||||
const THEMES = ['auto', 'light', 'dark'];
|
||||
const svg = (d) => `<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${d}</svg>`;
|
||||
const THEME_ICON = {
|
||||
auto: svg('<circle cx="12" cy="12" r="9"/><path d="M12 3v18" /><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/>'),
|
||||
light: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>'),
|
||||
dark: svg('<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>'),
|
||||
};
|
||||
|
||||
function setupTheme() {
|
||||
const btn = $('theme-btn');
|
||||
let theme = store.get('theme', 'auto');
|
||||
const apply = (t) => {
|
||||
if (t === 'auto') delete document.documentElement.dataset.theme;
|
||||
else document.documentElement.dataset.theme = t;
|
||||
if (btn) {
|
||||
btn.innerHTML = THEME_ICON[t];
|
||||
btn.title = `Theme: ${t}`;
|
||||
}
|
||||
};
|
||||
apply(theme);
|
||||
btn?.addEventListener('click', () => {
|
||||
theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length];
|
||||
store.set('theme', theme);
|
||||
apply(theme);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- navigation ----------
|
||||
|
||||
function grouped(views) {
|
||||
const groups = new Map();
|
||||
for (const v of views) {
|
||||
const c = v.category || 'Other';
|
||||
if (!groups.has(c)) groups.set(c, []);
|
||||
groups.get(c).push(v);
|
||||
}
|
||||
const rank = (c) => (cfg.categories.includes(c) ? cfg.categories.indexOf(c) : 999);
|
||||
return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b));
|
||||
}
|
||||
|
||||
function matches(v, q) {
|
||||
q = q.trim().toLowerCase();
|
||||
return !q || `${v.name} ${v.description || ''} ${v.category || ''}`.toLowerCase().includes(q);
|
||||
}
|
||||
|
||||
const listed = () => cfg.views.filter((v) => v.path !== '/');
|
||||
|
||||
function renderNav() {
|
||||
const q = $('nav-filter').value;
|
||||
const homeView = cfg.views.find((v) => v.path === '/');
|
||||
$('nav-list').replaceChildren(
|
||||
el('a.nav-item', { href: '/', dataset: { path: '/' } },
|
||||
el('span.nav-icon', {}, homeView?.icon || '⌂'), el('span.nav-label', {}, homeView?.name || 'Home')),
|
||||
...grouped(listed().filter((v) => matches(v, q))).map(([cat, views]) =>
|
||||
el('div.nav-group', {},
|
||||
el('div.nav-heading', {}, cat),
|
||||
views.map((v) => el('a.nav-item', { href: v.path, dataset: { path: v.path, view: v.id } },
|
||||
el('span.nav-icon', {}, v.icon), el('span.nav-label', {}, v.name), v.badge ? el('span.badge', { hidden: true }) : null)),
|
||||
),
|
||||
),
|
||||
);
|
||||
markActive();
|
||||
updateBadges();
|
||||
}
|
||||
|
||||
function updateBadges() {
|
||||
if (!cfg.sidebar) return;
|
||||
let total = 0;
|
||||
for (const v of cfg.views) {
|
||||
if (!v.badge) continue;
|
||||
let n = 0;
|
||||
try { n = v.badge() || 0; } catch {}
|
||||
total += n;
|
||||
const b = $('nav-list').querySelector(`.nav-item[data-view="${v.id}"] .badge`);
|
||||
if (b) {
|
||||
b.hidden = !n;
|
||||
b.textContent = n > 99 ? '99+' : String(n);
|
||||
b.title = `${n} new`;
|
||||
}
|
||||
}
|
||||
$('menu-btn')?.classList.toggle('has-badge', total > 0);
|
||||
}
|
||||
|
||||
function markActive() {
|
||||
if (!cfg.sidebar) return;
|
||||
const view = findView(location.pathname);
|
||||
for (const a of $('nav-list').querySelectorAll('.nav-item')) {
|
||||
const on = view ? a.dataset.path === view.path : a.dataset.path === '/';
|
||||
a.classList.toggle('active', on);
|
||||
if (on) a.setAttribute('aria-current', 'page');
|
||||
else a.removeAttribute('aria-current');
|
||||
}
|
||||
}
|
||||
|
||||
function setDrawer(open) {
|
||||
document.body.classList.toggle('drawer-open', open);
|
||||
$('menu-btn')?.setAttribute('aria-expanded', String(open));
|
||||
}
|
||||
|
||||
function setupNav() {
|
||||
const filter = $('nav-filter');
|
||||
filter.addEventListener('input', renderNav);
|
||||
filter.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
const first = listed().find((v) => matches(v, filter.value));
|
||||
if (first) {
|
||||
filter.value = '';
|
||||
renderNav();
|
||||
setDrawer(false);
|
||||
navigate(first.path);
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
filter.value = '';
|
||||
renderNav();
|
||||
filter.blur();
|
||||
setDrawer(false);
|
||||
}
|
||||
});
|
||||
document.addEventListener('keydown', (e) => {
|
||||
const a = document.activeElement;
|
||||
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(a?.tagName) || a?.isContentEditable;
|
||||
if (e.key === '/' && !typing && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
e.preventDefault();
|
||||
setDrawer(true);
|
||||
filter.focus();
|
||||
}
|
||||
});
|
||||
$('menu-btn')?.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open')));
|
||||
$('scrim')?.addEventListener('click', () => setDrawer(false));
|
||||
window.addEventListener('app:badges', updateBadges);
|
||||
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith(store.prefix)) updateBadges(); }); // other tabs
|
||||
setInterval(updateBadges, 60000);
|
||||
renderNav();
|
||||
}
|
||||
|
||||
// ---------- routing ----------
|
||||
|
||||
function findView(pathname) {
|
||||
return cfg.views.find((v) => (v.path === '/' ? pathname === '/' : pathname === v.path || pathname.startsWith(`${v.path}/`)));
|
||||
}
|
||||
|
||||
export function navigate(path, { replace = false } = {}) {
|
||||
if (path === location.pathname + location.search) return;
|
||||
history[replace ? 'replaceState' : 'pushState']({}, '', path);
|
||||
route();
|
||||
}
|
||||
|
||||
function setupLinks() {
|
||||
document.addEventListener('click', (e) => {
|
||||
const a = e.target.closest('a[href]');
|
||||
if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return;
|
||||
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const url = new URL(a.href, location.href);
|
||||
if (url.origin !== location.origin || cfg.passthrough.some((p) => url.pathname.startsWith(p))) return;
|
||||
if (url.pathname === location.pathname && url.search === location.search && url.hash) return; // in-page anchor
|
||||
e.preventDefault();
|
||||
setDrawer(false);
|
||||
navigate(url.pathname + url.search);
|
||||
});
|
||||
window.addEventListener('popstate', route);
|
||||
}
|
||||
|
||||
function setTitle(view, extra) {
|
||||
const isHome = !view || view.path === '/';
|
||||
const t = $('topbar-title');
|
||||
if (t) t.textContent = isHome ? '' : [view.name, extra].filter(Boolean).join(' · ');
|
||||
document.title = isHome ? cfg.name : `${[extra, view.name].filter(Boolean).join(' · ')} — ${cfg.name}`;
|
||||
}
|
||||
|
||||
async function route() {
|
||||
const seq = ++routeSeq;
|
||||
if (cleanup) {
|
||||
try { cleanup(); } catch (err) { console.error(err); }
|
||||
cleanup = null;
|
||||
}
|
||||
markActive();
|
||||
const root = $('view');
|
||||
const view = findView(location.pathname);
|
||||
document.body.dataset.view = view ? view.id : 'home';
|
||||
if (!view) {
|
||||
if (location.pathname !== '/') history.replaceState({}, '', '/');
|
||||
setTitle(null);
|
||||
renderHome(root);
|
||||
return;
|
||||
}
|
||||
setTitle(view);
|
||||
root.replaceChildren(el('div.loading', {}, 'Loading…'));
|
||||
try {
|
||||
const mod = await view.load();
|
||||
if (seq !== routeSeq) return; // navigated away while loading
|
||||
root.replaceChildren();
|
||||
const ctx = {
|
||||
rest: view.path === '/' ? '' : location.pathname.slice(view.path.length).replace(/^\//, ''),
|
||||
query: new URLSearchParams(location.search),
|
||||
navigate,
|
||||
setTitle: (extra) => setTitle(view, extra),
|
||||
};
|
||||
cleanup = (await mod.mount(root, ctx)) || null;
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
if (seq === routeSeq) root.replaceChildren(el('div.empty', {}, `Couldn't load ${view.name}: ${err.message}`));
|
||||
}
|
||||
}
|
||||
|
||||
function renderHome(root) {
|
||||
const filter = el('input.page-filter', { type: 'search', placeholder: 'Find…', 'aria-label': 'Filter' });
|
||||
const grid = el('div.card-grid');
|
||||
const draw = () =>
|
||||
grid.replaceChildren(
|
||||
...listed().filter((v) => matches(v, filter.value)).map((v) =>
|
||||
el('a.card-link', { href: v.path },
|
||||
el('div.card-link-icon', { 'aria-hidden': 'true' }, v.icon),
|
||||
el('div', {}, el('div.card-link-name', {}, v.name), el('div.card-link-desc', {}, v.description || '')),
|
||||
),
|
||||
),
|
||||
);
|
||||
filter.addEventListener('input', draw);
|
||||
filter.addEventListener('keydown', (e) => {
|
||||
const first = e.key === 'Enter' && grid.querySelector('a');
|
||||
if (first) navigate(new URL(first.href).pathname);
|
||||
});
|
||||
draw();
|
||||
root.replaceChildren(
|
||||
el('div.page', {},
|
||||
el('h1', {}, cfg.home.title || cfg.name),
|
||||
cfg.home.intro ? el('p.muted', {}, cfg.home.intro) : null,
|
||||
listed().length > 6 ? filter : null,
|
||||
grid,
|
||||
),
|
||||
);
|
||||
}
|
||||
253
app/static/js/ui.js
Normal file
253
app/static/js/ui.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// House UI helpers. Plain ES module, no dependencies; pairs with house.css.
|
||||
// Copy into the project (e.g. static/js/ui.js) unchanged.
|
||||
//
|
||||
// Per-browser storage is namespaced by <html data-app="<slug>"> so projects
|
||||
// on the same origin don't collide.
|
||||
|
||||
const NS = (document.documentElement.dataset.app || 'app') + ':';
|
||||
|
||||
/** el('button.primary', {onclick}, 'Save'): tag with optional .classes, props/attrs, children.
|
||||
* String values become attributes; set innerHTML with Object.assign (and only on sanitized HTML). */
|
||||
export function el(spec, props = {}, ...children) {
|
||||
const [tag, ...classes] = spec.split('.');
|
||||
const node = document.createElement(tag || 'div');
|
||||
if (classes.length) node.className = classes.join(' ');
|
||||
for (const [k, v] of Object.entries(props || {})) {
|
||||
if (v == null || v === false) continue;
|
||||
if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v);
|
||||
else if (k === 'dataset') Object.assign(node.dataset, v);
|
||||
else if (k in node && typeof v !== 'string') node[k] = v;
|
||||
else node.setAttribute(k, v === true ? '' : v);
|
||||
}
|
||||
for (const c of children.flat()) if (c != null && c !== false) node.append(c);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** A short confirmation in the corner: toast('Copied'), toast('Upload failed: too large', 'error'). */
|
||||
export function toast(message, kind = 'info') {
|
||||
let box = document.getElementById('toasts');
|
||||
if (!box) {
|
||||
box = el('div.toasts', { id: 'toasts', 'aria-live': 'polite' });
|
||||
document.body.append(box);
|
||||
}
|
||||
const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message);
|
||||
box.append(t);
|
||||
setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200);
|
||||
setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600);
|
||||
}
|
||||
|
||||
export async function copyText(text, what = 'Copied') {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch {
|
||||
const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' });
|
||||
document.body.append(ta);
|
||||
ta.select();
|
||||
document.execCommand('copy');
|
||||
ta.remove();
|
||||
}
|
||||
toast(what);
|
||||
}
|
||||
|
||||
/** Copies HTML as rich text (with a plain-text alternative) for pasting into docs and chat apps. */
|
||||
export async function copyRich(html, text, what = 'Copied') {
|
||||
try {
|
||||
if (!window.ClipboardItem || !navigator.clipboard?.write) throw new Error('no async clipboard');
|
||||
await navigator.clipboard.write([new ClipboardItem({
|
||||
'text/html': new Blob([html], { type: 'text/html' }),
|
||||
'text/plain': new Blob([text], { type: 'text/plain' }),
|
||||
})]);
|
||||
} catch {
|
||||
// Older browsers / insecure origins: select a rendered copy and use the legacy copy command.
|
||||
const holder = el('div', { contenteditable: 'true', style: 'position:fixed;left:-9999px;top:0' });
|
||||
holder.innerHTML = html;
|
||||
document.body.append(holder);
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(holder);
|
||||
const sel = getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand('copy');
|
||||
sel.removeAllRanges();
|
||||
holder.remove();
|
||||
}
|
||||
toast(what);
|
||||
}
|
||||
|
||||
export function downloadText(text, filename, type = 'text/plain') {
|
||||
const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` }));
|
||||
const a = el('a', { href: url, download: filename });
|
||||
document.body.append(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
}
|
||||
|
||||
/** Opens a file picker and resolves with {name, text}, or null if cancelled. */
|
||||
export function openTextFile(accept = '') {
|
||||
return new Promise((resolve) => {
|
||||
const input = el('input', { type: 'file', accept });
|
||||
input.addEventListener('change', async () => {
|
||||
const f = input.files[0];
|
||||
resolve(f ? { name: f.name, text: await f.text() } : null);
|
||||
});
|
||||
input.addEventListener('cancel', () => resolve(null));
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
// localStorage can be missing or throw (private windows, blocked storage); never let that break the page.
|
||||
export const store = {
|
||||
prefix: NS,
|
||||
get(key, fallback = null) {
|
||||
try {
|
||||
const v = localStorage.getItem(NS + key);
|
||||
return v == null ? fallback : JSON.parse(v);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
},
|
||||
set(key, value) {
|
||||
try {
|
||||
localStorage.setItem(NS + key, JSON.stringify(value));
|
||||
} catch {}
|
||||
},
|
||||
remove(key) {
|
||||
try {
|
||||
localStorage.removeItem(NS + key);
|
||||
} catch {}
|
||||
},
|
||||
};
|
||||
|
||||
export function formatBytes(n) {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
return `${(n / 1024 / 1024).toFixed(2)} MB`;
|
||||
}
|
||||
|
||||
/** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */
|
||||
export function debounce(fn, ms) {
|
||||
let t, pending;
|
||||
const d = (...args) => {
|
||||
clearTimeout(t);
|
||||
pending = args;
|
||||
t = setTimeout(d.flush, ms);
|
||||
};
|
||||
d.flush = () => {
|
||||
clearTimeout(t);
|
||||
if (pending) {
|
||||
const args = pending;
|
||||
pending = null;
|
||||
fn(...args);
|
||||
}
|
||||
};
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */
|
||||
export function onLeave(fn) {
|
||||
window.addEventListener('pagehide', fn);
|
||||
return () => window.removeEventListener('pagehide', fn);
|
||||
}
|
||||
|
||||
/** A segmented control: segmented([['edit','Edit'],...], current, onChange, 'View'). Has .set(value). */
|
||||
export function segmented(options, current, onChange, label = '') {
|
||||
const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label });
|
||||
const buttons = options.map(([value, text, title]) =>
|
||||
el('button', {
|
||||
type: 'button',
|
||||
role: 'radio',
|
||||
title: title || text,
|
||||
'aria-checked': String(value === current),
|
||||
onclick: () => set(value, true),
|
||||
}, text),
|
||||
);
|
||||
function set(value, fire) {
|
||||
options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value)));
|
||||
if (fire) onChange(value);
|
||||
}
|
||||
wrap.append(...buttons);
|
||||
wrap.set = (v) => set(v, false);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */
|
||||
export function tabIndent(ta, unit = ' ') {
|
||||
ta.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
e.preventDefault();
|
||||
const { selectionStart: s, selectionEnd: end, value } = ta;
|
||||
const lineStart = value.lastIndexOf('\n', s - 1) + 1;
|
||||
if (s === end && !e.shiftKey) {
|
||||
document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end');
|
||||
return;
|
||||
}
|
||||
const lines = value.slice(lineStart, end).split('\n');
|
||||
const out = e.shiftKey
|
||||
? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, '')))
|
||||
: lines.map((l) => unit + l);
|
||||
ta.setSelectionRange(lineStart, end);
|
||||
document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select');
|
||||
ta.setSelectionRange(lineStart, lineStart + out.join('\n').length);
|
||||
});
|
||||
}
|
||||
|
||||
/** A modal dialog: modal('Title', body, {wide, footer}). Returns the <dialog>; it removes itself when closed. */
|
||||
export function modal(title, body, { wide = false, footer = null } = {}) {
|
||||
const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title },
|
||||
el('div.modal-head', {},
|
||||
el('h2', {}, title),
|
||||
el('button.icon-btn', { type: 'button', 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'),
|
||||
),
|
||||
el('div.modal-body', {}, body),
|
||||
footer ? el('div.modal-foot', {}, footer) : null,
|
||||
);
|
||||
dlg.addEventListener('click', (e) => {
|
||||
if (e.target === dlg) dlg.close(); // click on the backdrop
|
||||
});
|
||||
dlg.addEventListener('close', () => dlg.remove());
|
||||
document.body.append(dlg);
|
||||
dlg.showModal();
|
||||
return dlg;
|
||||
}
|
||||
|
||||
/** Resolves true/false: await confirmDialog('Delete project?', 'This cannot be undone.', 'Delete project'). */
|
||||
export function confirmDialog(title, message, confirmLabel = 'Confirm', { danger = true } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let ok = false;
|
||||
const yes = el(`button.btn.${danger ? 'danger' : 'primary'}`, { type: 'button', onclick: () => { ok = true; dlg.close(); } }, confirmLabel);
|
||||
const no = el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel');
|
||||
const dlg = modal(title, el('p', {}, message), { footer: [no, yes] });
|
||||
dlg.addEventListener('close', () => resolve(ok));
|
||||
yes.focus();
|
||||
});
|
||||
}
|
||||
|
||||
/** A button that opens a menu: dropdown('Open in', [{label, icon?, onSelect}]). */
|
||||
export function dropdown(label, items) {
|
||||
const menu = el('div.menu', { role: 'menu', hidden: true });
|
||||
const btn = el('button.btn', { type: 'button', 'aria-haspopup': 'menu', 'aria-expanded': 'false', onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
toggle(menu.hidden);
|
||||
} }, label, el('span.caret', { 'aria-hidden': 'true' }, '▾'));
|
||||
for (const it of items) {
|
||||
menu.append(el('button.menu-item', { type: 'button', role: 'menuitem', onclick: () => { toggle(false); it.onSelect(); } },
|
||||
it.icon ? el('span.nav-icon', {}, it.icon) : null, it.label));
|
||||
}
|
||||
const outside = (e) => { if (!wrap.contains(e.target)) toggle(false); };
|
||||
const onKey = (e) => { if (e.key === 'Escape') { toggle(false); btn.focus(); } };
|
||||
function toggle(open) {
|
||||
menu.hidden = !open;
|
||||
btn.setAttribute('aria-expanded', String(open));
|
||||
if (open) {
|
||||
document.addEventListener('click', outside);
|
||||
document.addEventListener('keydown', onKey);
|
||||
menu.querySelector('button')?.focus();
|
||||
} else {
|
||||
document.removeEventListener('click', outside);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
}
|
||||
}
|
||||
const wrap = el('div.dropdown', {}, btn, menu);
|
||||
return wrap;
|
||||
}
|
||||
35
app/static/js/views/blocked.js
Normal file
35
app/static/js/views/blocked.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// Blocked domains: AdGuard's top blocked list plus what was blocked recently, and for whom.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ago, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root) {
|
||||
const ui = screen(root, [el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'), el('span.spacer'), el('a.btn', { href: '/queries?status=blocked' }, 'Blocked queries in the log')]);
|
||||
async function load() {
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const b = await get('/api/dns/blocked');
|
||||
fill(ui.body,
|
||||
el('p.lede', {}, b.num_queries ? `AdGuard Home blocked ${num(b.num_blocked)} of ${num(b.num_queries)} queries (${pct(b.num_blocked / b.num_queries, 1)}) in its stats period.` : 'No AdGuard stats yet.'),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Recently blocked', b.since ? `${num(b.sample)} blocked queries since ${when(b.since)}` : ''),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }, 'Clients', 'Last'],
|
||||
b.recent.map((r) => el('tr', {},
|
||||
el('td', {}, domainLink(r.domain), r.rule ? el('div.small.muted.mono', {}, r.rule) : null),
|
||||
el('td.num', {}, num(r.count)),
|
||||
el('td', {}, el('div', { style: 'display:grid;gap:2px' }, ...r.clients.slice(0, 4).map((c) => clientLink(c.ip, c.device)),
|
||||
r.clients.length > 4 ? el('span.small.muted', {}, `+${r.clients.length - 4} more`) : null)),
|
||||
el('td.nowrap', {}, ago(r.last)))), { empty: 'Nothing blocked recently.' })),
|
||||
el('div', {}, section('Most blocked', 'AdGuard stats period'),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }],
|
||||
b.top.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' }))),
|
||||
);
|
||||
ui.setStatus(`${b.recent.length} domains blocked recently`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
200
app/static/js/views/clients.js
Normal file
200
app/static/js/views/clients.js
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// Clients: every device seen, your labels for it, and one client's DNS activity.
|
||||
import { confirmDialog, debounce, el, store, toast } from '../ui.js';
|
||||
import { del, get, put } from '../api.js';
|
||||
import { ago, ms, num, when } from '../fmt.js';
|
||||
import { adguardProblem, domainLink, errorBox, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const SOURCE = { arp: 'Probe ARP', dhcp: 'DHCP lease', dns: 'DNS queries', adguard: 'AdGuard client' };
|
||||
const sourceName = (s) => SOURCE[s] || (s.startsWith('adguard-') ? `AdGuard ${s.slice(8)}` : s);
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : list(root, ctx);
|
||||
}
|
||||
|
||||
function list(root) {
|
||||
const f = store.get('client-filters', { q: '', cat: '', sus: false, online: false });
|
||||
const q = el('input.input', { type: 'search', value: f.q, placeholder: 'Name, IP or MAC', 'aria-label': 'Search clients' });
|
||||
const cat = el('select.select', { 'aria-label': 'Category' }, el('option', { value: '' }, 'All categories'));
|
||||
const sus = el('input', { type: 'checkbox', checked: f.sus });
|
||||
const online = el('input', { type: 'checkbox', checked: f.online });
|
||||
const ui = screen(root, [
|
||||
q, cat,
|
||||
el('label.check', {}, sus, 'Suspicious only'),
|
||||
el('label.check', {}, online, 'Active now'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
let data = null;
|
||||
|
||||
const save = () => store.set('client-filters', { q: q.value, cat: cat.value, sus: sus.checked, online: online.checked });
|
||||
const redraw = debounce(() => { save(); draw(); }, 120);
|
||||
for (const c of [q, cat, sus, online]) c.addEventListener('input', redraw);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
data = await get('/api/clients');
|
||||
if (cat.options.length === 1) {
|
||||
cat.append(...data.categories.map((c) => el('option', { value: c }, c)), el('option', { value: '-' }, 'No category'));
|
||||
cat.value = f.cat;
|
||||
}
|
||||
draw();
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const needle = q.value.trim().toLowerCase();
|
||||
const rows = data.clients.filter((c) =>
|
||||
(!needle || [c.display, c.hostname, c.ip, c.mac, c.name].some((v) => v && v.toLowerCase().includes(needle))) &&
|
||||
(!cat.value || (cat.value === '-' ? !c.category : c.category === cat.value)) &&
|
||||
(!sus.checked || c.suspicious) && (!online.checked || c.online));
|
||||
rows.sort((a, b) => (b.suspicious - a.suspicious) || ((b.queries || 0) - (a.queries || 0)) || a.display.localeCompare(b.display));
|
||||
const empty = data.clients.length
|
||||
? 'No clients match these filters.'
|
||||
: data.adguard ? 'No clients yet. They appear within a minute of AdGuard Home or a probe seeing them.'
|
||||
: 'No clients yet. Connect AdGuard Home (ADGUARD_URL in the hub’s .env) or add a probe; probes report the devices in their ARP table.';
|
||||
fill(ui.body, table(
|
||||
['Client', 'Category', 'IP', 'MAC', { text: 'Queries', props: { class: 'num', title: 'AdGuard Home stats period' } }, 'Last active', 'Seen by'],
|
||||
rows.map((c) => el(`tr${c.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, el('span.chips', {},
|
||||
el('a', { href: `/clients/${encodeURIComponent(c.key)}` }, el('strong', {}, c.display)),
|
||||
c.name && c.hostname && c.name !== c.hostname ? el('span.muted.small', {}, c.hostname) : null,
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null,
|
||||
c.new ? el('span.chip.new', { title: `First seen ${when(c.first_seen)}` }, 'New') : null)),
|
||||
el('td', {}, c.category || el('span.muted', {}, '—')),
|
||||
el('td.mono', {}, c.ip || '—'),
|
||||
el('td.mono', {}, c.mac || '—'),
|
||||
el('td.num', {}, num(c.queries)),
|
||||
el('td.nowrap', { title: when(c.last_seen) }, c.online ? el('span.chip.ok', {}, 'Active') : ago(c.last_seen)),
|
||||
el('td.small.muted', {}, c.sources.map(sourceName).join(', ')))),
|
||||
{ empty }));
|
||||
const n = data.clients;
|
||||
ui.setStatus(`${rows.length} of ${n.length} clients · ${n.filter((c) => c.online).length} active in the last 10 min · ${n.filter((c) => c.suspicious).length} suspicious`);
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(() => { if (!document.hidden) load(); }, 60000);
|
||||
return () => { clearInterval(t); redraw.flush(); };
|
||||
}
|
||||
|
||||
function detail(root, ctx, key) {
|
||||
const ui = screen(root, [
|
||||
el('button.btn.primary', { type: 'submit', form: 'client-form' }, 'Save changes'),
|
||||
el('a.btn', { href: `/queries?client=${encodeURIComponent(key)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn.danger', { type: 'button', onclick: () => forget() }, 'Forget client'),
|
||||
]);
|
||||
let c = null;
|
||||
let cursor = '';
|
||||
const qbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => loadQueries() }, 'Load older');
|
||||
const qwrap = el('div');
|
||||
const summary = el('div');
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
c = await get(`/api/clients/${encodeURIComponent(key)}`);
|
||||
ctx.setTitle(c.display);
|
||||
render();
|
||||
ui.setStatus(`${c.online ? 'Active now' : `Last active ${ago(c.last_seen)}`} · first seen ${when(c.first_seen)}`);
|
||||
loadSummary();
|
||||
loadQueries(true);
|
||||
} catch (err) {
|
||||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'No client with this id. It may have been merged into another entry once its MAC address was learned.', el('div', {}, el('a.btn', { href: '/clients' }, 'All clients'))) : errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
const name = el('input.input', { id: 'c-name', value: c.name, maxlength: 80, placeholder: c.hostname || c.ip || '' });
|
||||
const category = el('select.select', { id: 'c-cat' }, el('option', { value: '' }, 'No category'), ...c.categories.map((x) => el('option', { value: x }, x)));
|
||||
if (c.category && !c.categories.includes(c.category)) category.append(el('option', { value: c.category }, c.category));
|
||||
category.value = c.category;
|
||||
const suspicious = el('input', { type: 'checkbox', id: 'c-sus', checked: c.suspicious });
|
||||
const notes = el('textarea.textarea', { id: 'c-notes', rows: 3, maxlength: 2000, placeholder: 'Who owns it, why it is flagged…' });
|
||||
notes.value = c.notes;
|
||||
const form = el('form.form-grid', { id: 'client-form', onsubmit: async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
c = { ...c, ...(await put(`/api/clients/${encodeURIComponent(key)}`, { name: name.value, category: category.value, suspicious: suspicious.checked, notes: notes.value })) };
|
||||
ctx.setTitle(c.display);
|
||||
title.replaceWith(title = titleRow());
|
||||
toast('Changes saved');
|
||||
} catch (ex) { toast(ex.message, 'error'); }
|
||||
} },
|
||||
el('div.field', {}, el('label', { for: 'c-name' }, 'Name'), name, el('div.hint', {}, 'Shown everywhere instead of the hostname.')),
|
||||
el('div.field', {}, el('label', { for: 'c-cat' }, 'Category'), category),
|
||||
el('div.field.wide', {}, el('label.check', {}, suspicious, 'Suspicious: highlight this client in lists and query results')),
|
||||
el('div.field.wide', {}, el('label', { for: 'c-notes' }, 'Notes'), notes));
|
||||
const titleRow = () => el('div.title-row', {}, el('h2', {}, c.display),
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null, c.category ? el('span.chip', {}, c.category) : null,
|
||||
c.online ? el('span.chip.ok', {}, 'Active') : null);
|
||||
let title = titleRow();
|
||||
fill(ui.body,
|
||||
title,
|
||||
el('div.cols', { style: 'margin-top:12px' },
|
||||
el('dl.kv', {},
|
||||
el('dt', {}, 'IP address'), el('dd.mono', {}, c.ips.join(', ') || '—'),
|
||||
el('dt', {}, 'MAC address'), el('dd.mono', {}, c.mac || 'Unknown (no probe or DHCP lease has seen it)'),
|
||||
el('dt', {}, 'Hostname'), el('dd', {}, c.hostname || '—'),
|
||||
el('dt', {}, 'Queries'), el('dd', {}, c.queries == null ? '—' : `${num(c.queries)} in AdGuard’s stats period`),
|
||||
el('dt', {}, 'Seen by'), el('dd', {}, c.sources.map(sourceName).join(', ') || '—'),
|
||||
el('dt', {}, 'First seen'), el('dd', {}, when(c.first_seen)),
|
||||
el('dt', {}, 'Last active'), el('dd', {}, c.last_seen ? `${ago(c.last_seen)} (${when(c.last_seen)})` : '—')),
|
||||
form),
|
||||
summary,
|
||||
section('DNS requests', 'Newest first'),
|
||||
qwrap,
|
||||
);
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
summary.replaceChildren(section('Most requested domains'), el('div.loading', {}, 'Reading the query log…'));
|
||||
try {
|
||||
const s = await get(`/api/clients/${encodeURIComponent(key)}/summary`);
|
||||
summary.replaceChildren(
|
||||
section('Most requested domains', s.sample ? `From its last ${num(s.sample)} queries${s.since ? `, since ${when(s.since)}` : ''} · ${num(s.blocked)} blocked` : ''),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
s.top.map((d) => el('tr', {}, el('td', {}, domainLink(d.domain)), el('td.num', {}, num(d.count)), el('td.num', {}, d.blocked ? num(d.blocked) : '')),
|
||||
), { empty: 'No DNS queries from this client in the AdGuard query log.' }));
|
||||
} catch (err) {
|
||||
summary.replaceChildren(section('Most requested domains'), adguardProblem(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function loadQueries(reset = false) {
|
||||
if (reset) { cursor = ''; qbody.replaceChildren(); }
|
||||
more.disabled = true;
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { client: key, older_than: cursor, limit: 100 });
|
||||
cursor = r.oldest;
|
||||
qbody.append(...r.rows.map((q) => el(`tr${q.blocked ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, `${when(q.ts)}`),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!qbody.children.length) qwrap.replaceChildren(el('div.callout', {}, 'No DNS queries from this client in the AdGuard query log.'));
|
||||
else if (reset || !qwrap.querySelector('table')) qwrap.replaceChildren(
|
||||
el('div.table-wrap', {}, el('table.table', {}, el('thead', {}, el('tr', {}, ...['Time', 'Domain', 'Type', 'Result', 'Response'].map((h) => el('th', {}, h)))), qbody)),
|
||||
el('div.more', {}, more));
|
||||
more.hidden = r.done || !cursor;
|
||||
} catch (err) {
|
||||
qwrap.replaceChildren(adguardProblem(err));
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function forget() {
|
||||
if (!c) return;
|
||||
const ok = await confirmDialog(`Forget ${c.display}?`, 'Its name, category, flag and notes are deleted. If the device is still on the network it comes back as a new client.', 'Forget client');
|
||||
if (!ok) return;
|
||||
try { await del(`/api/clients/${encodeURIComponent(key)}`); toast(`Forgot ${c.display}`); ctx.navigate('/clients'); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
load();
|
||||
}
|
||||
107
app/static/js/views/domains.js
Normal file
107
app/static/js/views/domains.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// Domains: the most requested and most blocked, and one domain's detail.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { seriesLegend, stackedBars, hideTip } from '../charts.js';
|
||||
import { ago, hm, ms, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : overview(root, ctx);
|
||||
}
|
||||
|
||||
function openBox(ctx) {
|
||||
const input = el('input.input', { type: 'search', placeholder: 'example.com', 'aria-label': 'Domain to open' });
|
||||
const form = el('form', { style: 'display:contents', onsubmit: (e) => {
|
||||
e.preventDefault();
|
||||
const d = input.value.trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0];
|
||||
if (d) ctx.navigate(`/domains/${encodeURIComponent(d)}`);
|
||||
} }, input, el('button.btn', { type: 'submit' }, 'Open domain'));
|
||||
return form;
|
||||
}
|
||||
|
||||
function overview(root, ctx) {
|
||||
const ui = screen(root, [openBox(ctx), el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh')]);
|
||||
async function load() {
|
||||
try {
|
||||
const d = await get('/api/domains');
|
||||
const list = (rows) => table(['Domain', { text: 'Requests', props: { class: 'num' } }],
|
||||
rows.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' });
|
||||
fill(ui.body, el('div.cols', {},
|
||||
el('div', {}, section('Most requested'), list(d.top_queried)),
|
||||
el('div', {}, section('Most blocked'), list(d.top_blocked))));
|
||||
ui.setStatus(`${num(d.num_queries)} queries · ${num(d.num_blocked)} blocked in AdGuard’s stats period`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
|
||||
function detail(root, ctx, name) {
|
||||
ctx.setTitle(name);
|
||||
const ui = screen(root, [
|
||||
openBox(ctx),
|
||||
el('a.btn', { href: `/queries?domain=${encodeURIComponent(name)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
ui.setStatus('Reading the query log…');
|
||||
try {
|
||||
const d = await get(`/api/domains/${encodeURIComponent(name)}`);
|
||||
render(d);
|
||||
ui.setStatus(`Based on ${num(d.sample_rows)} queries for *.${d.base}${d.since ? ` since ${when(d.since)}` : ''}${d.complete ? ' (the whole AdGuard log)' : ''}`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(d) {
|
||||
const now = Date.now() / 1000;
|
||||
const hourLabel = (i, full) => {
|
||||
const t = now - (23 - i) * 3600;
|
||||
return full ? `${hm(t - 3600)} – ${hm(t)}` : i === 23 ? 'now' : `${23 - i} h ago`;
|
||||
};
|
||||
fill(ui.body,
|
||||
el('div.title-row', {}, el('h2', {}, d.domain),
|
||||
d.blocked ? el('span.chip.danger', {}, d.blocked === d.count ? 'Always blocked' : 'Sometimes blocked') : d.count ? el('span.chip.ok', {}, 'Allowed') : null,
|
||||
d.domain !== d.base ? el('a.chip', { href: `/domains/${encodeURIComponent(d.base)}` }, `part of ${d.base}`) : null),
|
||||
el('div.facts', {},
|
||||
fact('Requests', num(d.count), 'in the sample below'),
|
||||
fact('Blocked', d.count ? `${num(d.blocked)} (${pct(d.blocked / d.count)})` : '—'),
|
||||
fact('Clients', num(d.clients.length)),
|
||||
fact('Avg response', ms(d.avg_ms)),
|
||||
fact('Last request', d.last ? ago(d.last) : '—'),
|
||||
d.stats_count != null ? fact('AdGuard stats', num(d.stats_count), 'top-domain count for its stats period') : null),
|
||||
d.count ? el('div', {},
|
||||
section('Last 24 hours', 'Requests per hour'),
|
||||
seriesLegend([{ name: 'Allowed', color: 'var(--viz-1)' }, { name: 'Blocked', color: 'var(--viz-2)' }], 'box'),
|
||||
stackedBars({ n: 24, xLabel: hourLabel, height: 150, label: `Requests per hour for ${d.domain}`,
|
||||
series: [{ name: 'Allowed', color: 'var(--viz-1)', values: d.hours.map((h, i) => h - d.blocked_hours[i]) },
|
||||
{ name: 'Blocked', color: 'var(--viz-2)', values: d.blocked_hours }] })) : el('div.callout', { style: 'margin-top:12px' }, `No requests for ${d.domain} in the sample. Related domains under ${d.base} are below.`),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Clients requesting it'),
|
||||
table(['Client', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }, 'Last'],
|
||||
d.clients.map((c) => el(`tr${c.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, clientLink(c.ip, c.device, c.name)), el('td.num', {}, num(c.count)), el('td.num', {}, c.blocked ? num(c.blocked) : ''),
|
||||
el('td.nowrap', {}, ago(c.last)))), { empty: 'No clients in the sample.' })),
|
||||
el('div', {}, section(`Other names under ${d.base}`, 'Same domain, different subdomains'),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
d.related.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)), el('td.num', {}, r.blocked ? num(r.blocked) : ''))),
|
||||
{ empty: 'No other names under this domain in the sample.' }))),
|
||||
d.rules.length ? el('div', {}, section('Matching rules'), el('ul.mono', {}, ...d.rules.map(([r, n]) => el('li', {}, `${r} ×${n}`)))) : null,
|
||||
section('Recent requests'),
|
||||
table(['Time', 'Client', 'Type', 'Result', { text: 'Response', props: { class: 'num' } }],
|
||||
d.recent.map((q) => el('tr', {}, el('td.nowrap', {}, when(q.ts)), el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.mono', {}, q.type), el('td', {}, resultChip(q)), el('td.num', {}, ms(q.elapsed_ms)))), { empty: 'None in the sample.' }),
|
||||
);
|
||||
}
|
||||
const fact = (label, value, title) => el('div.fact', { title: title || '' }, el('span.label', {}, label), el('strong', {}, value));
|
||||
load();
|
||||
return hideTip;
|
||||
}
|
||||
130
app/static/js/views/health.js
Normal file
130
app/static/js/views/health.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// Network health: the live mesh matrix, status strips over time and the incident list.
|
||||
import { el, segmented, store } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { STATUS, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, showTip } from '../charts.js';
|
||||
import { axisTime, dur, ms, pct, when } from '../fmt.js';
|
||||
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
|
||||
|
||||
export function mount(root, ctx) {
|
||||
let range = store.get('health-range', '24h');
|
||||
const seg = segmented(RANGES, range, (v) => { range = v; store.set('health-range', v); load(); }, 'Time range');
|
||||
const ui = screen(root, [
|
||||
seg,
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
el('span.spacer'),
|
||||
el('a.btn', { href: '/probes' }, 'Manage probes'),
|
||||
]);
|
||||
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
try {
|
||||
const [mx, st, inc] = await Promise.all([
|
||||
get('/api/health/matrix', { window: 300 }),
|
||||
get('/api/health/strips', { range }),
|
||||
get('/api/health/incidents', { range }),
|
||||
]);
|
||||
render(mx, st, inc);
|
||||
const online = mx.probes.filter((p) => p.online).length;
|
||||
const ongoing = inc.incidents.filter((i) => i.ongoing).length;
|
||||
ui.setStatus(`${online} of ${mx.probes.length} probes reporting · ${inc.total} incidents in ${range}${ongoing ? ` · ${ongoing} ongoing` : ''} · updated ${new Date().toLocaleTimeString()}`,
|
||||
ongoing ? 'error' : '');
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(`Couldn't load health: ${err.message}`, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(mx, st, inc) {
|
||||
if (!mx.probes.length) {
|
||||
fill(ui.body, el('div.empty', {},
|
||||
el('p', {}, 'No probes yet. Probes are small containers on machines around the house that test the mesh and the internet link.'),
|
||||
el('a.btn.primary', { href: '/probes?add=1' }, 'Add a probe')));
|
||||
return;
|
||||
}
|
||||
fill(ui.body,
|
||||
section('Right now', 'Last 5 minutes, per probe and target. Select a probe for its charts.'),
|
||||
matrix(mx),
|
||||
section('Timeline', `${range} in ${st.buckets} slices of ${dur(st.width)}. A slice is down when half its checks fail, degraded when a fifth are slow or failing.`),
|
||||
statusLegend(),
|
||||
strips(st),
|
||||
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss.`),
|
||||
incidents(inc.incidents),
|
||||
);
|
||||
}
|
||||
|
||||
function matrix(mx) {
|
||||
if (!mx.targets.length) return el('div.callout', {}, 'No measurements in the last 5 minutes. Probes report every 30 seconds or so; check that they are running.');
|
||||
const byKey = new Map(mx.cells.map((c) => [`${c.probe_id}|${c.target}`, c]));
|
||||
const rows = mx.probes.map((p) => el('tr', {},
|
||||
el('th.row-head', {}, el('span.chips', {}, el('a', { href: `/probes/${p.id}` }, p.name), p.online ? null : el('span.chip.danger', {}, 'Offline'))),
|
||||
...mx.targets.map((t) => {
|
||||
const c = byKey.get(`${p.id}|${t.target}`);
|
||||
if (!c) return el('td', {}, el('div.cell-empty', {}, t.target === `probe:${p.id}` ? 'self' : '—'));
|
||||
const main = c.methods.icmp || c.methods.http || c.methods.dns;
|
||||
const loss = c.methods.icmp?.loss;
|
||||
const node = el(`a.cell.s-${c.status}`, { href: `/probes/${p.id}`, 'aria-label': `${p.name} to ${t.label}: ${STATUS[c.status].label}` },
|
||||
el('strong', {}, main?.latency != null ? ms(main.latency) : STATUS[c.status].label),
|
||||
el('span.muted', {}, [loss != null ? `${pct(loss)} loss` : null, c.status !== 'ok' ? STATUS[c.status].label : null].filter(Boolean).join(' · ') || 'OK'));
|
||||
const tip = () => [tipTitle(`${p.name} → ${t.label}`),
|
||||
...Object.entries(c.methods).map(([m, v]) => tipRow(v.latency != null ? ms(v.latency) : 'failed',
|
||||
`${METHOD[m] || m} · ${STATUS[v.status].label}${v.down ? ` · ${v.down}/${v.n} failed` : ''}${v.loss ? ` · ${pct(v.loss)} loss` : ''}`)),
|
||||
...Object.values(c.methods).filter((v) => v.error).slice(0, 1).map((v) => el('div.small.error-text', {}, v.error))];
|
||||
node.addEventListener('pointerenter', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||
node.addEventListener('pointermove', (e) => showTip(e.clientX, e.clientY, tip()));
|
||||
node.addEventListener('pointerleave', hideTip);
|
||||
node.addEventListener('focus', () => { const r = node.getBoundingClientRect(); showTip(r.right, r.bottom, tip()); });
|
||||
node.addEventListener('blur', hideTip);
|
||||
return el('td', {}, node);
|
||||
})));
|
||||
return el('div.table-wrap', {}, el('table.table.matrix', {},
|
||||
el('thead', {}, el('tr', {}, el('th', {}, 'From ↓ / to →'), ...mx.targets.map((t) => el('th', { title: t.target }, t.label)))),
|
||||
el('tbody', {}, ...rows)));
|
||||
}
|
||||
|
||||
function strips(st) {
|
||||
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const groups = new Map();
|
||||
for (const s of st.series) {
|
||||
if (!groups.has(s.probe_id)) groups.set(s.probe_id, []);
|
||||
groups.get(s.probe_id).push(s);
|
||||
}
|
||||
const probe = new Map(st.probes.map((p) => [p.id, p]));
|
||||
const describe = (s) => (i, b) => {
|
||||
const t0 = st.since + i * st.width;
|
||||
return [tipTitle(`${when(t0)} – ${xt(t0 + st.width)}`),
|
||||
el('div', {}, el('strong', {}, `${probe.get(s.probe_id)?.name} → ${s.label}`)),
|
||||
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`)
|
||||
: tipRow('No data', 'no checks reported'),
|
||||
b?.latency != null ? tipRow(ms(b.latency), 'average') : null];
|
||||
};
|
||||
return el('div.strips', {},
|
||||
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||
...[...groups].map(([pid, list]) => el('div.strip-group', {},
|
||||
el('h3', {}, el('a', { href: `/probes/${pid}` }, probe.get(pid)?.name || `Probe ${pid}`), probe.get(pid)?.online ? null : el('span.chip.danger', {}, 'Offline')),
|
||||
...list.map((s) => el('div.strip-row', {},
|
||||
el('span.name', { title: s.target }, s.label),
|
||||
strip(s.buckets, describe(s)),
|
||||
el('span.uptime', { title: 'Share of checks that succeeded' }, s.uptime == null ? '—' : `${s.uptime}%`))))));
|
||||
}
|
||||
|
||||
function incidents(list) {
|
||||
return table(['Started', 'Lasted', 'Probe', 'Target', 'Type', 'Checks', 'Detail'], list.map((i) => el('tr', {},
|
||||
el('td.nowrap', { title: when(i.start) }, when(i.start)),
|
||||
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||
el('td', {}, el('a', { href: `/probes/${i.probe_id}` }, i.probe)),
|
||||
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||
el('td', {}, statusChip(i.type)),
|
||||
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')),
|
||||
)), { empty: `No incidents in the last ${range}.` });
|
||||
}
|
||||
|
||||
load();
|
||||
const stop = every(30000, load);
|
||||
return () => { stop(); hideTip(); };
|
||||
}
|
||||
253
app/static/js/views/probes.js
Normal file
253
app/static/js/views/probes.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// Probes: the list, adding one (with its install command), and one probe's detail and charts.
|
||||
import { confirmDialog, copyText, el, modal, segmented, store, toast } from '../ui.js';
|
||||
import { del, get, patch, post } from '../api.js';
|
||||
import { lineChart, seriesLegend, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, STATUS } from '../charts.js';
|
||||
import { ago, axisTime, dur, mbps, ms, pct, when } from '../fmt.js';
|
||||
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS', throughput: 'Throughput' };
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, Number(ctx.rest)) : list(root, ctx);
|
||||
}
|
||||
|
||||
function installCommand(info, token) {
|
||||
const hub = info.hub_url || location.origin;
|
||||
return `curl -fsSL ${info.install_url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`;
|
||||
}
|
||||
|
||||
function commandBlock(cmd) {
|
||||
const loopback = /^(localhost|127\.|\[::1\])/.test(location.hostname) && cmd.includes(location.origin);
|
||||
return el('div', { style: 'display:grid;gap:6px' },
|
||||
el('div.cmd', {}, el('pre', {}, cmd), el('button.btn', { type: 'button', onclick: () => copyText(cmd, 'Install command copied') }, 'Copy')),
|
||||
loopback ? el('div.callout.error', {}, `You opened this page at ${location.host}, which other machines can't reach. Replace HUB_URL with the hub's LAN address, or set HUB_PUBLIC_URL in the hub's .env.`) : null);
|
||||
}
|
||||
|
||||
function onlineChip(p) {
|
||||
if (!p.last_seen) return el('span.chip', {}, 'Never reported');
|
||||
return p.online ? el('span.chip.ok', {}, 'Reporting') : el('span.chip.danger', {}, 'Offline');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- list
|
||||
|
||||
function list(root, ctx) {
|
||||
const ui = screen(root, [
|
||||
el('button.btn.primary', { type: 'button', onclick: () => addProbe() }, 'Add probe'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
let info = null;
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
info = await get('/api/probes');
|
||||
const rows = info.probes.map((p) => el('tr', {},
|
||||
el('td', {}, el('a', { href: `/probes/${p.id}` }, el('strong', {}, p.name))),
|
||||
el('td', {}, onlineChip(p)),
|
||||
el('td.mono', {}, p.address ? `${p.address}:${p.port || 8765}` : '—'),
|
||||
el('td', {}, p.hostname || '—'),
|
||||
el('td', {}, p.icmp == null ? '—' : p.icmp ? 'Yes' : el('span.chip.warn', { title: 'Run install-probe.sh again on that machine to enable ping' }, 'Not permitted')),
|
||||
el('td.mono', {}, p.version || '—'),
|
||||
el('td.nowrap', { title: when(p.last_seen) }, ago(p.last_seen)),
|
||||
));
|
||||
fill(ui.body,
|
||||
el('p.lede', {}, 'Each probe tests every other probe (ping, HTTP and throughput), the gateway, DNS servers and the internet, then reports here.'),
|
||||
table(['Name', 'Status', 'Address', 'Host', 'Ping', 'Version', 'Last report'], rows,
|
||||
{ empty: 'No probes yet. Add one, then run its install command on a machine on the network.' }),
|
||||
);
|
||||
const off = info.probes.filter((p) => !p.online).length;
|
||||
ui.setStatus(`${info.probes.length} probes · ${off} not reporting · they report every ${info.interval} s`, off ? 'error' : '');
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function addProbe() {
|
||||
const name = el('input.input', { id: 'probe-name', required: true, maxlength: 60, placeholder: 'Living room', autocomplete: 'off' });
|
||||
const err = el('div.error', { hidden: true });
|
||||
const submit = el('button.btn.primary', { type: 'submit', form: 'add-probe' }, 'Add probe');
|
||||
const form = el('form.field', { id: 'add-probe', onsubmit: async (e) => {
|
||||
e.preventDefault();
|
||||
submit.disabled = true;
|
||||
try {
|
||||
const p = await post('/api/probes', { name: name.value.trim() });
|
||||
dlg.close();
|
||||
showInstall(p);
|
||||
load();
|
||||
} catch (ex) {
|
||||
err.textContent = ex.message; err.hidden = false; name.setAttribute('aria-invalid', 'true');
|
||||
submit.disabled = false;
|
||||
}
|
||||
} }, el('label', { for: 'probe-name' }, 'Name'), name,
|
||||
el('div.hint', {}, 'Where it sits, so the matrix reads well: Office, Garage, Upstairs AP.'), err);
|
||||
const dlg = modal('Add a probe', form, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), submit] });
|
||||
name.focus();
|
||||
}
|
||||
|
||||
function showInstall(p) {
|
||||
const cmd = installCommand(info, p.token);
|
||||
const dlg = modal(`Install “${p.name}”`, el('div', { style: 'display:grid;gap:12px' },
|
||||
el('p', { style: 'margin:0' }, 'Run this on the machine that will be the probe. It starts on boot and keeps running. On Linux hosts it uses Docker (installed if needed). On macOS and inside Proxmox LXC containers it installs natively as a system service; there, Linux needs root: put sudo env before HUB_URL.'),
|
||||
commandBlock(cmd),
|
||||
el('p.small.muted', { style: 'margin:0' }, `The probe reports to ${info.hub_url || location.origin}. If that address isn't reachable from the probe, change HUB_URL in the command. The command is also on the probe's page.`),
|
||||
), { wide: true, footer: [el('a.btn', { href: `/probes/${p.id}`, onclick: () => dlg.close() }, 'Open probe'), el('button.btn.primary', { type: 'button', onclick: () => dlg.close() }, 'Done')] });
|
||||
}
|
||||
|
||||
load();
|
||||
if (ctx.query.get('add')) { history.replaceState({}, '', '/probes'); setTimeout(addProbe, 0); }
|
||||
return every(30000, load);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- detail
|
||||
|
||||
function detail(root, ctx, id) {
|
||||
let range = store.get('probe-range', '24h');
|
||||
const seg = segmented(RANGES, range, (v) => { range = v; store.set('probe-range', v); load(); }, 'Time range');
|
||||
const ui = screen(root, [
|
||||
seg,
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => rename() }, 'Rename'),
|
||||
el('button.btn.danger', { type: 'button', onclick: () => remove() }, 'Remove probe'),
|
||||
]);
|
||||
let probe = null, listInfo = null;
|
||||
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
try {
|
||||
const [p, li, st, ser, inc] = await Promise.all([
|
||||
get(`/api/probes/${id}`), get('/api/probes'),
|
||||
get('/api/health/strips', { range, probe: id }), get('/api/health/series', { probe: id, range }),
|
||||
get('/api/health/incidents', { range, probe: id, limit: 50 }),
|
||||
]);
|
||||
probe = p; listInfo = li;
|
||||
ctx.setTitle(p.name);
|
||||
render(st, ser, inc);
|
||||
ui.setStatus(`${p.online ? 'Reporting' : 'Not reporting'} · last report ${ago(p.last_seen)} · ${inc.total} incidents in ${range}`, p.online ? '' : 'error');
|
||||
} catch (err) {
|
||||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'This probe was removed.', el('div', {}, el('a.btn', { href: '/probes' }, 'All probes'))) : errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(st, ser, inc) {
|
||||
const p = probe;
|
||||
const addr = el('input.input', { value: p.address_locked ? p.address : '', placeholder: p.address ? `${p.address} (detected)` : 'detected from reports', 'aria-label': 'Address other probes use', style: 'max-width:260px' });
|
||||
const saveAddr = el('button.btn.small', { type: 'button', onclick: async () => {
|
||||
try { probe = await patch(`/api/probes/${id}`, { address: addr.value.trim() }); toast(addr.value.trim() ? 'Address saved' : 'Address will be detected again'); load(); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
} }, 'Save');
|
||||
fill(ui.body,
|
||||
el('div.title-row', {}, el('h2', {}, p.name), onlineChip(p)),
|
||||
el('div.cols', {},
|
||||
el('dl.kv', {},
|
||||
el('dt', {}, 'Address'), el('dd', {}, el('span.chips', {}, addr, saveAddr)),
|
||||
el('dt', {}, 'Port'), el('dd.mono', {}, String(p.port || 8765)),
|
||||
el('dt', {}, 'Host'), el('dd', {}, p.hostname || '—'),
|
||||
el('dt', {}, 'Ping'), el('dd', {}, p.icmp == null ? '—' : p.icmp ? 'Works' : 'Not permitted on this host. Run install-probe.sh again, which sets net.ipv4.ping_group_range.'),
|
||||
el('dt', {}, 'Version'), el('dd.mono', {}, p.version || '—'),
|
||||
el('dt', {}, 'Added'), el('dd', {}, when(p.created)),
|
||||
el('dt', {}, 'Last report'), el('dd', {}, `${ago(p.last_seen)}${p.last_seen ? ` (${when(p.last_seen)})` : ''}`),
|
||||
),
|
||||
el('div', {},
|
||||
el('div.label', { style: 'margin-bottom:6px' }, 'Install or reinstall'),
|
||||
commandBlock(installCommand(listInfo, p.token)),
|
||||
el('p.small.muted', {}, 'Leave Address empty to use what the probe reports. Set it when other probes must reach this one at a different address.')),
|
||||
),
|
||||
section('Timeline', `${range} in slices of ${dur(st.width)}`),
|
||||
statusLegend(),
|
||||
stripsFor(st),
|
||||
section('Latency', 'Average per slice. Red ticks mark slices with failed checks.'),
|
||||
seriesLegend([{ name: 'Ping', color: 'var(--viz-1)' }, { name: 'HTTP or DNS', color: 'var(--viz-2)' }]),
|
||||
multiples(ser),
|
||||
throughputChart(ser),
|
||||
section('Incidents'),
|
||||
table(['Started', 'Lasted', 'Target', 'Type', 'Checks', 'Detail'], inc.incidents.map((i) => el('tr', {},
|
||||
el('td.nowrap', {}, when(i.start)),
|
||||
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||||
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
|
||||
el('td', {}, statusChip(i.type)),
|
||||
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
|
||||
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')))), { empty: `No incidents in the last ${range}.` }),
|
||||
);
|
||||
}
|
||||
|
||||
function stripsFor(st) {
|
||||
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||||
const xt = axisTime(SPANS[range]);
|
||||
return el('div.strips', {},
|
||||
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
|
||||
...st.series.map((s) => el('div.strip-row', {},
|
||||
el('span.name', { title: s.target }, s.label),
|
||||
strip(s.buckets, (i, b) => [tipTitle(`${when(st.since + i * st.width)} – ${xt(st.since + (i + 1) * st.width)}`),
|
||||
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`) : tipRow('No data', ''),
|
||||
b?.latency != null ? tipRow(ms(b.latency), 'average') : null]),
|
||||
el('span.uptime', {}, s.uptime == null ? '—' : `${s.uptime}%`))));
|
||||
}
|
||||
|
||||
function multiples(ser) {
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const xLabel = (i, full) => (full ? `${when(ser.since + i * ser.width)} – ${xt(ser.since + (i + 1) * ser.width)}` : xt(ser.since + (i + 0.5) * ser.width));
|
||||
const cards = ser.targets.filter((t) => t.methods.icmp || t.methods.http || t.methods.dns).map((t) => {
|
||||
const second = t.methods.http || t.methods.dns;
|
||||
const series = [];
|
||||
if (t.methods.icmp) series.push({ name: 'Ping', color: 'var(--viz-1)', values: t.methods.icmp.map((b) => b?.avg ?? null) });
|
||||
if (second) series.push({ name: t.methods.http ? 'HTTP' : 'DNS', color: 'var(--viz-2)', values: second.map((b) => b?.avg ?? null) });
|
||||
const methods = Object.entries(t.methods).filter(([m]) => m !== 'throughput');
|
||||
const marks = Array.from({ length: ser.buckets }, (_, i) => methods.reduce((a, [, arr]) => a + (arr[i]?.failed || 0), 0));
|
||||
return el('div.multiple', {},
|
||||
el('h4', {}, t.label, el('span.chip', {}, t.kind === 'lan' ? 'LAN' : 'Internet')),
|
||||
lineChart({ n: ser.buckets, xLabel, series, marks, fmt: ms, height: 140, label: `Latency to ${t.label}`,
|
||||
describe: (i) => {
|
||||
const out = [];
|
||||
for (const [m, arr] of methods) {
|
||||
const b = arr[i];
|
||||
if (b?.failed) out.push(el('div.small.error-text', {}, `${METHOD[m]}: ${b.failed} of ${b.n} failed`));
|
||||
if (m === 'icmp' && b?.loss) out.push(el('div.small', {}, `Ping loss ${pct(b.loss)}`));
|
||||
}
|
||||
return out;
|
||||
} }));
|
||||
});
|
||||
return cards.length ? el('div.multiples', {}, ...cards) : el('div.callout', {}, `No latency data in the last ${range}.`);
|
||||
}
|
||||
|
||||
function throughputChart(ser) {
|
||||
const tp = ser.targets.filter((t) => t.methods.throughput);
|
||||
if (!tp.length) return null;
|
||||
const xt = axisTime(SPANS[range]);
|
||||
const xLabel = (i, full) => (full ? when(ser.since + i * ser.width) : xt(ser.since + (i + 0.5) * ser.width));
|
||||
return el('div', {},
|
||||
section('Throughput to other probes', 'A timed download from each peer, every few minutes.'),
|
||||
el('div.multiples', {}, ...tp.map((t) => el('div.multiple', {},
|
||||
el('h4', {}, t.label),
|
||||
lineChart({ n: ser.buckets, xLabel, fmt: mbps, height: 120, label: `Throughput from ${t.label}`,
|
||||
series: [{ name: 'Throughput', color: 'var(--viz-1)', values: t.methods.throughput.map((b) => b?.mbps ?? null) }],
|
||||
marks: t.methods.throughput.map((b) => b?.failed || 0) })))));
|
||||
}
|
||||
|
||||
async function rename() {
|
||||
const input = el('input.input', { value: probe?.name || '', maxlength: 60, 'aria-label': 'Name' });
|
||||
const save = el('button.btn.primary', { type: 'button', onclick: async () => {
|
||||
try { await patch(`/api/probes/${id}`, { name: input.value.trim() }); dlg.close(); toast('Renamed'); load(); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
} }, 'Save name');
|
||||
const dlg = modal('Rename probe', input, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), save] });
|
||||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') save.click(); });
|
||||
input.select();
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (!probe) return;
|
||||
const ok = await confirmDialog(`Remove ${probe.name}?`,
|
||||
'Its history is deleted and its token stops working. The probe keeps running on its machine until you uninstall it there; the installer printed the uninstall command, and the README lists it.', 'Remove probe');
|
||||
if (!ok) return;
|
||||
try { await del(`/api/probes/${id}`); toast(`Removed ${probe.name}`); ctx.navigate('/probes'); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
load();
|
||||
const stop = every(30000, load);
|
||||
return () => { stop(); hideTip(); };
|
||||
}
|
||||
67
app/static/js/views/queries.js
Normal file
67
app/static/js/views/queries.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// The DNS query log from AdGuard Home, with search, result filter and client filter.
|
||||
import { debounce, el, segmented } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ms, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
const params = ctx.query;
|
||||
let status = params.get('status') || 'all';
|
||||
const client = params.get('client') || '';
|
||||
const ip = params.get('ip') || '';
|
||||
const domain = params.get('domain') || '';
|
||||
const search = el('input.input', { type: 'search', value: params.get('q') || '', placeholder: 'Domain or client', 'aria-label': 'Search queries' });
|
||||
const seg = segmented([['all', 'All'], ['blocked', 'Blocked'], ['allowed', 'Allowed']], status, (v) => { status = v; sync(); load(true); }, 'Result');
|
||||
const filterChip = client || ip || domain
|
||||
? el('span.chip.accent', {}, `${client ? 'Client' : ip ? 'IP' : 'Domain'}: ${client || ip || domain} `,
|
||||
el('a', { href: '/queries', 'aria-label': 'Clear filter', style: 'color:inherit;text-decoration:none' }, '✕'))
|
||||
: null;
|
||||
const ui = screen(root, [search, seg, filterChip, el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load(true) }, 'Refresh')]);
|
||||
const tbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => load() }, 'Load older');
|
||||
let cursor = '', count = 0, seq = 0;
|
||||
|
||||
function sync() {
|
||||
const u = new URLSearchParams(location.search);
|
||||
search.value ? u.set('q', search.value) : u.delete('q');
|
||||
status !== 'all' ? u.set('status', status) : u.delete('status');
|
||||
history.replaceState({}, '', `/queries${u.size ? `?${u}` : ''}`);
|
||||
}
|
||||
search.addEventListener('input', debounce(() => { sync(); load(true); }, 350));
|
||||
|
||||
async function load(reset = false) {
|
||||
const my = ++seq;
|
||||
if (reset) { cursor = ''; count = 0; }
|
||||
more.disabled = true;
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { search: search.value.trim(), status, client, ip, domain, older_than: cursor, limit: 100 });
|
||||
if (my !== seq) return;
|
||||
if (reset) tbody.replaceChildren();
|
||||
cursor = r.oldest;
|
||||
count += r.rows.length;
|
||||
tbody.append(...r.rows.map((q) => el(`tr${q.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, when(q.ts)),
|
||||
el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!ui.body.querySelector('table')) {
|
||||
fill(ui.body, el('div.table-wrap', {}, el('table.table', {},
|
||||
el('thead', {}, el('tr', {}, ...['Time', 'Client', 'Domain', 'Type', 'Result', { t: 'Response', c: 'num' }].map((h) => el('th', h.c ? { class: h.c } : {}, h.t || h)))), tbody)),
|
||||
el('div.more', {}, more));
|
||||
}
|
||||
if (!count) fill(ui.body, el('div.empty', {}, 'No queries match.'));
|
||||
more.hidden = r.done || !cursor;
|
||||
ui.setStatus(`${count} queries${r.done ? ' · end of the AdGuard log' : ''}`);
|
||||
} catch (err) {
|
||||
if (my !== seq) return;
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
load(true);
|
||||
}
|
||||
42
app/static/js/views/settings.js
Normal file
42
app/static/js/views/settings.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Settings: what the hub is configured to do. Values live in the hub's .env.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { num } from '../fmt.js';
|
||||
|
||||
export async function mount(root) {
|
||||
const intro = el('p.muted', {}, 'These come from the hub’s .env file.');
|
||||
const page = el('div.page', {}, el('h1', {}, 'Settings'), intro);
|
||||
root.append(page);
|
||||
try {
|
||||
const [i, dns] = await Promise.all([get('/api/info'), get('/api/dns/status')]);
|
||||
intro.textContent = `These come from ${i.env_file} on the hub (${i.install_mode} install). Edit that file, then restart the hub to apply: ${i.install_mode === 'docker' ? 'docker restart network-monitor' : 'sudo systemctl restart network-monitor (macOS: sudo launchctl kickstart -k system/dev.neilbantoc.network-monitor)'}. Deploy new code with ${i.update_command}.`;
|
||||
const row = (k, v, env) => [el('dt', {}, k), el('dd', {}, v, env ? el('span.muted.small.mono', {}, ` ${env}`) : null)];
|
||||
const list = (xs) => (xs.length ? xs.join(', ') : 'none');
|
||||
page.append(
|
||||
el('h2', {}, 'AdGuard Home'),
|
||||
el('dl.kv', {},
|
||||
...row('Status', dns.ok ? el('span.chip.ok', {}, `Connected · ${dns.version}`) : el('span.chip.danger', {}, dns.configured ? 'Not reachable' : 'Not set up')),
|
||||
...(dns.url ? row('Address', dns.url, 'ADGUARD_URL') : []),
|
||||
...(dns.ok ? [] : row('Problem', dns.message))),
|
||||
el('h2', {}, 'Probes'),
|
||||
el('dl.kv', {},
|
||||
...row('Report every', `${i.probe_interval} s`, 'PROBE_INTERVAL'),
|
||||
...row('LAN DNS servers', list(i.lan_dns_servers), 'LAN_DNS_SERVERS'),
|
||||
...row('Public DNS servers', list(i.dns_servers), 'DNS_SERVERS'),
|
||||
...row('DNS test name', i.dns_query_name, 'DNS_QUERY_NAME'),
|
||||
...row('Internet HTTP checks', list(i.wan_http_urls), 'WAN_HTTP_URLS'),
|
||||
...row('VPS', i.vps_url || 'none', 'VPS_URL'),
|
||||
...row('Throughput test', i.throughput_every ? `${num(i.throughput_bytes / 1e6)} MB from each peer every ${i.throughput_every} reports` : 'off', 'THROUGHPUT_EVERY, THROUGHPUT_BYTES')),
|
||||
el('h2', {}, 'Thresholds and storage'),
|
||||
el('dl.kv', {},
|
||||
...row('Slow on the LAN', `over ${i.thresholds.lan_ms} ms`, 'SLOW_LAN_MS'),
|
||||
...row('Slow to the internet', `over ${i.thresholds.wan_ms} ms`, 'SLOW_WAN_MS'),
|
||||
...row('Slow DNS', `over ${i.thresholds.dns_ms} ms`, 'SLOW_DNS_MS'),
|
||||
...row('Keep measurements', `${i.retention_days} days`, 'RETENTION_DAYS'),
|
||||
...row('Password', i.password ? 'On' : 'Off: anyone on the network can open this page', 'UI_PASSWORD'),
|
||||
...row('Version', i.version)),
|
||||
);
|
||||
} catch (err) {
|
||||
page.append(el('div.callout.error', {}, err.message));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue