refactor: introduce model layer for centralized data synchronization

Add hoover model.js as a central reactive store per subsystem, replacing
per-component data fetching with a single source of truth.

- Add hoover/model.js with modelRegister, modelFetch, and WS invalidation
- Refactor websocket.js to route messages to model refresh (drop per-component
  subscribe/unsubscribe)
- Simplify component.js by removing WS subscription management
- Add refresh option to apiSubmit, deprecate refactorLoad and checkAbort
- Rewrite all pages to use getModel() instead of inline data fetching
- Bootstrap model registrations in app.js
- Add GET /api/firewall/state endpoint
- Fix restart-services.sh restart order and add service health verification
- Update hoover.md docs with model layer architecture
This commit is contained in:
2026-06-22 22:54:29 +00:00
parent 633505e7dc
commit b673e87c9b
27 changed files with 952 additions and 838 deletions
+136 -12
View File
@@ -1,16 +1,16 @@
import { h, render, Link, hComp, ToastContainer, connect, requestUpdate, reactive } from '/static/hoover/index.js?v=6';
import { h, render, Link, hComp, ToastContainer, connect, apiFetch, modelRegister, modelFetch, reactive } from '/static/hoover/index.js?v=7';
import DashboardPage from '/static/pages/dashboard.js?v=6';
import InterfacesPage from '/static/pages/interfaces.js?v=6';
import ZonesPage from '/static/pages/zones.js?v=6';
import RulesPage from '/static/pages/rules.js?v=6';
import NatPage from '/static/pages/nat.js?v=6';
import DhcpPage from '/static/pages/dhcp.js?v=6';
import ProxyPage from '/static/pages/proxy.js?v=6';
import CertsPage from '/static/pages/certs.js?v=6';
import WireguardPage from '/static/pages/wireguard.js?v=6';
import LogsPage from '/static/pages/logs.js?v=6';
import NotFoundPage from '/static/pages/notfound.js?v=6';
import DashboardPage from '/static/pages/dashboard.js?v=7';
import InterfacesPage from '/static/pages/interfaces.js?v=7';
import ZonesPage from '/static/pages/zones.js?v=7';
import RulesPage from '/static/pages/rules.js?v=7';
import NatPage from '/static/pages/nat.js?v=7';
import DhcpPage from '/static/pages/dhcp.js?v=7';
import ProxyPage from '/static/pages/proxy.js?v=7';
import CertsPage from '/static/pages/certs.js?v=7';
import WireguardPage from '/static/pages/wireguard.js?v=7';
import LogsPage from '/static/pages/logs.js?v=7';
import NotFoundPage from '/static/pages/notfound.js?v=7';
/* ── Navigation items ──────────────────────────────────────── */
const Nav = [
@@ -26,6 +26,130 @@ const Nav = [
{ path: '/logs', label: 'Logs' },
];
/* ── Model registration ────────────────────────────────────── */
modelRegister('status', {
subsystem: 'status',
fetch: async () => {
const r = await apiFetch('/api/status/all');
if (!r.ok) throw new Error(r.error);
return r.data;
},
});
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 r.data || [];
},
});
modelRegister('acme', {
subsystem: 'acme',
fetch: async () => {
const r = await apiFetch('/api/certs/list');
if (!r.ok) throw new Error(r.error);
return r.data || [];
},
});
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 };
},
});
/* ── Initial fetch ─────────────────────────────────────────── */
for (const name of ['status', 'firewall', 'network', 'dnsmasq', 'nginx', 'wireguard', 'acme']) {
modelFetch(name);
}
modelFetch('logs', 'journal');
/* ── Page map ──────────────────────────────────────────────── */
const Pages = {
dashboard: DashboardPage,
+12 -4
View File
@@ -6,7 +6,8 @@
* ToastContainer component for rendering queued toasts.
*/
import { h } from './vdom.js?v=6';
import { h } from './vdom.js?v=7';
import { modelFetch } from './model.js?v=7';
/**
* JSON-friendly fetch wrapper.
@@ -100,6 +101,8 @@ export function ToastContainer() {
/**
* Create an abort-checking function from an AbortController.
*
* @deprecated Use model layer (`modelRegister` / `modelFetch`) for data
* fetching with abort handling and loading state management.
* @param {AbortController} ac
* @returns {function} () => boolean
*/
@@ -112,6 +115,8 @@ export function checkAbort(ac) {
*
* Sets loading=true before, loading=false after, tracks errors.
*
* @deprecated Use model layer (`modelRegister` / `modelFetch`) for data
* fetching with abort handling and loading state management.
* @param {object} state - Reactive state object
* @param {function} dataKey - (s) => any, current data to compare for refresh detection
* @param {function} fetchFn - (state, signal, isAborted) => Promise
@@ -204,7 +209,7 @@ export async function poll(opts) {
* @param {function} [opts.body] - () => object, body builder
* @param {function} [opts.validate] - (body) => string|null, validation function
* @param {string} [opts.successMsg] - Success toast message
* @param {function} [opts.reload] - () => Promise, data reload function
* @param {string|string[]} [opts.refresh] - Model name(s) to refresh via modelFetch
* @param {string} [opts.submitText] - Submit button text (default: 'Submit')
* @returns {object[]} Array of action descriptors
*/
@@ -215,7 +220,7 @@ export function apiSubmit(opts) {
body,
validate,
successMsg = 'Saved',
reload,
refresh,
submitText = 'Submit',
closeModal,
} = opts;
@@ -235,7 +240,10 @@ export function apiSubmit(opts) {
if (res.ok) {
toast(successMsg, 'success');
if (closeModal) closeModal();
if (reload) await reload();
if (refresh) {
const models = Array.isArray(refresh) ? refresh : [refresh];
await Promise.all(models.map(m => modelFetch(m)));
}
} else {
toast(res.error || 'Failed', 'error');
}
+28 -85
View File
@@ -4,72 +4,53 @@
* Component wrapper: definePage, lifecycle hooks, state caching.
*
* definePage wraps a page definition into a renderer function compatible
* with hoover's render engine. Handles reactive state creation, WS
* subscription registration on mount, and cleanup on unmount.
* with hoover's render engine. Handles reactive state creation and
* lifecycle management. Data loading is handled by the model layer.
*
* Usage:
* export default definePage({
* init() { return { data: null, loading: true, error: null }; },
* subscribe: ['*'], // WS topics to subscribe to
* async load(state) { ... }, // called on mount
* init() { return { firewall: getModel('firewall') }; },
* async load(state) { ... }, // optional, for one-time setup
* render(state) { return [vnodes],
* });
*/
import { reactive } from './reactivity.js?v=6';
import { h } from './vdom.js?v=6';
import { _compExpandedCache } from './render.js?v=6';
import { reactive } from './reactivity.js?v=7';
import { h } from './vdom.js?v=7';
import { _compExpandedCache } from './render.js?v=7';
/** Registry of mounted components: key → { state, subscriptions, loadAbort, entry, isLoading } */
/** Registry of mounted components: key → { state } */
const _mounted = new Map();
/** Check whether a state object belongs to a currently mounted component.
* Used by websocket.js to skip auto-refresh for unmounted pages. */
export function isComponentStateMounted(state) {
for (const entry of _mounted.values()) {
if (entry.state === state) return true;
}
return false;
}
/** Get the full mounted entry for a state object.
* Used by websocket.js to abort in-flight loads before triggering a refresh. */
export function getComponentEntry(state) {
for (const entry of _mounted.values()) {
if (entry.state === state) return entry;
}
return null;
}
/** External subscribe function from websocket.js.
* Set via setSubscribeFn() when the websocket module initializes.
*/
let _subscribeFn = null;
export function setSubscribeFn(fn) {
_subscribeFn = fn;
}
/**
* Define a page component.
*
* @param {object} def — Page definition
* @param {function} def.init — Return initial state object
* @param {string[]} [def.subscribe] — WS topics to subscribe to on mount
* @param {function} def.load — Async function to load data into state
* @param {function} [def.load] — Optional one-time setup called on mount
* @param {function} def.render — Render function that returns vnodes
* @returns {object} — Component renderer compatible with h('#comp', ...)
*/
export function definePage(def) {
const state = reactive(def.init());
let state = null;
let stateInitialized = false;
const renderer = () => {
if (!stateInitialized) {
state = reactive(def.init());
stateInitialized = true;
}
return def.render(state);
};
renderer._pageDef = {
state,
subscribe: def.subscribe || [],
get state() {
if (!stateInitialized) {
state = reactive(def.init());
stateInitialized = true;
}
return state;
},
load: def.load || null,
onUnmount: def.onUnmount || null,
};
@@ -88,43 +69,18 @@ export function mountComponent(key, renderer) {
let entry = _mounted.get(key);
if (entry) {
// Re-mount: component already exists with its data and subscriptions.
// Don't abort or restart loads — that re-render was triggered by a
// state change (load completion, reactive update, etc). Let existing
// in-flight loads complete naturally. WS handles auto-refresh.
// Re-mount: component already exists with its state.
// Don't re-run load — that re-render was triggered by a reactive update.
return;
} else {
// Fresh mount
entry = {
state: pd.state,
subscriptions: [],
loadAbort: null,
requestId: 0,
};
_mounted.set(key, entry);
}
// Clear error on re-mount; load() decides loading vs refreshing
entry = { state: pd.state };
_mounted.set(key, entry);
pd.state.error = null;
// Fire load with fresh AbortController
if (pd.load) {
if (entry.isLoading) return;
const abortController = new AbortController();
entry.loadAbort = abortController;
entry.requestId++;
entry.isLoading = true;
Promise.resolve()
.then(() => pd.load(pd.state, abortController, entry))
.finally(() => { entry.isLoading = false; });
}
// Register WS subscriptions (only on fresh mount)
if (!entry.subscriptions.length && _subscribeFn && pd.subscribe.length) {
for (const topic of pd.subscribe) {
const unsub = _subscribeFn(renderer, topic, pd.load, pd.state);
if (unsub) entry.subscriptions.push(unsub);
}
Promise.resolve().then(() => pd.load(pd.state));
}
}
@@ -138,19 +94,6 @@ export function unmountComponent(key, renderer) {
const pd = renderer._pageDef;
// Cancel load
if (entry.loadAbort) {
entry.loadAbort.abort();
}
// Invalidate any in-flight callbacks
entry.requestId++;
// Unsubscribe from WS
for (const unsub of entry.subscriptions) {
try { unsub(); } catch (_) {}
}
// Fire custom onUnmount
if (pd.onUnmount) {
try { pd.onUnmount(entry.state); } catch (_) {}
}
+18 -11
View File
@@ -4,9 +4,10 @@
* Data display components: Badge, StatusDot, Empty, Card.
*/
import { h } from '../vdom.js?v=6';
import { esc } from '../helpers.js?v=6';
import { apiFetch, toast } from '../api.js?v=6';
import { h } from '../vdom.js?v=7';
import { esc } from '../helpers.js?v=7';
import { apiFetch, toast } from '../api.js?v=7';
import { modelFetch } from '../model.js?v=7';
/**
* Colored badge/span.
@@ -62,13 +63,13 @@ export function Card(props = {}) {
}
/**
* A Remove button that confirms, deletes via API, toasts, and reloads.
* A Remove button that confirms, deletes via API, toasts, and refreshes models.
*
* @param {object} props
* @param {string} props.url - API DELETE URL
* @param {string} props.message - Confirmation prompt text
* @param {string} [props.success] - Success toast message (default: 'Removed')
* @param {function} [props.reload] - Function to call on success (e.g., load)
* @param {string|string[]} [props.refresh] - Model name(s) to refresh via modelFetch
* @param {string} [props.label] - Button text (default: 'Remove')
* @param {object} [props.body] - Optional JSON body to send with DELETE
*/
@@ -81,7 +82,10 @@ export function ConfirmDelete(props = {}) {
const r = await apiFetch(props.url, opts);
if (r.ok) {
toast(props.success || 'Removed', 'success');
if (props.reload) await props.reload();
if (props.refresh) {
const names = Array.isArray(props.refresh) ? props.refresh : [props.refresh];
names.forEach(n => modelFetch(n));
}
} else {
toast(r.error || 'Failed', 'error');
}
@@ -90,7 +94,7 @@ export function ConfirmDelete(props = {}) {
/**
* An action button that POSTs to an API endpoint, toasts on result,
* and optionally reloads state. Supports toggle labels for on/off buttons.
* and optionally refreshes models. Supports toggle labels for on/off buttons.
*
* @param {object} props
* @param {string} props.url - API URL
@@ -102,7 +106,7 @@ export function ConfirmDelete(props = {}) {
* @param {boolean} [props.condition] - Toggle condition for labelOn/labelOff
* @param {string} [props.successMsg] - Success toast message
* @param {string} [props.errorType] - Toast type for errors (default: 'error')
* @param {function} [props.reload] - () => Promise, called on success
* @param {string|string[]} [props.refresh] - Model name(s) to refresh via modelFetch
* @param {string} [props.cls] - Button CSS classes (default: 'btn btn-outline')
* @param {boolean} [props.disabled] - Disabled state
*/
@@ -122,7 +126,10 @@ export function ActionButton(props = {}) {
const resp = await apiFetch(props.url, opts);
if (resp.ok) {
if (props.successMsg) toast(props.successMsg, 'success');
if (props.reload) await props.reload();
if (props.refresh) {
const names = Array.isArray(props.refresh) ? props.refresh : [props.refresh];
names.forEach(n => modelFetch(n));
}
} else {
toast(resp.error || 'Failed', props.errorType || 'error');
}
@@ -249,7 +256,7 @@ export function ServiceStatus(props = {}) {
* @param {string} props.removeUrl - API DELETE URL
* @param {string} props.removeMessage - Confirmation prompt text
* @param {string} [props.removeSuccess] - Success toast message
* @param {function} [props.removeReload] - Reload function
* @param {string|string[]} [props.removeRefresh] - Model name(s) to refresh
* @param {string} [props.removeLabel] - Delete button label (default: 'Remove')
* @param {object} [props.removeBody] - Optional JSON body to send with DELETE
* @param {string} [props.editCls] - Override classes for edit button (default: 'btn btn-sm btn-outline')
@@ -265,7 +272,7 @@ export function ActionCell(props = {}) {
url: props.removeUrl,
message: props.removeMessage,
success: props.removeSuccess,
reload: props.removeReload,
refresh: props.removeRefresh,
label: props.removeLabel || 'Remove',
body: props.removeBody,
}),
+36 -5
View File
@@ -4,8 +4,9 @@
* Layout components: PageHeader, Tabs, SectionTitle, DataTableSection, ActionGroup.
*/
import { h } from '../vdom.js?v=6';
import { Table } from './data.js?v=6';
import { h } from '../vdom.js?v=7';
import { Table } from './data.js?v=7';
import { collectLoadingModels } from '../model.js?v=7';
/**
* Page header with title, optional subtitle, and action buttons.
@@ -25,14 +26,17 @@ export function PageHeader(props = {}) {
);
}
/**
/**
* Handle loading/error/no-data states and return early if applicable.
* Returns null when data is ready for the page to render its content.
*
* Accepts a model object (with loading/refreshing/error/data properties) as
* the `data` parameter to check the model's data property directly.
*
* @param {object} state - Page state with loading/error flags
* @param {string} title - Page header title
* @param {string} [subtitle] - Page header subtitle
* @param {*} [data] - Data presence check for "no data" state
* @param {*} [data] - Data to check (or model object with .data property)
* @returns {VNode[]|null}
*/
export function renderGuard(state, title, subtitle, data) {
@@ -54,7 +58,7 @@ export function renderGuard(state, title, subtitle, data) {
),
];
}
if ((data === undefined || data === null) && !state.loading) {
if (isEmpty(data) && !state.loading) {
return [
PageHeader({ title, subtitle }),
h('div', { class: 'card', key: 'no-data' },
@@ -65,6 +69,33 @@ export function renderGuard(state, title, subtitle, data) {
return null;
}
/**
* Convenience wrapper for pages consuming multiple models.
* Internally calls collectLoadingModels then delegates to renderGuard.
*
* @param {string} title - Page header title
* @param {string} [subtitle] - Page header subtitle
* @param {...object} models - Model objects to combine
* @returns {VNode[]|null}
*/
export function renderGuardMulti(title, subtitle, ...models) {
const combined = collectLoadingModels(...models);
return renderGuard(combined, title, subtitle);
}
/**
* Check if a value is "empty" for renderGuard's no-data check.
* @param {*} data
* @returns {boolean}
*/
function isEmpty(data) {
if (data === null || data === undefined || data === '') return true;
if (Array.isArray(data)) return data.length === 0;
if (typeof data === 'object') return Object.keys(data).length === 0;
if (typeof data === 'number') return false;
return !data;
}
/**
* Tab bar component. Writes to state[prop] on tab click.
* The caller is responsible for rendering tab body content.
+7 -7
View File
@@ -6,9 +6,9 @@
* avoid fighting with the main render cycle.
*/
import { esc } from '../helpers.js?v=6';
import { att_esc } from '../helpers.js?v=6';
import { apiSubmit } from '../api.js?v=6';
import { esc } from '../helpers.js?v=7';
import { att_esc } from '../helpers.js?v=7';
import { apiSubmit } from '../api.js?v=7';
const _modalQueue = [];
@@ -114,7 +114,7 @@ export function formModal(inner, title, fields, actions) {
* @param {string[]} props.selected - Currently selected values
* @param {string} props.fieldKey - JSON key for the field
* @param {string} [props.successMsg] - Success toast message
* @param {function} [props.reload] - () => Promise, called on success
* @param {string|string[]} [props.refresh] - Model name(s) to refresh via modelFetch
* @returns {function} () => void, calls openModal
*/
export function MultiSelectModal(props = {}) {
@@ -138,7 +138,7 @@ export function MultiSelectModal(props = {}) {
.map(o => o.value),
}),
successMsg: props.successMsg || 'Updated',
reload: props.reload,
refresh: props.refresh,
closeModal: () => closeModal(),
}),
],
@@ -160,7 +160,7 @@ export function MultiSelectModal(props = {}) {
* @param {function} [props.submit.body] - (data) => object
* @param {function} [props.submit.validate] - (body) => string|null
* @param {string|function} [props.submit.successMsg] - Toast message or (data) => string
* @param {function} [props.reload] - (data) => Promise, called on success with the data argument
* @param {string|string[]} [props.refresh] - Model name(s) to refresh via modelFetch
* @param {function} [props.handler] - Custom submit handler override (bypasses apiSubmit)
* @param {string} [props.submitLabel] - Submit button label (default: 'Submit')
* @returns {function} (data) => void, calls openModal
@@ -194,7 +194,7 @@ export function QuickModal(props = {}) {
successMsg: typeof props.submit.successMsg === 'function'
? props.submit.successMsg(data)
: (props.submit.successMsg || 'Done'),
reload: props.reload ? () => props.reload(data) : undefined,
refresh: props.refresh || undefined,
closeModal: () => closeModal(),
}),
];
+2 -2
View File
@@ -5,8 +5,8 @@
* Uses the toast/dismissToast state from api.js.
*/
import { h } from '../vdom.js?v=6';
import { _toasts, dismissToast } from '../api.js?v=6';
import { h } from '../vdom.js?v=7';
import { _toasts, dismissToast } from '../api.js?v=7';
/**
* Render all pending toast notifications.
+15 -12
View File
@@ -5,37 +5,40 @@
*/
/* ── Reactivity ──────────────────────────────────────────────── */
export { reactive, requestUpdate } from './reactivity.js?v=6';
export { reactive, requestUpdate } from './reactivity.js?v=7';
/* ── VDOM ────────────────────────────────────────────────────── */
export { h } from './vdom.js?v=6';
export { h } from './vdom.js?v=7';
/* ── Render ──────────────────────────────────────────────────── */
export { render } from './render.js?v=6';
export { render } from './render.js?v=7';
/* ── Component ───────────────────────────────────────────────── */
export { definePage, hComp } from './component.js?v=6';
export { definePage, hComp } from './component.js?v=7';
/* ── Router ──────────────────────────────────────────────────── */
export { createRouter, Link } from './router.js?v=6';
export { createRouter, Link } from './router.js?v=7';
/* ── WebSocket ───────────────────────────────────────────────── */
export { connect, onMessage } from './websocket.js?v=6';
export { connect, onMessage } from './websocket.js?v=7';
/* ── API & Toast ─────────────────────────────────────────────── */
export { apiFetch, toast, dismissToast, apiSubmit, refactorLoad, checkAbort, poll } from './api.js?v=6';
export { apiFetch, toast, dismissToast, apiSubmit, checkAbort, poll, refactorLoad } from './api.js?v=7';
/* ── Model ───────────────────────────────────────────────────── */
export { modelRegister, getModel, modelFetch, collectLoadingModels } from './model.js?v=7';
/* ── Helpers ─────────────────────────────────────────────────── */
export { esc, att_esc, enc, $val, parseZones, downloadBlob } from './helpers.js?v=6';
export { esc, att_esc, enc, $val, parseZones, downloadBlob } from './helpers.js?v=7';
/* ── UI Components: Layout ───────────────────────────────────── */
export { PageHeader, renderGuard, Tabs, SectionTitle, ActionGroup, DataTableSection } from './components/layout.js?v=6';
export { PageHeader, renderGuard, renderGuardMulti, Tabs, SectionTitle, ActionGroup, DataTableSection } from './components/layout.js?v=7';
/* ── UI Components: Data ─────────────────────────────────────── */
export { Badge, StatusDot, Empty, Card, ConfirmDelete, Table, ActionButton, certStatusBadge, serviceStatusBadge, StatCard, StatusText, ServiceStatus, ActionCell, MonoText, ZoneSelect } from './components/data.js?v=6';
export { Badge, StatusDot, Empty, Card, ConfirmDelete, Table, ActionButton, certStatusBadge, serviceStatusBadge, StatCard, StatusText, ServiceStatus, ActionCell, MonoText, ZoneSelect } from './components/data.js?v=7';
/* ── UI Components: Modal ────────────────────────────────────── */
export { openModal, closeModal, closeAllModals, formModal, MultiSelectModal, QuickModal } from './components/modal.js?v=6';
export { openModal, closeModal, closeAllModals, formModal, MultiSelectModal, QuickModal } from './components/modal.js?v=7';
/* ── UI Components: Toast ────────────────────────────────────── */
export { ToastContainer } from './components/toast.js?v=6';
export { ToastContainer } from './components/toast.js?v=7';
+138
View File
@@ -0,0 +1,138 @@
/**
* Hoover — model.js
*
* Central reactive store for subsystem models. Each subsystem gets one
* reactive model with { data, loading, refreshing, error }. Hoover handles
* fetching, WS invalidation, loading states, and abort management.
*
* API:
* modelRegister(name, definition) — register at app bootstrap
* getModel(name) — return reactive model object
* modelFetch(name, signal?, param?) — trigger fetch with in-flight dedup
* refreshByTopic(topic) — WS callback: refresh all models matching topic
* collectLoadingModels(...models) — combine loading/refreshing/error
*/
import { reactive } from './reactivity.js?v=7';
/** Registered models: name → { model, subsystem, fetch } */
const _models = new Map();
/** In-flight fetch promises for dedup: name → Promise */
const _fetchPromises = new Map();
/**
* Register a subsystem model.
*
* @param {string} name - Model name (e.g. 'firewall', 'dnsmasq')
* @param {object} definition
* @param {string} definition.subsystem - WS topic to listen for ('*' = all)
* @param {function} definition.fetch - async (signal?, param?) => Promise<data>
* @param {any} [definition.defaultData] - Initial data value (default: null)
* @returns {object} reactive model
*/
export function modelRegister(name, definition) {
const model = reactive({
data: definition.defaultData ?? null,
loading: true,
refreshing: false,
error: null,
});
_models.set(name, {
model,
subsystem: definition.subsystem,
fetch: definition.fetch,
});
return model;
}
/**
* Get a reactive model by name. Throws if not registered.
* @param {string} name
* @returns {object} reactive model
*/
export function getModel(name) {
const entry = _models.get(name);
if (!entry) throw new Error('Model not registered: ' + name);
return entry.model;
}
/** Build dedup key from model name and optional param. */
function _dedupKey(name, param) {
return param !== undefined ? `${name}:${String(param)}` : name;
}
/**
* Trigger a fetch for the named model.
*
* In-flight dedup: if a fetch is already running, returns the existing
* promise. Models never abort in-progress fetches since other consumers
* may still need the data.
*
* @param {string} name - Model name
* @param {AbortSignal|*} [signalOrParam] - AbortSignal (backward compat) or param
* @param {AbortSignal} [signal] - AbortSignal when a param was provided
*/
export function modelFetch(name, signalOrParam, signal) {
const entry = _models.get(name);
if (!entry) return;
const isSignal = signalOrParam instanceof AbortSignal || signalOrParam === undefined;
const param = isSignal ? undefined : signalOrParam;
const actualSignal = isSignal ? signalOrParam : signal;
const model = entry.model;
const isInitial = model.loading && model.data === null;
const key = _dedupKey(name, param);
if (_fetchPromises.has(key)) return _fetchPromises.get(key);
if (isInitial) model.loading = true;
else model.refreshing = true;
model.error = null;
const promise = (async () => {
try {
const data = await entry.fetch(actualSignal, param);
model.data = data;
} catch (e) {
model.error = e.message || 'Fetch failed';
} finally {
model.loading = false;
model.refreshing = false;
}
})();
_fetchPromises.set(key, promise);
promise.finally(() => _fetchPromises.delete(key));
return promise;
}
/**
* Refresh all models whose subsystem topic matches the given topic.
* Topic '*' matches every model. Model subsystem '*' matches every topic.
*/
export function refreshByTopic(topic) {
for (const [name, entry] of _models) {
if (entry.subsystem === '*') {
modelFetch(name);
} else if (entry.subsystem === topic || topic === '*') {
modelFetch(name);
}
}
}
/**
* Combine loading/refreshing/error from multiple models.
* @param {...object} models
* @returns {{loading: boolean, refreshing: boolean, error: string|null}}
*/
export function collectLoadingModels(...models) {
return {
loading: models.some(m => m.loading),
refreshing: models.some(m => m.refreshing),
error: models.find(m => m.error)?.error ?? null,
};
}
+3 -3
View File
@@ -5,12 +5,12 @@
* batched re-render loop integration with reactivity.js.
*/
import { requestUpdate, setCommitFn } from './reactivity.js?v=6';
import { requestUpdate, setCommitFn } from './reactivity.js?v=7';
import {
_vnodeDom, createDom, getDom, patchNode, sweepDom,
setMountFn, setUnmountFn,
} from './vdom.js?v=6';
import { mountComponent, unmountComponent } from './component.js?v=6';
} from './vdom.js?v=7';
import { mountComponent, unmountComponent } from './component.js?v=7';
/** Container → previous root vnodes */
export const _renderSlots = new Map();
+2 -2
View File
@@ -5,8 +5,8 @@
* navigation). Link component for client-side navigation.
*/
import { reactive } from './reactivity.js?v=6';
import { h } from './vdom.js?v=6';
import { reactive } from './reactivity.js?v=7';
import { h } from './vdom.js?v=7';
/**
* Hash-based router.
+31 -124
View File
@@ -1,19 +1,19 @@
/**
* Hoover — websocket.js
*
* WebSocket connection manager with auto-reconnect, subscribe/unsubscribe
* per component per topic, and version-track messages.
*
* The _wsSubs Map stores entries keyed by renderer function so that
* auto-refresh messages from the backend can trigger page reloads.
* WebSocket connection manager with auto-reconnect. WS messages are routed
* to model-based refresh and direct onMessage handlers.
* Page-level subscribe/unsubscribe is replaced by the model layer.
*/
import { setSubscribeFn, isComponentStateMounted, getComponentEntry } from './component.js?v=6';
import { refreshByTopic } from './model.js?v=7';
const _wsSubs = new Map();
let _wsConn = null;
let _wsReconnectMs = 0;
/** Direct onMessage handlers: { topics, handler, unsubscribed }[] */
const _directHandlers = [];
/**
* Build the WebSocket URL. Supports an override via `window.__WS_URL__`
* (useful for proxy setups). Falls back to port 9091 when the current
@@ -52,57 +52,13 @@ function _wsConnect() {
};
}
/** Per-state debounce timer (shared across all subscriptions for that state). */
const _wsDebounceTimers = new Map();
/**
* Fire the debounced load for a component state.
*
* Only one load fires per state regardless of how many subscriptions
* matched. Passes the mount entry so refactorLoad can toggle
* loading / refreshing flags correctly.
*/
function debouncedLoad(state, entry) {
if (!isComponentStateMounted(state)) return;
// Abort any in-flight load for this component
if (entry && entry.loadAbort) entry.loadAbort.abort();
const ac = new AbortController();
const firstSub = [..._wsSubs.values()]
.find(s => !s.unsubscribed && s.state === state);
if (firstSub) {
firstSub.loadFn(state, ac, entry);
}
}
/**
* Debounce helper: coalesces all matching subscriptions for the same
* component state into a single reload, keyed by state object.
*/
function scheduleReload(state) {
if (_wsDebounceTimers.has(state)) {
clearTimeout(_wsDebounceTimers.get(state));
}
_wsDebounceTimers.set(state, setTimeout(() => {
_wsDebounceTimers.delete(state);
const entry = getComponentEntry(state);
debouncedLoad(state, entry);
}, 300));
}
/**
* Route an incoming WS message to subscribed components.
* Route an incoming WS message to model refresh and direct handlers.
*
* Expected message shapes:
* { type: 'versions', updated: ['firewall', 'dnsmasq', …] }
* { type: 'notify', topic: 'firewall' }
* { type: 'status', topic: 'firewall', … }
*
* Components subscribed to wildcard ('*') match every topic.
*
* Uses per-component-state debouncing (300ms) to prevent a burst of WS
* messages or multiple matching topics from triggering overlapping
* loads. All subscriptions that share the same state object are
* coalesced into a single debounced reload.
*/
function handleMessage(msg) {
const topics = [];
@@ -115,88 +71,39 @@ function handleMessage(msg) {
topics.push(msg.topic || '*');
}
// Track which states have already been scheduled to avoid
// double-scheduling when multiple subscriptions of the same
// component match the same message.
const scheduled = new Set();
// Refresh models for each topic
for (const topic of topics) {
refreshByTopic(topic);
}
for (const s of _wsSubs.values()) {
if (s.unsubscribed || !isComponentStateMounted(s.state)) continue;
const matched = s.topic === '*' || topics.some(t => t === s.topic || t === '*');
if (!matched) continue;
if (scheduled.has(s.state)) continue;
scheduled.add(s.state);
scheduleReload(s.state);
// Notify direct onMessage handlers
for (const h of _directHandlers) {
if (h.unsubscribed) continue;
if (topics.some(t => h.topics.includes(t) || h.topics.includes('*'))) {
try { h.handler(msg); } catch (_) {}
}
}
}
/**
* Subscribe a component to WS topics.
*
* Called by component.js on mount. Returns an unsubscribe function
* called by component.js on unmount.
*
* Key is `componentFn + ':' + topic` so a component can subscribe to
* multiple topics without overwriting previous subscriptions.
*
* @param {function} componentFn The page renderer function (used as map key)
* @param {string} topic Topic to listen for ('*' = all)
* @param {function} loadFn Function to call when topic updates
* @param {object} state Reactive state passed to loadFn
* @returns {function} unsubscribe
*/
function subscribe(componentFn, topic, loadFn, state) {
const key = componentFn + ':' + topic;
const entry = { componentFn, topic, loadFn, state, unsubscribed: false };
_wsSubs.set(key, entry);
return () => {
entry.unsubscribed = true;
// Clear per-state debounce timer if this was the last active
// subscription for that state
const remaining = [..._wsSubs.values()]
.some(s => !s.unsubscribed && s.state === entry.state);
if (!remaining && _wsDebounceTimers.has(entry.state)) {
clearTimeout(_wsDebounceTimers.get(entry.state));
_wsDebounceTimers.delete(entry.state);
}
_wsSubs.delete(key);
};
}
/** Register the subscribe function with component.js and kick off connection. */
setSubscribeFn(subscribe);
/** Start the WebSocket connection. */
export function connect() {
_wsConnect();
}
/**
* Public subscribe API for direct one-off usage (e.g. from page code).
* Handler receives the raw parsed message when a matching topic arrives.
* @param {string|string[]} topics
* @param {function} handler
* @returns {function} unsubscribe
*/
export function onMessage(topics, handler) {
const tArray = Array.isArray(topics) ? topics : [topics];
const fns = [];
for (const t of tArray) {
const entry = {
componentFn: handler, topic: t, loadFn: handler, state: {},
unsubscribed: false
};
_wsSubs.set(handler + ':' + t, entry);
fns.push(() => {
entry.unsubscribed = true;
if (_wsDebounceTimers.has(entry.state)) {
clearTimeout(_wsDebounceTimers.get(entry.state));
_wsDebounceTimers.delete(entry.state);
}
_wsSubs.delete(handler + ':' + t);
});
}
return () => fns.forEach(f => f());
const entry = { topics: tArray, handler, unsubscribed: false };
_directHandlers.push(entry);
return () => {
entry.unsubscribed = true;
const idx = _directHandlers.indexOf(entry);
if (idx !== -1) _directHandlers.splice(idx, 1);
};
}
/** Start the WebSocket connection. */
export function connect() {
_wsConnect();
}
+1 -1
View File
@@ -14,6 +14,6 @@
</div>
</div>
<script>window.__WS_URL__ = "__WS_URL_PLACEHOLDER__"</script>
<script type="module" src="/static/app.js?v=6"></script>
<script type="module" src="/static/app.js?v=7"></script>
</body>
</html>
+9 -22
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, Empty, Table, renderGuard, esc, enc, $val, apiFetch, toast, openModal, closeModal, formModal, definePage, refactorLoad, ActionCell, certStatusBadge, poll } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Empty, Table, renderGuard, esc, enc, $val, apiFetch, toast, openModal, closeModal, formModal, definePage, getModel, modelFetch, ActionCell, certStatusBadge, poll } from '/static/hoover/index.js?v=7';
function issueCertModal(state) {
openModal((inner, idx) => {
@@ -40,7 +40,7 @@ async function pollCertIssue(rid, state) {
onErrorKey: (d) => d.status === 'failed',
onComplete: (d) => {
toast('Certificate issued for ' + (d.domain || rid), 'success');
load(state);
modelFetch('acme');
},
onError: (d) => {
toast('Issuance failed: ' + (d?.error || 'unknown'), 'error');
@@ -48,30 +48,17 @@ async function pollCertIssue(rid, state) {
});
}
async function load(state, abortController, entry) {
await refactorLoad(state,
s => s.certs?.length,
async (s, sig, isAborted) => {
const r = await apiFetch('/api/certs/list', { signal: sig });
if (isAborted()) return;
if (r.ok) s.certs = r.data || [];
else s.error = r.error;
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { certs: [] };
return {
acme: getModel('acme'),
};
},
subscribe: ['acme'],
load,
render(state) {
const guard = renderGuard(state, 'Certificates', 'ACME certificate management', state.certs);
const guard = renderGuard(state.acme, 'Certificates', 'ACME certificate management', state.acme.data);
if (guard) return guard;
const rows = state.certs.map(c => {
const rows = (state.acme.data || []).map(c => {
const badge = certStatusBadge({ expired: c.expired, daysRemaining: c.days_remaining });
return h('tr', { key: c.domain },
@@ -89,7 +76,7 @@ export default definePage({
removeUrl: '/api/certs/' + enc(c.domain),
removeMessage: 'Remove certificate for ' + c.domain + '?',
removeSuccess: 'Certificate removed',
removeReload: () => load(state),
removeRefresh: 'acme',
}),
);
});
@@ -109,4 +96,4 @@ export default definePage({
: Empty({ text: 'No certificates found. Issue a certificate to get started.' }),
];
},
});
});
+7 -18
View File
@@ -1,27 +1,16 @@
import { h, PageHeader, apiFetch, definePage, renderGuard, refactorLoad, ServiceStatus, StatCard } from '/static/hoover/index.js?v=6';
import { h, PageHeader, definePage, getModel, renderGuard, ServiceStatus, StatCard } from '/static/hoover/index.js?v=7';
export default definePage({
init() {
return { data: null };
},
subscribe: ['firewall', 'dnsmasq', 'wireguard', 'acme', 'networkd'],
async load(state, abortController, entry) {
await refactorLoad(state,
s => s.data,
async (s, sig, isAborted) => {
const res = await apiFetch('/api/status/all', { signal: sig });
if (isAborted()) return;
if (res.ok) s.data = res.data;
else s.error = res.error;
},
{ entry, abortController },
);
return {
status: getModel('status'),
};
},
render(state) {
const guard = renderGuard(state, 'Dashboard', 'System overview', state.data);
const guard = renderGuard(state.status, 'Dashboard', 'System overview', state.status.data);
if (guard) return guard;
const d = state.data;
const d = state.status.data;
const fwZones = (d.firewall?.zones) || {};
const net = d.net || {};
const nCount = Object.keys(net).length;
@@ -69,4 +58,4 @@ export default definePage({
),
];
},
});
});
+21 -49
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, ConfirmDelete, Tabs, Table, ServiceStatus, renderGuard, esc, enc, $val, apiFetch, toast, definePage, refactorLoad, ActionButton, ActionGroup, QuickModal } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Badge, ConfirmDelete, Tabs, Table, ServiceStatus, renderGuard, esc, enc, $val, apiFetch, toast, definePage, getModel, modelFetch, ActionButton, ActionGroup, QuickModal } from '/static/hoover/index.js?v=7';
const addRange = QuickModal({
title: 'Add DHCP Range',
@@ -19,7 +19,7 @@ const addRange = QuickModal({
validate: (b) => !b.start || !b.end ? 'Start and end are required' : null,
successMsg: 'Range added',
},
reload: (s) => load(s),
refresh: 'dnsmasq',
});
const addLease = QuickModal({
@@ -39,7 +39,7 @@ const addLease = QuickModal({
validate: (b) => !b.mac || !b.ip ? 'MAC and IP are required' : null,
successMsg: 'Lease added',
},
reload: (s) => load(s),
refresh: 'dnsmasq',
});
const addDns = QuickModal({
@@ -54,55 +54,27 @@ const addDns = QuickModal({
validate: (b) => !b.name || !b.address ? 'Name and address are required' : null,
successMsg: 'DNS record added',
},
reload: (s) => load(s),
refresh: 'dnsmasq',
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => Object.keys(s.config || {}).length,
async (s, sig, isAborted) => {
const [cfgR, stR, lsR] = await Promise.allSettled([
apiFetch('/api/dhcp/config', { signal: sig }),
apiFetch('/api/dhcp/status', { signal: sig }),
apiFetch('/api/dhcp/leases', { signal: sig }),
]);
if (isAborted()) return;
const errors = [];
if (cfgR.status === 'rejected') errors.push(cfgR.reason?.message || 'Failed');
else if (!cfgR.value.ok) errors.push(cfgR.value.error || 'Failed');
if (stR.status === 'rejected') errors.push(stR.reason?.message || 'Failed');
else if (!stR.value.ok) errors.push(stR.value.error || 'Failed');
if (lsR.status === 'rejected') errors.push(lsR.reason?.message || 'Failed');
else if (!lsR.value.ok) errors.push(lsR.value.error || 'Failed');
if (errors.length) {
s.error = errors[0];
return;
}
s.config = cfgR.value.data || {};
s.status = stR.value.data || {};
s.leases = lsR.value.data || [];
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { config: {}, status: {}, leases: [], activeTab: 'ranges' };
return {
dnsmasq: getModel('dnsmasq'),
activeTab: 'ranges',
};
},
subscribe: ['dnsmasq'],
load,
render(state) {
const guard = renderGuard(state, 'DHCP & DNS', null, state.leases);
const guard = renderGuard(state.dnsmasq, 'DHCP & DNS', 'Dnsmasq management', state.dnsmasq.data);
if (guard) return guard;
const cfg = state.config || {};
const cfg = state.dnsmasq.data?.config || {};
const ranges = cfg.ranges || [];
const staticLeases = cfg.static_leases || [];
const dnsRecords = cfg.dns_records || [];
const statusUp = state.status || {};
const status = state.dnsmasq.data?.status || {};
const rangesRows = ranges.map((r, i) => h('tr', { key: (r.interface || '_g') + '-' + r.start + '-' + r.end },
const rangesRows = ranges.map((r) => h('tr', { key: (r.interface || '_g') + '-' + r.start + '-' + r.end },
h('td', null, r.interface || '(global)'),
h('td', null, esc(r.start)),
h('td', null, esc(r.end)),
@@ -113,12 +85,12 @@ export default definePage({
message: 'Remove range ' + r.start + ' - ' + r.end + '?',
body: { interface: r.interface || '', start: r.start, end: r.end },
success: 'Range removed',
reload: () => load(state),
refresh: 'dnsmasq',
}),
),
));
const leaseRows = staticLeases.map((l, i) => h('tr', { key: l.mac },
const leaseRows = staticLeases.map((l) => h('tr', { key: l.mac },
h('td', null, esc(l.mac)),
h('td', null, esc(l.ip)),
h('td', null, l.hostname || '-'),
@@ -127,12 +99,12 @@ export default definePage({
url: '/api/dhcp/static-lease/' + enc(l.mac),
message: 'Remove lease ' + l.mac + '?',
success: 'Lease removed',
reload: () => load(state),
refresh: 'dnsmasq',
}),
),
));
const dnsRows = dnsRecords.map((rec, i) => h('tr', { key: rec.name },
const dnsRows = dnsRecords.map((rec) => h('tr', { key: rec.name },
h('td', null, h('strong', null, esc(rec.name || 'unnamed'))),
h('td', { class: 'text-sm' }, esc(rec.address || '-')),
h('td', null,
@@ -140,7 +112,7 @@ export default definePage({
url: '/api/dhcp/dns-record/' + enc(rec.name || ''),
message: 'Remove DNS record ' + (rec.name || 'unnamed') + '?',
success: 'Record removed',
reload: () => load(state),
refresh: 'dnsmasq',
}),
),
));
@@ -154,13 +126,13 @@ export default definePage({
url: '/api/dhcp/apply',
successMsg: 'dnsmasq applied',
label: 'Apply',
reload: () => load(state),
refresh: 'dnsmasq',
}),
);
return [
PageHeader({ title: 'DHCP & DNS', subtitle: 'Dnsmasq management', actions }),
ServiceStatus({ state: statusUp.state || 'down', label: 'Dnsmasq' }),
ServiceStatus({ state: status.state || 'down', label: 'Dnsmasq' }),
Tabs({ state, tabs: tabNames }),
state.activeTab === 'ranges'
? Table({ columns: ['Interface', 'Start', 'End', 'Lease', 'Action'], rows: rangesRows, emptyText: 'No DHCP ranges' }) : null,
@@ -169,7 +141,7 @@ export default definePage({
state.activeTab === 'dns'
? Table({ columns: ['Name', 'Address', 'Action'], rows: dnsRows, emptyText: 'No custom DNS records' }) : null,
state.activeTab === 'active'
? Table({ columns: ['MAC', 'IP', 'Hostname', 'Expires'], rows: (state.leases || []).map((l, i) => h('tr', { key: l.mac || i },
? Table({ columns: ['MAC', 'IP', 'Hostname', 'Expires'], rows: (state.dnsmasq.data?.leases || []).map((l) => h('tr', { key: l.mac || l.ip },
h('td', null, esc(l.mac || '-')),
h('td', null, esc(l.ip || '-')),
h('td', null, esc(l.hostname || '-')),
@@ -177,4 +149,4 @@ export default definePage({
)), emptyText: 'No active leases' }) : null,
];
},
});
});
+35 -43
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Table, renderGuard, enc, $val, apiFetch, toast, definePage, refactorLoad, StatusText, QuickModal, ZoneSelect } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Table, renderGuardMulti, enc, $val, apiFetch, toast, definePage, getModel, modelFetch, StatusText, QuickModal, ZoneSelect } from '/static/hoover/index.js?v=7';
async function changeZone(name, zone, state) {
const r = await apiFetch('/api/firewall/zones/' + enc(zone) + '/interfaces', {
@@ -7,7 +7,8 @@ async function changeZone(name, zone, state) {
});
if (r.ok) {
toast(name + ' \u2192 ' + zone, 'success');
await load(state);
modelFetch('firewall');
modelFetch('network');
} else {
toast(r.error || 'Failed', 'error');
}
@@ -32,53 +33,44 @@ const cfgModalFn = QuickModal({
}),
successMsg: 'Config saved',
},
reload: (s) => load(s),
refresh: ['firewall', 'network'],
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => s.ifaces?.length,
async (s, sig, isAborted) => {
const [fw, net] = await Promise.all([
apiFetch('/api/firewall/zones', { signal: sig }),
apiFetch('/api/network/interfaces', { signal: sig }),
]);
if (isAborted()) return;
if (fw.ok) s.zones = fw.data?.available || [];
else s.error = fw.error;
if (net.ok) {
const ifaceZone = {};
for (const [zoneName, ifaces] of Object.entries(fw.data?.active || {})) {
for (const name of (ifaces || [])) ifaceZone[name] = zoneName;
}
const ifacesObj = net.data?.interfaces || {};
s.ifaces = Object.entries(ifacesObj).map(([name, entry]) => ({
name,
mac: entry?.runtime?.mac || null,
ips: [...(entry?.config?.addresses || []), ...(entry?.runtime?.addresses || [])],
state: (entry?.runtime?.state || '').startsWith('routable') || (entry?.runtime?.state || '').startsWith('carrier') ? 'up' : 'down',
zone: ifaceZone[name] || null,
config: entry?.config || {},
}));
} else if (!s.error) {
s.error = net.error;
}
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { ifaces: [], zones: [] };
return {
firewall: getModel('firewall'),
network: getModel('network'),
};
},
subscribe: ['firewall', 'networkd'],
load,
render(state) {
const guard = renderGuard(state, 'Interfaces', 'Network interface management', state.ifaces.length);
const guard = renderGuardMulti('Interfaces', 'Network interface management', state.firewall, state.network);
if (guard) return guard;
const rows = state.ifaces.map(iface => {
const fwZones = state.firewall.data?.zones || {};
const netData = state.network.data?.interfaces || {};
const zones = fwZones.available || [];
const activeZones = fwZones.active || {};
const ifaces = Object.entries(netData).map(([name, entry]) => {
let zone = null;
for (const [zoneName, ifaces] of Object.entries(activeZones)) {
if ((ifaces || []).includes(name)) {
zone = zoneName;
break;
}
}
return {
name,
mac: entry?.runtime?.mac || null,
ips: [...(entry?.config?.addresses || []), ...(entry?.runtime?.addresses || [])],
state: (entry?.runtime?.state || '').startsWith('routable') || (entry?.runtime?.state || '').startsWith('carrier') ? 'up' : 'down',
zone,
config: entry?.config || {},
};
});
const rows = ifaces.map(iface => {
return h('tr', { key: iface.name },
h('td', null, h('strong', null, iface.name)),
h('td', { class: 'text-muted' }, String(iface.mac || 'N/A')),
@@ -86,7 +78,7 @@ export default definePage({
h('td', null, StatusText({ status: iface.state })),
h('td', null,
ZoneSelect({
zones: state.zones,
zones,
value: iface.zone,
onChange: (z) => changeZone(iface.name, z, state),
}),
@@ -108,4 +100,4 @@ export default definePage({
}),
];
},
});
});
+33 -84
View File
@@ -1,108 +1,57 @@
import { h, PageHeader, Tabs, esc, definePage, refactorLoad } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Tabs, esc, definePage, renderGuard, modelFetch, getModel } from '/static/hoover/index.js?v=7';
const logTabs = [
{ key: 'journal', label: 'Journal', url: '/api/logs/journal' },
{ key: 'nginx-access', label: 'Nginx Access', url: '/api/logs/nginx/access' },
{ key: 'nginx-error', label: 'Nginx Error', url: '/api/logs/nginx/error' },
{ key: 'dnsmasq', label: 'Dnsmasq', url: '/api/logs/dnsmasq' },
{ key: 'app', label: 'App', url: '/api/logs/app' },
{ key: 'journal', label: 'Journal' },
{ key: 'nginx-access', label: 'Nginx Access' },
{ key: 'nginx-error', label: 'Nginx Error' },
{ key: 'dnsmasq', label: 'Dnsmasq' },
{ key: 'app', label: 'App' },
];
async function fetchLog(state, url, signal) {
if (signal?.aborted) return;
const res = await fetch(url, { signal });
if (signal?.aborted) return;
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const text = await res.text();
if (signal?.aborted) return;
state.lines = text.split('\n').filter(l => l.length > 0);
}
export default definePage({
init() {
return { activeTab: 'journal', lines: [], loading: false, _abortCtrl: null };
},
subscribe: [],
async load(state, abortController, entry) {
await refactorLoad(state,
s => s.lines?.length,
async (s, sig, isAborted) => {
const tab = logTabs.find(t => t.key === s.activeTab) || logTabs[0];
await fetchLog(s, tab.url, sig);
},
{ entry, abortController },
);
},
onUnmount(state) {
state._abortCtrl?.abort();
state.lines = [];
return {
logs: getModel('logs'),
activeTab: 'journal',
};
},
render(state) {
const tab = logTabs.find(t => t.key === state.activeTab) || logTabs[0];
const logData = state.logs.data;
const stale = logData?.tab !== state.activeTab;
const guard = renderGuard(state.logs, 'Logs', 'System and service logs', stale ? undefined : logData?.data);
if (guard) return guard;
const lineVnodes = state.lines.map((line, i) =>
const lines = logData.data || [];
const tab = logTabs.find(t => t.key === state.activeTab) || logTabs[0];
const lineVnodes = lines.map((line, i) =>
h('div', { class: 'log-line', key: i }, esc(line))
);
const tabsBody = Tabs({
state,
tabs: logTabs.map(t => t.key),
formatLabel: (k) => {
const t = logTabs.find(t => t.key === k);
return t ? t.label : k.charAt(0).toUpperCase() + k.slice(1);
},
onTabClick: (key) => modelFetch('logs', key),
});
return [
PageHeader({ title: 'Logs', subtitle: 'System & service logs' }),
Tabs({
state,
tabs: logTabs.map(t => t.key),
formatLabel: (k) => {
const tab = logTabs.find(t => t.key === k);
return tab ? tab.label : k.charAt(0).toUpperCase() + k.slice(1);
},
onTabClick: async (key) => {
const tab = logTabs.find(t => t.key === key);
if (!tab) return;
state._abortCtrl?.abort();
const ctrl = new AbortController();
state._abortCtrl = ctrl;
const tabs = state.lines?.length ? state : null;
state.refreshing = !!tabs;
if (!tabs) state.loading = true;
state.error = null;
try {
await fetchLog(state, tab.url, ctrl.signal);
} catch (e) {
if (!ctrl.signal.aborted) state.error = String(e);
}
state.loading = false;
state.refreshing = false;
},
}),
PageHeader({ title: 'Logs', subtitle: 'System and service logs' }),
h('div', { class: 'card', key: 'log-card' },
tabsBody,
h('div', { class: 'card-header' },
h('span', null, tab.label),
h('button', {
class: 'btn btn-sm btn-outline',
style: 'float:right;',
'on:click': async () => {
state._abortCtrl?.abort();
const ctrl = new AbortController();
state._abortCtrl = ctrl;
state.refreshing = true;
state.error = null;
try {
await fetchLog(state, tab.url, ctrl.signal);
} catch (e) {
if (!ctrl.signal.aborted) state.error = String(e);
}
state.loading = false;
state.refreshing = false;
},
}, '\u21BB')
'on:click': () => modelFetch('logs', state.activeTab),
}, '\u21BB'),
),
h('div', { class: 'card-body log-body' },
state.loading && !state.refreshing
? h('div', { class: 'loading' }, state.refreshing ? 'Refreshing...' : 'Loading...')
: state.error
? h('div', { class: 'error-msg' }, state.error)
: lineVnodes.length > 0
? h('pre', null, lineVnodes)
: h('div', { class: 'text-muted text-sm' }, 'No log lines available')
)
h('pre', null, lineVnodes),
),
),
];
},
+14 -33
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, StatusDot, Card, Table, renderGuard, enc, $val, apiFetch, toast, definePage, refactorLoad, ActionButton, DataTableSection, SectionTitle, ActionGroup, QuickModal, ConfirmDelete, ZoneSelect } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Badge, StatusDot, Card, Table, renderGuard, enc, $val, apiFetch, toast, definePage, getModel, modelFetch, ActionButton, DataTableSection, SectionTitle, ActionGroup, QuickModal, ConfirmDelete } from '/static/hoover/index.js?v=7';
const addFwd = QuickModal({
title: 'Add Port Forward',
@@ -11,7 +11,7 @@ const addFwd = QuickModal({
],
submit: {
url: '/api/firewall/forward-port',
body: (s) => ({
body: () => ({
zone: $val('fwd-zone'),
port: parseInt($val('fwd-port')),
proto: ($val('fwd-proto') || 'tcp').trim(),
@@ -21,43 +21,23 @@ const addFwd = QuickModal({
validate: (b) => !b.zone || !b.port || !b.proto ? 'Zone, port, and proto are required' : null,
successMsg: 'Forward rule added',
},
reload: (s) => load(s._s),
refresh: 'firewall',
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => Object.keys(s.config || {}).length,
async (s, sig, isAborted) => {
const r = await apiFetch('/api/firewall/config', { signal: sig });
if (isAborted()) return;
if (r.ok) s.config = r.data || {};
else s.error = r.error;
const zr = await apiFetch('/api/firewall/zones', { signal: sig });
if (isAborted()) return;
if (zr.ok) s.activeZones = Object.keys(zr.data?.active || {});
else if (!s.error) s.error = zr.error;
const sr = await apiFetch('/api/firewall/state', { signal: sig });
if (isAborted()) return;
if (sr.ok) s.stateData = sr.data;
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { config: {}, activeZones: [], stateData: null };
return {
firewall: getModel('firewall'),
};
},
subscribe: ['firewall'],
load,
render(state) {
const guard = renderGuard(state, 'NAT', 'Masquerade & port forwarding', state.config);
const guard = renderGuard(state.firewall, 'NAT', 'Masquerade & port forwarding', state.firewall.data?.config);
if (guard) return guard;
const cfg = state.config || {};
const cfg = state.firewall.data?.config || {};
const zoneData = cfg.zones || {};
const sIface = (state.stateData || {}).interfaces || [];
const sIface = (state.firewall.data?.state || {}).interfaces || [];
const masqZones = new Set(
Object.entries(zoneData)
.filter(([, zcfg]) => !!zcfg.masquerade)
@@ -94,7 +74,7 @@ export default definePage({
labelOn: 'Disable', labelOff: 'Enable', condition: masq,
body: () => ({ zone, enable: !masq }),
successMsg: 'Masquerade ' + (masq ? 'disabled' : 'enabled') + ' on ' + zone,
reload: () => load(state),
refresh: 'firewall',
}),
),
);
@@ -117,7 +97,7 @@ export default definePage({
url: '/api/firewall/forward-port/' + enc(zone) + '/' + port + '/' + enc(proto),
message: 'Remove forward ' + zone + ':' + port + '/' + proto + '?',
success: 'Rule removed',
reload: () => load(state),
refresh: 'firewall',
}),
),
));
@@ -148,7 +128,8 @@ export default definePage({
Card({ children: [
ActionGroup(
h('button', { class: 'btn btn-sm btn-primary',
'on:click': () => addFwd({ zones: state.activeZones, _s: state }) }, 'Add Forward'),
'on:click': () => addFwd({ zones: Object.keys(zoneData) })
}, 'Add Forward'),
),
Table({
columns: ['Zone', 'Proto', 'Port', 'To Addr', 'To Port', 'Action'],
@@ -159,4 +140,4 @@ export default definePage({
]}),
];
},
});
});
+2 -6
View File
@@ -1,12 +1,8 @@
import { h, PageHeader, definePage } from '/static/hoover/index.js?v=6';
import { h, PageHeader, definePage } from '/static/hoover/index.js?v=7';
export default definePage({
init() {
return { path: '' };
},
subscribe: [],
async load(state) {
state.path = location.hash.slice(1) || '';
return { path: location.hash.slice(1) || '' };
},
render(state) {
return [
+15 -30
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, Empty, Table, renderGuard, esc, enc, $val, apiFetch, toast, definePage, refactorLoad, ActionButton, ActionCell, certStatusBadge, ActionGroup, QuickModal } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Badge, Empty, Table, renderGuardMulti, esc, enc, $val, apiFetch, toast, definePage, getModel, modelFetch, ActionButton, ActionCell, certStatusBadge, ActionGroup, QuickModal } from '/static/hoover/index.js?v=7';
const addDomain = QuickModal({
title: 'Add Proxy Domain',
@@ -21,7 +21,7 @@ const addDomain = QuickModal({
validate: (b) => !b.domain || !b.backend_host || !b.backend_port ? 'Domain, host, and port are required' : null,
successMsg: 'Domain added',
},
reload: (s) => load(s),
refresh: ['nginx', 'acme'],
});
const editDomain = QuickModal({
@@ -35,7 +35,7 @@ const editDomain = QuickModal({
submit: {
url: (d) => '/api/proxy/domains/' + enc(d.domain),
method: 'PUT',
body: (d) => ({
body: () => ({
backend_host: ($val('pe-host') || '').trim(),
backend_port: parseInt($val('pe-port')),
backend_proto: ($val('pe-proto') || 'http').trim(),
@@ -44,37 +44,22 @@ const editDomain = QuickModal({
validate: (b) => !b.backend_host || !b.backend_port ? 'Host and port are required' : null,
successMsg: 'Domain updated',
},
reload: (s) => load(s._s),
refresh: ['nginx', 'acme'],
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => s.domains?.length,
async (s, sig, isAborted) => {
const domainsR = await apiFetch('/api/proxy/domains', { signal: sig });
if (isAborted()) return;
if (domainsR.ok) s.domains = domainsR.data || [];
else s.error = domainsR.error;
const certsR = await apiFetch('/api/certs/list', { signal: sig });
if (isAborted()) return;
if (certsR.ok) s.certs = certsR.data || [];
else if (!s.error) s.error = certsR.error;
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { domains: [], certs: [] };
return {
nginx: getModel('nginx'),
acme: getModel('acme'),
};
},
subscribe: ['nginx', 'acme'],
load,
render(state) {
const guard = renderGuard(state, 'Proxy', 'Nginx reverse proxy', state.domains);
const guard = renderGuardMulti('Proxy', 'Nginx reverse proxy', state.nginx, state.acme);
if (guard) return guard;
const rows = state.domains.map(d => {
const domains = state.nginx.data || [];
const rows = domains.map(d => {
const certBadge = certStatusBadge({
certStatus: d.cert_status,
daysRemaining: d.days_remaining,
@@ -89,11 +74,11 @@ export default definePage({
h('td', null, certBadge),
ActionCell({
editLabel: 'Edit',
editClick: () => editDomain({ ...d, _s: state }),
editClick: () => editDomain(d),
removeUrl: '/api/proxy/domains/' + enc(d.domain),
removeMessage: 'Remove proxy for ' + d.domain + '?',
removeSuccess: 'Domain removed',
removeReload: () => load(state),
removeRefresh: ['nginx', 'acme'],
removeLabel: 'Delete',
}),
);
@@ -105,7 +90,7 @@ export default definePage({
url: '/api/proxy/apply',
successMsg: 'Nginx applied & reloaded',
label: 'Apply',
reload: () => load(state),
refresh: ['nginx', 'acme'],
}),
);
@@ -119,4 +104,4 @@ export default definePage({
: Empty({ text: 'No proxy domains configured. Add a domain to start terminating SSL.' }),
];
},
});
});
+12 -28
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Empty, Card, ConfirmDelete, Table, renderGuard, esc, enc, $val, apiFetch, toast, definePage, refactorLoad, MonoText, QuickModal } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Empty, Card, ConfirmDelete, Table, renderGuard, esc, enc, $val, apiFetch, toast, definePage, getModel, modelFetch, MonoText, QuickModal } from '/static/hoover/index.js?v=7';
const addRule = QuickModal({
title: 'Add Rich Rule',
@@ -8,41 +8,25 @@ const addRule = QuickModal({
],
submit: {
url: '/api/firewall/rich-rules',
body: (s) => ({ zone: $val('rule-zone'), rule: ($val('rule-text') || '').trim() }),
body: () => ({ zone: $val('rule-zone'), rule: ($val('rule-text') || '').trim() }),
validate: (b) => !b.zone || !b.rule ? 'Zone and rule are required' : null,
successMsg: 'Rule added',
},
reload: (s) => load(s._s),
refresh: 'firewall',
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => Object.keys(s.config || {}).length,
async (s, sig, isAborted) => {
const r = await apiFetch('/api/firewall/config', { signal: sig });
if (isAborted()) return;
if (r.ok) s.config = r.data || {};
else s.error = r.error;
const zr = await apiFetch('/api/firewall/zones', { signal: sig });
if (isAborted()) return;
if (zr.ok) s.zones = Object.keys(zr.data?.active || {});
else if (!s.error) s.error = zr.error;
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { config: {}, zones: [] };
return {
firewall: getModel('firewall'),
};
},
subscribe: ['firewall'],
load,
render(state) {
const guard = renderGuard(state, 'Rules', 'Firewall rich rules', state.config);
const guard = renderGuard(state.firewall, 'Rules', 'Firewall rich rules', state.firewall.data?.config);
if (guard) return guard;
const cfg = state.config || {};
const cfg = state.firewall.data?.config || {};
const zones = state.firewall.data?.zones?.available || [];
const zoneData = cfg.zones || {};
const zoneRules = {};
Object.entries(zoneData).forEach(([zname, zcfg]) => {
@@ -67,7 +51,7 @@ export default definePage({
url: '/api/firewall/rich-rules/' + enc(zone) + '/' + enc(ruleId || ''),
message: 'Remove rule: ' + ruleText.substring(0, 40) + '...?',
success: 'Rule removed',
reload: () => load(state),
refresh: 'firewall',
}),
),
);
@@ -83,9 +67,9 @@ export default definePage({
title: 'Rules',
subtitle: 'Firewall rich rules',
actions: h('button', { class: 'btn btn-primary',
'on:click': () => addRule({ zones: state.zones, _s: state }), }, 'Add Rule'),
'on:click': () => addRule({ zones }), }, 'Add Rule'),
}),
...(cards.length ? cards : [Empty({ text: 'No rich rules configured.' })]),
];
},
});
});
+14 -35
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, StatusDot, Empty, Table, ServiceStatus, renderGuard, esc, enc, $val, apiFetch, toast, openModal, closeModal, formModal, definePage, apiSubmit, refactorLoad, ActionButton, ActionCell, MonoText, ActionGroup, QuickModal, downloadBlob } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Badge, StatusDot, Empty, Table, ServiceStatus, renderGuard, esc, enc, $val, apiFetch, toast, openModal, closeModal, formModal, definePage, getModel, modelFetch, ActionButton, ActionCell, MonoText, ActionGroup, QuickModal, downloadBlob } from '/static/hoover/index.js?v=7';
const addPeer = QuickModal({
title: 'Add WireGuard Peer',
@@ -19,7 +19,7 @@ const addPeer = QuickModal({
validate: (b) => !b.name ? 'Name is required' : null,
successMsg: 'Peer added',
},
reload: (s) => load(s),
refresh: 'wireguard',
});
function downloadConfigModal(peerName, config, state) {
@@ -50,42 +50,21 @@ function downloadConfigModal(peerName, config, state) {
});
}
async function load(state, abortController, entry) {
await refactorLoad(state,
s => s.peers?.length,
async (s, sig, isAborted) => {
const stR = await apiFetch('/api/wireguard/status', { signal: sig });
if (isAborted()) return;
if (stR.ok) s.status = stR.data || {};
else s.error = stR.error;
const pR = await apiFetch('/api/wireguard/peers', { signal: sig });
if (isAborted()) return;
if (pR.ok) s.peers = pR.data || [];
else if (!s.error) s.error = pR.error;
const cfgR = await apiFetch('/api/wireguard/config', { signal: sig });
if (isAborted()) return;
if (cfgR.ok) s.config = cfgR.data || {};
else if (!s.error) s.error = cfgR.error;
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { status: {}, peers: [], config: {} };
return {
wireguard: getModel('wireguard'),
};
},
subscribe: ['wireguard'],
load,
render(state) {
const guard = renderGuard(state, 'WireGuard', 'Tunnel: ' + ((state.status || {}).state || 'unknown') + ', Listen: ' + ((state.config?.interface || {}).listen_port || '-'), state.peers);
const guard = renderGuard(state.wireguard, 'WireGuard', null, state.wireguard.data?.peers);
if (guard) return guard;
const st = state.status || {};
const st = state.wireguard.data?.status || {};
const isUp = st.state === 'up';
const listenPort = (state.config?.interface || {}).listen_port || '-';
const listenPort = (state.wireguard.data?.config?.interface || {}).listen_port || '-';
const peerRows = state.peers.map(p => {
const peerRows = (state.wireguard.data?.peers || []).map(p => {
const hasHandshake = !!p.latest_handshake;
return h('tr', { key: p.name },
h('td', null,
@@ -103,11 +82,11 @@ export default definePage({
),
ActionCell({
editLabel: 'Config',
editClick: () => downloadConfigModal(p.name, state.config, state),
editClick: () => downloadConfigModal(p.name, state.wireguard.data?.config, state),
removeUrl: '/api/wireguard/peers/' + enc(p.name),
removeMessage: 'Remove peer ' + p.name + '?',
removeSuccess: 'Peer removed',
removeReload: () => load(state),
removeRefresh: 'wireguard',
}),
);
});
@@ -118,13 +97,13 @@ export default definePage({
url: '/api/wireguard/' + (isUp ? 'down' : 'up'),
labelOn: 'Stop', labelOff: 'Start', condition: isUp,
successMsg: 'Tunnel ' + (isUp ? 'stopped' : 'started'),
reload: () => load(state),
refresh: 'wireguard',
}),
ActionButton({
url: '/api/wireguard/apply',
successMsg: 'Config applied',
label: 'Apply',
reload: () => load(state),
refresh: 'wireguard',
}),
);
@@ -143,4 +122,4 @@ export default definePage({
: Empty({ text: 'No peers configured. Add a peer above.' }),
];
},
});
});
+22 -69
View File
@@ -1,4 +1,4 @@
import { h, PageHeader, Badge, Empty, ConfirmDelete, renderGuard, enc, esc, $val, apiFetch, toast, definePage, refactorLoad, MultiSelectModal, QuickModal } from '/static/hoover/index.js?v=6';
import { h, PageHeader, Badge, Empty, ConfirmDelete, renderGuard, enc, esc, $val, definePage, getModel, MultiSelectModal, QuickModal } from '/static/hoover/index.js?v=7';
const addZone = QuickModal({
title: 'Add Zone',
@@ -12,75 +12,28 @@ const addZone = QuickModal({
validate: (b) => !b.name ? 'Zone name required' : null,
successMsg: 'Zone created',
},
reload: (s) => load(s),
refresh: 'firewall',
});
async function load(state, abortController, entry) {
await refactorLoad(state,
s => Object.keys(s.zones || {}).length,
async (s, sig, isAborted) => {
const [zRes, svcRes, ifRes] = await Promise.allSettled([
apiFetch('/api/firewall/zones', { signal: sig }),
apiFetch('/api/firewall/services', { signal: sig }),
apiFetch('/api/firewall/interfaces', { signal: sig }),
]);
if (isAborted()) return;
const errors = [];
if (zRes.status === 'rejected') errors.push(zRes.reason?.message || 'Failed');
else if (!zRes.value.ok) errors.push(zRes.value.error || 'Failed');
if (svcRes.status === 'rejected') errors.push(svcRes.reason?.message || 'Failed');
else if (!svcRes.value.ok) errors.push(svcRes.value.error || 'Failed');
if (ifRes.status === 'rejected') errors.push(ifRes.reason?.message || 'Failed');
else if (!ifRes.value.ok) errors.push(ifRes.value.error || 'Failed');
if (errors.length) {
s.error = errors[0];
return;
}
const data = zRes.value.data || {};
const activeZones = data.active || {};
const availableZones = data.available || [];
const detailPromises = availableZones.map(name =>
apiFetch('/api/firewall/zones/' + enc(name), { signal: sig })
);
const detailResults = await Promise.allSettled(detailPromises);
if (isAborted()) return;
const zones = {};
for (let i = 0; i < availableZones.length; i++) {
const name = availableZones[i];
const res = detailResults[i];
const detail = res.status === 'fulfilled' ? res.value : null;
if (detail && detail.ok) {
zones[name] = detail.data;
const activeIfaces = activeZones[name];
if (Array.isArray(activeIfaces)) {
zones[name].interfaces = activeIfaces;
}
}
}
s.zones = zones;
s.services = svcRes.value.data || [];
s.interfaces = ifRes.value.data || [];
},
{ entry, abortController },
);
}
export default definePage({
init() {
return { zones: {}, services: [], interfaces: [] };
return {
firewall: getModel('firewall'),
};
},
subscribe: ['firewall'],
load,
render(state) {
const guard = renderGuard(state, 'Zones', 'Firewall zone management', Object.keys(state.zones || {}).length);
const guard = renderGuard(state.firewall, 'Zones', 'Firewall zones', state.firewall.data?.zones);
if (guard) return guard;
const zoneCards = Object.entries(state.zones || []).map(([name, zdata]) => {
const zones = state.firewall.data?.zones?.available || [];
const activeZones = state.firewall.data?.zones?.active || {};
const zoneDetails = {};
for (const name of zones) {
const activeIfaces = activeZones[name];
zoneDetails[name] = { interfaces: Array.isArray(activeIfaces) ? activeIfaces : [] };
}
const zoneCards = Object.entries(zoneDetails).map(([name, zdata]) => {
const z = typeof zdata === 'object' ? zdata : {};
const ifacesArr = Array.isArray(z.interfaces) ? z.interfaces : [];
const svcsArr = Array.isArray(z.services) ? z.services : [];
@@ -110,29 +63,29 @@ export default definePage({
'on:click': () => MultiSelectModal({
title: 'Interfaces: ' + name,
url: '/api/firewall/zones/' + enc(name) + '/interfaces',
options: state.interfaces,
options: state.firewall.data?.interfaces || [],
selected: ifacesArr,
fieldKey: 'interfaces',
successMsg: 'Interfaces updated',
reload: () => load(state),
refresh: 'firewall',
})(),
}, 'Interfaces'),
h('button', { class: 'btn btn-sm btn-outline',
'on:click': () => MultiSelectModal({
title: 'Services: ' + name,
url: '/api/firewall/zones/' + enc(name) + '/services',
options: state.services,
options: state.firewall.data?.services || [],
selected: svcsArr,
fieldKey: 'services',
successMsg: 'Services updated',
reload: () => load(state),
refresh: 'firewall',
})(),
}, 'Services'),
ConfirmDelete({
url: '/api/firewall/zones/' + enc(name),
message: 'Delete zone ' + name + '?',
success: 'Zone ' + name + ' deleted',
reload: () => load(state),
refresh: 'firewall',
label: 'Delete',
}),
),
@@ -144,11 +97,11 @@ export default definePage({
title: 'Zones',
subtitle: 'Firewall zones',
actions: h('button', { class: 'btn btn-primary',
'on:click': () => addZone(state), }, 'Add Zone'),
'on:click': () => addZone(), }, 'Add Zone'),
}),
zoneCards.length
? h('div', { class: 'card-grid' }, ...zoneCards)
: Empty({ text: 'No zones configured. Add a zone to get started.' }),
];
},
});
});