Files
vacuum-wall/webui/static/app.js
T
mteehan 9c9f92ad04 fix: daemon /run spawn hardening, auth guard before first paint, WS refresh cap, interfaces runtime state
systemd: pre-create volatile /run paths so vacuum-walld's ProtectSystem=strict namespace setup cannot fail with 226/NAMESPACE — RuntimeDirectory=vacuum-wall nginx plus a tmpfiles.d spec (installed to /etc/tmpfiles.d/) covering /run/firewalld and /run/nginx.pid. Drop /run/sudo from ReadWritePaths: NOPASSWD children never need it, and its absence crash-looped restarts after sudo removed /run/sudo.

webui: run the auth session check before mounting the shell so logged-out visitors never flash the sidebar or a protected page; router guard and sidebar now react to auth state, and the login page renders full-bleed.

ws: cap refresh->reconnect episodes at 2 consecutive failures; if the WS path stays dead after a token refresh, abandon reconnection instead of looping refreshAuth forever (UI keeps working via REST until reload).

api: GET /api/network/interfaces now includes loopback and returns per-interface {config, runtime}; dashboard reads runtime.state (carrier counts as up) and the interfaces page filters lo client-side.

daemon: re-collect nginx state after lazy config migration (cached list went stale when the on-disk format changed under it), skip system_import.nginx when config.json already exists (re-parsing vacuum-wall's own generated sites is lossy), and poll nginx (60s) / acme (300s) state so file drift self-heals.
2026-08-19 15:32:36 +00:00

342 lines
15 KiB
JavaScript

import { h, render, Link, hComp, ToastContainer, connect, disconnect, apiFetch, modelRegister, modelFetch, reactive, createAuthModel, isAuthenticated, getAuthData } from '/static/hoover/index.js';
import DashboardPage from '/static/pages/dashboard.js';
import InterfacesPage from '/static/pages/interfaces.js';
import ZonesPage from '/static/pages/zones.js';
import RulesPage from '/static/pages/rules.js';
import NatPage from '/static/pages/nat.js';
import DhcpPage from '/static/pages/dhcp.js';
import ProxyPage from '/static/pages/proxy.js';
import BackendsPage from '/static/pages/backends.js';
import CertsPage from '/static/pages/certs.js';
import WireguardPage from '/static/pages/wireguard.js';
import LogsPage from '/static/pages/logs.js';
import NotFoundPage from '/static/pages/notfound.js';
import LoginPage from '/static/pages/login.js';
import PasskeysPage from '/static/pages/passkeys.js';
import UsersPage from '/static/pages/users.js';
/* ── Navigation items ──────────────────────────────────────── */
const _NavBase = [
{ path: '/dashboard', label: 'Dashboard' },
{ path: '/interfaces', label: 'Interfaces' },
{ path: '/zones', label: 'Zones' },
{ path: '/rules', label: 'Rules' },
{ path: '/nat', label: 'NAT' },
{ path: '/dhcp', label: 'DHCP' },
{ path: '/proxy', label: 'Proxy' },
{ path: '/backends', label: 'Backends' },
{ path: '/certs', label: 'Certs' },
{ path: '/wireguard', label: 'WireGuard' },
{ path: '/logs', label: 'Logs' },
{ path: '/passkeys', label: 'Passkeys' },
];
function getNav() {
const perms = getAuthData()?.permissions;
const nav = [..._NavBase];
if (perms && perms.auth === 'rw') {
nav.push({ path: '/users', label: 'Users' });
}
return nav;
}
/* ── Auth model (silent topic — the daemon never broadcasts 'auth') ── */
modelRegister('auth', createAuthModel());
modelRegister('firewall', {
subsystem: 'firewall',
fetch: async () => {
const [cfg, zones, services, interfaces, state] = await Promise.allSettled([
apiFetch('/api/firewall/config'),
apiFetch('/api/firewall/zones'),
apiFetch('/api/firewall/services'),
apiFetch('/api/firewall/interfaces'),
apiFetch('/api/firewall/state'),
]);
const result = {};
if (cfg.status === 'fulfilled' && cfg.value.ok) result.config = cfg.value.data || {};
else if (cfg.status === 'rejected' || !cfg.value.ok) throw new Error(cfg.status === 'rejected' ? (cfg.reason?.message || 'Failed') : (cfg.value.error || 'Failed'));
if (zones.status === 'fulfilled' && zones.value.ok) result.zones = zones.value.data || {};
else if (zones.status === 'rejected' || !zones.value.ok) throw new Error(zones.status === 'rejected' ? (zones.reason?.message || 'Failed') : (zones.value.error || 'Failed'));
if (services.status === 'fulfilled' && services.value.ok) result.services = services.value.data || [];
else if (services.status === 'rejected' || !services.value.ok) throw new Error(services.status === 'rejected' ? (services.reason?.message || 'Failed') : (services.value.error || 'Failed'));
if (interfaces.status === 'fulfilled' && interfaces.value.ok) result.interfaces = interfaces.value.data || [];
else if (interfaces.status === 'rejected' || !interfaces.value.ok) throw new Error(interfaces.status === 'rejected' ? (interfaces.reason?.message || 'Failed') : (interfaces.value.error || 'Failed'));
if (state.status === 'fulfilled' && state.value.ok) result.state = state.value.data || {};
return result;
},
});
modelRegister('network', {
subsystem: 'networkd',
fetch: async () => {
const r = await apiFetch('/api/network/interfaces');
if (!r.ok) throw new Error(r.error);
return r.data || { interfaces: {} };
},
});
modelRegister('dnsmasq', {
subsystem: 'dnsmasq',
fetch: async () => {
const [cfg, status, leases] = await Promise.allSettled([
apiFetch('/api/dhcp/config'),
apiFetch('/api/dhcp/status'),
apiFetch('/api/dhcp/leases'),
]);
const result = {};
if (cfg.status === 'fulfilled' && cfg.value.ok) result.config = cfg.value.data || {};
else if (cfg.status === 'rejected' || !cfg.value.ok) throw new Error(cfg.status === 'rejected' ? (cfg.reason?.message || 'Failed') : (cfg.value.error || 'Failed'));
if (status.status === 'fulfilled' && status.value.ok) result.status = status.value.data || {};
else if (status.status === 'rejected' || !status.value.ok) throw new Error(status.status === 'rejected' ? (status.reason?.message || 'Failed') : (status.value.error || 'Failed'));
if (leases.status === 'fulfilled' && leases.value.ok) result.leases = leases.value.data || [];
else if (leases.status === 'rejected' || !leases.value.ok) throw new Error(leases.status === 'rejected' ? (leases.reason?.message || 'Failed') : (leases.value.error || 'Failed'));
return result;
},
});
modelRegister('nginx', {
subsystem: 'nginx',
fetch: async () => {
const r = await apiFetch('/api/proxy/domains');
if (!r.ok) throw new Error(r.error);
return { domains: r.data || [] };
},
});
modelRegister('backends', {
subsystem: 'nginx',
fetch: async () => {
const r = await apiFetch('/api/proxy/backends');
if (!r.ok) throw new Error(r.error);
return r.data || {};
},
});
modelRegister('acme', {
subsystem: 'acme',
fetch: async () => {
const [listR, acctR] = await Promise.allSettled([
apiFetch('/api/certs/list'),
apiFetch('/api/certs/account'),
]);
const result = {};
if (listR.status === 'fulfilled' && listR.value.ok) {
result.certs = listR.value.data || [];
} else if (listR.status === 'rejected' || !listR.value.ok) {
throw new Error(listR.status === 'rejected' ? (listR.reason?.message || 'Failed') : (listR.value.error || 'Failed'));
}
if (acctR.status === 'fulfilled' && acctR.value.ok) {
result.account = acctR.value.data || { registered: false, email: '', ca: '' };
}
return result;
},
});
modelRegister('wireguard', {
subsystem: 'wireguard',
fetch: async () => {
const [stR, pR, cfgR] = await Promise.allSettled([
apiFetch('/api/wireguard/status'),
apiFetch('/api/wireguard/peers'),
apiFetch('/api/wireguard/config'),
]);
const result = {};
if (stR.status === 'fulfilled' && stR.value.ok) result.status = stR.value.data || {};
else if (stR.status === 'rejected' || !stR.value.ok) throw new Error(stR.status === 'rejected' ? (stR.reason?.message || 'Failed') : (stR.value.error || 'Failed'));
if (pR.status === 'fulfilled' && pR.value.ok) result.peers = pR.value.data || [];
else if (pR.status === 'rejected' || !pR.value.ok) throw new Error(pR.status === 'rejected' ? (pR.reason?.message || 'Failed') : (pR.value.error || 'Failed'));
if (cfgR.status === 'fulfilled' && cfgR.value.ok) result.config = cfgR.value.data || {};
return result;
},
});
const LOG_TABS = {
journal: '/api/logs/journal',
'nginx-access': '/api/logs/nginx/access',
'nginx-error': '/api/logs/nginx/error',
dnsmasq: '/api/logs/dnsmasq',
app: '/api/logs/app',
};
modelRegister('logs', {
subsystem: '*',
fetch: async (signal, tab) => {
const tabKey = tab || 'journal';
const url = LOG_TABS[tabKey];
if (!url) throw new Error('Unknown log tab: ' + tabKey);
const r = await apiFetch(url, { signal });
if (!r.ok) throw new Error(r.error);
return { data: (r.data || '').split('\n').filter(l => l.length > 0), tab: tabKey };
},
});
modelRegister('status', {
subsystem: '*',
fetch: async () => {
const [pendingR, metricsR] = await Promise.allSettled([
apiFetch('/api/status/pending'),
apiFetch('/api/status/system-metrics'),
]);
const result = {};
if (pendingR.status === 'fulfilled' && pendingR.value.ok) {
result.pending = pendingR.value.data || {};
}
if (metricsR.status === 'fulfilled' && metricsR.value.ok) {
result.metrics = metricsR.value.data || {};
}
return result;
},
});
/* ── Initial fetch (after auth check) ───────────────────────── */
function fetchInitialData() {
for (const name of ['firewall', 'network', 'dnsmasq', 'nginx', 'backends', 'wireguard', 'acme', 'status']) {
modelFetch(name);
}
modelFetch('logs', 'journal');
}
/* ── Page map ──────────────────────────────────────────────── */
const Pages = {
login: LoginPage,
dashboard: DashboardPage,
interfaces: InterfacesPage,
zones: ZonesPage,
rules: RulesPage,
nat: NatPage,
dhcp: DhcpPage,
proxy: ProxyPage,
backends: BackendsPage,
certs: CertsPage,
wireguard: WireguardPage,
logs: LogsPage,
passkeys: PasskeysPage,
users: UsersPage,
};
/* ── Router ────────────────────────────────────────────────── */
const router = {
state: reactive({ path: location.hash.slice(1) || '/dashboard' }),
component() {
const { path } = this.state;
// Auth guard: unauthenticated users see the login page for any
// protected route (manual hash entry, back/forward, runtime
// expiry). Reactive — the auth model's data mutation re-renders
// this function, so the real page appears the instant login
// completes.
if (path !== '/login' && !isAuthenticated()) {
return hComp(LoginPage, '/login');
}
const name = path.replace(/^\//, '');
const page = Pages[name] || NotFoundPage;
return hComp(page, path);
},
};
// Set once the bootstrap session check settles (and implicitly on every
// later login/logout transition — isAuthenticated flips reactively). Until
// then the hashchange clamp below must NOT force unauthenticated hashes to
// #/login: a valid-session reload arrives with its 'check' still in flight,
// and clamping early would strand the user on login.
let authChecked = false;
window.location.hash || (window.location.hash = router.state.path);
window.addEventListener('hashchange', () => {
const raw = location.hash.slice(1) || '/dashboard';
const path = raw !== '/login' && authChecked && !isAuthenticated() ? '/login' : raw;
router.state.path = path;
// Keep the URL in sync with the clamped path (loop-safe: the follow-up
// hashchange lands on the already-clamped '/login').
if (location.hash.slice(1) !== path) location.hash = path;
});
/* ── Sidebar render root ───────────────────────────────────── */
function Sidebar() {
// No nav when logged out — unauthenticated users get the full-bleed
// login page. Reactive: the auth model's terminal transition (logout /
// session expiry) re-renders this root back to null.
if (!isAuthenticated()) return null;
const current = router.state.path;
const nav = getNav();
return h('div', { class: 'sidebar' },
h('div', { class: 'logo' }, 'Vacuum Wall'),
h('nav', null,
nav.map(item =>
Link({
path: item.path,
class: current === item.path ? 'active' : '',
children: [item.label],
}),
),
),
);
}
/* ── Main content render root ──────────────────────────────── */
function MainContent() {
return [
router.component(),
ToastContainer(),
];
}
/* ── Init ──────────────────────────────────────────────────── */
export async function initApp() {
// Listen for login events to update router state after auth
window.addEventListener('auth:login', () => {
// Defer to a macrotask: at dispatch time (microtask) the login form's
// hash change has not run yet — router.state.path is still '/login'.
// The deferred check runs after the hashchange task, so a fresh login
// fetches all models. connect() is idempotent (_wsConnect no-ops with
// a live connection) and gives the post-login session its WS — today
// WS only connects on an authenticated page load (pre-existing gap).
setTimeout(() => {
connect();
if (!router.state.path.startsWith('/login')) {
fetchInitialData();
}
}, 0);
});
// Terminal auth transition — close the WS socket so a same-tab relogin
// establishes a fresh connection with the new user's token.
window.addEventListener('auth:logout', () => {
disconnect();
});
// Check auth state BEFORE mounting the shell: an unauthenticated visitor
// must never flash the sidebar or a protected page before the redirect
// to #/login lands.
await modelFetch('auth', { action: 'check' });
authChecked = true;
if (isAuthenticated()) {
// A session restored at bootstrap (or a reload) may leave the URL on
// #/login — the auth guard renders the login form for that hash even
// when authenticated. Bounce to the default page so a valid session
// never strands the user on a stale login screen.
if (router.state.path === '/login') {
window.location.hash = '/dashboard';
}
fetchInitialData();
setTimeout(connect, 0);
} else if (router.state.path !== '/login') {
// No valid session — redirect to login before the first paint.
window.location.hash = '/login';
}
const sidebarEl = document.getElementById('sidebar');
const mainEl = document.getElementById('main');
if (sidebarEl && mainEl) {
render(sidebarEl, Sidebar);
render(mainEl, MainContent);
}
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initApp);
} else {
initApp();
}