diff --git a/src/client/build.ts b/src/client/build.ts new file mode 100644 index 0000000..5d49be4 --- /dev/null +++ b/src/client/build.ts @@ -0,0 +1,67 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import zlib from 'node:zlib'; +import esbuild from 'esbuild'; + +const CORE_BUDGET_BYTES = 50 * 1024; +const clientDir = path.resolve('src/client'); +const outDir = path.resolve('dist/public'); + +async function buildClient(): Promise { + fs.rmSync(outDir, { recursive: true, force: true }); + fs.mkdirSync(outDir, { recursive: true }); + + await esbuild.build({ + entryPoints: [path.join(clientDir, 'ts', 'main.ts')], + bundle: true, + format: 'esm', + splitting: true, + minify: true, + sourcemap: false, + target: 'es2020', + outdir: outDir, + entryNames: '[name]', + chunkNames: 'chunks/[name]-[hash]', + }); + + for (const cssFile of ['themes.css', 'base.css']) { + await esbuild.build({ + entryPoints: [path.join(clientDir, 'css', cssFile)], + minify: true, + outfile: path.join(outDir, cssFile), + }); + } + + for (const asset of ['index.html', 'manifest.json', 'icon.svg']) { + fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset)); + } + + const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js']; + let totalRaw = 0; + let totalGzip = 0; + + for (const file of coreAssets) { + const buf = fs.readFileSync(path.join(outDir, file)); + const gz = zlib.gzipSync(buf, { level: 9 }); + totalRaw += buf.length; + totalGzip += gz.length; + console.log( + ` ${file.padEnd(14)} raw=${buf.length}B gzip=${gz.length}B`, + ); + } + + console.log( + `Core bundle total: raw=${totalRaw}B (${(totalRaw / 1024).toFixed(2)} KB), gzip=${totalGzip}B (${(totalGzip / 1024).toFixed(2)} KB / 50.00 KB budget)`, + ); + + if (totalGzip >= CORE_BUDGET_BYTES) { + throw new Error( + `Core client gzipped bundle (${totalGzip}B) exceeded 50KB budget (${CORE_BUDGET_BYTES}B)`, + ); + } +} + +buildClient().catch((err) => { + console.error(err); + process.exit(1); +}); diff --git a/src/client/css/base.css b/src/client/css/base.css new file mode 100644 index 0000000..87b99fb --- /dev/null +++ b/src/client/css/base.css @@ -0,0 +1,457 @@ +*, +*::before, +*::after { + box-sizing: border-box; + border-radius: 0 !important; + box-shadow: none !important; + backdrop-filter: none !important; +} + +html, +body { + margin: 0; + padding: 0; + background: var(--bg); + color: var(--fg); + font-family: ui-monospace, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace; + font-size: 14px; + line-height: 1.45; + min-height: 100dvh; +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip: rect(0 0 0 0); + white-space: nowrap; +} + +.app-shell { + display: flex; + flex-direction: column; + min-height: 100dvh; +} + +.topbar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 8px 12px; + background: var(--bg-panel); + border-bottom: 1px solid var(--border); +} + +.topbar-brand, +.topbar-actions, +.row, +.row-between, +.dialog-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.row-between { + justify-content: space-between; +} + +.dialog-actions { + justify-content: flex-end; + margin-top: 12px; +} + +.brand-mark { + font-weight: 700; + color: var(--accent); + letter-spacing: 0.04em; +} + +.primary-nav { + display: flex; + flex-wrap: wrap; + gap: 2px; + padding: 6px 12px; + background: var(--bg-elevated); + border-bottom: 1px solid var(--border); +} + +.nav-link { + display: inline-flex; + align-items: center; + min-height: 36px; + padding: 4px 10px; + border: 1px solid transparent; + color: var(--fg-muted); + text-decoration: none; + font-size: 13px; +} + +.nav-link:hover, +.nav-link.active { + color: var(--fg); + border-color: var(--border); + background: var(--bg-panel); +} + +.nav-link.active { + color: var(--accent); + border-color: var(--accent); +} + +.global-banner { + padding: 8px 12px; + background: var(--bg-elevated); + border-bottom: 1px solid var(--warn); + color: var(--warn); + font-size: 13px; +} + +.view-root { + flex: 1 1 auto; + padding: 12px; + max-width: 1400px; + width: 100%; + margin: 0 auto; +} + +.grid-2 { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.grid-3 { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; +} + +.config-layout { + display: grid; + grid-template-columns: 280px minmax(0, 1fr); + gap: 12px; +} + +.panel { + background: var(--bg-panel); + border: 1px solid var(--border); + padding: 12px; + margin-bottom: 12px; +} + +.panel-region { + content-visibility: auto; + contain-intrinsic-size: auto 320px auto 260px; +} + +@supports not (content-visibility: auto) { + .panel-region { + contain: layout style paint; + } +} + +.panel h1, +.panel h2, +.panel h3 { + margin: 0 0 8px; + font-size: 15px; + color: var(--accent); +} + +.stack { + display: flex; + flex-direction: column; + gap: 8px; +} + +.mono { + font-family: ui-monospace, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace; +} + +.muted { + color: var(--fg-muted); +} + +.ok-text { + color: var(--ok); +} + +.warn-text { + color: var(--warn); +} + +.err-text { + color: var(--err); +} + +.badge { + display: inline-block; + padding: 2px 6px; + border: 1px solid var(--border); + background: var(--bg); + font-size: 12px; + font-weight: 700; +} + +.badge-ok { + color: var(--ok); + border-color: var(--ok); +} + +.badge-warn { + color: var(--warn); + border-color: var(--warn); +} + +.badge-err { + color: var(--err); + border-color: var(--err); +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 40px; + padding: 6px 12px; + background: var(--bg-elevated); + color: var(--fg); + border: 1px solid var(--border); + font-family: inherit; + font-size: 13px; + cursor: pointer; +} + +.btn:hover:not(:disabled) { + border-color: var(--accent); +} + +.btn-sm { + min-height: 32px; + padding: 4px 8px; + font-size: 12px; +} + +.btn-primary { + background: var(--accent); + color: var(--accent-fg); + border-color: var(--accent); + font-weight: 700; +} + +.btn-danger { + color: var(--err); + border-color: var(--err); +} + +.btn-safe-on { + color: var(--warn); + border-color: var(--warn); + font-weight: 700; +} + +.btn:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +body[data-safe-mode="true"] .mutating-action { + opacity: 0.45; + cursor: not-allowed; +} + +input, +select, +textarea { + width: 100%; + min-height: 40px; + padding: 6px 8px; + background: var(--bg); + color: var(--fg); + border: 1px solid var(--border); + font-family: inherit; + font-size: 13px; +} + +.input-sm { + width: auto; + min-height: 32px; + padding: 4px 8px; +} + +textarea.code-editor { + min-height: 380px; + line-height: 1.4; + tab-size: 2; + white-space: pre; + overflow-wrap: normal; + overflow-x: auto; +} + +label { + display: block; + font-size: 12px; + color: var(--fg-muted); +} + +.table-wrap { + width: 100%; + overflow-x: auto; +} + +table { + width: 100%; + border-collapse: collapse; + font-size: 13px; +} + +th, +td { + text-align: left; + padding: 6px 8px; + border: 1px solid var(--border); + vertical-align: top; +} + +th { + background: var(--bg-elevated); + color: var(--fg-muted); +} + +.file-list { + list-style: none; + margin: 0; + padding: 0; +} + +.file-btn { + width: 100%; + justify-content: space-between; + text-align: left; + margin-bottom: 4px; +} + +.file-btn.active { + border-color: var(--accent); + color: var(--accent); +} + +.qr-box { + display: inline-block; + background: #ffffff; + padding: 8px; + border: 1px solid var(--border); +} + +.qr-box svg { + display: block; + width: 180px; + height: 180px; +} + +.auth-center { + max-width: 500px; + margin: 24px auto; +} + +.form-msg { + min-height: 18px; + margin: 0; + font-size: 12px; +} + +.code-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 6px; +} + +.code-chip { + padding: 6px 8px; + background: var(--bg); + border: 1px solid var(--border); + text-align: center; +} + +dialog { + max-width: 480px; + width: calc(100% - 24px); + padding: 16px; + background: var(--bg-panel); + color: var(--fg); + border: 1px solid var(--accent); +} + +dialog.dialog-wide { + max-width: 860px; +} + +dialog:modal { + overscroll-behavior: contain; +} + +dialog::backdrop { + background: rgba(0, 0, 0, 0.75); + overflow: hidden; + overscroll-behavior: contain; +} + +.diff-body { + max-height: 55dvh; + overflow: auto; + padding: 8px; + background: var(--bg); + border: 1px solid var(--border); + font-size: 12px; + margin: 8px 0; +} + +.diff-add { + color: var(--ok); +} + +.diff-del { + color: var(--err); +} + +@media (max-width: 767px) { + .grid-2, + .grid-3, + .config-layout { + grid-template-columns: 1fr; + } + + .btn, + .nav-link, + input, + select { + min-height: 44px; + } + + .app-shell { + padding-bottom: 62px; + } + + .primary-nav { + position: fixed; + left: 0; + right: 0; + bottom: 0; + z-index: 20; + flex-wrap: nowrap; + overflow-x: auto; + padding: 4px 6px; + border-top: 1px solid var(--border); + border-bottom: none; + } + + .nav-link { + flex: 0 0 auto; + padding: 6px 10px; + } +} diff --git a/src/client/css/themes.css b/src/client/css/themes.css new file mode 100644 index 0000000..9c34d62 --- /dev/null +++ b/src/client/css/themes.css @@ -0,0 +1,85 @@ +:root, +[data-theme="phosphor-green"] { + color-scheme: dark; + --bg: #080c09; + --bg-panel: #0d140f; + --bg-elevated: #121c15; + --fg: #c9f7d5; + --fg-muted: #6fa07c; + --border: #214029; + --accent: #33ff66; + --accent-fg: #041409; + --ok: #33ff66; + --warn: #f0b429; + --err: #ff4d4f; + accent-color: var(--accent); + scrollbar-color: var(--border) var(--bg); +} + +[data-theme="amber-term"] { + color-scheme: dark; + --bg: #0d0904; + --bg-panel: #161007; + --bg-elevated: #21180b; + --fg: #ffe3b3; + --fg-muted: #b5894b; + --border: #4d3616; + --accent: #ffb000; + --accent-fg: #1a1000; + --ok: #66d966; + --warn: #ffb000; + --err: #ff574d; + accent-color: var(--accent); + scrollbar-color: var(--border) var(--bg); +} + +[data-theme="nord-dark"] { + color-scheme: dark; + --bg: #1e222a; + --bg-panel: #252a34; + --bg-elevated: #2e3440; + --fg: #eceff4; + --fg-muted: #98a4b8; + --border: #434c5e; + --accent: #88c0d0; + --accent-fg: #141820; + --ok: #a3be8c; + --warn: #ebcb8b; + --err: #bf616a; + accent-color: var(--accent); + scrollbar-color: var(--border) var(--bg); +} + +[data-theme="gruvbox-dark"] { + color-scheme: dark; + --bg: #1d2021; + --bg-panel: #282828; + --bg-elevated: #32302f; + --fg: #ebdbb2; + --fg-muted: #a89984; + --border: #504945; + --accent: #fabd2f; + --accent-fg: #1d2021; + --ok: #b8bb26; + --warn: #fe8019; + --err: #fb4934; + accent-color: var(--accent); + scrollbar-color: var(--border) var(--bg); +} + +[data-theme="paper-light"] { + color-scheme: light; + --bg: #f6f4ee; + --bg-panel: #ffffff; + --bg-elevated: #ece9df; + --fg: #171717; + --fg-muted: #5a5952; + --border: #b8b3a6; + --accent: #0d5c3e; + --accent-fg: #ffffff; + --ok: #0d6b3c; + --warn: #a66000; + --err: #b31d28; + accent-color: var(--accent); + scrollbar-color: var(--border) var(--bg); +} diff --git a/src/client/icon.svg b/src/client/icon.svg new file mode 100644 index 0000000..36bb9d7 --- /dev/null +++ b/src/client/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/client/index.html b/src/client/index.html new file mode 100644 index 0000000..0e856c1 --- /dev/null +++ b/src/client/index.html @@ -0,0 +1,120 @@ + + + + + + + + GCoordinator — SSH Control Plane + + + + + + +
+ + + + + + +
+
+ + + +

