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:
neil 2026-11-04 18:10:29 -08:00
commit 54a765510a
63 changed files with 6464 additions and 0 deletions

253
app/static/js/ui.js Normal file
View 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;
}