diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index 48c2183..b8455d4 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -79,6 +79,10 @@ export interface ClientSecuritySettings { elevateOnLogin: boolean; keepElevationOnSafeMode: boolean; enableEmergencySecretsBackup: boolean; + allowSameOriginProxy?: boolean; + egressAllowedCidrs?: string[]; + sessionTtlHours?: number; + sessionIdleTimeoutMin?: number; } export interface ClientAuthRequirements { diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts index 9014748..240bca9 100644 --- a/src/client/ts/views/alerts-view.ts +++ b/src/client/ts/views/alerts-view.ts @@ -23,7 +23,7 @@ interface AlertChannelItem { interface AlertRuleItem { id: string; name: string; - kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system'; + kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event'; severity: 'warn' | 'critical'; target: { serverId?: string; tags?: string[]; all?: boolean }; forConsecutivePolls: number; @@ -40,6 +40,7 @@ interface AlertRuleItem { probeId?: string; systemId?: string; item?: string; + events?: string[]; } interface MaintenanceWindowItem { @@ -330,11 +331,12 @@ export async function renderAlertsView( const chUrl = el('input', { placeholder: 'Webhook / base URL (optional for ntfy.sh or Telegram)' }); const chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' }); const chRef = el('select', {}); - for (const cr of credsRes.credentials) { + const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret'); + for (const cr of webhookCreds) { chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`)); } - if (credsRes.credentials.length === 0) { - chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add in Vault)')); + if (webhookCreds.length === 0) { + chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)')); } const chForm = el( 'form', @@ -385,7 +387,9 @@ export async function renderAlertsView( ? `offline >= ${r.offlineSec}s` : r.kind === 'probe' ? `probe ${r.probeId ?? '*'}` - : `system ${r.systemId}/${r.item ?? '*'}`; + : r.kind === 'security-event' + ? `security-event [${r.events?.join(', ') ?? ''}]` + : `system ${r.systemId}/${r.item ?? '*'}`; const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable'); toggleBtn.addEventListener('click', () => { void saveConfig({ @@ -404,9 +408,9 @@ export async function renderAlertsView( const ruleId = el('input', { placeholder: 'high-cpu', required: true }); const ruleName = el('input', { placeholder: 'High CPU Usage', required: true }); - const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system')); + const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system'), el('option', { value: 'security-event' }, 'security-event')); const ruleSev = el('select', {}, el('option', { value: 'warn' }, 'warn'), el('option', { value: 'critical' }, 'critical')); - const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system (e.g. cpuPct)' }); + const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system or events csv (auth.lockout,ssh.host_key_mismatch,vault.panic_lock)' }); const ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' }); const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' }); const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' }); @@ -443,6 +447,17 @@ export async function renderAlertsView( nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined }; } else if (ruleKind.value === 'system') { nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' }; + } else if (ruleKind.value === 'security-event') { + const events = ruleParam1.value + .split(',') + .map((e) => e.trim()) + .filter(Boolean); + nextRule = { + ...base, + kind: 'security-event', + forConsecutivePolls: 1, + events: events.length > 0 ? events : ['auth.lockout', 'ssh.host_key_mismatch', 'vault.panic_lock'], + }; } else { nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) }; } diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index 6dab298..fd1c305 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -87,16 +87,36 @@ export async function renderAuthView( placeholder: '6-digit code from authenticator', required: true, }); + const bootTokInput = el('input', { + id: 'boot-token', + name: 'bootstrapToken', + type: 'password', + autocomplete: 'off', + placeholder: 'GCOORD_BOOTSTRAP_TOKEN (auto-filled unless operator-only)', + }) as HTMLInputElement; let secretBase32 = ''; - let bootstrapToken = ''; try { const data = await apiFetch('/api/auth/bootstrap'); secretBase32 = data.secretBase32; - bootstrapToken = data.bootstrapToken ?? ''; - const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); - if (doc.documentElement.nodeName === 'svg') { - qrContainer.append(document.importNode(doc.documentElement, true)); + bootTokInput.value = data.bootstrapToken ?? ''; + if ( + typeof data.qrDataUri === 'string' && + /^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(data.qrDataUri) + ) { + const img = el('img', { + src: data.qrDataUri, + alt: 'TOTP Enrollment QR Code', + width: 200, + height: 200, + style: 'background:#fff;padding:6px;display:block', + }); + qrContainer.append(img); + } else { + 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) { @@ -119,6 +139,8 @@ export async function renderAuthView( el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), codeInput, + el('label', { for: 'boot-token' }, 'Bootstrap Token (if GCOORD_BOOTSTRAP_TOKEN is enforced)'), + bootTokInput, statusMsg, submitBtn, ); @@ -128,6 +150,7 @@ export async function renderAuthView( statusMsg.textContent = ''; submitBtn.disabled = true; try { + const tok = bootTokInput.value.trim(); const res = await apiFetch<{ csrfToken: string; recoveryCodes: string[]; @@ -138,7 +161,7 @@ export async function renderAuthView( password: passInput.value, totpCode: codeInput.value.trim(), secretBase32, - ...(bootstrapToken ? { bootstrapToken } : {}), + ...(tok ? { bootstrapToken: tok } : {}), initialSafeMode, securityPreset: presetSelect.value, }, diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts index 6bc070f..2f440df 100644 --- a/src/client/ts/views/config-view.ts +++ b/src/client/ts/views/config-view.ts @@ -1,3 +1,4 @@ +import { collapseDiffHunks, computeLineDiff, type CollapsedDiffEntry } from '../../../shared/diff.js'; import { apiFetch, type ApiError } from '../api.js'; import { confirmDialog, openDiffModal } from '../dialogs.js'; import { @@ -5,9 +6,11 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ConfigOverview, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; interface FileDetails { @@ -236,18 +239,14 @@ export async function renderConfigView( } }); - const saveBtn = el( - 'button', - { type: 'button', class: 'btn btn-primary mutating-action' }, - 'Save Config', - ); - saveBtn.addEventListener('click', async () => { + const saveFile = async () => { msgEl.replaceChildren(); try { await apiFetch('/api/config/file', { method: 'PUT', body: { path: details.filePath, content: editor.value }, }); + showToast(`Saved ${details.filePath}.`, 'ok'); await onReloadOverview(); } catch (err) { const apiErr = err as ApiError; @@ -256,9 +255,44 @@ export async function renderConfigView( msgEl.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`)); } } + }; + + const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview Changes'); + previewBtn.addEventListener('click', () => { + const diff = computeLineDiff(details.rawContent, editor.value, 'saved', 'draft'); + const hunks = diff.collapsedLines ?? collapseDiffHunks(diff.lines); + msgEl.replaceChildren( + el('div', { class: 'mono muted' }, `+${diff.additions} / -${diff.deletions}`), + el( + 'pre', + { class: 'diff-body mono', style: 'max-height:220px' }, + ...hunks.map((entry) => + entry.type === 'hunk' + ? el('div', { class: 'diff-hunk-sep' }, entry.text) + : el( + 'div', + { class: entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '' }, + `${entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '} ${entry.text}`, + ), + ), + ), + ); }); - const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn); + const saveBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary mutating-action' }, + 'Save Config', + ); + saveBtn.addEventListener('click', () => void saveFile()); + + const onCtrlS = () => { + if (editor.isConnected && !state.safeMode) void saveFile(); + }; + window.addEventListener('gcoord:save', onCtrlS); + registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS)); + + const actionRow = el('div', { class: 'row' }, fmtBtn, previewBtn, saveBtn); if (isAiEnabled(state)) { const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]'); aiBtn.addEventListener('click', async () => { @@ -336,7 +370,10 @@ export async function renderConfigView( 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 }> }; + diff: { + lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; + collapsedLines?: CollapsedDiffEntry[]; + }; }>(`/api/config/revisions/${rev.id}/diff`); openDiffModal({ revisionId: res.revision.id, @@ -344,6 +381,7 @@ export async function renderConfigView( source: res.revision.source, createdAt: res.revision.createdAt, lines: res.diff.lines, + collapsedLines: res.diff.collapsedLines, onRollback: async () => { await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); await onReloadOverview(); diff --git a/src/client/ts/views/settings-ops-panel.ts b/src/client/ts/views/settings-ops-panel.ts new file mode 100644 index 0000000..34af14b --- /dev/null +++ b/src/client/ts/views/settings-ops-panel.ts @@ -0,0 +1,360 @@ +import { apiFetch } from '../api.js'; +import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { showToast } from '../toast.js'; + +interface AuditRow { + id: number; + ts: number; + action: string; + actor_ip: string; + target: string | null; + status: string; + details: string | null; +} + +interface BackupScheduleStatus { + enabled: boolean; + cron: string; + timezone: string; + destination: 'local' | 'sftp'; + running: boolean; + lastRunAt: number | null; + lastStatus: 'never' | 'ok' | 'error' | 'skipped'; + lastFilename: string | null; + lastError: string | null; + nextRunAt: number | null; + localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; +} + +export async function renderSettingsOpsPanels( + host: HTMLElement, + state: ClientState, + creds: Array<{ id: string; name: string; type: string }>, + onReloadState: () => Promise, +): Promise { + const settingsObj = (state.overview?.settings ?? {}) as Record; + const runtimeCfg = (settingsObj.runtime ?? {}) as { throttleMode?: string }; + const metricsCfg = (settingsObj.metrics ?? {}) as { + prometheusEnabled?: boolean; + prometheusSecretRef?: string; + prometheusTokenHash?: string; + }; + const schedCfg = (settingsObj.scheduledBackup ?? {}) as { + enabled?: boolean; + cron?: string; + timezone?: string; + destination?: 'local' | 'sftp'; + localDir?: string; + remoteServerId?: string; + remotePath?: string; + retentionCount?: number; + passphraseSecretRef?: string; + }; + + // 1. Runtime Resource Profile & Prometheus /metrics + const opsGrid = el('div', { class: 'grid-2' }); + + const rtPanel = el('section', { class: 'panel panel-region' }); + rtPanel.append( + el('h2', {}, 'Runtime Throttle Profile'), + el( + 'p', + { class: 'muted' }, + 'Tune polling, log caps, and worker concurrency for constrained 1 vCPU / 1 GB RAM VPS vs larger servers.', + ), + ); + const modeSel = el( + 'select', + {}, + el('option', { value: 'low-resource', selected: (runtimeCfg.throttleMode ?? 'low-resource') === 'low-resource' }, 'low-resource (1 vCPU / 1 GB RAM — bounded polls & caches)'), + el('option', { value: 'balanced', selected: runtimeCfg.throttleMode === 'balanced' }, 'balanced (moderate parallelism & buffer caps)'), + el('option', { value: 'unthrottled', selected: runtimeCfg.throttleMode === 'unthrottled' }, 'unthrottled (high parallelism for multi-core hosts)'), + ) as HTMLSelectElement; + const rtMsg = el('p', { class: 'form-msg' }); + const saveRtBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Save Runtime Mode'); + saveRtBtn.addEventListener('click', async () => { + rtMsg.textContent = ''; + try { + const nextSettings = { + ...settingsObj, + runtime: { throttleMode: modeSel.value }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `runtime.throttleMode -> ${modeSel.value}`, + }, + }); + showToast(`Runtime profile set to ${modeSel.value}.`, 'ok'); + await onReloadState(); + } catch (err) { + rtMsg.className = 'form-msg err-text'; + rtMsg.textContent = extractErrorMessage(err); + } + }); + rtPanel.append(el('label', {}, 'Throttle Mode'), modeSel, el('div', { class: 'row', style: 'margin-top:8px' }, saveRtBtn), rtMsg); + + const promPanel = el('section', { class: 'panel panel-region' }); + promPanel.append( + el('h2', {}, 'Prometheus /metrics Endpoint'), + el( + 'p', + { class: 'muted' }, + 'Exposes fleet gauges on GET /metrics with Bearer token auth (either rotated token hash or Vault secret).', + ), + ); + const promChk = el('input', { type: 'checkbox', checked: metricsCfg.prometheusEnabled ? true : undefined }) as HTMLInputElement; + const promMsg = el('p', { class: 'form-msg' }); + const tokenBox = el('pre', { class: 'mono warn-text', hidden: true }); + const copyPromBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: true }, 'Copy Bearer Token'); + copyPromBtn.addEventListener('click', () => { + void navigator.clipboard?.writeText(tokenBox.textContent ?? ''); + copyPromBtn.textContent = 'Copied!'; + }); + + const savePromBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Metrics Setting'); + savePromBtn.addEventListener('click', async () => { + try { + const nextSettings = { + ...settingsObj, + metrics: { ...metricsCfg, prometheusEnabled: promChk.checked }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `metrics.prometheusEnabled -> ${String(promChk.checked)}`, + }, + }); + showToast(`Prometheus /metrics ${promChk.checked ? 'enabled' : 'disabled'}.`, 'ok'); + await onReloadState(); + } catch (err) { + promMsg.className = 'form-msg err-text'; + promMsg.textContent = extractErrorMessage(err); + } + }); + + const rotPromBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Rotate Bearer Token'); + rotPromBtn.addEventListener('click', async () => { + try { + const r = await apiFetch<{ token: string; prometheusEnabled: boolean }>('/api/config/prometheus-token', { + method: 'POST', + body: { enable: true }, + }); + promChk.checked = r.prometheusEnabled; + tokenBox.hidden = false; + tokenBox.textContent = r.token; + copyPromBtn.hidden = false; + promMsg.className = 'form-msg ok-text'; + promMsg.textContent = 'New Bearer token generated (copy now — shown once):'; + showToast('Rotated Prometheus Bearer token.', 'ok'); + } catch (err) { + promMsg.className = 'form-msg err-text'; + promMsg.textContent = extractErrorMessage(err); + } + }); + + promPanel.append( + el('label', { class: 'chk-row' }, promChk, 'Enable GET /metrics endpoint'), + el( + 'div', + { class: 'mono muted', style: 'margin-top:4px' }, + metricsCfg.prometheusTokenHash + ? 'Auth status: Bearer token hash configured' + : metricsCfg.prometheusSecretRef + ? `Auth status: Vault ref ${metricsCfg.prometheusSecretRef}` + : 'Auth status: Rotate Bearer Token to enable authenticated scrapes', + ), + el('div', { class: 'row', style: 'margin-top:8px' }, savePromBtn, rotPromBtn), + promMsg, + tokenBox, + copyPromBtn, + ); + + opsGrid.append(rtPanel, promPanel); + host.append(opsGrid); + + // 2. Scheduled Encrypted Backups + const schedPanel = el('section', { class: 'panel panel-region' }); + const schedStatusRes = await apiFetch<{ schedule: BackupScheduleStatus }>('/api/backup/schedule').catch(() => null); + const st = schedStatusRes?.schedule; + schedPanel.append( + el('h2', {}, 'Scheduled .gcoord.enc Backups'), + el( + 'p', + { class: 'muted mono' }, + st + ? `Status: ${st.lastStatus.toUpperCase()} | Running: ${String(st.running)} | Local bundles: ${st.localFiles.length} | Next: ${fmtTime(st.nextRunAt)}${st.lastError ? ` | Err: ${st.lastError}` : ''}` + : 'Backup scheduler unavailable.', + ), + ); + + const sbEnChk = el('input', { type: 'checkbox', checked: schedCfg.enabled ? true : undefined }) as HTMLInputElement; + const sbCronInp = el('input', { value: schedCfg.cron ?? '0 3 * * *', placeholder: '0 3 * * *' }) as HTMLInputElement; + const sbTzInp = el('input', { value: schedCfg.timezone ?? 'UTC', placeholder: 'UTC' }) as HTMLInputElement; + const sbDestSel = el( + 'select', + {}, + el('option', { value: 'local', selected: (schedCfg.destination ?? 'local') === 'local' }, 'local'), + el('option', { value: 'sftp', selected: schedCfg.destination === 'sftp' }, 'sftp'), + ) as HTMLSelectElement; + const sbLocalDirInp = el('input', { value: schedCfg.localDir ?? 'backups', placeholder: 'backups' }) as HTMLInputElement; + const sbRetInp = el('input', { type: 'number', min: 1, max: 100, value: String(schedCfg.retentionCount ?? 7) }) as HTMLInputElement; + const sbSrvInp = el('input', { value: schedCfg.remoteServerId ?? '', placeholder: 'Remote Server ID (sftp)' }) as HTMLInputElement; + const sbPathInp = el('input', { value: schedCfg.remotePath ?? '', placeholder: '/var/backups/gcoord (sftp)' }) as HTMLInputElement; + const sbRefSel = el( + 'select', + {}, + el('option', { value: '' }, '(Use Vault Master Key)'), + ...creds.map((c) => el('option', { value: c.id, selected: schedCfg.passphraseSecretRef === c.id }, `${c.id} (${c.type})`)), + ) as HTMLSelectElement; + + const sbMsg = el('p', { class: 'form-msg' }); + const saveSbBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Schedule'); + saveSbBtn.addEventListener('click', async () => { + sbMsg.textContent = ''; + try { + const nextSettings = { + ...settingsObj, + scheduledBackup: { + enabled: sbEnChk.checked, + cron: sbCronInp.value.trim() || '0 3 * * *', + timezone: sbTzInp.value.trim() || 'UTC', + destination: sbDestSel.value as 'local' | 'sftp', + localDir: sbLocalDirInp.value.trim() || 'backups', + retentionCount: Number(sbRetInp.value || 7), + ...(sbSrvInp.value.trim() ? { remoteServerId: sbSrvInp.value.trim() } : {}), + ...(sbPathInp.value.trim() ? { remotePath: sbPathInp.value.trim() } : {}), + ...(sbRefSel.value ? { passphraseSecretRef: sbRefSel.value } : {}), + }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: 'Update scheduled backup configuration', + }, + }); + showToast('Scheduled backup config saved.', 'ok'); + await onReloadState(); + } catch (err) { + sbMsg.className = 'form-msg err-text'; + sbMsg.textContent = extractErrorMessage(err); + } + }); + + const runSbBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Run Backup Now'); + runSbBtn.addEventListener('click', async () => { + sbMsg.className = 'form-msg muted'; + sbMsg.textContent = 'Running scheduled backup...'; + try { + const r = await apiFetch<{ ok: boolean; filename?: string; error?: string }>('/api/backup/schedule/run', { + method: 'POST', + body: {}, + }); + sbMsg.className = r.ok ? 'form-msg ok-text' : 'form-msg err-text'; + sbMsg.textContent = r.ok ? `Backup created: ${r.filename ?? 'ok'}` : (r.error ?? 'Backup failed'); + showToast(sbMsg.textContent, r.ok ? 'ok' : 'err'); + } catch (err) { + sbMsg.className = 'form-msg err-text'; + sbMsg.textContent = extractErrorMessage(err); + } + }); + + schedPanel.append( + el('label', { class: 'chk-row' }, sbEnChk, 'Enable scheduled encrypted backups'), + el( + 'div', + { class: 'grid-3', style: 'margin-top:8px' }, + el('div', {}, el('label', {}, 'Cron'), sbCronInp), + el('div', {}, el('label', {}, 'Timezone'), sbTzInp), + el('div', {}, el('label', {}, 'Destination'), sbDestSel), + el('div', {}, el('label', {}, 'Local Dir (under data/)'), sbLocalDirInp), + el('div', {}, el('label', {}, 'Retention Count'), sbRetInp), + el('div', {}, el('label', {}, 'Passphrase Secret'), sbRefSel), + el('div', {}, el('label', {}, 'Remote Server (SFTP)'), sbSrvInp), + el('div', {}, el('label', {}, 'Remote Path (SFTP)'), sbPathInp), + ), + el('div', { class: 'row', style: 'margin-top:8px' }, saveSbBtn, runSbBtn), + sbMsg, + ); + host.append(schedPanel); + + // 3. Filterable & Exportable Audit Log + const auditPanel = el('section', { class: 'panel panel-region' }); + const initialAudit = await apiFetch<{ total: number; items: AuditRow[]; actions?: string[] }>('/api/audit?limit=40'); + + const actSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: '' }, 'All Actions'), + ...(initialAudit.actions ?? []).map((a) => el('option', { value: a }, a)), + ) as HTMLSelectElement; + const stSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: '' }, 'All Statuses'), + el('option', { value: 'ok' }, 'ok'), + el('option', { value: 'denied' }, 'denied'), + el('option', { value: 'error' }, 'error'), + ) as HTMLSelectElement; + const qInput = el('input', { type: 'search', class: 'input-sm', placeholder: 'Filter target/IP/details...' }) as HTMLInputElement; + const applyBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Filter'); + const exportCsvLink = el('a', { href: '/api/audit/export?format=csv', class: 'btn btn-sm', download: '' }, 'Export CSV'); + const exportNdLink = el('a', { href: '/api/audit/export?format=ndjson', class: 'btn btn-sm', download: '' }, 'Export NDJSON'); + const titleEl = el('h2', {}, `Security & Action Audit Log (${initialAudit.total} entries)`); + const aBody = el('tbody'); + + const buildAuditQuery = () => { + const p = new URLSearchParams(); + p.set('limit', '60'); + if (actSel.value) p.set('action', actSel.value); + if (stSel.value) p.set('status', stSel.value); + if (qInput.value.trim()) p.set('q', qInput.value.trim()); + return p.toString(); + }; + + const renderRows = (rows: AuditRow[], total: number) => { + titleEl.textContent = `Security & Action Audit Log (${total} matching)`; + const qStr = buildAuditQuery(); + exportCsvLink.setAttribute('href', `/api/audit/export?format=csv&${qStr}`); + exportNdLink.setAttribute('href', `/api/audit/export?format=ndjson&${qStr}`); + aBody.replaceChildren(); + for (const row of rows) { + 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 ?? '—'), + ), + ); + } + }; + renderRows(initialAudit.items, initialAudit.total); + + applyBtn.addEventListener('click', async () => { + const res = await apiFetch<{ total: number; items: AuditRow[] }>(`/api/audit?${buildAuditQuery()}`); + renderRows(res.items, res.total); + }); + + 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'))), + aBody, + ); + auditPanel.append( + el('div', { class: 'row-between' }, titleEl, el('div', { class: 'row' }, exportCsvLink, exportNdLink)), + el('div', { class: 'row', style: 'margin:8px 0' }, actSel, stSel, qInput, applyBtn), + el('div', { class: 'table-wrap' }, aTable), + ); + host.append(auditPanel); +} diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 2524ecc..55c942e 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -20,16 +20,6 @@ interface SessionRow { current: boolean; } -interface AuditRow { - id: number; - ts: number; - action: string; - actor_ip: string; - target: string | null; - status: string; - details: string | null; -} - interface FactorsData { passwords: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>; @@ -55,9 +45,8 @@ export async function renderSettingsView( ): Promise { root.replaceChildren(); - const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([ + const [sessRes, factorsRes, credsRes] = await Promise.all([ apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'), - apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'), apiFetch('/api/auth/factors'), apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>( '/api/vault/credentials', @@ -198,12 +187,33 @@ export async function renderSettingsView( 'select', {}, el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'), - el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session (7d)'), + el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session'), el('option', { value: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'), - el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'), + el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour'), + el('option', { value: '15m', selected: sec.stepUpPolicy === '15m' ? true : undefined }, '15 minutes (v1.1 default)'), el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'), el('option', { value: 'every-action', selected: sec.stepUpPolicy === 'every-action' ? true : undefined }, 'Every sensitive action'), ); + const allowSameOriginProxyChk = el('input', { + type: 'checkbox', + checked: sec.allowSameOriginProxy ? true : undefined, + }) as HTMLInputElement; + const egressCidrsInput = el('input', { + value: (sec.egressAllowedCidrs ?? []).join(', '), + placeholder: 'e.g. 10.20.0.0/24 (blank = block all private IPs)', + }) as HTMLInputElement; + const sessTtlInput = el('input', { + type: 'number', + min: 1, + max: 720, + value: String(sec.sessionTtlHours ?? 168), + }) as HTMLInputElement; + const sessIdleInput = el('input', { + type: 'number', + min: 0, + max: 10080, + value: String(sec.sessionIdleTimeoutMin ?? 60), + }) as HTMLInputElement; const methodSel = el( 'select', {}, @@ -270,6 +280,7 @@ export async function renderSettingsView( policyMsg.textContent = ''; try { const nextSecurity: ClientSecuritySettings = { + ...sec, requireTotpOnLogin: reqTotpChk.checked, passwordMode: pwModeSel.value as 'any' | 'all', totpMode: totpModeSel.value as 'any' | 'all', @@ -278,6 +289,13 @@ export async function renderSettingsView( elevateOnLogin: elevateLoginChk.checked, keepElevationOnSafeMode: keepSafeChk.checked, enableEmergencySecretsBackup: backupChk.checked, + allowSameOriginProxy: allowSameOriginProxyChk.checked, + egressAllowedCidrs: egressCidrsInput.value + .split(',') + .map((s) => s.trim()) + .filter(Boolean), + sessionTtlHours: Number(sessTtlInput.value || 168), + sessionIdleTimeoutMin: Number(sessIdleInput.value || 0), }; const nextSettings = { ...(state.overview?.settings ?? {}), @@ -307,14 +325,18 @@ export async function renderSettingsView( el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel), el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel), el('div', {}, el('label', {}, 'Step-Up Method'), methodSel), + el('div', {}, el('label', {}, 'Session Max Lifetime (hours)'), sessTtlInput), + el('div', {}, el('label', {}, 'Session Idle Timeout (min, 0=off)'), sessIdleInput), ), + el('div', { style: 'margin-top:8px' }, el('label', {}, 'Egress Allowed CIDRs / IPs (CSV)'), egressCidrsInput), el( 'div', { class: 'stack', style: 'margin-top:8px' }, el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'), el('label', { class: 'chk-row' }, elevateLoginChk, 'Auto-elevate session on Login (skips immediate Step-Up)'), el('label', { class: 'chk-row' }, keepSafeChk, 'Keep Step-Up elevation when toggling Safe Mode ON'), - el('label', { class: 'chk-row' }, backupChk, 'Maintain automatic chmod 0600 secrets backup in data/recovery/'), + el('label', { class: 'chk-row' }, allowSameOriginProxyChk, 'Allow same-origin HTTP proxy fallback (less strict cookie isolation than isolated origin)'), + el('label', { class: 'chk-row' }, backupChk, 'Maintain passwordless emergency secrets backup in data/recovery/ (master key + vault creds only; login passwords never stored)'), ), el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn), policyMsg, @@ -730,7 +752,7 @@ export async function renderSettingsView( 'p', { class: 'muted' }, isWebAuthnSupported() - ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification.' + ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification. Reverse-proxy overrides: GCOORD_WEBAUTHN_RP_ID and GCOORD_WEBAUTHN_ORIGINS.' : 'Passkeys require HTTPS (e.g. Cloudflare Tunnel) or http://localhost — plain HTTP or raw IP URLs block navigator.credentials.', ), ); @@ -817,7 +839,7 @@ export async function renderSettingsView( el( 'p', { class: 'muted mono' }, - `Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, + `Passwordless bundle (login passwords are never written) — Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, ), ); const bMsg = el('p', { class: 'form-msg' }); @@ -947,41 +969,9 @@ export async function renderSettingsView( sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); root.append(sessPanel); - // 6. 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); + // 6. Runtime Profile, Prometheus /metrics, Scheduled Backups & Filterable Audit Log (lazy chunk) + const opsHost = el('div', { class: 'stack' }); + root.append(opsHost); + const { renderSettingsOpsPanels } = await import('./settings-ops-panel.js'); + await renderSettingsOpsPanels(opsHost, state, credsRes.credentials, onReloadState); } diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index a24300b..752682b 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -7,11 +7,23 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; +interface SystemActionInputDef { + name: string; + type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; + label?: string; + description?: string; + required?: boolean; + default?: unknown; + options?: string[]; +} + interface SystemActionDef { id: string; label: string; @@ -19,6 +31,7 @@ interface SystemActionDef { mode: 'oneshot' | 'stream' | 'interactive'; sudo: boolean; confirm: boolean; + inputs?: SystemActionInputDef[]; } interface SystemParamDef { @@ -65,6 +78,88 @@ interface ServerSnapshotView { } let unsubStreamListener: (() => void) | null = null; +let unsubStreamChannel: (() => void) | null = null; + +function releaseSystemStream(): void { + if (unsubStreamChannel) { + unsubStreamChannel(); + unsubStreamChannel = null; + } + if (unsubStreamListener) { + unsubStreamListener(); + unsubStreamListener = null; + } +} + +async function promptActionInputs( + actionLabel: string, + defs: SystemActionInputDef[], +): Promise | null> { + if (!defs || defs.length === 0) return {}; + return new Promise((resolve) => { + const dialog = document.createElement('dialog'); + dialog.className = 'dialog-wide'; + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel'); + const ctrls = new Map(); + const fieldsBox = el('div', { class: 'stack' }); + for (const def of defs) { + let node: HTMLInputElement | HTMLSelectElement; + if (def.type === 'select' && def.options) { + const sel = el('select', { required: def.required !== false }); + for (const opt of def.options) { + sel.append(el('option', { value: opt, selected: def.default === opt }, opt)); + } + node = sel; + } else if (def.type === 'boolean') { + node = el('input', { type: 'checkbox', checked: Boolean(def.default) }) as HTMLInputElement; + } else { + node = el('input', { + type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', + value: def.default !== undefined ? String(def.default) : '', + required: def.required !== false, + placeholder: def.description ?? def.name, + }) as HTMLInputElement; + } + ctrls.set(def.name, { def, node }); + fieldsBox.append(el('label', {}, `${def.label ?? def.name} (${def.type})`), node); + } + + const form = el( + 'form', + { class: 'stack' }, + fieldsBox, + el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Run')), + ); + + let settled = false; + const finish = (val: Record | null) => { + if (settled) return; + settled = true; + if (dialog.open) dialog.close(); + dialog.remove(); + resolve(val); + }; + closeBtn.addEventListener('click', () => finish(null)); + dialog.addEventListener('close', () => finish(null)); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + const out: Record = {}; + for (const [k, { def, node }] of ctrls.entries()) { + out[k] = + def.type === 'boolean' + ? (node as HTMLInputElement).checked + : def.type === 'number' + ? Number(node.value) + : node.value; + } + finish(out); + }); + + dialog.append(el('h1', {}, `Action Inputs: ${actionLabel}`), form); + document.body.append(dialog); + dialog.showModal(); + }); +} function healthBadgeClass(h: string): string { if (h === 'ok') return 'badge badge-ok'; @@ -175,6 +270,12 @@ async function runSystemAction(opts: { onFinished: () => Promise; }): Promise { const { action } = opts; + let actionInputs: Record | undefined; + if (action.inputs && action.inputs.length > 0) { + const prompted = await promptActionInputs(action.label, action.inputs); + if (!prompted) return; + actionInputs = prompted; + } if (action.confirm) { const target = opts.subItemName ?? opts.itemName ?? opts.serverId; const ok = await confirmDialog( @@ -186,20 +287,28 @@ async function runSystemAction(opts: { opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`)); - const res = await apiFetch< + let res: | { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number } | { mode: 'stream'; jobId: string } - | { mode: 'interactive'; session: { sessionId: string } } - >( - `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, - { - method: 'POST', - body: { - itemName: opts.itemName, - subItemName: opts.subItemName, + | { mode: 'interactive'; session: { sessionId: string } }; + try { + res = await apiFetch( + `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, + { + method: 'POST', + body: { + itemName: opts.itemName, + subItemName: opts.subItemName, + ...(actionInputs ? { inputs: actionInputs } : {}), + }, }, - }, - ); + ); + } catch (err) { + const msg = extractErrorMessage(err); + opts.outputHost.replaceChildren(el('p', { class: 'err-text mono' }, msg)); + showToast(msg, 'err'); + return; + } if (res.mode === 'interactive') { window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`; @@ -242,16 +351,14 @@ async function runSystemAction(opts: { } // Stream mode - if (unsubStreamListener) { - unsubStreamListener(); - unsubStreamListener = null; - } + releaseSystemStream(); const logPre = el('pre', { class: 'stream-log mono' }); - const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream'); + const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Stream'); stopBtn.addEventListener('click', async () => { await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' }); stopBtn.disabled = true; + showToast(`Stream ${res.jobId} cancelled.`, 'warn'); }); const streamAiBtn = isAiEnabled(opts.state) ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') @@ -303,7 +410,7 @@ async function runSystemAction(opts: { logPre.scrollTop = logPre.scrollHeight; }); - opts.wsClient.subscribe([`stream:${res.jobId}`]); + unsubStreamChannel = opts.wsClient.subscribe([`stream:${res.jobId}`]); } export async function renderSystemsView( @@ -311,10 +418,8 @@ export async function renderSystemsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - if (unsubStreamListener) { - unsubStreamListener(); - unsubStreamListener = null; - } + releaseSystemStream(); + registerViewCleanup(releaseSystemStream); root.replaceChildren(); const segs = state.routeSegments ?? []; const forceRefresh = state.routeQuery?.refresh === '1'; @@ -567,14 +672,16 @@ export async function renderSystemsView( // Quick Editable Files via SFTP inline diff editor if (item.editableFiles.length > 0) { + const needsSudo = system.actions.some((a) => a.sudo); const editRow = el('div', { class: 'chip-list' }); for (const fPath of item.editableFiles) { editRow.append( el( 'a', { - href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`, + href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}${needsSudo ? '&sudo=1' : ''}`, class: 'btn btn-sm', + title: fPath, }, `Edit ${fPath.split('/').pop()}`, ), diff --git a/src/client/ts/views/vault-view.ts b/src/client/ts/views/vault-view.ts index 1789733..02359ed 100644 --- a/src/client/ts/views/vault-view.ts +++ b/src/client/ts/views/vault-view.ts @@ -1,6 +1,7 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { showToast } from '../toast.js'; interface VaultCredMeta { id: string; @@ -123,19 +124,44 @@ export async function renderVaultView( onPanicLock: () => Promise, ): Promise { root.replaceChildren(); - const vaultData = await apiFetch<{ - state: 'uninitialized' | 'locked' | 'unlocked'; - runtimeReady?: boolean; - isPanicLocked?: boolean; - credentials: VaultCredMeta[]; - }>('/api/vault/credentials'); - const runtimeReady = Boolean(vaultData.runtimeReady ?? vaultData.state === 'unlocked'); - state.vaultState = vaultData.state; + const [vaultData, statusRes] = await Promise.all([ + apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + runtimeReady?: boolean; + sealState?: string; + isPanicLocked?: boolean; + credentials: VaultCredMeta[]; + }>('/api/vault/credentials'), + apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + runtimeReady: boolean; + sealState: string; + isPanicLocked: boolean; + }>('/api/vault/status').catch(() => null), + ]); + const runtimeReady = Boolean(statusRes?.runtimeReady ?? vaultData.runtimeReady ?? vaultData.state === 'unlocked'); + const sealState = statusRes?.sealState ?? vaultData.sealState ?? (runtimeReady ? 'unsealed' : 'sealed'); + state.vaultState = statusRes?.state ?? vaultData.state; state.vaultRuntimeReady = runtimeReady; - if (vaultData.isPanicLocked !== undefined) { - state.isPanicLocked = vaultData.isPanicLocked; + if (statusRes?.isPanicLocked !== undefined || vaultData.isPanicLocked !== undefined) { + state.isPanicLocked = Boolean(statusRes?.isPanicLocked ?? vaultData.isPanicLocked); } + const doSealVault = async () => { + const ok = await confirmDialog( + 'dialog-confirm', + 'Seal the Vault now? This wipes the in-memory master key (collectors/SSH will pause until unsealed with the 32-byte key), without revoking your admin login session.', + ); + if (!ok) return; + try { + await apiFetch('/api/vault/seal', { method: 'POST', body: {} }); + showToast('Vault sealed and runtime master key cleared from memory.', 'warn'); + await onStateChanged(); + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }; + const statusPanel = el('section', { class: 'panel' }); if (vaultData.state === 'uninitialized') { @@ -283,13 +309,23 @@ export async function renderVaultView( }); statusPanel.append( - el('h1', {}, 'Encrypted Vault — [LOCKED]'), + el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()} / ${sealState.toUpperCase()}]`), el( 'p', { class: 'muted' }, - 'Established secrets remain active in the background for stat collectors, SSH, SFTP, Terminal, Systems, and Tunnels. Unlock the Vault to add, update, delete, rotate, or reveal secrets.', + 'Established secrets remain active in memory while unsealed (chmod 0600 data/vault.key or GCOORD_MASTER_KEY env). Unlock to edit, or Seal to zeroize keys from RAM without dropping sessions.', + ), + el( + 'div', + { class: 'row' }, + unlockBtn, + (() => { + const sealBtn = el('button', { type: 'button', class: 'btn mutating-action' }, 'Seal Vault'); + sealBtn.addEventListener('click', () => void doSealVault()); + return sealBtn; + })(), + panicBtn, ), - el('div', { class: 'row' }, unlockBtn, panicBtn), lockMsg, credTableWrap, revealBox, @@ -308,9 +344,15 @@ export async function renderVaultView( await apiFetch('/api/vault/lock', { method: 'POST' }); await onStateChanged(); }); + const sealUnlockedBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Seal Vault', + ); + sealUnlockedBtn.addEventListener('click', () => void doSealVault()); statusPanel.append( - el('div', { class: 'row-between' }, el('h1', {}, 'Encrypted Vault — [UNLOCKED]'), lockBtn), + el('div', { class: 'row-between' }, el('h1', {}, `Encrypted Vault — [UNLOCKED / ${sealState.toUpperCase()}]`), el('div', { class: 'row' }, lockBtn, sealUnlockedBtn)), credTableWrap, revealBox, ); diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 83a4b30..4d0bb20 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -7,16 +7,18 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; type WfSubTab = 'workflows' | 'broadcast' | 'snippets'; interface WorkflowInputDef { name: string; - type: 'string' | 'number' | 'boolean' | 'server' | 'select'; + type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; label?: string; description?: string; required?: boolean; @@ -26,7 +28,7 @@ interface WorkflowInputDef { interface WorkflowStepDef { id: string; - type: 'exec' | 'read-file' | 'system-action' | 'transfer'; + type: 'exec' | 'read-file' | 'system-action' | 'transfer' | 'http' | 'notify'; dependsOn?: Array; target?: { serverId?: string; tags?: string[]; all?: boolean }; command?: string; @@ -39,7 +41,19 @@ interface WorkflowStepDef { mode?: 'hub-relayed' | 'direct'; source?: { serverId: string; path: string }; destination?: { serverId: string; path: string }; + url?: string; + method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + body?: string; + secretRef?: string; + expectedStatus?: number; + channelIds?: string[]; + title?: string; + message?: string; + severity?: 'warn' | 'critical'; timeoutSec?: number; + retries?: number; + retryBackoffSec?: number; + when?: string; sudo?: boolean; captureAs?: string; onFailure?: string | { action: string; channelId?: string; workflowId?: string }; @@ -108,6 +122,18 @@ let activeSubTab: WfSubTab = 'workflows'; let selectedRunDetailId: string | null = null; let broadcastPresetSnippetId: string | null = null; let unsubWfWs: (() => void) | null = null; +let unsubWfChannel: (() => void) | null = null; + +function releaseWfWs(): void { + if (unsubWfChannel) { + unsubWfChannel(); + unsubWfChannel = null; + } + if (unsubWfWs) { + unsubWfWs(); + unsubWfWs = null; + } +} function statusBadgeClass(status: string): string { if (status === 'succeeded' || status === 'ok') return 'badge badge-ok'; @@ -251,10 +277,10 @@ async function promptWorkflowInputs( ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) }); } else { ctrl = el('input', { - type: def.type === 'number' ? 'number' : 'text', - value: def.default !== undefined ? String(def.default) : '', + type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', + value: def.type === 'secret' ? '' : def.default !== undefined ? String(def.default) : '', required: def.required, - placeholder: def.description ?? def.name, + placeholder: def.type === 'secret' ? '(secret input — masked in logs)' : (def.description ?? def.name), }); } fields.set(def.name, ctrl); @@ -419,7 +445,7 @@ function openWorkflowEditorDialog( const sType = el( 'select', { class: 'input-sm' }, - ...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) => + ...(['exec', 'read-file', 'system-action', 'transfer', 'http', 'notify'] as const).map((t) => el('option', { value: t, selected: step.type === t }, t), ), ); @@ -429,6 +455,14 @@ function openWorkflowEditorDialog( step.mode = 'hub-relayed'; step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' }; step.destination = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file.bak' }; + } else if (step.type === 'http' && !step.url) { + step.method = 'POST'; + step.url = 'https://example.invalid/webhook'; + } else if (step.type === 'notify' && !step.channelIds) { + step.channelIds = ['ops-webhook']; + step.title = 'Workflow Notification'; + step.message = 'Step reached'; + step.severity = 'warn'; } redrawSteps(); }); @@ -462,6 +496,26 @@ function openWorkflowEditorDialog( redrawSteps(); }); + const sRetries = el('input', { + class: 'input-sm', + type: 'number', + min: 0, + max: 5, + value: String(step.retries ?? 0), + placeholder: 'retries (0-5)', + }) as HTMLInputElement; + sRetries.addEventListener('input', () => { + step.retries = Number(sRetries.value || 0); + }); + const sWhen = el('input', { + class: 'input-sm', + value: step.when ?? '', + placeholder: 'when expr (e.g. inputs.env == "prod")', + }) as HTMLInputElement; + sWhen.addEventListener('input', () => { + step.when = sWhen.value.trim() || undefined; + }); + card.append( el( 'div', @@ -469,10 +523,57 @@ function openWorkflowEditorDialog( el('strong', {}, `Step #${idx + 1}`), el('div', { class: 'row' }, sId, sType, rmBtn), ), - sDeps, + el('div', { class: 'grid-3', style: 'margin-top:6px' }, sDeps, sRetries, sWhen), ); - if (step.type === 'transfer') { + if (step.type === 'http') { + const mSel = el( + 'select', + { class: 'input-sm' }, + ...(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const).map((m) => + el('option', { value: m, selected: (step.method ?? 'POST') === m }, m), + ), + ) as HTMLSelectElement; + const uIn = el('input', { class: 'input-sm', value: step.url ?? '', placeholder: 'https://...' }) as HTMLInputElement; + const secIn = el('input', { class: 'input-sm', value: step.secretRef ?? '', placeholder: 'secretRef (api-token/webhook-secret)' }) as HTMLInputElement; + const expIn = el('input', { class: 'input-sm', type: 'number', value: step.expectedStatus ? String(step.expectedStatus) : '', placeholder: 'expectedStatus' }) as HTMLInputElement; + const bArea = el('textarea', { rows: 2, placeholder: 'Optional HTTP JSON body' }, step.body ?? '') as HTMLTextAreaElement; + bArea.value = step.body ?? ''; + const syncHttp = () => { + step.method = mSel.value as WorkflowStepDef['method']; + step.url = uIn.value.trim(); + step.secretRef = secIn.value.trim() || undefined; + step.expectedStatus = expIn.value.trim() ? Number(expIn.value) : undefined; + step.body = bArea.value || undefined; + }; + [mSel, uIn, secIn, expIn, bArea].forEach((n) => n.addEventListener('input', syncHttp)); + card.append( + el('div', { class: 'grid-2', style: 'margin-top:6px' }, mSel, uIn, secIn, expIn), + bArea, + ); + } else if (step.type === 'notify') { + const chIn = el('input', { class: 'input-sm', value: (step.channelIds ?? []).join(', '), placeholder: 'channelIds (comma-sep)' }) as HTMLInputElement; + const tIn = el('input', { class: 'input-sm', value: step.title ?? '', placeholder: 'Notification title' }) as HTMLInputElement; + const sevSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: 'warn', selected: (step.severity ?? 'warn') === 'warn' }, 'warn'), + el('option', { value: 'critical', selected: step.severity === 'critical' }, 'critical'), + ) as HTMLSelectElement; + const mArea = el('textarea', { rows: 2, placeholder: 'Notification message' }, step.message ?? '') as HTMLTextAreaElement; + mArea.value = step.message ?? ''; + const syncNotify = () => { + step.channelIds = chIn.value.split(',').map((s) => s.trim()).filter(Boolean); + step.title = tIn.value; + step.severity = sevSel.value as 'warn' | 'critical'; + step.message = mArea.value; + }; + [chIn, tIn, sevSel, mArea].forEach((n) => n.addEventListener('input', syncNotify)); + card.append( + el('div', { class: 'grid-3', style: 'margin-top:6px' }, chIn, tIn, sevSel), + mArea, + ); + } else if (step.type === 'transfer') { const modeSel = el( 'select', { class: 'input-sm' }, @@ -675,11 +776,12 @@ export async function renderWorkflowsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - if (unsubWfWs) { - unsubWfWs(); - unsubWfWs = null; - } - wsClient.subscribe(['workflows']); + releaseWfWs(); + const unsubBase = wsClient.subscribe(['workflows']); + registerViewCleanup(() => { + releaseWfWs(); + unsubBase(); + }); root.replaceChildren(); const tabBar = el( @@ -761,17 +863,18 @@ export async function renderWorkflowsView( const watchRunStream = (runId: string, wfId: string) => { streamPanel.hidden = false; const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`); - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel Run'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Run'); cancelBtn.addEventListener('click', async () => { cancelBtn.disabled = true; await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }); + showToast(`Cancellation requested for run ${runId}.`, 'warn'); }); streamPanel.replaceChildren( el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn), logPre, ); - if (unsubWfWs) unsubWfWs(); + releaseWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { if (frame.stream !== 'meta') { @@ -791,7 +894,7 @@ export async function renderWorkflowsView( } } }); - wsClient.subscribe([`stream:wf:${runId}`]); + unsubWfChannel = wsClient.subscribe([`stream:wf:${runId}`]); }; const loadRunDetail = async (runId: string) => { @@ -802,6 +905,29 @@ export async function renderWorkflowsView( }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); detailPanel.hidden = false; renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); + const uniqueSteps = [...new Set(res.stepLogs.map((l) => l.stepId))]; + if (uniqueSteps.length > 0) { + const lazyPre = el('pre', { class: 'stream-log mono', hidden: true }); + const stepRow = el('div', { class: 'row', style: 'margin-top:8px' }, el('span', { class: 'muted' }, 'Inspect step:')); + for (const sid of uniqueSteps) { + const b = el('button', { type: 'button', class: 'btn btn-sm' }, sid); + b.addEventListener('click', async () => { + try { + const sLogs = await apiFetch<{ logs: WorkflowStepLogItem[] }>( + `/api/workflows/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(sid)}/logs`, + ); + lazyPre.hidden = false; + lazyPre.textContent = sLogs.logs + .map((l) => `[${l.serverId}] exit=${String(l.exitCode)}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`) + .join('\n---\n') || '(empty)'; + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }); + stepRow.append(b); + } + detailPanel.append(stepRow, lazyPre); + } if (isAiEnabled(state)) { const diagBtn = el( 'button', @@ -944,9 +1070,10 @@ export async function renderWorkflowsView( }); const actRow = el('div', { class: 'row' }, inspectBtn); if (r.status === 'running' || r.status === 'queued') { - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel'); cancelBtn.addEventListener('click', async () => { await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' }); + showToast(`Cancelled run ${r.runId}.`, 'warn'); await renderWorkflowsView(root, state, wsClient); }); actRow.append(cancelBtn); @@ -1034,7 +1161,7 @@ export async function renderWorkflowsView( const msgEl = el('p', { class: 'form-msg' }); const cardsGrid = el('div', { class: 'grid-2' }); - const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action', hidden: true }, 'Cancel Broadcast'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger', hidden: true }, 'Cancel Broadcast'); let activeJobId: string | null = null; cancelBtn.addEventListener('click', async () => { if (!activeJobId) return; @@ -1099,7 +1226,7 @@ export async function renderWorkflowsView( ); } - if (unsubWfWs) unsubWfWs(); + releaseWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return; try { @@ -1134,20 +1261,77 @@ export async function renderWorkflowsView( cancelBtn.hidden = true; msgEl.className = 'form-msg ok-text'; msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`; + void loadBroadcastHistory(); } } catch { // Ignore meta parse error } }); - wsClient.subscribe([`stream:${activeJobId}`]); + unsubWfChannel = wsClient.subscribe([`stream:${activeJobId}`]); } catch (err) { msgEl.className = 'form-msg err-text'; msgEl.textContent = extractErrorMessage(err); } }); + const histPanel = el('section', { class: 'panel panel-region' }); + const loadBroadcastHistory = async () => { + histPanel.replaceChildren(el('h2', {}, 'Broadcast History')); + try { + const hRes = await apiFetch<{ + jobs: Array<{ + jobId: string; + snippetId?: string; + command: string; + createdAt: number; + finishedAt: number | null; + done: boolean; + cancelled: boolean; + targets: Array<{ status: string }>; + }>; + }>('/api/workflows/broadcast/history?limit=25'); + if (hRes.jobs.length === 0) { + histPanel.append(el('p', { class: 'muted' }, 'No past fleet broadcasts recorded yet.')); + return; + } + const tbl = el('table'); + tbl.append( + el('thead', {}, el('tr', {}, el('th', {}, 'Job ID'), el('th', {}, 'Command / Snippet'), el('th', {}, 'Result'), el('th', {}, 'Started'), el('th', {}, 'Export'))), + ); + const tbody = el('tbody'); + for (const j of hRes.jobs) { + const okCount = j.targets.filter((t) => t.status === 'ok').length; + tbody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, j.jobId), + el('td', { class: 'mono' }, j.snippetId ? `[${j.snippetId}] ${j.command.slice(0, 50)}` : j.command.slice(0, 60)), + el('td', { class: 'mono' }, `${okCount}/${j.targets.length} ok${j.cancelled ? ' (cancelled)' : ''}`), + el('td', { class: 'mono' }, fmtTime(j.createdAt)), + el( + 'td', + {}, + el( + 'div', + { class: 'row' }, + el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=json`, class: 'btn btn-sm', download: '' }, 'JSON'), + el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=csv`, class: 'btn btn-sm', download: '' }, 'CSV'), + ), + ), + ), + ); + } + tbl.append(tbody); + histPanel.append(el('div', { class: 'table-wrap' }, tbl)); + } catch (err) { + histPanel.append(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }; + panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form); - root.append(panel, cardsGrid); + root.append(panel, cardsGrid, histPanel); + void loadBroadcastHistory(); return; }