Step-Up 2FA Verification

+

Enter a fresh 6-digit TOTP code to elevate this session for 5 minutes.

+
+ + +

+
+ + +
+
+
+ + + +

Engage Emergency Panic Lock?

+

+ This will immediately zeroize the in-memory vault master key, wipe decrypted secrets, + close all active WebSocket connections, and revoke every admin session. + You will have to sign in again and manually unlock the vault. +

+
+ + +
+
+ + + +

Confirm Action

+

+
+ + +
+
+ + + +
+

Revision Diff

+ +
+

+

+    
+ +
+
+ + + + diff --git a/src/client/manifest.json b/src/client/manifest.json new file mode 100644 index 0000000..a8e1519 --- /dev/null +++ b/src/client/manifest.json @@ -0,0 +1,17 @@ +{ + "name": "GCoordinator", + "short_name": "GCoord", + "description": "Self-hosted SSH control plane, monitoring hub, systems manager, and automation engine.", + "start_url": "/", + "display": "standalone", + "background_color": "#0b110d", + "theme_color": "#0b110d", + "icons": [ + { + "src": "/icon.svg", + "sizes": "any", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] +} diff --git a/src/client/ts/api.ts b/src/client/ts/api.ts new file mode 100644 index 0000000..1737dc3 --- /dev/null +++ b/src/client/ts/api.ts @@ -0,0 +1,113 @@ +export interface ApiError extends Error { + status: number; + code?: string; + issues?: Array<{ path: string; message: string }>; + retryAfterSec?: number; +} + +let inMemoryCsrf: string | null = null; +let safeModeActive = false; +let stepUpHandler: (() => Promise) | null = null; +let unauthorizedHandler: (() => void) | null = null; + +export function setCsrfToken(token: string | null): void { + inMemoryCsrf = token; +} + +export function setApiSafeMode(enabled: boolean): void { + safeModeActive = enabled; +} + +export function registerStepUpHandler(fn: () => Promise): void { + stepUpHandler = fn; +} + +export function registerUnauthorizedHandler(fn: () => void): void { + unauthorizedHandler = fn; +} + +function readCookie(name: string): string | null { + const prefix = `${name}=`; + for (const part of document.cookie.split(';')) { + const trimmed = part.trim(); + if (trimmed.startsWith(prefix)) { + return decodeURIComponent(trimmed.slice(prefix.length)); + } + } + return null; +} + +export async function apiFetch( + url: string, + options: { + method?: string; + body?: unknown; + allowStepUpRetry?: boolean; + } = {}, +): Promise { + const method = (options.method ?? 'GET').toUpperCase(); + const headers: Record = {}; + + if (options.body !== undefined) { + headers['Content-Type'] = 'application/json'; + } + + if (method !== 'GET' && method !== 'HEAD') { + const csrf = readCookie('gcoord_csrf') ?? inMemoryCsrf; + if (csrf) headers['X-CSRF-Token'] = csrf; + if (safeModeActive) headers['X-GCoord-Safe-Mode'] = '1'; + } + + const res = await fetch(url, { + method, + headers, + body: options.body !== undefined ? JSON.stringify(options.body) : undefined, + credentials: 'same-origin', + }); + + const text = await res.text(); + let data: Record = {}; + if (text) { + try { + data = JSON.parse(text) as Record; + } catch { + data = { message: text }; + } + } + + if (!res.ok) { + if ( + res.status === 403 && + data.error === 'STEP_UP_REQUIRED' && + options.allowStepUpRetry !== false && + stepUpHandler + ) { + const elevated = await stepUpHandler(); + if (elevated) { + return apiFetch(url, { ...options, allowStepUpRetry: false }); + } + } + + if (res.status === 401 && unauthorizedHandler && !url.startsWith('/api/auth/')) { + unauthorizedHandler(); + } + + const err = new Error( + typeof data.message === 'string' + ? data.message + : typeof data.error === 'string' + ? data.error + : `HTTP ${res.status}`, + ) as ApiError; + err.status = res.status; + err.code = typeof data.error === 'string' ? data.error : undefined; + err.issues = Array.isArray(data.issues) + ? (data.issues as Array<{ path: string; message: string }>) + : undefined; + err.retryAfterSec = + typeof data.retryAfterSec === 'number' ? data.retryAfterSec : undefined; + throw err; + } + + return data as T; +} diff --git a/src/client/ts/dialogs.ts b/src/client/ts/dialogs.ts new file mode 100644 index 0000000..52729ba --- /dev/null +++ b/src/client/ts/dialogs.ts @@ -0,0 +1,123 @@ +import { apiFetch } from './api.js'; +import { el, extractErrorMessage } from './state.js'; + +export interface DiffModalData { + revisionId: number; + filePath: string; + source: string; + createdAt: number; + lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; + onRollback: () => Promise; +} + +export function promptStepUp(onElevated: (elevatedUntil: number) => void): Promise { + const dialog = document.getElementById('dialog-stepup') as HTMLDialogElement; + const form = document.getElementById('dialog-stepup-form') as HTMLFormElement; + const input = document.getElementById('stepup-code-input') as HTMLInputElement; + const errEl = document.getElementById('stepup-error') as HTMLElement; + const cancelBtn = document.getElementById('stepup-cancel-btn') as HTMLButtonElement; + + return new Promise((resolve) => { + let settled = false; + input.value = ''; + errEl.textContent = ''; + + const finish = (ok: boolean) => { + if (settled) return; + settled = true; + form.removeEventListener('submit', onSubmit); + cancelBtn.removeEventListener('click', onCancel); + dialog.removeEventListener('close', onClose); + if (dialog.open) dialog.close(); + dialog.returnValue = ''; + resolve(ok); + }; + + const onCancel = () => finish(false); + const onClose = () => finish(false); + + const onSubmit = async (ev: Event) => { + ev.preventDefault(); + errEl.textContent = ''; + try { + const res = await apiFetch<{ elevatedUntil: number }>('/api/auth/step-up', { + method: 'POST', + body: { code: input.value.trim() }, + allowStepUpRetry: false, + }); + onElevated(res.elevatedUntil); + finish(true); + } catch (err) { + errEl.textContent = extractErrorMessage(err); + input.select(); + } + }; + + form.addEventListener('submit', onSubmit); + cancelBtn.addEventListener('click', onCancel); + dialog.addEventListener('close', onClose); + dialog.showModal(); + }); +} + +export function confirmDialog(dialogId: string, message?: string): Promise { + const dialog = document.getElementById(dialogId) as HTMLDialogElement; + if (message !== undefined && dialogId === 'dialog-confirm') { + const msgEl = document.getElementById('dialog-confirm-msg'); + if (msgEl) msgEl.textContent = message; + } + + return new Promise((resolve) => { + const onClose = () => { + const confirmed = dialog.returnValue === 'confirm'; + dialog.returnValue = ''; + dialog.removeEventListener('close', onClose); + resolve(confirmed); + }; + dialog.addEventListener('close', onClose); + dialog.showModal(); + }); +} + +export function openDiffModal(data: DiffModalData): void { + const dialog = document.getElementById('dialog-diff') as HTMLDialogElement; + const metaEl = document.getElementById('dialog-diff-meta') as HTMLElement; + const bodyEl = document.getElementById('dialog-diff-body') as HTMLElement; + const closeBtn = document.getElementById('dialog-diff-close') as HTMLButtonElement; + const rollbackBtn = document.getElementById('dialog-diff-rollback') as HTMLButtonElement; + + metaEl.textContent = `${data.filePath} — Revision #${data.revisionId} (${data.source})`; + bodyEl.replaceChildren(); + for (const line of data.lines) { + const prefix = line.type === 'add' ? '+ ' : line.type === 'del' ? '- ' : ' '; + const cls = + line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; + bodyEl.append(el('div', { class: cls }, `${prefix}${line.text}`)); + } + + const cleanup = () => { + closeBtn.removeEventListener('click', onClose); + rollbackBtn.removeEventListener('click', onRollbackClick); + dialog.removeEventListener('close', cleanup); + dialog.returnValue = ''; + }; + + const onClose = () => { + dialog.close(); + }; + + const onRollbackClick = async () => { + rollbackBtn.disabled = true; + try { + await data.onRollback(); + dialog.close(); + } finally { + rollbackBtn.disabled = false; + } + }; + + closeBtn.addEventListener('click', onClose); + rollbackBtn.addEventListener('click', onRollbackClick); + dialog.addEventListener('close', cleanup); + dialog.showModal(); +} diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts new file mode 100644 index 0000000..4ebf8ae --- /dev/null +++ b/src/client/ts/main.ts @@ -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([ + '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 { + state.overview = await apiFetch('/api/config/overview'); + updateTopBarUi(); +} + +async function renderCurrentView(): Promise { + 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 { + 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 { + 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 { + 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(); +}); diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts new file mode 100644 index 0000000..e62f896 --- /dev/null +++ b/src/client/ts/state.ts @@ -0,0 +1,97 @@ +import type { + ConfigError, + ConfigWarning, + VaultState, +} from '../../shared/ws-protocol.js'; + +export type RouteId = + | 'dashboard' + | 'systems' + | 'terminal' + | 'sftp' + | 'workflows' + | 'alerts' + | 'config' + | 'vault' + | 'settings'; + +export interface OverviewFileEntry { + filePath: string; + entityType: string; + id?: string; + hasError: boolean; + warningCount: number; +} + +export interface ConfigOverview { + files: OverviewFileEntry[]; + diagnostics: { warnings: ConfigWarning[]; errors: ConfigError[] }; + servers: Array>; + systems: Array>; + workflows: Array>; + snippets: { snippets?: Array> }; + alerts: { + channels?: Array>; + rules?: Array>; + maintenanceWindows?: Array>; + }; + settings: Record; +} + +export interface ClientState { + bootstrapped: boolean; + authenticated: boolean; + vaultState: VaultState; + isPanicLocked: boolean; + safeMode: boolean; + defaultMobileSafeMode: boolean; + elevatedUntil: number | null; + theme: string; + route: RouteId; + overview: ConfigOverview | null; +} + +export const SAFE_MODE_STORAGE_KEY = 'gcoord_device_safe_mode'; +export const THEME_STORAGE_KEY = 'gcoord_theme'; + +export function initialDeviceSafeMode(defaultMobileSafeMode: boolean): boolean { + const stored = localStorage.getItem(SAFE_MODE_STORAGE_KEY); + if (stored === '1') return true; + if (stored === '0') return false; + return defaultMobileSafeMode && window.innerWidth < 768; +} + +export function applyTheme(theme: string): void { + document.documentElement.setAttribute('data-theme', theme); + localStorage.setItem(THEME_STORAGE_KEY, theme); +} + +export function el( + tag: K, + attrs: Record = {}, + ...children: Array +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v === undefined || v === false) continue; + if (v === true) { + node.setAttribute(k, ''); + } else { + node.setAttribute(k, String(v)); + } + } + for (const child of children) { + node.append(typeof child === 'string' ? document.createTextNode(child) : child); + } + return node; +} + +export function fmtTime(ts: number | string | null | undefined): string { + if (!ts) return '—'; + const d = new Date(ts); + return Number.isNaN(d.getTime()) ? '—' : d.toISOString().replace('T', ' ').slice(0, 19); +} + +export function extractErrorMessage(err: unknown): string { + return err instanceof Error ? err.message : String(err); +} diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts new file mode 100644 index 0000000..bbcb196 --- /dev/null +++ b/src/client/ts/views/auth-view.ts @@ -0,0 +1,261 @@ +import { apiFetch, setCsrfToken } from '../api.js'; +import { el, extractErrorMessage } from '../state.js'; + +interface BootstrapData { + secretBase32: string; + otpauthUri: string; + qrSvg: string; +} + +export async function renderAuthView( + root: HTMLElement, + bootstrapped: boolean, + initialSafeMode: boolean, + onAuthenticated: () => Promise, +): Promise { + root.replaceChildren(); + const wrap = el('div', { class: 'auth-center panel' }); + + if (!bootstrapped) { + wrap.append( + el('h1', {}, 'GCoordinator — First-Run Admin Setup'), + el( + 'p', + { class: 'muted' }, + 'Create the single admin password and enroll TOTP 2FA. No third-party identity service is used.', + ), + ); + + const statusMsg = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); + const qrContainer = el('div', { class: 'qr-box' }); + const secretLine = el('div', { class: 'mono warn-text' }); + + const form = el('form', { class: 'stack' }); + const userInput = el('input', { + id: 'boot-username', + name: 'username', + type: 'text', + value: 'admin', + autocomplete: 'username', + spellcheck: 'false', + autocapitalize: 'none', + autocorrect: 'off', + required: true, + }); + const passInput = el('input', { + id: 'boot-password', + name: 'password', + type: 'password', + minlength: 10, + autocomplete: 'new-password', + enterkeyhint: 'next', + placeholder: 'Minimum 10 characters', + required: true, + }); + const showPassBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Show'); + showPassBtn.addEventListener('click', () => { + const showing = passInput.type === 'text'; + passInput.type = showing ? 'password' : 'text'; + showPassBtn.textContent = showing ? 'Show' : 'Hide'; + }); + + const codeInput = el('input', { + id: 'boot-totp', + name: 'totpCode', + type: 'text', + inputmode: 'numeric', + autocomplete: 'one-time-code', + enterkeyhint: 'done', + pattern: '[0-9]{6}', + maxlength: 6, + placeholder: '6-digit code from authenticator', + required: true, + }); + + let secretBase32 = ''; + try { + const data = await apiFetch('/api/auth/bootstrap'); + secretBase32 = data.secretBase32; + const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); + if (doc.documentElement.nodeName === 'svg') { + qrContainer.append(document.importNode(doc.documentElement, true)); + } + secretLine.textContent = `Secret: ${data.secretBase32}`; + } catch (err) { + statusMsg.textContent = extractErrorMessage(err); + } + + const submitBtn = el( + 'button', + { type: 'submit', class: 'btn btn-primary' }, + 'Create Admin & Enroll 2FA', + ); + + form.append( + el('label', { for: 'boot-username' }, 'Admin Username'), + userInput, + el('label', { for: 'boot-password' }, 'Master Login Password (>= 10 chars)'), + el('div', { class: 'row' }, el('div', { style: 'flex:1' }, passInput), showPassBtn), + el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), + el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), + codeInput, + statusMsg, + submitBtn, + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + statusMsg.textContent = ''; + submitBtn.disabled = true; + try { + const res = await apiFetch<{ + csrfToken: string; + recoveryCodes: string[]; + }>('/api/auth/bootstrap', { + method: 'POST', + body: { + username: userInput.value.trim(), + password: passInput.value, + totpCode: codeInput.value.trim(), + secretBase32, + initialSafeMode, + }, + }); + setCsrfToken(res.csrfToken); + + // One-time recovery codes step + wrap.replaceChildren( + el('h1', {}, 'Save Single-Use Recovery Codes'), + el( + 'p', + { class: 'warn-text' }, + 'Each recovery code works once if you lose your TOTP device. These will NOT be shown again.', + ), + el( + 'div', + { class: 'code-grid' }, + ...res.recoveryCodes.map((c) => el('div', { class: 'code-chip mono' }, c)), + ), + ); + + const copyBtn = el('button', { type: 'button', class: 'btn' }, 'Copy Codes'); + copyBtn.addEventListener('click', () => { + void navigator.clipboard?.writeText(res.recoveryCodes.join('\n')); + copyBtn.textContent = 'Copied!'; + }); + + const dlBtn = el('button', { type: 'button', class: 'btn' }, 'Download .txt'); + dlBtn.addEventListener('click', () => { + const blob = new Blob([`${res.recoveryCodes.join('\n')}\n`], { + type: 'text/plain', + }); + const a = document.createElement('a'); + a.href = URL.createObjectURL(blob); + a.download = 'gcoordinator-recovery-codes.txt'; + a.click(); + URL.revokeObjectURL(a.href); + }); + + const ackBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary' }, + 'I Saved My Codes — Enter GCoordinator', + ); + ackBtn.addEventListener('click', () => { + void onAuthenticated(); + }); + + wrap.append(el('div', { class: 'dialog-actions' }, copyBtn, dlBtn, ackBtn)); + } catch (err) { + statusMsg.textContent = extractErrorMessage(err); + submitBtn.disabled = false; + } + }); + + wrap.append(form); + root.append(wrap); + return; + } + + // Standard Sign-In Form + wrap.append( + el('h1', {}, 'GCoordinator — Admin Sign In'), + el('p', { class: 'muted' }, 'Authenticate with password and TOTP 2FA (or a recovery code).'), + ); + + const form = el('form', { class: 'stack' }); + const userInput = el('input', { + id: 'login-username', + name: 'username', + type: 'text', + value: 'admin', + autocomplete: 'username', + spellcheck: 'false', + autocapitalize: 'none', + autocorrect: 'off', + required: true, + }); + const passInput = el('input', { + id: 'login-password', + name: 'password', + type: 'password', + autocomplete: 'current-password', + enterkeyhint: 'next', + required: true, + }); + const showPassBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Show'); + showPassBtn.addEventListener('click', () => { + const showing = passInput.type === 'text'; + passInput.type = showing ? 'password' : 'text'; + showPassBtn.textContent = showing ? 'Show' : 'Hide'; + }); + + const codeInput = el('input', { + id: 'login-code', + name: 'code', + type: 'text', + autocomplete: 'one-time-code', + inputmode: 'numeric', + enterkeyhint: 'done', + placeholder: '6-digit TOTP or XXXXX-XXXXX recovery code', + required: true, + }); + const statusMsg = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); + const submitBtn = el('button', { type: 'submit', class: 'btn btn-primary' }, 'Sign In'); + + form.append( + el('label', { for: 'login-username' }, 'Username'), + userInput, + el('label', { for: 'login-password' }, 'Password'), + el('div', { class: 'row' }, el('div', { style: 'flex:1' }, passInput), showPassBtn), + el('label', { for: 'login-code' }, 'TOTP 2FA / Recovery Code'), + codeInput, + statusMsg, + submitBtn, + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + statusMsg.textContent = ''; + submitBtn.disabled = true; + try { + const res = await apiFetch<{ csrfToken: string }>('/api/auth/login', { + method: 'POST', + body: { + username: userInput.value.trim(), + password: passInput.value, + code: codeInput.value.trim(), + initialSafeMode, + }, + }); + setCsrfToken(res.csrfToken); + await onAuthenticated(); + } catch (err) { + statusMsg.textContent = extractErrorMessage(err); + submitBtn.disabled = false; + } + }); + + wrap.append(form); + root.append(wrap); +} diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts new file mode 100644 index 0000000..6df092d --- /dev/null +++ b/src/client/ts/views/config-view.ts @@ -0,0 +1,339 @@ +import { apiFetch, type ApiError } from '../api.js'; +import { confirmDialog, openDiffModal } from '../dialogs.js'; +import { el, extractErrorMessage, fmtTime, type ConfigOverview } from '../state.js'; + +interface FileDetails { + filePath: string; + entityType: string; + rawContent: string; + error: { filePath: string; message: string; issues?: Array<{ path: string; message: string }> } | null; + warnings: Array<{ filePath: string; code: string; message: string }>; + revisions: Array<{ + id: number; + sha256: string; + source: string; + summary: string | null; + createdAt: number; + }>; +} + +function buildTemplate(kind: 'server' | 'system' | 'workflow', id: string): string { + if (kind === 'server') { + return JSON.stringify( + { + id, + name: id, + host: '10.10.0.10', + port: 22, + username: 'ops', + credentialId: 'cred-ed25519-main', + tags: ['prod'], + osHint: 'auto', + pollIntervalSec: 10, + probes: [], + systems: [], + tunnels: [], + enabled: true, + }, + null, + 2, + ); + } + if (kind === 'system') { + return JSON.stringify( + { + id, + name: id, + cacheTtlSec: 45, + params: [], + discovery: { type: 'command', command: 'echo "default"', parser: 'lines' }, + status: { command: 'true', parser: 'exit-code', health: { healthyExitCodes: [0] } }, + actions: [], + editableFiles: [], + }, + null, + 2, + ); + } + return JSON.stringify( + { + id, + name: id, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log', pinToDashboard: false }, + steps: [ + { + id: 'step-1', + type: 'exec', + target: { all: true }, + dependsOn: [], + command: 'uname -a', + }, + ], + }, + null, + 2, + ); +} + +let selectedPath = 'settings.json'; + +export async function renderConfigView( + root: HTMLElement, + overview: ConfigOverview, + onReloadOverview: () => Promise, +): Promise { + root.replaceChildren(); + + if ( + overview.files.length > 0 && + !overview.files.some((f) => f.filePath === selectedPath) + ) { + selectedPath = overview.files[0]!.filePath; + } + + const layout = el('div', { class: 'config-layout' }); + const sidebar = el('aside', { class: 'panel' }); + sidebar.append(el('h1', {}, 'Config Files (/data/config)')); + + // Quick New Entity creator + const newKind = el( + 'select', + { 'aria-label': 'New config entity type' }, + el('option', { value: 'server' }, 'servers/.json'), + el('option', { value: 'system' }, 'systems/.json'), + el('option', { value: 'workflow' }, 'workflows/.json'), + ); + const newIdInput = el('input', { placeholder: 'new-entity-id' }); + const createBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm mutating-action' }, + '+ Create', + ); + const createErr = el('p', { class: 'form-msg err-text' }); + + createBtn.addEventListener('click', async () => { + createErr.textContent = ''; + const id = newIdInput.value.trim(); + if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(id)) { + createErr.textContent = 'Invalid slug ID.'; + return; + } + const kind = newKind.value as 'server' | 'system' | 'workflow'; + const folder = kind === 'server' ? 'servers' : kind === 'system' ? 'systems' : 'workflows'; + const targetPath = `${folder}/${id}.json`; + try { + await apiFetch('/api/config/file', { + method: 'PUT', + body: { path: targetPath, content: buildTemplate(kind, id), summary: 'Created via UI' }, + }); + selectedPath = targetPath; + await onReloadOverview(); + } catch (err) { + createErr.textContent = extractErrorMessage(err); + } + }); + + sidebar.append( + el('div', { class: 'stack' }, newKind, el('div', { class: 'row' }, el('div', { style: 'flex:1' }, newIdInput), createBtn), createErr), + ); + + const fileList = el('ul', { class: 'file-list' }); + for (const f of overview.files) { + const badges = el('span', { class: 'row' }); + if (f.hasError) badges.append(el('span', { class: 'badge badge-err' }, 'ERR')); + if (f.warningCount > 0) { + badges.append(el('span', { class: 'badge badge-warn' }, `WARN:${f.warningCount}`)); + } + + const btn = el( + 'button', + { + type: 'button', + class: `btn btn-sm file-btn${f.filePath === selectedPath ? ' active' : ''}`, + }, + el('span', { class: 'mono' }, f.filePath), + badges, + ); + btn.addEventListener('click', () => { + selectedPath = f.filePath; + void renderConfigView(root, overview, onReloadOverview); + }); + fileList.append(el('li', {}, btn)); + } + sidebar.append(fileList); + + // Main editor panel + const mainPanel = el('section', { class: 'panel' }); + let details: FileDetails; + try { + details = await apiFetch( + `/api/config/file?path=${encodeURIComponent(selectedPath)}`, + ); + } catch (err) { + mainPanel.append(el('p', { class: 'err-text' }, extractErrorMessage(err))); + layout.append(sidebar, mainPanel); + root.append(layout); + return; + } + + mainPanel.append( + el('div', { class: 'row-between' }, el('h1', {}, details.filePath), el('span', { class: 'badge' }, details.entityType)), + ); + + if (details.error) { + const errBox = el('div', { class: 'panel' }); + errBox.append(el('p', { class: 'err-text' }, `[ERR] ${details.error.message}`)); + for (const issue of details.error.issues ?? []) { + errBox.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`)); + } + mainPanel.append(errBox); + } + + if (details.warnings.length > 0) { + const warnBox = el('div', { class: 'panel' }); + for (const w of details.warnings) { + warnBox.append(el('div', { class: 'warn-text' }, `[WARN:${w.code}] ${w.message}`)); + } + mainPanel.append(warnBox); + } + + const editor = el('textarea', { + class: 'code-editor mono', + spellcheck: 'false', + 'aria-label': `JSON content for ${details.filePath}`, + }); + editor.value = details.rawContent; + editor.addEventListener('keydown', (ev) => { + if (ev.key === 'Tab') { + ev.preventDefault(); + const start = editor.selectionStart; + const end = editor.selectionEnd; + editor.value = `${editor.value.slice(0, start)} ${editor.value.slice(end)}`; + editor.selectionStart = editor.selectionEnd = start + 2; + } + }); + + const msgEl = el('div', { class: 'stack' }); + const fmtBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Format JSON'); + fmtBtn.addEventListener('click', () => { + msgEl.replaceChildren(); + try { + editor.value = `${JSON.stringify(JSON.parse(editor.value), null, 2)}\n`; + } catch (err) { + msgEl.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + + const saveBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary mutating-action' }, + 'Save Config', + ); + saveBtn.addEventListener('click', async () => { + msgEl.replaceChildren(); + try { + await apiFetch('/api/config/file', { + method: 'PUT', + body: { path: details.filePath, content: editor.value }, + }); + await onReloadOverview(); + } catch (err) { + const apiErr = err as ApiError; + msgEl.append(el('p', { class: 'err-text' }, apiErr.message)); + for (const issue of apiErr.issues ?? []) { + msgEl.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`)); + } + } + }); + + const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn); + if (details.filePath.includes('/')) { + const delBtn = el( + 'button', + { type: 'button', class: 'btn btn-danger mutating-action' }, + 'Delete File', + ); + delBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Delete "${details.filePath}" from disk?`); + if (!ok) return; + try { + await apiFetch(`/api/config/file?path=${encodeURIComponent(details.filePath)}`, { + method: 'DELETE', + }); + selectedPath = 'settings.json'; + await onReloadOverview(); + } catch (err) { + msgEl.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + actionRow.append(delBtn); + } + + mainPanel.append(editor, actionRow, msgEl); + + // Revisions table + const revSection = el('div', { class: 'panel panel-region' }); + revSection.append(el('h2', {}, 'Revision History')); + const revTable = el('table'); + revTable.append( + el( + 'thead', + {}, + el('tr', {}, el('th', {}, '#'), el('th', {}, 'Time'), el('th', {}, 'Source'), el('th', {}, 'Actions')), + ), + ); + const revBody = el('tbody'); + for (const rev of details.revisions) { + const diffBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Diff'); + diffBtn.addEventListener('click', async () => { + const res = await apiFetch<{ + revision: { id: number; filePath: string; source: string; createdAt: number }; + diff: { lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }> }; + }>(`/api/config/revisions/${rev.id}/diff`); + openDiffModal({ + revisionId: res.revision.id, + filePath: res.revision.filePath, + source: res.revision.source, + createdAt: res.revision.createdAt, + lines: res.diff.lines, + onRollback: async () => { + await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); + await onReloadOverview(); + }, + }); + }); + + const rbBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Rollback', + ); + rbBtn.addEventListener('click', async () => { + try { + await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); + await onReloadOverview(); + } catch (err) { + msgEl.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + + revBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, `#${rev.id}`), + el('td', { class: 'mono' }, fmtTime(rev.createdAt)), + el('td', {}, `${rev.source}${rev.summary ? ` — ${rev.summary}` : ''}`), + el('td', {}, el('div', { class: 'row' }, diffBtn, rbBtn)), + ), + ); + } + revTable.append(revBody); + revSection.append(el('div', { class: 'table-wrap' }, revTable)); + mainPanel.append(revSection); + + layout.append(sidebar, mainPanel); + root.append(layout); +} diff --git a/src/client/ts/views/section-shells.ts b/src/client/ts/views/section-shells.ts new file mode 100644 index 0000000..3a5284c --- /dev/null +++ b/src/client/ts/views/section-shells.ts @@ -0,0 +1,122 @@ +import { el, type ConfigOverview, type RouteId } from '../state.js'; + +export function renderSectionShell( + root: HTMLElement, + route: Exclude, + overview: ConfigOverview, +): void { + root.replaceChildren(); + + if (route === 'dashboard') { + const summary = el('div', { class: 'grid-3' }); + summary.append( + el('div', { class: 'panel' }, el('h2', {}, 'Servers'), el('div', { class: 'mono' }, `${overview.servers.length} configured`), el('a', { href: '#config', class: 'btn btn-sm' }, 'Manage Servers')), + el('div', { class: 'panel' }, el('h2', {}, 'Custom Systems'), el('div', { class: 'mono' }, `${overview.systems.length} presets/definitions`), el('a', { href: '#systems', class: 'btn btn-sm' }, 'View Systems')), + el('div', { class: 'panel' }, el('h2', {}, 'Workflows & Alerts'), el('div', { class: 'mono' }, `${overview.workflows.length} DAGs, ${(overview.alerts.rules ?? []).length} rules`), el('a', { href: '#workflows', class: 'btn btn-sm' }, 'View Workflows')), + ); + root.append(summary); + + const srvPanel = el('section', { class: 'panel panel-region' }); + srvPanel.append(el('h1', {}, 'Fleet Inventory (Phase 2 Live SSH Telemetry Ready)')); + if (overview.servers.length === 0) { + srvPanel.append( + el('p', { class: 'muted' }, 'No server JSON configs yet. Add one in Config -> servers/.json.'), + ); + } else { + const grid = el('div', { class: 'grid-2' }); + for (const s of overview.servers) { + grid.append( + el( + 'div', + { class: 'panel' }, + el('div', { class: 'row-between' }, el('strong', {}, String(s.name ?? s.id)), el('span', { class: 'badge' }, s.enabled === false ? 'DISABLED' : 'CONFIGURED')), + el('div', { class: 'mono muted' }, `${String(s.username)}@${String(s.host)}:${String(s.port ?? 22)}`), + el('div', { class: 'muted' }, `Cred: ${String(s.credentialId)} | Poll: ${String(s.pollIntervalSec ?? 10)}s`), + ), + ); + } + srvPanel.append(grid); + } + root.append(srvPanel); + return; + } + + if (route === 'systems') { + const panel = el('section', { class: 'panel' }); + panel.append( + el('h1', {}, 'Custom Systems Definitions (/data/config/systems/*.json)'), + el('p', { class: 'muted' }, 'Live SSH discovery, multi-file activeFiles[] overlays, and interactive debug shells activate in Phase 3.'), + ); + const grid = el('div', { class: 'grid-3' }); + for (const sys of overview.systems) { + const actions = Array.isArray(sys.actions) ? sys.actions : []; + grid.append( + el( + 'div', + { class: 'panel panel-region' }, + el('h2', {}, String(sys.name ?? sys.id)), + el('p', { class: 'muted' }, String(sys.description ?? '')), + el('div', { class: 'mono' }, `ID: ${String(sys.id)} | TTL: ${String(sys.cacheTtlSec ?? 45)}s`), + el('div', { class: 'muted' }, `Actions (${actions.length}): ${actions.map((a) => String((a as Record).id)).join(', ')}`), + ), + ); + } + panel.append(grid); + root.append(panel); + return; + } + + if (route === 'workflows') { + const panel = el('section', { class: 'panel' }); + panel.append( + el('h1', {}, 'DAG Workflows & Command Snippets'), + el('p', { class: 'muted' }, 'Full-DAG execution, croner triggers, and Ad-Hoc Fleet Broadcast activate in Phase 4.'), + ); + if (overview.workflows.length === 0) { + panel.append(el('p', { class: 'muted' }, 'No workflows configured yet. Create one in Config -> workflows/.json.')); + } else { + for (const wf of overview.workflows) { + const steps = Array.isArray(wf.steps) ? wf.steps : []; + panel.append( + el( + 'div', + { class: 'panel' }, + el('strong', {}, `${String(wf.name ?? wf.id)} (${String(wf.id)})`), + el('div', { class: 'mono muted' }, `Steps: ${steps.length} | Overlap: ${String(wf.overlapPolicy ?? 'skip')}`), + ), + ); + } + } + const snips = overview.snippets.snippets ?? []; + panel.append(el('h2', {}, `Saved Snippets (${snips.length})`)); + for (const sn of snips) { + panel.append(el('div', { class: 'mono' }, `• ${String(sn.id)}: ${String(sn.command)}`)); + } + root.append(panel); + return; + } + + if (route === 'alerts') { + const panel = el('section', { class: 'panel' }); + const rules = overview.alerts.rules ?? []; + const channels = overview.alerts.channels ?? []; + const windows = overview.alerts.maintenanceWindows ?? []; + panel.append( + el('h1', {}, 'Alerting, Channels & Maintenance Windows'), + el('p', { class: 'muted' }, `Configured in alerts.json: ${rules.length} rules, ${channels.length} channels, ${windows.length} maintenance windows. AlertEngine evaluates live samples starting Phase 4.`), + ); + root.append(panel); + return; + } + + const label = route === 'terminal' ? 'Persistent PTY Terminal (xterm.js)' : 'SFTP File Manager & Tunnel Proxy'; + root.append( + el( + 'section', + { class: 'panel' }, + el('h1', {}, label), + el('p', { class: 'muted' }, 'Interactive SSH client, lazy-loaded xterm.js, and SFTP manager activate in Phase 3 after SSHPool in Phase 2.'), + el('a', { href: '#config', class: 'btn btn-sm' }, 'Configure Servers'), + ), + ); +} diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts new file mode 100644 index 0000000..be7d7a0 --- /dev/null +++ b/src/client/ts/views/settings-view.ts @@ -0,0 +1,240 @@ +import { apiFetch } from '../api.js'; +import { confirmDialog, promptStepUp } from '../dialogs.js'; +import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; + +interface SessionRow { + idPrefix: string; + ip: string; + userAgent: string; + safeMode: boolean; + elevatedUntil: number | null; + lastSeenAt: number; + current: boolean; +} + +interface AuditRow { + id: number; + ts: number; + action: string; + actor_ip: string; + target: string | null; + status: string; + details: string | null; +} + +export async function renderSettingsView( + root: HTMLElement, + state: ClientState, + onThemeChange: (theme: string) => void, + onReloadState: () => Promise, +): Promise { + root.replaceChildren(); + + const [sessRes, auditRes] = await Promise.all([ + apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), + apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'), + ]); + + // Preferences & Step-Up Elevation panel + const topGrid = el('div', { class: 'grid-2' }); + + const prefPanel = el('section', { class: 'panel' }); + prefPanel.append(el('h1', {}, 'Appearance & Mobile Safety')); + const themeSelect = el( + 'select', + {}, + ...['phosphor-green', 'amber-term', 'nord-dark', 'gruvbox-dark', 'paper-light'].map( + (t) => + el( + 'option', + { value: t, selected: state.theme === t ? true : undefined }, + t, + ), + ), + ); + themeSelect.addEventListener('change', () => onThemeChange(themeSelect.value)); + + const persistThemeBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm mutating-action' }, + 'Save Theme as Default (settings.json)', + ); + const prefMsg = el('p', { class: 'form-msg' }); + persistThemeBtn.addEventListener('click', async () => { + prefMsg.textContent = ''; + try { + const nextSettings = { + ...(state.overview?.settings ?? {}), + theme: themeSelect.value, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `Default theme -> ${themeSelect.value}`, + }, + }); + prefMsg.className = 'form-msg ok-text'; + prefMsg.textContent = 'Saved default theme in settings.json.'; + } catch (err) { + prefMsg.className = 'form-msg err-text'; + prefMsg.textContent = extractErrorMessage(err); + } + }); + prefPanel.append( + el('label', {}, 'Active UI Theme'), + themeSelect, + el('div', { class: 'row' }, persistThemeBtn), + prefMsg, + ); + + const mfaPanel = el('section', { class: 'panel' }); + mfaPanel.append(el('h1', {}, 'Step-Up 2FA Elevation')); + const isElevated = state.elevatedUntil !== null && state.elevatedUntil > Date.now(); + mfaPanel.append( + el( + 'p', + { class: isElevated ? 'ok-text' : 'muted' }, + isElevated + ? `Elevated until ${fmtTime(state.elevatedUntil)}` + : 'Not currently elevated. Sensitive vault actions require a 5-minute step-up TOTP check.', + ), + ); + const stepBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm mutating-action' }, + 'Elevate Session (5 min)', + ); + stepBtn.addEventListener('click', async () => { + const ok = await promptStepUp((until) => { + state.elevatedUntil = until; + }); + if (ok) await onReloadState(); + }); + const dropBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Drop Elevation'); + dropBtn.addEventListener('click', async () => { + await apiFetch('/api/auth/drop-elevation', { method: 'POST' }); + state.elevatedUntil = null; + await onReloadState(); + }); + mfaPanel.append(el('div', { class: 'row' }, stepBtn, dropBtn)); + topGrid.append(prefPanel, mfaPanel); + root.append(topGrid); + + // Active Sessions + const sessPanel = el('section', { class: 'panel panel-region' }); + const revokeOthersBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Revoke Other Sessions', + ); + revokeOthersBtn.addEventListener('click', async () => { + await apiFetch('/api/auth/sessions/revoke-all', { + method: 'POST', + body: { keepCurrent: true }, + }); + await onReloadState(); + }); + const revokeAllBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Revoke ALL Sessions', + ); + revokeAllBtn.addEventListener('click', async () => { + const ok = await confirmDialog( + 'dialog-confirm', + 'Revoke ALL active sessions including this browser?', + ); + if (!ok) return; + await apiFetch('/api/auth/sessions/revoke-all', { + method: 'POST', + body: { keepCurrent: false }, + }); + await onReloadState(); + }); + + sessPanel.append( + el( + 'div', + { class: 'row-between' }, + el('h2', {}, 'Active Admin Sessions'), + el('div', { class: 'row' }, revokeOthersBtn, revokeAllBtn), + ), + ); + + const sTable = el('table'); + sTable.append( + el( + 'thead', + {}, + el('tr', {}, el('th', {}, 'Session'), el('th', {}, 'IP'), el('th', {}, 'Last Seen'), el('th', {}, 'Flags'), el('th', {}, 'Action')), + ), + ); + const sBody = el('tbody'); + for (const s of sessRes.sessions) { + const revBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Revoke', + ); + revBtn.addEventListener('click', async () => { + await apiFetch(`/api/auth/sessions/${encodeURIComponent(s.idPrefix)}`, { + method: 'DELETE', + }); + await onReloadState(); + }); + sBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, `${s.idPrefix}${s.current ? ' [CURRENT]' : ''}`), + el('td', { class: 'mono' }, s.ip), + el('td', { class: 'mono' }, fmtTime(s.lastSeenAt)), + el('td', {}, `${s.safeMode ? '[SAFE] ' : ''}${s.userAgent.slice(0, 48)}`), + el('td', {}, revBtn), + ), + ); + } + sTable.append(sBody); + sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); + root.append(sessPanel); + + // Audit Log + const auditPanel = el('section', { class: 'panel panel-region' }); + auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`)); + const aTable = el('table'); + aTable.append( + el( + 'thead', + {}, + el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details')), + ), + ); + const aBody = el('tbody'); + for (const row of auditRes.items) { + aBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, fmtTime(row.ts)), + el('td', { class: 'mono' }, row.action), + el( + 'td', + {}, + el( + 'span', + { class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` }, + row.status, + ), + ), + el('td', { class: 'mono' }, row.target ?? '—'), + el('td', { class: 'mono' }, row.actor_ip), + el('td', { class: 'mono muted' }, row.details ?? '—'), + ), + ); + } + aTable.append(aBody); + auditPanel.append(el('div', { class: 'table-wrap' }, aTable)); + root.append(auditPanel); +} diff --git a/src/client/ts/views/vault-view.ts b/src/client/ts/views/vault-view.ts new file mode 100644 index 0000000..81b57b7 --- /dev/null +++ b/src/client/ts/views/vault-view.ts @@ -0,0 +1,429 @@ +import { apiFetch } from '../api.js'; +import { confirmDialog } from '../dialogs.js'; +import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; + +interface VaultCredMeta { + id: string; + name: string; + type: string; + fingerprint?: string; + publicKey?: string; + hasPassphrase?: boolean; + updatedAt: string; +} + +export async function renderVaultView( + root: HTMLElement, + state: ClientState, + onStateChanged: () => Promise, + onPanicLock: () => Promise, +): Promise { + root.replaceChildren(); + const vaultData = await apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + credentials: VaultCredMeta[]; + }>('/api/vault/credentials'); + state.vaultState = vaultData.state; + + const statusPanel = el('section', { class: 'panel' }); + statusPanel.append( + el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()}]`), + ); + + if (vaultData.state === 'uninitialized') { + const msg = el('p', { class: 'form-msg' }); + const keyInput = el('input', { + id: 'vault-init-key', + type: 'password', + placeholder: 'Optional 64-hex or base64 master key (leave blank to auto-generate)', + }); + const initBtn = el( + 'button', + { type: 'submit', class: 'btn btn-primary mutating-action' }, + 'Initialize vault.enc', + ); + const form = el( + 'form', + { class: 'stack' }, + el('label', { for: 'vault-init-key' }, '32-Byte Master Key (Optional)'), + keyInput, + msg, + el('div', { class: 'row' }, initBtn), + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + msg.textContent = ''; + try { + const res = await apiFetch<{ state: string; generatedKeyHex?: string }>( + '/api/vault/init', + { + method: 'POST', + body: keyInput.value.trim() ? { masterKey: keyInput.value.trim() } : {}, + }, + ); + if (res.generatedKeyHex) { + const box = el( + 'div', + { class: 'panel' }, + el('h2', {}, 'Store Generated Master Key Safely'), + el( + 'p', + { class: 'warn-text' }, + 'Copy this 64-hex key to your password manager or Docker secret. Without it, vault.enc cannot be unlocked after a restart or Panic Lock.', + ), + el('pre', { class: 'mono' }, res.generatedKeyHex), + ); + const contBtn = el('button', { type: 'button', class: 'btn btn-primary' }, 'Continue'); + contBtn.addEventListener('click', () => { + void onStateChanged(); + }); + box.append(contBtn); + statusPanel.replaceChildren(box); + return; + } + await onStateChanged(); + } catch (err) { + msg.className = 'form-msg err-text'; + msg.textContent = extractErrorMessage(err); + } + }); + + statusPanel.append(form); + root.append(statusPanel); + return; + } + + if (vaultData.state === 'locked') { + if (state.isPanicLocked) { + statusPanel.append( + el( + 'p', + { class: 'err-text' }, + 'Emergency Panic Lock was engaged. Enter the 32-byte master key manually to unlock.', + ), + ); + } + const keyInput = el('input', { + id: 'vault-unlock-key', + type: 'password', + autocomplete: 'off', + placeholder: 'Paste 64-hex or base64 master key', + required: true, + }); + const msg = el('p', { class: 'form-msg err-text' }); + const form = el( + 'form', + { class: 'stack' }, + el('label', { for: 'vault-unlock-key' }, 'Master Key'), + keyInput, + msg, + el('div', { class: 'row' }, el('button', { type: 'submit', class: 'btn btn-primary' }, 'Unlock Vault')), + ); + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + msg.textContent = ''; + try { + await apiFetch('/api/vault/unlock', { + method: 'POST', + body: { masterKey: keyInput.value.trim() }, + }); + await onStateChanged(); + } catch (err) { + msg.textContent = extractErrorMessage(err); + } + }); + statusPanel.append(form); + root.append(statusPanel); + return; + } + + // Unlocked view + const revealBox = el('div', { class: 'panel', hidden: true }); + const credTableWrap = el('div', { class: 'table-wrap' }); + const table = el('table'); + table.append( + el( + 'thead', + {}, + el( + 'tr', + {}, + el('th', {}, 'ID'), + el('th', {}, 'Name'), + el('th', {}, 'Type'), + el('th', {}, 'Fingerprint / Updated'), + el('th', {}, 'Actions'), + ), + ), + ); + const tbody = el('tbody'); + + if (vaultData.credentials.length === 0) { + tbody.append( + el('tr', {}, el('td', { colspan: 5, class: 'muted' }, 'No credentials stored in vault yet.')), + ); + } else { + for (const c of vaultData.credentials) { + const revealBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Reveal'); + revealBtn.addEventListener('click', async () => { + try { + const res = await apiFetch<{ credential: Record }>( + `/api/vault/credentials/${encodeURIComponent(c.id)}/reveal`, + ); + revealBox.hidden = false; + revealBox.replaceChildren( + el('div', { class: 'row-between' }, el('strong', {}, `Secret: ${c.id}`)), + el('pre', { class: 'diff-body mono' }, JSON.stringify(res.credential, null, 2)), + ); + const hideBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Hide Secret'); + hideBtn.addEventListener('click', () => { + revealBox.hidden = true; + revealBox.replaceChildren(); + }); + revealBox.append(hideBtn); + } catch (err) { + revealBox.hidden = false; + revealBox.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + + const delBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Delete', + ); + delBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Delete vault credential "${c.id}"?`); + if (!ok) return; + try { + await apiFetch(`/api/vault/credentials/${encodeURIComponent(c.id)}`, { + method: 'DELETE', + }); + await onStateChanged(); + } catch (err) { + revealBox.hidden = false; + revealBox.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + + const actionRow = el('div', { class: 'row' }, revealBtn, delBtn); + if (c.publicKey) { + const copyPubBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Copy PubKey'); + copyPubBtn.addEventListener('click', () => { + void navigator.clipboard?.writeText(c.publicKey!); + copyPubBtn.textContent = 'Copied'; + }); + actionRow.prepend(copyPubBtn); + } + + tbody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, c.id), + el('td', {}, c.name), + el('td', {}, el('span', { class: 'badge' }, c.type)), + el( + 'td', + { class: 'mono muted' }, + `${c.fingerprint ?? '—'}\n${fmtTime(c.updatedAt)}`, + ), + el('td', {}, actionRow), + ), + ); + } + } + table.append(tbody); + credTableWrap.append(table); + statusPanel.append(credTableWrap, revealBox); + root.append(statusPanel); + + // Two-column tools: Generate Ed25519 + Add Secret + const toolsGrid = el('div', { class: 'grid-2' }); + + // 1. Generate Ed25519 + const edPanel = el('section', { class: 'panel panel-region' }); + edPanel.append(el('h2', {}, 'Generate Ed25519 SSH Keypair')); + const edId = el('input', { placeholder: 'cred-ed25519-prod', required: true }); + const edName = el('input', { placeholder: 'Production Key', required: true }); + const edComment = el('input', { placeholder: 'ops@gcoordinator (optional)' }); + const edPass = el('input', { type: 'password', placeholder: 'Optional key passphrase' }); + const edMsg = el('p', { class: 'form-msg' }); + const edForm = el( + 'form', + { class: 'stack' }, + el('label', {}, 'Credential ID'), + edId, + el('label', {}, 'Display Name'), + edName, + el('label', {}, 'SSH Public Key Comment'), + edComment, + el('label', {}, 'Key Passphrase (Optional)'), + edPass, + edMsg, + el( + 'button', + { type: 'submit', class: 'btn btn-primary mutating-action' }, + 'Generate & Store Keypair', + ), + ); + edForm.addEventListener('submit', async (ev) => { + ev.preventDefault(); + edMsg.textContent = ''; + try { + await apiFetch('/api/vault/generate-ed25519', { + method: 'POST', + body: { + id: edId.value.trim(), + name: edName.value.trim(), + comment: edComment.value.trim() || undefined, + passphrase: edPass.value || undefined, + }, + }); + await onStateChanged(); + } catch (err) { + edMsg.className = 'form-msg err-text'; + edMsg.textContent = extractErrorMessage(err); + } + }); + edPanel.append(edForm); + + // 2. Manual Credential Upsert + const addPanel = el('section', { class: 'panel panel-region' }); + addPanel.append(el('h2', {}, 'Add / Update Vault Secret')); + const addId = el('input', { placeholder: 'sudo-prod-ops', required: true }); + const addName = el('input', { placeholder: 'Prod Sudo Password', required: true }); + const addType = el( + 'select', + {}, + el('option', { value: 'sudo-password' }, 'sudo-password'), + el('option', { value: 'ssh-password' }, 'ssh-password'), + el('option', { value: 'ssh-key' }, 'ssh-key'), + el('option', { value: 'webhook-secret' }, 'webhook-secret'), + el('option', { value: 'api-token' }, 'api-token'), + ); + const addSecret = el('textarea', { + rows: 4, + placeholder: 'Password, webhook URL/token, or OpenSSH private key', + required: true, + }); + const addMsg = el('p', { class: 'form-msg' }); + const addForm = el( + 'form', + { class: 'stack' }, + el('label', {}, 'Credential ID'), + addId, + el('label', {}, 'Name'), + addName, + el('label', {}, 'Type'), + addType, + el('label', {}, 'Secret Value / Private Key'), + addSecret, + addMsg, + el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Save to Vault'), + ); + addForm.addEventListener('submit', async (ev) => { + ev.preventDefault(); + addMsg.textContent = ''; + const t = addType.value; + const val = addSecret.value; + const payload: Record = { + id: addId.value.trim(), + name: addName.value.trim(), + type: t, + }; + if (t === 'ssh-key') payload.privateKey = val; + else if (t === 'webhook-secret') payload.secret = val; + else if (t === 'api-token') payload.token = val; + else payload.password = val; + + try { + await apiFetch('/api/vault/credentials', { method: 'POST', body: payload }); + await onStateChanged(); + } catch (err) { + addMsg.className = 'form-msg err-text'; + addMsg.textContent = extractErrorMessage(err); + } + }); + addPanel.append(addForm); + toolsGrid.append(edPanel, addPanel); + root.append(toolsGrid); + + // Master-Key Rotation & Panic Lock Panel + const dangerPanel = el('section', { class: 'panel panel-region' }); + dangerPanel.append(el('h2', {}, 'Master-Key Rotation & Emergency Panic Lock')); + const rotBox = el('div', { class: 'stack' }); + const prepBtn = el( + 'button', + { type: 'button', class: 'btn mutating-action' }, + 'Prepare Master-Key Rotation', + ); + const panicBtn = el( + 'button', + { type: 'button', class: 'btn btn-danger' }, + 'Engage Emergency Panic Lock', + ); + panicBtn.addEventListener('click', () => { + void onPanicLock(); + }); + + prepBtn.addEventListener('click', async () => { + rotBox.replaceChildren(); + try { + const prep = await apiFetch<{ + candidateKeyHex: string; + confirmToken: string; + }>('/api/vault/rotate-key/prepare', { method: 'POST' }); + + const confirmInput = el('input', { + placeholder: 'Paste the new 64-hex key above to confirm you saved it', + required: true, + }); + const copyKeyBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Copy New Key'); + copyKeyBtn.addEventListener('click', () => { + void navigator.clipboard?.writeText(prep.candidateKeyHex); + copyKeyBtn.textContent = 'Copied!'; + }); + const commitBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary mutating-action' }, + 'Re-Encrypt vault.enc Atomically', + ); + const rotMsg = el('p', { class: 'form-msg' }); + + commitBtn.addEventListener('click', async () => { + rotMsg.textContent = ''; + try { + await apiFetch('/api/vault/rotate-key/commit', { + method: 'POST', + body: { + confirmToken: prep.confirmToken, + confirmedKeyHex: confirmInput.value.trim(), + }, + }); + rotMsg.className = 'form-msg ok-text'; + rotMsg.textContent = + 'vault.enc re-encrypted cleanly. Update GCOORD_MASTER_KEY / Docker secret before next restart.'; + } catch (err) { + rotMsg.className = 'form-msg err-text'; + rotMsg.textContent = extractErrorMessage(err); + } + }); + + rotBox.append( + el('p', { class: 'warn-text' }, 'New Candidate 32-Byte Master Key (Hex):'), + el('pre', { class: 'mono' }, prep.candidateKeyHex), + copyKeyBtn, + confirmInput, + commitBtn, + rotMsg, + ); + } catch (err) { + rotBox.append(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }); + + dangerPanel.append(el('div', { class: 'row' }, prepBtn, panicBtn), rotBox); + root.append(dangerPanel); +} diff --git a/src/client/ts/ws-client.ts b/src/client/ts/ws-client.ts new file mode 100644 index 0000000..c0b45cd --- /dev/null +++ b/src/client/ts/ws-client.ts @@ -0,0 +1,113 @@ +import type { ClientWsFrame, ServerWsFrame } from '../../shared/ws-protocol.js'; + +export type WsConnectionStatus = 'online' | 'reconnecting' | 'offline'; + +export class MultiplexWsClient { + private ws: WebSocket | null = null; + private reconnectAttempt = 0; + private reconnectTimer: number | null = null; + private pingTimer: number | null = null; + private shouldRun = false; + private channels = new Set(['config', 'alerts']); + private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>(); + private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>(); + + onFrame(listener: (frame: ServerWsFrame) => void): () => void { + this.frameListeners.add(listener); + return () => this.frameListeners.delete(listener); + } + + onStatus(listener: (status: WsConnectionStatus) => void): () => void { + this.statusListeners.add(listener); + return () => this.statusListeners.delete(listener); + } + + connect(): void { + this.shouldRun = true; + this.openSocket(); + } + + disconnect(): void { + this.shouldRun = false; + if (this.reconnectTimer !== null) { + window.clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + if (this.pingTimer !== null) { + window.clearInterval(this.pingTimer); + this.pingTimer = null; + } + if (this.ws) { + this.ws.close(1000, 'Client disconnect'); + this.ws = null; + } + this.emitStatus('offline'); + } + + send(frame: ClientWsFrame): void { + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify(frame)); + } + } + + subscribe(channels: string[]): void { + for (const ch of channels) this.channels.add(ch); + this.send({ type: 'sub', channels }); + } + + private openSocket(): void { + if (!this.shouldRun) return; + if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) { + return; + } + + const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const socket = new WebSocket(`${proto}//${window.location.host}/ws`); + this.ws = socket; + + socket.addEventListener('open', () => { + this.reconnectAttempt = 0; + this.emitStatus('online'); + if (this.channels.size > 0) { + this.send({ type: 'sub', channels: [...this.channels] }); + } + if (this.pingTimer !== null) window.clearInterval(this.pingTimer); + this.pingTimer = window.setInterval(() => { + this.send({ type: 'ping', ts: Date.now() }); + }, 20_000); + }); + + socket.addEventListener('message', (ev) => { + try { + const frame = JSON.parse(String(ev.data)) as ServerWsFrame; + for (const listener of this.frameListeners) { + listener(frame); + } + } catch { + // Ignore malformed server frame + } + }); + + socket.addEventListener('close', (ev) => { + if (this.pingTimer !== null) { + window.clearInterval(this.pingTimer); + this.pingTimer = null; + } + this.ws = null; + if (!this.shouldRun || ev.code === 4001) { + this.emitStatus('offline'); + return; + } + this.emitStatus('reconnecting'); + const delay = Math.min(10_000, 500 * 2 ** this.reconnectAttempt); + this.reconnectAttempt = Math.min(this.reconnectAttempt + 1, 6); + this.reconnectTimer = window.setTimeout(() => this.openSocket(), delay); + }); + } + + private emitStatus(status: WsConnectionStatus): void { + for (const listener of this.statusListeners) { + listener(status); + } + } +}