feat(client): build flat multi-theme ES2020 UI shell, Vault/Config editors, and esbuild pipeline

This commit is contained in:
tyuXX 2026-11-26 18:27:27 +00:00
parent 9cedd83a07
commit ce7e42fbc2
16 changed files with 2910 additions and 0 deletions

321
src/client/ts/main.ts Normal file
View file

@ -0,0 +1,321 @@
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
import {
apiFetch,
registerStepUpHandler,
registerUnauthorizedHandler,
setApiSafeMode,
setCsrfToken,
} from './api.js';
import { confirmDialog, promptStepUp } from './dialogs.js';
import {
SAFE_MODE_STORAGE_KEY,
THEME_STORAGE_KEY,
applyTheme,
initialDeviceSafeMode,
type ClientState,
type ConfigOverview,
type RouteId,
} from './state.js';
import { renderAuthView } from './views/auth-view.js';
import { renderConfigView } from './views/config-view.js';
import { renderSectionShell } from './views/section-shells.js';
import { renderSettingsView } from './views/settings-view.js';
import { renderVaultView } from './views/vault-view.js';
import { MultiplexWsClient } from './ws-client.js';
const VALID_ROUTES = new Set<RouteId>([
'dashboard',
'systems',
'terminal',
'sftp',
'workflows',
'alerts',
'config',
'vault',
'settings',
]);
const wsClient = new MultiplexWsClient();
const state: ClientState = {
bootstrapped: false,
authenticated: false,
vaultState: 'uninitialized',
isPanicLocked: false,
safeMode: false,
defaultMobileSafeMode: true,
elevatedUntil: null,
theme: localStorage.getItem(THEME_STORAGE_KEY) ?? 'phosphor-green',
route: 'dashboard',
overview: null,
};
function currentRouteFromHash(): RouteId {
const raw = window.location.hash.replace(/^#/, '') as RouteId;
return VALID_ROUTES.has(raw) ? raw : 'dashboard';
}
function updateTopBarUi(): void {
const topbar = document.getElementById('topbar')!;
const nav = document.getElementById('primary-nav')!;
const vaultBadge = document.getElementById('vault-badge')!;
const safeBtn = document.getElementById('safe-toggle-btn')!;
const themeSelect = document.getElementById('theme-select') as HTMLSelectElement;
const stepupBadge = document.getElementById('stepup-badge')!;
const banner = document.getElementById('global-banner')!;
topbar.hidden = !state.authenticated;
nav.hidden = !state.authenticated;
document.body.setAttribute('data-safe-mode', state.safeMode ? 'true' : 'false');
safeBtn.textContent = state.safeMode ? '[SAFE: ON]' : '[SAFE: OFF]';
safeBtn.setAttribute('aria-pressed', state.safeMode ? 'true' : 'false');
safeBtn.className = state.safeMode ? 'btn btn-sm btn-safe-on' : 'btn btn-sm';
vaultBadge.textContent = `[VAULT: ${state.vaultState.toUpperCase()}]`;
vaultBadge.className = `badge ${state.vaultState === 'unlocked' ? 'badge-ok' : 'badge-warn'}`;
themeSelect.value = state.theme;
if (state.elevatedUntil && state.elevatedUntil > Date.now()) {
const remSec = Math.ceil((state.elevatedUntil - Date.now()) / 1000);
stepupBadge.hidden = false;
stepupBadge.textContent = `[2FA: ${remSec}s]`;
} else {
state.elevatedUntil = null;
stepupBadge.hidden = true;
}
for (const link of nav.querySelectorAll('.nav-link')) {
const r = link.getAttribute('data-route');
link.classList.toggle('active', r === state.route);
}
const errCount = state.overview?.diagnostics.errors.length ?? 0;
const warnCount = state.overview?.diagnostics.warnings.length ?? 0;
if (state.authenticated && (errCount > 0 || warnCount > 0)) {
banner.hidden = false;
banner.textContent = `Config Diagnostics: ${errCount} error(s), ${warnCount} warning(s). Check Config view for details.`;
} else {
banner.hidden = true;
}
}
async function refreshOverview(): Promise<void> {
state.overview = await apiFetch<ConfigOverview>('/api/config/overview');
updateTopBarUi();
}
async function renderCurrentView(): Promise<void> {
const root = document.getElementById('view-root')!;
updateTopBarUi();
if (!state.authenticated) {
await renderAuthView(root, state.bootstrapped, state.safeMode, async () => {
await bootstrapApp();
});
return;
}
if (!state.overview) {
await refreshOverview();
}
const route = state.route;
if (route === 'config') {
await renderConfigView(root, state.overview!, async () => {
await refreshOverview();
await renderCurrentView();
});
return;
}
if (route === 'vault') {
await renderVaultView(
root,
state,
async () => {
await syncStatusAndRender();
},
triggerPanicLock,
);
return;
}
if (route === 'settings') {
await renderSettingsView(
root,
state,
(theme) => {
state.theme = theme;
applyTheme(theme);
updateTopBarUi();
},
syncStatusAndRender,
);
return;
}
renderSectionShell(root, route, state.overview!);
}
async function triggerPanicLock(): Promise<void> {
const confirmed = await confirmDialog('dialog-panic');
if (!confirmed) return;
await apiFetch('/api/security/panic-lock', { method: 'POST' });
handleLocalSessionReset(true);
}
function handleLocalSessionReset(panic = false): void {
wsClient.disconnect();
setCsrfToken(null);
state.authenticated = false;
state.elevatedUntil = null;
state.overview = null;
if (panic) {
state.vaultState = 'locked';
state.isPanicLocked = true;
}
void renderCurrentView();
}
async function syncStatusAndRender(): Promise<void> {
const status = await apiFetch<{
bootstrapped: boolean;
authenticated: boolean;
safeMode?: boolean;
elevatedUntil?: number | null;
vaultState: ClientState['vaultState'];
isPanicLocked?: boolean;
defaultMobileSafeMode: boolean;
theme: string;
}>('/api/auth/status');
state.bootstrapped = status.bootstrapped;
state.authenticated = status.authenticated;
state.vaultState = status.vaultState;
state.isPanicLocked = Boolean(status.isPanicLocked);
state.defaultMobileSafeMode = status.defaultMobileSafeMode;
state.elevatedUntil = status.elevatedUntil ?? null;
if (!localStorage.getItem(THEME_STORAGE_KEY)) {
state.theme = status.theme;
}
applyTheme(state.theme);
const deviceSafe = initialDeviceSafeMode(status.defaultMobileSafeMode);
state.safeMode = status.authenticated ? Boolean(status.safeMode || deviceSafe) : deviceSafe;
setApiSafeMode(state.safeMode);
if (state.authenticated) {
// Sync device safe mode to server session if device enforces read-only
if (deviceSafe && !status.safeMode) {
await apiFetch('/api/auth/safe-mode', {
method: 'POST',
body: { enabled: true },
});
}
await refreshOverview();
}
await renderCurrentView();
}
async function bootstrapApp(): Promise<void> {
state.route = currentRouteFromHash();
await syncStatusAndRender();
if (state.authenticated) {
wsClient.connect();
}
}
document.addEventListener('DOMContentLoaded', () => {
applyTheme(state.theme);
registerStepUpHandler(() =>
promptStepUp((until) => {
state.elevatedUntil = until;
updateTopBarUi();
}),
);
registerUnauthorizedHandler(() => {
handleLocalSessionReset(false);
});
wsClient.onStatus((wsStatus) => {
const badge = document.getElementById('ws-badge')!;
badge.textContent =
wsStatus === 'online'
? '[ONLINE]'
: wsStatus === 'reconnecting'
? '[RECONNECTING...]'
: '[OFFLINE]';
badge.className = `badge ${
wsStatus === 'online'
? 'badge-ok'
: wsStatus === 'reconnecting'
? 'badge-warn'
: 'badge-err'
}`;
});
wsClient.onFrame((frame: ServerWsFrame) => {
if (frame.type === 'hello') {
state.vaultState = frame.vaultState;
state.elevatedUntil = frame.elevatedUntil;
updateTopBarUi();
} else if (frame.type === 'security:panic-lock') {
handleLocalSessionReset(true);
} else if (frame.type === 'config:updated' && state.authenticated) {
void refreshOverview().then(() => {
if (state.route === 'config' || state.route === 'dashboard') {
void renderCurrentView();
}
});
}
});
document.getElementById('safe-toggle-btn')!.addEventListener('click', async () => {
const next = !state.safeMode;
localStorage.setItem(SAFE_MODE_STORAGE_KEY, next ? '1' : '0');
state.safeMode = next;
setApiSafeMode(next);
if (next) state.elevatedUntil = null;
wsClient.send({ type: 'safe-mode', enabled: next });
if (state.authenticated) {
await apiFetch('/api/auth/safe-mode', {
method: 'POST',
body: { enabled: next },
});
}
updateTopBarUi();
});
document.getElementById('theme-select')!.addEventListener('change', (ev) => {
const theme = (ev.target as HTMLSelectElement).value;
state.theme = theme;
applyTheme(theme);
updateTopBarUi();
});
document.getElementById('panic-btn')!.addEventListener('click', () => {
void triggerPanicLock();
});
document.getElementById('logout-btn')!.addEventListener('click', async () => {
try {
await apiFetch('/api/auth/logout', { method: 'POST' });
} catch {
// Proceed with local cleanup even if session already expired
}
handleLocalSessionReset(false);
});
window.addEventListener('hashchange', () => {
state.route = currentRouteFromHash();
void renderCurrentView();
});
window.setInterval(() => {
if (state.elevatedUntil) updateTopBarUi();
}, 1000);
void bootstrapApp();
});