// 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(); }