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

View file

@ -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<void>,
): Promise<void> {
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<BootstrapData>('/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);
}

View file

@ -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<void>,
): Promise<void> {
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/<id>.json'),
el('option', { value: 'system' }, 'systems/<id>.json'),
el('option', { value: 'workflow' }, 'workflows/<id>.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<FileDetails>(
`/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);
}

View file

@ -0,0 +1,122 @@
import { el, type ConfigOverview, type RouteId } from '../state.js';
export function renderSectionShell(
root: HTMLElement,
route: Exclude<RouteId, 'config' | 'vault' | 'settings'>,
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/<id>.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<string, unknown>).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/<id>.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'),
),
);
}

View file

@ -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<void>,
): Promise<void> {
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);
}

View file

@ -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<void>,
onPanicLock: () => Promise<void>,
): Promise<void> {
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<string, unknown> }>(
`/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<string, unknown> = {
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);
}