360 lines
15 KiB
TypeScript
360 lines
15 KiB
TypeScript
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<void>,
|
|
): Promise<void> {
|
|
const settingsObj = (state.overview?.settings ?? {}) as Record<string, unknown>;
|
|
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);
|
|
}
|