Compare commits
10 commits
55948591db
...
b12df1e2d7
| Author | SHA1 | Date | |
|---|---|---|---|
| b12df1e2d7 | |||
| 6dcfa81925 | |||
| 01aae91982 | |||
| 076df61f4d | |||
| fbc1eb94e0 | |||
| 413053182b | |||
| 3791f83bf6 | |||
| 41e79c3df3 | |||
| 7272ad58bd | |||
| f21699963f |
44 changed files with 11018 additions and 137 deletions
|
|
@ -2,6 +2,11 @@ import fs from 'node:fs';
|
|||
import path from 'node:path';
|
||||
import readline from 'node:readline/promises';
|
||||
import { parseArgs } from 'node:util';
|
||||
import {
|
||||
createBackupBundle,
|
||||
restoreBackupBundle,
|
||||
verifyBackupSummaryOnly,
|
||||
} from '../server/security/backup.js';
|
||||
import { EmergencyRecoveryService } from '../server/security/recovery-store.js';
|
||||
import { VaultService } from '../server/security/vault.js';
|
||||
|
||||
|
|
@ -14,12 +19,42 @@ Commands:
|
|||
--current-key-file <path> Path to file containing current 32-byte key
|
||||
--new-key-out <path> Optional output file (0600) for generated key
|
||||
|
||||
Phase 5 commands (scheduled):
|
||||
backup | verify-backup | restore
|
||||
backup Create an AES-256-GCM .gcoord.enc portable backup bundle
|
||||
--out <path.gcoord.enc> Output bundle path (required)
|
||||
--data-dir <path> Data directory (default: GCOORD_DATA_DIR or ./data)
|
||||
--key-file <path> Path to 32-byte Vault master key (default mode)
|
||||
--passphrase-file <path> Path to passphrase file (overrides key-file using scrypt)
|
||||
|
||||
verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data
|
||||
<path.gcoord.enc> Backup bundle path (or --bundle <path>)
|
||||
--key-file <path> Path to 32-byte master key
|
||||
--passphrase-file <path> Path to backup passphrase file
|
||||
--vault-key-file <path> Optional Vault master key to also decrypt/verify vault.enc
|
||||
--json Print verification summary as JSON
|
||||
|
||||
restore Atomically restore config/, vault.enc, known_hosts, and alert_silences
|
||||
<path.gcoord.enc> Backup bundle path (or --bundle <path>)
|
||||
--data-dir <path> Target data directory (default: GCOORD_DATA_DIR or ./data)
|
||||
--key-file <path> Path to 32-byte master key
|
||||
--passphrase-file <path> Path to backup passphrase file
|
||||
--vault-key-file <path> Optional Vault master key if backup used a passphrase
|
||||
`);
|
||||
}
|
||||
|
||||
async function readCurrentKey(keyFile?: string): Promise<string> {
|
||||
async function promptHiddenOrLine(promptText: string): Promise<string> {
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stderr,
|
||||
});
|
||||
try {
|
||||
const answer = await rl.question(promptText);
|
||||
return answer.trim();
|
||||
} finally {
|
||||
rl.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function readCurrentKey(keyFile?: string, dataDir?: string): Promise<string> {
|
||||
if (keyFile) {
|
||||
return fs.readFileSync(keyFile, 'utf8').trim();
|
||||
}
|
||||
|
|
@ -29,16 +64,42 @@ async function readCurrentKey(keyFile?: string): Promise<string> {
|
|||
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
|
||||
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
|
||||
}
|
||||
const rl = readline.createInterface({
|
||||
input: process.stdin,
|
||||
output: process.stderr,
|
||||
});
|
||||
try {
|
||||
const answer = await rl.question('Enter current 32-byte vault master key (hex or base64): ');
|
||||
return answer.trim();
|
||||
} finally {
|
||||
rl.close();
|
||||
if (dataDir) {
|
||||
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
|
||||
if (fs.existsSync(localKeyFile)) {
|
||||
return fs.readFileSync(localKeyFile, 'utf8').trim();
|
||||
}
|
||||
}
|
||||
return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): ');
|
||||
}
|
||||
|
||||
function readOptionalKeyNonInteractive(keyFile?: string, dataDir?: string): string | undefined {
|
||||
if (keyFile) {
|
||||
return fs.readFileSync(keyFile, 'utf8').trim();
|
||||
}
|
||||
if (process.env.GCOORD_MASTER_KEY?.trim()) {
|
||||
return process.env.GCOORD_MASTER_KEY.trim();
|
||||
}
|
||||
if (fs.existsSync('/run/secrets/gcoord_master_key')) {
|
||||
return fs.readFileSync('/run/secrets/gcoord_master_key', 'utf8').trim();
|
||||
}
|
||||
if (dataDir) {
|
||||
const localKeyFile = path.join(path.resolve(dataDir), 'vault.key');
|
||||
if (fs.existsSync(localKeyFile)) {
|
||||
return fs.readFileSync(localKeyFile, 'utf8').trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readOptionalPassphrase(passphraseFile?: string): string | undefined {
|
||||
if (passphraseFile) {
|
||||
return fs.readFileSync(passphraseFile, 'utf8').trim();
|
||||
}
|
||||
if (process.env.GCOORD_BACKUP_PASSPHRASE?.trim()) {
|
||||
return process.env.GCOORD_BACKUP_PASSPHRASE.trim();
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function runRotateKey(args: string[]): Promise<number> {
|
||||
|
|
@ -89,6 +150,147 @@ async function runRotateKey(args: string[]): Promise<number> {
|
|||
return 0;
|
||||
}
|
||||
|
||||
async function runBackup(args: string[]): Promise<number> {
|
||||
const parsed = parseArgs({
|
||||
args,
|
||||
options: {
|
||||
out: { type: 'string' },
|
||||
'data-dir': { type: 'string' },
|
||||
'key-file': { type: 'string' },
|
||||
'passphrase-file': { type: 'string' },
|
||||
},
|
||||
allowPositionals: true,
|
||||
});
|
||||
|
||||
const outRaw = parsed.values.out ?? parsed.positionals[0];
|
||||
if (!outRaw) {
|
||||
console.error('Error: --out <path.gcoord.enc> is required');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const dataDir = path.resolve(
|
||||
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data',
|
||||
);
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
const masterKey = passphrase
|
||||
? readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir)
|
||||
: await readCurrentKey(parsed.values['key-file'], dataDir);
|
||||
|
||||
const result = createBackupBundle({
|
||||
dataDir,
|
||||
masterKey,
|
||||
passphrase,
|
||||
});
|
||||
|
||||
const outPath = path.resolve(outRaw);
|
||||
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
||||
const tmpPath = `${outPath}.tmp.${process.pid}.${Date.now()}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, result.serialized, 'utf8');
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
fs.renameSync(tmpPath, outPath);
|
||||
fs.chmodSync(outPath, 0o600);
|
||||
|
||||
console.log(
|
||||
`Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function runVerifyBackup(args: string[]): Promise<number> {
|
||||
const parsed = parseArgs({
|
||||
args,
|
||||
options: {
|
||||
bundle: { type: 'string' },
|
||||
'key-file': { type: 'string' },
|
||||
'passphrase-file': { type: 'string' },
|
||||
'vault-key-file': { type: 'string' },
|
||||
json: { type: 'boolean', default: false },
|
||||
},
|
||||
allowPositionals: true,
|
||||
});
|
||||
|
||||
const bundleArg = parsed.values.bundle ?? parsed.positionals[0];
|
||||
if (!bundleArg) {
|
||||
console.error('Error: backup bundle path is required');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']);
|
||||
if (!passphrase && !masterKey) {
|
||||
const rawMeta = JSON.parse(rawBuf.toString('utf8')) as { kdf?: string };
|
||||
if (rawMeta.kdf === 'scrypt') {
|
||||
throw new Error('Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)');
|
||||
}
|
||||
masterKey = await readCurrentKey(undefined);
|
||||
}
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']);
|
||||
|
||||
const summary = verifyBackupSummaryOnly(rawBuf, {
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
});
|
||||
|
||||
if (parsed.values.json) {
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
} else {
|
||||
console.log(
|
||||
`Backup verified cleanly (createdAt=${summary.createdAt}, kdf=${summary.kdf}, configs=${summary.configFileCount}, vault=${summary.hasVault ? (summary.vaultVerified ? `verified(${summary.vaultCredentialCount ?? 0} creds)` : 'unverified') : 'none'}, knownHosts=${summary.knownHostsCount})`,
|
||||
);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function runRestore(args: string[]): Promise<number> {
|
||||
const parsed = parseArgs({
|
||||
args,
|
||||
options: {
|
||||
bundle: { type: 'string' },
|
||||
'data-dir': { type: 'string' },
|
||||
'key-file': { type: 'string' },
|
||||
'passphrase-file': { type: 'string' },
|
||||
'vault-key-file': { type: 'string' },
|
||||
},
|
||||
allowPositionals: true,
|
||||
});
|
||||
|
||||
const bundleArg = parsed.values.bundle ?? parsed.positionals[0];
|
||||
if (!bundleArg) {
|
||||
console.error('Error: backup bundle path is required');
|
||||
return 1;
|
||||
}
|
||||
|
||||
const dataDir = path.resolve(
|
||||
parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data',
|
||||
);
|
||||
const rawBuf = fs.readFileSync(path.resolve(bundleArg));
|
||||
const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']);
|
||||
let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir);
|
||||
if (!passphrase && !masterKey) {
|
||||
masterKey = await readCurrentKey(undefined, dataDir);
|
||||
}
|
||||
const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir);
|
||||
|
||||
const { summary } = restoreBackupBundle(rawBuf, {
|
||||
dataDir,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
});
|
||||
|
||||
console.log(
|
||||
`Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`,
|
||||
);
|
||||
return 0;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const [command, ...rest] = process.argv.slice(2);
|
||||
if (!command || command === '-h' || command === '--help') {
|
||||
|
|
@ -99,10 +301,14 @@ async function main(): Promise<void> {
|
|||
if (command === 'rotate-key') {
|
||||
process.exit(await runRotateKey(rest));
|
||||
}
|
||||
|
||||
if (command === 'backup' || command === 'verify-backup' || command === 'restore') {
|
||||
console.error(`Command "${command}" is scheduled for Phase 5 (.gcoord.enc portable backup).`);
|
||||
process.exit(2);
|
||||
if (command === 'backup') {
|
||||
process.exit(await runBackup(rest));
|
||||
}
|
||||
if (command === 'verify-backup') {
|
||||
process.exit(await runVerifyBackup(rest));
|
||||
}
|
||||
if (command === 'restore') {
|
||||
process.exit(await runRestore(rest));
|
||||
}
|
||||
|
||||
console.error(`Unknown command: ${command}`);
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import zlib from 'node:zlib';
|
|||
import esbuild from 'esbuild';
|
||||
|
||||
const CORE_BUDGET_BYTES = 50 * 1024;
|
||||
const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024;
|
||||
const clientDir = path.resolve('src/client');
|
||||
const outDir = path.resolve('dist/public');
|
||||
|
||||
|
|
@ -65,6 +66,11 @@ async function buildClient(): Promise<void> {
|
|||
const cBuf = fs.readFileSync(path.join(chunksDir, chunk));
|
||||
const cGz = zlib.gzipSync(cBuf, { level: 9 });
|
||||
console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B`);
|
||||
if (!chunk.startsWith('terminal-view-') && cGz.length >= LAZY_CHUNK_BUDGET_BYTES) {
|
||||
throw new Error(
|
||||
`Lazy chunk ${chunk} (${cGz.length}B gzipped) exceeded 20KB budget (${LAZY_CHUNK_BUDGET_BYTES}B)`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -150,7 +150,7 @@ body {
|
|||
|
||||
.panel-region {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 320px auto 260px;
|
||||
contain-intrinsic-size: auto none auto 260px;
|
||||
}
|
||||
|
||||
@supports not (content-visibility: auto) {
|
||||
|
|
@ -628,6 +628,35 @@ dialog::backdrop {
|
|||
background: var(--bg-elevated);
|
||||
}
|
||||
|
||||
dialog:modal {
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
dialog::backdrop {
|
||||
overflow: hidden;
|
||||
overscroll-behavior: contain;
|
||||
background: rgba(0, 0, 0, 0.65);
|
||||
}
|
||||
|
||||
dialog.ai-drawer {
|
||||
border: 1px solid var(--border);
|
||||
background: var(--bg-panel);
|
||||
color: var(--fg);
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
dialog.ai-drawer[open] {
|
||||
margin: 0 0 0 auto;
|
||||
width: min(560px, 100vw);
|
||||
max-width: 100vw;
|
||||
height: 100dvh;
|
||||
max-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
border-left: 1px solid var(--accent);
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.metric-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
|
|
@ -639,15 +668,17 @@ dialog::backdrop {
|
|||
}
|
||||
|
||||
.btn,
|
||||
.btn-sm,
|
||||
.nav-link,
|
||||
.touch-key,
|
||||
input,
|
||||
select {
|
||||
select,
|
||||
.input-sm {
|
||||
min-height: 44px;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
padding-bottom: 62px;
|
||||
padding-bottom: calc(64px + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
|
||||
.primary-nav {
|
||||
|
|
@ -658,7 +689,7 @@ dialog::backdrop {
|
|||
z-index: 20;
|
||||
flex-wrap: nowrap;
|
||||
overflow-x: auto;
|
||||
padding: 4px 6px;
|
||||
padding: 4px 6px calc(4px + env(safe-area-inset-bottom, 0px));
|
||||
border-top: 1px solid var(--border);
|
||||
border-bottom: none;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -83,3 +83,54 @@
|
|||
accent-color: var(--accent);
|
||||
scrollbar-color: var(--border) var(--bg);
|
||||
}
|
||||
|
||||
[data-theme="solarized-dark"] {
|
||||
color-scheme: dark;
|
||||
--bg: #002b36;
|
||||
--bg-panel: #073642;
|
||||
--bg-elevated: #0d4352;
|
||||
--fg: #eee8d5;
|
||||
--fg-muted: #93a1a1;
|
||||
--border: #265966;
|
||||
--accent: #2aa198;
|
||||
--accent-fg: #00222b;
|
||||
--ok: #859900;
|
||||
--warn: #b58900;
|
||||
--err: #dc322f;
|
||||
accent-color: var(--accent);
|
||||
scrollbar-color: var(--border) var(--bg);
|
||||
}
|
||||
|
||||
[data-theme="tokyo-night"] {
|
||||
color-scheme: dark;
|
||||
--bg: #1a1b26;
|
||||
--bg-panel: #1f2335;
|
||||
--bg-elevated: #292e42;
|
||||
--fg: #c0caf5;
|
||||
--fg-muted: #7aa2f7;
|
||||
--border: #3b4261;
|
||||
--accent: #7dcfff;
|
||||
--accent-fg: #15161e;
|
||||
--ok: #9ece6a;
|
||||
--warn: #e0af68;
|
||||
--err: #f7768e;
|
||||
accent-color: var(--accent);
|
||||
scrollbar-color: var(--border) var(--bg);
|
||||
}
|
||||
|
||||
[data-theme="high-contrast"] {
|
||||
color-scheme: dark;
|
||||
--bg: #000000;
|
||||
--bg-panel: #080808;
|
||||
--bg-elevated: #141414;
|
||||
--fg: #ffffff;
|
||||
--fg-muted: #cccccc;
|
||||
--border: #ffffff;
|
||||
--accent: #00ff00;
|
||||
--accent-fg: #000000;
|
||||
--ok: #00ff00;
|
||||
--warn: #ffff00;
|
||||
--err: #ff3333;
|
||||
accent-color: var(--accent);
|
||||
scrollbar-color: var(--border) var(--bg);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@
|
|||
<span id="ws-badge" class="badge badge-warn">[OFFLINE]</span>
|
||||
<span id="vault-badge" class="badge badge-warn">[VAULT]</span>
|
||||
<span id="stepup-badge" class="badge badge-ok" hidden></span>
|
||||
<a id="alerts-badge" href="#alerts" class="badge badge-err" hidden>[ALERTS: 0]</a>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
<label class="sr-only" for="theme-select">Theme</label>
|
||||
|
|
@ -28,6 +29,9 @@
|
|||
<option value="nord-dark">nord-dark</option>
|
||||
<option value="gruvbox-dark">gruvbox-dark</option>
|
||||
<option value="paper-light">paper-light</option>
|
||||
<option value="solarized-dark">solarized-dark</option>
|
||||
<option value="tokyo-night">tokyo-night</option>
|
||||
<option value="high-contrast">high-contrast</option>
|
||||
</select>
|
||||
<button id="safe-toggle-btn" type="button" class="btn btn-sm" aria-pressed="false">[SAFE: OFF]</button>
|
||||
<button id="panic-btn" type="button" class="btn btn-sm btn-danger">[PANIC LOCK]</button>
|
||||
|
|
|
|||
|
|
@ -26,7 +26,6 @@ import {
|
|||
patchDashboardServerTick,
|
||||
renderDashboardView,
|
||||
} from './views/dashboard-view.js';
|
||||
import { renderSectionShell } from './views/section-shells.js';
|
||||
import { renderServerDetailView } from './views/server-detail-view.js';
|
||||
import { renderSettingsView } from './views/settings-view.js';
|
||||
import { renderVaultView } from './views/vault-view.js';
|
||||
|
|
@ -54,6 +53,7 @@ const state: ClientState = {
|
|||
safeMode: false,
|
||||
defaultMobileSafeMode: true,
|
||||
elevatedUntil: null,
|
||||
activeAlertCount: 0,
|
||||
theme: localStorage.getItem(THEME_STORAGE_KEY) ?? 'phosphor-green',
|
||||
route: 'dashboard',
|
||||
overview: null,
|
||||
|
|
@ -98,6 +98,7 @@ function updateTopBarUi(): void {
|
|||
const safeBtn = document.getElementById('safe-toggle-btn')!;
|
||||
const themeSelect = document.getElementById('theme-select') as HTMLSelectElement;
|
||||
const stepupBadge = document.getElementById('stepup-badge')!;
|
||||
const alertsBadge = document.getElementById('alerts-badge')!;
|
||||
const banner = document.getElementById('global-banner')!;
|
||||
|
||||
topbar.hidden = !state.authenticated;
|
||||
|
|
@ -133,6 +134,13 @@ function updateTopBarUi(): void {
|
|||
stepupBadge.hidden = true;
|
||||
}
|
||||
|
||||
if (state.authenticated && state.activeAlertCount > 0) {
|
||||
alertsBadge.hidden = false;
|
||||
alertsBadge.textContent = `[ALERTS: ${state.activeAlertCount}]`;
|
||||
} else {
|
||||
alertsBadge.hidden = true;
|
||||
}
|
||||
|
||||
const activeNavRoute = state.route === 'server-detail' ? 'dashboard' : state.route;
|
||||
for (const link of nav.querySelectorAll('.nav-link')) {
|
||||
const r = link.getAttribute('data-route');
|
||||
|
|
@ -150,7 +158,12 @@ function updateTopBarUi(): void {
|
|||
}
|
||||
|
||||
async function refreshOverview(): Promise<void> {
|
||||
state.overview = await apiFetch<ConfigOverview>('/api/config/overview');
|
||||
const [overview, alertsSummary] = await Promise.all([
|
||||
apiFetch<ConfigOverview>('/api/config/overview'),
|
||||
apiFetch<{ activeCount: number }>('/api/alerts?limit=1').catch(() => ({ activeCount: 0 })),
|
||||
]);
|
||||
state.overview = overview;
|
||||
state.activeAlertCount = alertsSummary.activeCount ?? 0;
|
||||
updateTopBarUi();
|
||||
}
|
||||
|
||||
|
|
@ -187,7 +200,7 @@ async function renderCurrentView(): Promise<void> {
|
|||
return;
|
||||
}
|
||||
if (route === 'config') {
|
||||
await renderConfigView(root, state.overview!, async () => {
|
||||
await renderConfigView(root, state.overview!, state, wsClient, async () => {
|
||||
await refreshOverview();
|
||||
await renderCurrentView();
|
||||
});
|
||||
|
|
@ -233,9 +246,14 @@ async function renderCurrentView(): Promise<void> {
|
|||
await renderSystemsView(root, state, wsClient);
|
||||
return;
|
||||
}
|
||||
|
||||
if (route === 'workflows' || route === 'alerts') {
|
||||
renderSectionShell(root, route, state.overview!);
|
||||
if (route === 'workflows') {
|
||||
const { renderWorkflowsView } = await import('./views/workflows-view.js');
|
||||
await renderWorkflowsView(root, state, wsClient);
|
||||
return;
|
||||
}
|
||||
if (route === 'alerts') {
|
||||
const { renderAlertsView } = await import('./views/alerts-view.js');
|
||||
await renderAlertsView(root, state, wsClient);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -406,6 +424,12 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||
if (needsRefresh) {
|
||||
void renderCurrentView();
|
||||
}
|
||||
} else if (frame.type === 'alerts:update') {
|
||||
state.activeAlertCount = frame.activeCount;
|
||||
updateTopBarUi();
|
||||
if (state.authenticated && state.route === 'alerts') {
|
||||
void renderCurrentView();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -103,6 +103,7 @@ export interface ClientState {
|
|||
safeMode: boolean;
|
||||
defaultMobileSafeMode: boolean;
|
||||
elevatedUntil: number | null;
|
||||
activeAlertCount: number;
|
||||
theme: string;
|
||||
route: RouteId;
|
||||
selectedServerId?: string;
|
||||
|
|
@ -116,6 +117,28 @@ export interface ClientState {
|
|||
export const SAFE_MODE_STORAGE_KEY = 'gcoord_device_safe_mode';
|
||||
export const THEME_STORAGE_KEY = 'gcoord_theme';
|
||||
|
||||
export const CLIENT_THEME_IDS = [
|
||||
'phosphor-green',
|
||||
'amber-term',
|
||||
'nord-dark',
|
||||
'gruvbox-dark',
|
||||
'paper-light',
|
||||
'solarized-dark',
|
||||
'tokyo-night',
|
||||
'high-contrast',
|
||||
] as const;
|
||||
|
||||
const THEME_BG_COLORS: Record<string, string> = {
|
||||
'phosphor-green': '#080c09',
|
||||
'amber-term': '#0d0904',
|
||||
'nord-dark': '#1e222a',
|
||||
'gruvbox-dark': '#1d2021',
|
||||
'paper-light': '#f6f4ee',
|
||||
'solarized-dark': '#002b36',
|
||||
'tokyo-night': '#1a1b26',
|
||||
'high-contrast': '#000000',
|
||||
};
|
||||
|
||||
export function initialDeviceSafeMode(defaultMobileSafeMode: boolean): boolean {
|
||||
const stored = localStorage.getItem(SAFE_MODE_STORAGE_KEY);
|
||||
if (stored === '1') return true;
|
||||
|
|
@ -126,6 +149,30 @@ export function initialDeviceSafeMode(defaultMobileSafeMode: boolean): boolean {
|
|||
export function applyTheme(theme: string): void {
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem(THEME_STORAGE_KEY, theme);
|
||||
const meta = document.querySelector('meta[name="theme-color"]');
|
||||
if (meta) {
|
||||
meta.setAttribute('content', THEME_BG_COLORS[theme] ?? '#080c09');
|
||||
}
|
||||
}
|
||||
|
||||
export function isAiEnabled(state: ClientState): boolean {
|
||||
const ai = state.overview?.settings?.ai as { enabled?: boolean } | undefined;
|
||||
return Boolean(ai?.enabled);
|
||||
}
|
||||
|
||||
export function appendBoundedStreamText(
|
||||
preEl: { textContent: string | null },
|
||||
chunk: string,
|
||||
maxChars = 65_536,
|
||||
): void {
|
||||
const combined = `${preEl.textContent ?? ''}${chunk}`;
|
||||
if (combined.length <= maxChars) {
|
||||
preEl.textContent = combined;
|
||||
return;
|
||||
}
|
||||
const marker = '...[truncated older stream output]...\n';
|
||||
const keep = Math.max(256, maxChars - marker.length);
|
||||
preEl.textContent = `${marker}${combined.slice(-keep)}`;
|
||||
}
|
||||
|
||||
export function el<K extends keyof HTMLElementTagNameMap>(
|
||||
|
|
|
|||
352
src/client/ts/views/ai-drawer.ts
Normal file
352
src/client/ts/views/ai-drawer.ts
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import {
|
||||
appendBoundedStreamText,
|
||||
el,
|
||||
extractErrorMessage,
|
||||
type ClientState,
|
||||
} from '../state.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup';
|
||||
export type ClientAiDraftKind =
|
||||
| 'workflow'
|
||||
| 'system'
|
||||
| 'snippet'
|
||||
| 'server'
|
||||
| 'alerts'
|
||||
| 'settings';
|
||||
|
||||
export interface OpenAiDrawerOptions {
|
||||
state: ClientState;
|
||||
wsClient: MultiplexWsClient;
|
||||
surface: ClientAiSurface;
|
||||
title?: string;
|
||||
initialPrompt?: string;
|
||||
contextText?: string;
|
||||
serverId?: string;
|
||||
targetPath?: string;
|
||||
defaultDraftKind?: ClientAiDraftKind;
|
||||
onInsertTerminalText?: (cmd: string) => void;
|
||||
onApplied?: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
interface PreviewResponse {
|
||||
enabled: boolean;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
surface: ClientAiSurface;
|
||||
defaultDraftKind?: ClientAiDraftKind;
|
||||
systemPrompt: string;
|
||||
inventorySummary: string;
|
||||
sanitizedContext: string;
|
||||
redactedCount: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
function extractLastFencedBlock(text: string, langPattern: RegExp): string | null {
|
||||
const re = /```([a-zA-Z0-9_-]*)\s*\r?\n([\s\S]*?)```/g;
|
||||
let match: RegExpExecArray | null;
|
||||
let last: string | null = null;
|
||||
while ((match = re.exec(text)) !== null) {
|
||||
const lang = match[1] ?? '';
|
||||
if (langPattern.test(lang)) {
|
||||
last = match[2]!.trim();
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise<void> {
|
||||
const existing = document.getElementById('ai-drawer-dialog');
|
||||
if (existing) existing.remove();
|
||||
|
||||
const dialog = document.createElement('dialog');
|
||||
dialog.id = 'ai-drawer-dialog';
|
||||
dialog.className = 'ai-drawer';
|
||||
dialog.setAttribute('aria-labelledby', 'ai-drawer-title');
|
||||
|
||||
const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close');
|
||||
const titleEl = el(
|
||||
'h1',
|
||||
{ id: 'ai-drawer-title' },
|
||||
opts.title ?? `AI Assistant (${opts.surface})`,
|
||||
);
|
||||
|
||||
const previewSummary = el('summary', { class: 'muted mono' }, 'Loading sanitized context preview...');
|
||||
const previewPre = el('pre', { class: 'stream-log mono', style: 'max-height:180px' }, '');
|
||||
const previewDetails = el('details', { class: 'panel', style: 'margin:0' }, previewSummary, previewPre);
|
||||
|
||||
const streamPre = el(
|
||||
'pre',
|
||||
{ class: 'stream-log mono', style: 'flex:1 1 auto;min-height:160px;max-height:none;margin:0' },
|
||||
'Ask the assistant to draft a schema-checked JSON config, snippet, or debug log error.\nAll drafts require explicit review before Apply.\n',
|
||||
);
|
||||
|
||||
const draftBar = el('div', { class: 'stack', hidden: true });
|
||||
const draftKindSel = el(
|
||||
'select',
|
||||
{ class: 'input-sm', 'aria-label': 'Draft schema type' },
|
||||
...(['workflow', 'system', 'snippet', 'server', 'alerts', 'settings'] as const).map((k) =>
|
||||
el('option', { value: k, selected: opts.defaultDraftKind === k ? true : undefined }, k),
|
||||
),
|
||||
);
|
||||
const draftOutputBox = el('div', { class: 'stack' });
|
||||
|
||||
const promptArea = el('textarea', {
|
||||
rows: 3,
|
||||
autofocus: true,
|
||||
placeholder: 'Describe what you want to create or diagnose (no secrets sent)...',
|
||||
});
|
||||
if (opts.initialPrompt) promptArea.value = opts.initialPrompt;
|
||||
|
||||
const statusLine = el('p', { class: 'form-msg muted' }, '');
|
||||
const sendBtn = el('button', { type: 'submit', class: 'btn btn-primary btn-sm' }, 'Send');
|
||||
const stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Stop');
|
||||
|
||||
const history: Array<{ role: 'user' | 'assistant'; content: string }> = [];
|
||||
let activeChatId: string | null = null;
|
||||
let currentReply = '';
|
||||
let unsubWs: (() => void) | null = null;
|
||||
|
||||
const cleanup = () => {
|
||||
if (activeChatId) {
|
||||
opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId });
|
||||
activeChatId = null;
|
||||
}
|
||||
if (unsubWs) {
|
||||
unsubWs();
|
||||
unsubWs = null;
|
||||
}
|
||||
dialog.returnValue = '';
|
||||
dialog.remove();
|
||||
};
|
||||
|
||||
closeBtn.addEventListener('click', () => {
|
||||
if (dialog.open) dialog.close();
|
||||
});
|
||||
dialog.addEventListener('close', cleanup);
|
||||
|
||||
const refreshDraftActions = () => {
|
||||
draftBar.replaceChildren();
|
||||
draftOutputBox.replaceChildren();
|
||||
const jsonBlock = extractLastFencedBlock(currentReply, /^(?:json)?$/i);
|
||||
const shBlock = extractLastFencedBlock(currentReply, /^(?:sh|bash|zsh|shell)$/i);
|
||||
if (!jsonBlock && (!shBlock || !opts.onInsertTerminalText)) {
|
||||
draftBar.hidden = true;
|
||||
return;
|
||||
}
|
||||
draftBar.hidden = false;
|
||||
const btnRow = el('div', { class: 'row' });
|
||||
|
||||
if (shBlock && opts.onInsertTerminalText) {
|
||||
const insertBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-primary mutating-action' },
|
||||
'Insert into Prompt (No Enter)',
|
||||
);
|
||||
insertBtn.addEventListener('click', () => {
|
||||
const cleanCmd = shBlock.replace(/[\r\n]+$/, '');
|
||||
opts.onInsertTerminalText!(cleanCmd);
|
||||
if (dialog.open) dialog.close();
|
||||
});
|
||||
btnRow.append(insertBtn);
|
||||
}
|
||||
|
||||
if (jsonBlock) {
|
||||
const validateBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Validate JSON Draft');
|
||||
validateBtn.addEventListener('click', async () => {
|
||||
draftOutputBox.replaceChildren(el('p', { class: 'muted mono' }, 'Validating against Zod schema...'));
|
||||
try {
|
||||
const res = await apiFetch<
|
||||
| {
|
||||
valid: true;
|
||||
kind: string;
|
||||
targetPath: string;
|
||||
normalizedJson: string;
|
||||
diffLines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>;
|
||||
}
|
||||
| { valid: false; issues: Array<{ path: string; message: string }> }
|
||||
>('/api/ai/validate-draft', {
|
||||
method: 'POST',
|
||||
body: { kind: draftKindSel.value, jsonText: jsonBlock },
|
||||
});
|
||||
|
||||
draftOutputBox.replaceChildren();
|
||||
if (!res.valid) {
|
||||
draftOutputBox.append(el('p', { class: 'err-text' }, 'Schema validation failed:'));
|
||||
for (const iss of res.issues) {
|
||||
draftOutputBox.append(el('div', { class: 'mono err-text' }, ` ${iss.path}: ${iss.message}`));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const diffPreview = res.diffLines
|
||||
.slice(0, 80)
|
||||
.map((l) => `${l.type === 'add' ? '+' : l.type === 'del' ? '-' : ' '} ${l.text}`)
|
||||
.join('\n');
|
||||
const applyBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-primary mutating-action' },
|
||||
`Apply to ${res.targetPath}`,
|
||||
);
|
||||
applyBtn.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog(
|
||||
'dialog-confirm',
|
||||
`Apply validated AI draft to "${res.targetPath}"?`,
|
||||
);
|
||||
if (!ok) return;
|
||||
await apiFetch('/api/config/file', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
path: res.targetPath,
|
||||
content: res.normalizedJson,
|
||||
summary: `Applied AI ${res.kind} draft`,
|
||||
},
|
||||
});
|
||||
await opts.onApplied?.();
|
||||
if (dialog.open) dialog.close();
|
||||
});
|
||||
|
||||
draftOutputBox.append(
|
||||
el('div', { class: 'row-between' }, el('span', { class: 'badge badge-ok' }, `[VALID] -> ${res.targetPath}`), applyBtn),
|
||||
el('pre', { class: 'diff-body mono', style: 'max-height:180px' }, diffPreview),
|
||||
);
|
||||
} catch (err) {
|
||||
draftOutputBox.replaceChildren(el('p', { class: 'err-text' }, extractErrorMessage(err)));
|
||||
}
|
||||
});
|
||||
btnRow.append(draftKindSel, validateBtn);
|
||||
}
|
||||
|
||||
draftBar.append(btnRow, draftOutputBox);
|
||||
};
|
||||
|
||||
unsubWs = opts.wsClient.onFrame((frame: ServerWsFrame) => {
|
||||
if (frame.type !== 'ai:delta' || frame.chatId !== activeChatId) return;
|
||||
if (frame.chunk) {
|
||||
currentReply += frame.chunk;
|
||||
appendBoundedStreamText(streamPre, frame.chunk);
|
||||
streamPre.scrollTop = streamPre.scrollHeight;
|
||||
}
|
||||
if (frame.error) {
|
||||
statusLine.className = 'form-msg err-text';
|
||||
statusLine.textContent = frame.error;
|
||||
}
|
||||
if (frame.done) {
|
||||
if (currentReply) history.push({ role: 'assistant', content: currentReply });
|
||||
appendBoundedStreamText(streamPre, '\n');
|
||||
activeChatId = null;
|
||||
sendBtn.disabled = false;
|
||||
stopBtn.disabled = true;
|
||||
if (!frame.error) {
|
||||
statusLine.className = 'form-msg ok-text';
|
||||
statusLine.textContent = 'Response complete. Review any extracted draft below.';
|
||||
}
|
||||
refreshDraftActions();
|
||||
}
|
||||
});
|
||||
|
||||
stopBtn.addEventListener('click', async () => {
|
||||
if (!activeChatId) return;
|
||||
const cid = activeChatId;
|
||||
opts.wsClient.send({ type: 'ai:cancel', chatId: cid });
|
||||
await apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
stopBtn.disabled = true;
|
||||
statusLine.textContent = 'Cancelling...';
|
||||
});
|
||||
|
||||
const form = el(
|
||||
'form',
|
||||
{ class: 'stack', style: 'margin-top:4px' },
|
||||
promptArea,
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
statusLine,
|
||||
el('div', { class: 'row' }, stopBtn, sendBtn),
|
||||
),
|
||||
);
|
||||
|
||||
form.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
const prompt = promptArea.value.trim();
|
||||
if (!prompt || activeChatId) return;
|
||||
promptArea.value = '';
|
||||
history.push({ role: 'user', content: prompt });
|
||||
appendBoundedStreamText(streamPre, `\n> ${prompt}\n\n`);
|
||||
currentReply = '';
|
||||
draftBar.hidden = true;
|
||||
sendBtn.disabled = true;
|
||||
stopBtn.disabled = false;
|
||||
statusLine.className = 'form-msg muted';
|
||||
statusLine.textContent = 'Streaming response...';
|
||||
|
||||
try {
|
||||
const started = await apiFetch<{
|
||||
chatId: string;
|
||||
redactedCount: number;
|
||||
truncated: boolean;
|
||||
}>('/api/ai/chat', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
surface: opts.surface,
|
||||
messages: history.slice(-12),
|
||||
contextText: opts.contextText,
|
||||
serverId: opts.serverId,
|
||||
targetPath: opts.targetPath,
|
||||
},
|
||||
});
|
||||
activeChatId = started.chatId;
|
||||
opts.wsClient.subscribe([`ai:${started.chatId}`]);
|
||||
} catch (err) {
|
||||
history.pop();
|
||||
sendBtn.disabled = false;
|
||||
stopBtn.disabled = true;
|
||||
statusLine.className = 'form-msg err-text';
|
||||
statusLine.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
|
||||
dialog.append(
|
||||
el('div', { class: 'row-between' }, titleEl, closeBtn),
|
||||
previewDetails,
|
||||
streamPre,
|
||||
draftBar,
|
||||
form,
|
||||
);
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
|
||||
try {
|
||||
const preview = await apiFetch<PreviewResponse>('/api/ai/context-preview', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
surface: opts.surface,
|
||||
contextText: opts.contextText,
|
||||
serverId: opts.serverId,
|
||||
targetPath: opts.targetPath,
|
||||
},
|
||||
});
|
||||
if (!opts.defaultDraftKind && preview.defaultDraftKind) {
|
||||
draftKindSel.value = preview.defaultDraftKind;
|
||||
}
|
||||
previewSummary.textContent = `Sanitized Context Preview (${preview.redactedCount} redacted${preview.truncated ? ', truncated' : ''}) — model: ${preview.model}`;
|
||||
previewPre.textContent = [
|
||||
preview.systemPrompt,
|
||||
'',
|
||||
'INVENTORY:',
|
||||
preview.inventorySummary,
|
||||
...(preview.sanitizedContext ? ['', 'CONTEXT:', preview.sanitizedContext] : []),
|
||||
].join('\n');
|
||||
if (!preview.enabled) {
|
||||
statusLine.className = 'form-msg warn-text';
|
||||
statusLine.textContent = 'AI Assistant is currently disabled in Settings -> AI Assistant.';
|
||||
}
|
||||
} catch (err) {
|
||||
previewSummary.textContent = `Context preview unavailable: ${extractErrorMessage(err)}`;
|
||||
}
|
||||
}
|
||||
472
src/client/ts/views/alerts-view.ts
Normal file
472
src/client/ts/views/alerts-view.ts
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import {
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
type ClientState,
|
||||
} from '../state.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
interface AlertChannelItem {
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'discord' | 'telegram' | 'ntfy' | 'generic';
|
||||
url?: string;
|
||||
secretRef: string;
|
||||
chatId?: string;
|
||||
topic?: string;
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
interface AlertRuleItem {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system';
|
||||
severity: 'warn' | 'critical';
|
||||
target: { serverId?: string; tags?: string[]; all?: boolean };
|
||||
forConsecutivePolls: number;
|
||||
cooldownSec: number;
|
||||
channelIds: string[];
|
||||
remediationWorkflowId?: string;
|
||||
enabled: boolean;
|
||||
metric?: string;
|
||||
operator?: string;
|
||||
threshold?: number;
|
||||
mountPoint?: string;
|
||||
thresholdPct?: number;
|
||||
offlineSec?: number;
|
||||
probeId?: string;
|
||||
systemId?: string;
|
||||
item?: string;
|
||||
}
|
||||
|
||||
interface MaintenanceWindowItem {
|
||||
id: string;
|
||||
name: string;
|
||||
cron: string;
|
||||
timezone: string;
|
||||
durationMinutes: number;
|
||||
target: { serverId?: string; tags?: string[]; all?: boolean };
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
interface AlertsPayload {
|
||||
alertsConfig: {
|
||||
version: 1;
|
||||
channels: AlertChannelItem[];
|
||||
rules: AlertRuleItem[];
|
||||
maintenanceWindows: MaintenanceWindowItem[];
|
||||
};
|
||||
activeCount: number;
|
||||
activeEvents: Array<{
|
||||
id: string;
|
||||
ruleId: string;
|
||||
serverId: string | null;
|
||||
state: string;
|
||||
severity: string;
|
||||
message: string;
|
||||
webhookStatus: string | null;
|
||||
triggeredAt: number;
|
||||
}>;
|
||||
recentEvents: Array<{
|
||||
id: string;
|
||||
ruleId: string;
|
||||
serverId: string | null;
|
||||
state: string;
|
||||
severity: string;
|
||||
message: string;
|
||||
webhookStatus: string | null;
|
||||
triggeredAt: number;
|
||||
resolvedAt: number | null;
|
||||
}>;
|
||||
silences: Array<{
|
||||
id: string;
|
||||
scopeType: string;
|
||||
targetId: string;
|
||||
reason: string | null;
|
||||
expiresAt: number;
|
||||
}>;
|
||||
activeMaintenanceWindowIds: string[];
|
||||
}
|
||||
|
||||
export async function renderAlertsView(
|
||||
root: HTMLElement,
|
||||
state: ClientState,
|
||||
wsClient: MultiplexWsClient,
|
||||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
const [data, credsRes] = await Promise.all([
|
||||
apiFetch<AlertsPayload>('/api/alerts'),
|
||||
apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials').catch(() => ({
|
||||
credentials: [],
|
||||
})),
|
||||
]);
|
||||
|
||||
state.activeAlertCount = data.activeCount;
|
||||
const cfg = data.alertsConfig;
|
||||
|
||||
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
void renderAlertsView(root, state, wsClient);
|
||||
});
|
||||
const aiHelpBtn = isAiEnabled(state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Setup Helper]')
|
||||
: null;
|
||||
if (aiHelpBtn) {
|
||||
aiHelpBtn.addEventListener('click', async () => {
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state,
|
||||
wsClient,
|
||||
surface: 'setup',
|
||||
title: 'AI Alert Rules & Channels Helper',
|
||||
contextText: JSON.stringify(cfg, null, 2),
|
||||
targetPath: 'alerts.json',
|
||||
defaultDraftKind: 'alerts',
|
||||
onApplied: () => renderAlertsView(root, state, wsClient),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
root.append(
|
||||
el(
|
||||
'section',
|
||||
{ class: 'panel row-between' },
|
||||
el('div', {}, el('h1', {}, `Alerting & Webhooks (${data.activeCount} firing)`), el('p', { class: 'muted' }, `${cfg.rules.length} rules, ${cfg.channels.length} channels, ${cfg.maintenanceWindows.length} maintenance windows, ${data.silences.length} active silences.`)),
|
||||
el('div', { class: 'row' }, ...(aiHelpBtn ? [aiHelpBtn] : []), refreshBtn),
|
||||
),
|
||||
);
|
||||
|
||||
// 1. Firing Incidents + Quick Snooze
|
||||
const firingPanel = el('section', { class: 'panel panel-region' });
|
||||
firingPanel.append(el('h2', {}, `Active Firing Alerts (${data.activeEvents.length})`));
|
||||
if (data.activeEvents.length === 0) {
|
||||
firingPanel.append(el('p', { class: 'ok-text' }, 'All monitored rules are currently healthy.'));
|
||||
} else {
|
||||
for (const evt of data.activeEvents) {
|
||||
const snoozeButtons = (
|
||||
[
|
||||
['Snooze 30m', 'rule', evt.ruleId, 30],
|
||||
['Mute Server 2h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 120],
|
||||
['Mute 12h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 720],
|
||||
] as const
|
||||
).map(([label, scopeType, targetId, durationMinutes]) => {
|
||||
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, label);
|
||||
b.addEventListener('click', async () => {
|
||||
await apiFetch('/api/alerts/silences', {
|
||||
method: 'POST',
|
||||
body: { scopeType, targetId, durationMinutes, reason: `Quick snooze from ${evt.id}` },
|
||||
});
|
||||
await renderAlertsView(root, state, wsClient);
|
||||
});
|
||||
return b;
|
||||
});
|
||||
const diagBtn = isAiEnabled(state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Diagnose]')
|
||||
: null;
|
||||
if (diagBtn) {
|
||||
diagBtn.addEventListener('click', async () => {
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state,
|
||||
wsClient,
|
||||
surface: 'logs',
|
||||
title: `AI Alert Debugger (${evt.ruleId})`,
|
||||
contextText: `Alert ${evt.id} (${evt.severity})\nRule: ${evt.ruleId}\nServer: ${evt.serverId ?? 'hub'}\nMessage: ${evt.message}\nWebhook: ${evt.webhookStatus ?? 'none'}`,
|
||||
serverId: evt.serverId ?? undefined,
|
||||
});
|
||||
});
|
||||
}
|
||||
firingPanel.append(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'alert-box' },
|
||||
el('div', { class: 'row-between' }, el('strong', { class: evt.severity === 'critical' ? 'err-text' : 'warn-text' }, `[${evt.severity.toUpperCase()}] ${evt.ruleId}${evt.serverId ? ` @ ${evt.serverId}` : ''}`), el('div', { class: 'row' }, ...snoozeButtons, ...(diagBtn ? [diagBtn] : []))),
|
||||
el('div', { class: 'mono' }, evt.message),
|
||||
el('div', { class: 'mono muted' }, `Fired: ${fmtTime(evt.triggeredAt)} | Webhook: ${evt.webhookStatus ?? 'none'}`),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
root.append(firingPanel);
|
||||
|
||||
// 2. Silences & Maintenance Windows
|
||||
const silPanel = el('section', { class: 'panel panel-region' });
|
||||
silPanel.append(el('h2', {}, 'Active Silences / Snoozes'));
|
||||
const silScope = el(
|
||||
'select',
|
||||
{ class: 'input-sm' },
|
||||
el('option', { value: 'server' }, 'server'),
|
||||
el('option', { value: 'rule' }, 'rule'),
|
||||
el('option', { value: 'tag' }, 'tag'),
|
||||
el('option', { value: 'all' }, 'all'),
|
||||
);
|
||||
const silTarget = el('input', { class: 'input-sm', placeholder: 'Target ID (or * for all)' });
|
||||
const silDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 43200, value: '120' });
|
||||
const silReason = el('input', { class: 'input-sm', placeholder: 'Reason (optional)' });
|
||||
const silForm = el(
|
||||
'form',
|
||||
{ class: 'row', style: 'margin-bottom:8px' },
|
||||
silScope,
|
||||
silTarget,
|
||||
silDur,
|
||||
silReason,
|
||||
el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, 'Add Silence'),
|
||||
);
|
||||
silForm.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
await apiFetch('/api/alerts/silences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
scopeType: silScope.value,
|
||||
targetId: silScope.value === 'all' ? '*' : silTarget.value.trim(),
|
||||
durationMinutes: Number(silDur.value || 60),
|
||||
reason: silReason.value.trim() || undefined,
|
||||
},
|
||||
});
|
||||
await renderAlertsView(root, state, wsClient);
|
||||
});
|
||||
silPanel.append(silForm);
|
||||
|
||||
for (const s of data.silences) {
|
||||
const unmuteBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Remove');
|
||||
unmuteBtn.addEventListener('click', async () => {
|
||||
await apiFetch(`/api/alerts/silences/${encodeURIComponent(s.id)}`, { method: 'DELETE' });
|
||||
await renderAlertsView(root, state, wsClient);
|
||||
});
|
||||
silPanel.append(
|
||||
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `[${s.scopeType}:${s.targetId}] expires ${fmtTime(s.expiresAt)}${s.reason ? ` — ${s.reason}` : ''}`), unmuteBtn),
|
||||
);
|
||||
}
|
||||
|
||||
// Maintenance windows inside same card
|
||||
silPanel.append(el('h2', { style: 'margin-top:12px' }, `Scheduled Maintenance Windows (${cfg.maintenanceWindows.length})`));
|
||||
const saveConfig = async (nextCfg: AlertsPayload['alertsConfig']) => {
|
||||
await apiFetch('/api/alerts/config', { method: 'PUT', body: nextCfg });
|
||||
await renderAlertsView(root, state, wsClient);
|
||||
};
|
||||
|
||||
for (const w of cfg.maintenanceWindows) {
|
||||
const active = data.activeMaintenanceWindowIds.includes(w.id);
|
||||
const rmWin = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
||||
rmWin.addEventListener('click', () => {
|
||||
void saveConfig({
|
||||
...cfg,
|
||||
maintenanceWindows: cfg.maintenanceWindows.filter((x) => x.id !== w.id),
|
||||
});
|
||||
});
|
||||
silPanel.append(
|
||||
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `${w.name} (${w.id}) | cron "${w.cron}" ${w.timezone} (${w.durationMinutes}m) ${active ? '[ACTIVE NOW]' : ''}`), rmWin),
|
||||
);
|
||||
}
|
||||
const mwId = el('input', { class: 'input-sm', placeholder: 'nightly-maint', required: true });
|
||||
const mwName = el('input', { class: 'input-sm', placeholder: 'Nightly Updates', required: true });
|
||||
const mwCron = el('input', { class: 'input-sm', value: '0 3 * * *', required: true });
|
||||
const mwDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 1440, value: '60', required: true });
|
||||
const mwForm = el('form', { class: 'row', style: 'margin-top:6px' }, mwId, mwName, mwCron, mwDur, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Window'));
|
||||
mwForm.addEventListener('submit', (ev) => {
|
||||
ev.preventDefault();
|
||||
void saveConfig({
|
||||
...cfg,
|
||||
maintenanceWindows: [
|
||||
...cfg.maintenanceWindows,
|
||||
{
|
||||
id: mwId.value.trim(),
|
||||
name: mwName.value.trim(),
|
||||
cron: mwCron.value.trim(),
|
||||
timezone: 'UTC',
|
||||
durationMinutes: Number(mwDur.value || 60),
|
||||
target: { all: true },
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
silPanel.append(mwForm);
|
||||
root.append(silPanel);
|
||||
|
||||
// 3. Notification Channels & Test Alert
|
||||
const chanPanel = el('section', { class: 'panel panel-region' });
|
||||
chanPanel.append(el('h2', {}, `Webhook Channels (${cfg.channels.length})`));
|
||||
const chanStatusMsg = el('p', { class: 'form-msg' });
|
||||
const cTbl = el('table');
|
||||
cTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Type'), el('th', {}, 'Endpoint / Ref'), el('th', {}, 'Actions'))));
|
||||
const cBody = el('tbody');
|
||||
for (const ch of cfg.channels) {
|
||||
const testBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Send Test Alert');
|
||||
testBtn.addEventListener('click', async () => {
|
||||
chanStatusMsg.textContent = `Sending test alert to "${ch.id}"...`;
|
||||
try {
|
||||
const res = await apiFetch<{ ok: boolean; statusCode?: number; error?: string }>(
|
||||
`/api/alerts/channels/${encodeURIComponent(ch.id)}/test`,
|
||||
{ method: 'POST' },
|
||||
);
|
||||
chanStatusMsg.className = res.ok ? 'form-msg ok-text' : 'form-msg err-text';
|
||||
chanStatusMsg.textContent = res.ok
|
||||
? `Test alert delivered to "${ch.id}" (HTTP ${String(res.statusCode ?? 200)}).`
|
||||
: `Test alert failed for "${ch.id}": ${res.error ?? `HTTP ${String(res.statusCode)}`}`;
|
||||
} catch (err) {
|
||||
chanStatusMsg.className = 'form-msg err-text';
|
||||
chanStatusMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
const delCh = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
||||
delCh.addEventListener('click', async () => {
|
||||
const ok = await confirmDialog('dialog-confirm', `Delete alert channel "${ch.id}"?`);
|
||||
if (!ok) return;
|
||||
await saveConfig({ ...cfg, channels: cfg.channels.filter((x) => x.id !== ch.id) });
|
||||
});
|
||||
cBody.append(
|
||||
el('tr', {}, el('td', { class: 'mono' }, `${ch.id} (${ch.name})`), el('td', {}, el('span', { class: 'badge' }, ch.type)), el('td', { class: 'mono' }, `${ch.url ?? ch.topic ?? ch.chatId ?? '—'} [vault:${ch.secretRef}]`), el('td', {}, el('div', { class: 'row' }, testBtn, delCh))),
|
||||
);
|
||||
}
|
||||
cTbl.append(cBody);
|
||||
|
||||
const chId = el('input', { placeholder: 'ops-webhook', required: true });
|
||||
const chName = el('input', { placeholder: 'Ops Webhook', required: true });
|
||||
const chType = el('select', {}, el('option', { value: 'generic' }, 'generic'), el('option', { value: 'discord' }, 'discord'), el('option', { value: 'telegram' }, 'telegram'), el('option', { value: 'ntfy' }, 'ntfy'));
|
||||
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) {
|
||||
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)'));
|
||||
}
|
||||
const chForm = el(
|
||||
'form',
|
||||
{ class: 'stack', style: 'margin-top:8px' },
|
||||
el('div', { class: 'grid-3' }, chId, chName, chType),
|
||||
el('div', { class: 'grid-3' }, chUrl, chExtra, chRef),
|
||||
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Add Webhook Channel')),
|
||||
);
|
||||
chForm.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
chanStatusMsg.textContent = '';
|
||||
try {
|
||||
await saveConfig({
|
||||
...cfg,
|
||||
channels: [
|
||||
...cfg.channels,
|
||||
{
|
||||
id: chId.value.trim(),
|
||||
name: chName.value.trim(),
|
||||
type: chType.value as AlertChannelItem['type'],
|
||||
url: chUrl.value.trim() || undefined,
|
||||
secretRef: chRef.value.trim(),
|
||||
chatId: chType.value === 'telegram' ? chExtra.value.trim() || undefined : undefined,
|
||||
topic: chType.value === 'ntfy' ? chExtra.value.trim() || undefined : undefined,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
} catch (err) {
|
||||
chanStatusMsg.className = 'form-msg err-text';
|
||||
chanStatusMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
chanPanel.append(el('div', { class: 'table-wrap' }, cTbl), chanStatusMsg, chForm);
|
||||
root.append(chanPanel);
|
||||
|
||||
// 4. Alert Rules
|
||||
const rulesPanel = el('section', { class: 'panel panel-region' });
|
||||
rulesPanel.append(el('h2', {}, `Alert Rules (${cfg.rules.length})`));
|
||||
const rMsg = el('p', { class: 'form-msg err-text' });
|
||||
for (const r of cfg.rules) {
|
||||
const condText =
|
||||
r.kind === 'metric'
|
||||
? `${r.metric} ${r.operator} ${r.threshold}`
|
||||
: r.kind === 'disk'
|
||||
? `disk ${r.mountPoint ?? '*'} >= ${r.thresholdPct}%`
|
||||
: r.kind === 'offline'
|
||||
? `offline >= ${r.offlineSec}s`
|
||||
: r.kind === 'probe'
|
||||
? `probe ${r.probeId ?? '*'}`
|
||||
: `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({
|
||||
...cfg,
|
||||
rules: cfg.rules.map((x) => (x.id === r.id ? { ...x, enabled: !x.enabled } : x)),
|
||||
});
|
||||
});
|
||||
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
||||
delBtn.addEventListener('click', () => {
|
||||
void saveConfig({ ...cfg, rules: cfg.rules.filter((x) => x.id !== r.id) });
|
||||
});
|
||||
rulesPanel.append(
|
||||
el('div', { class: 'row-between panel' }, el('div', {}, el('strong', {}, `${r.name} (${r.id})`), el('div', { class: 'mono muted' }, `${condText} | for=${r.forConsecutivePolls} | cooldown=${r.cooldownSec}s | channels=[${r.channelIds.join(',')}]${r.remediationWorkflowId ? ` | fix=${r.remediationWorkflowId}` : ''}`)), el('div', { class: 'row' }, toggleBtn, delBtn)),
|
||||
);
|
||||
}
|
||||
|
||||
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 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 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)' });
|
||||
const ruleRemWf = el('input', { placeholder: 'remediationWorkflowId (optional)' });
|
||||
const ruleForm = el(
|
||||
'form',
|
||||
{ class: 'stack', style: 'margin-top:8px' },
|
||||
el('div', { class: 'grid-3' }, ruleId, ruleName, ruleKind),
|
||||
el('div', { class: 'grid-3' }, ruleSev, ruleParam1, ruleThresh),
|
||||
el('div', { class: 'grid-3' }, rulePolls, ruleChans, ruleRemWf),
|
||||
rMsg,
|
||||
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, '+ Add Alert Rule')),
|
||||
);
|
||||
ruleForm.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
rMsg.textContent = '';
|
||||
const base = {
|
||||
id: ruleId.value.trim(),
|
||||
name: ruleName.value.trim(),
|
||||
severity: ruleSev.value as 'warn' | 'critical',
|
||||
target: { all: true },
|
||||
forConsecutivePolls: Number(rulePolls.value || 3),
|
||||
cooldownSec: 300,
|
||||
channelIds: ruleChans.value.split(',').map((c) => c.trim()).filter(Boolean),
|
||||
remediationWorkflowId: ruleRemWf.value.trim() || undefined,
|
||||
enabled: true,
|
||||
};
|
||||
let nextRule: AlertRuleItem;
|
||||
if (ruleKind.value === 'disk') {
|
||||
nextRule = { ...base, kind: 'disk', mountPoint: ruleParam1.value.trim() || undefined, thresholdPct: Number(ruleThresh.value || 90) };
|
||||
} else if (ruleKind.value === 'offline') {
|
||||
nextRule = { ...base, kind: 'offline', offlineSec: Number(ruleThresh.value || 60) };
|
||||
} else if (ruleKind.value === 'probe') {
|
||||
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 {
|
||||
nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) };
|
||||
}
|
||||
try {
|
||||
await saveConfig({ ...cfg, rules: [...cfg.rules, nextRule] });
|
||||
} catch (err) {
|
||||
rMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
rulesPanel.append(ruleForm);
|
||||
root.append(rulesPanel);
|
||||
|
||||
// 5. Recent History
|
||||
const histPanel = el('section', { class: 'panel panel-region' });
|
||||
histPanel.append(el('h2', {}, `Recent Alert Events (${data.recentEvents.length})`));
|
||||
const hTbl = el('table');
|
||||
hTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Rule'), el('th', {}, 'Server'), el('th', {}, 'State'), el('th', {}, 'Message'), el('th', {}, 'Time'))));
|
||||
const hBody = el('tbody');
|
||||
for (const e of data.recentEvents) {
|
||||
hBody.append(
|
||||
el('tr', {}, el('td', { class: 'mono' }, e.ruleId), el('td', { class: 'mono' }, e.serverId ?? '—'), el('td', {}, el('span', { class: e.state === 'firing' ? 'badge badge-err' : 'badge badge-ok' }, `[${e.state.toUpperCase()}]`)), el('td', { class: 'mono' }, e.message), el('td', { class: 'mono' }, fmtTime(e.triggeredAt))),
|
||||
);
|
||||
}
|
||||
hTbl.append(hBody);
|
||||
histPanel.append(el('div', { class: 'table-wrap' }, hTbl));
|
||||
root.append(histPanel);
|
||||
}
|
||||
|
|
@ -1,6 +1,14 @@
|
|||
import { apiFetch, type ApiError } from '../api.js';
|
||||
import { confirmDialog, openDiffModal } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ConfigOverview } from '../state.js';
|
||||
import {
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
type ClientState,
|
||||
type ConfigOverview,
|
||||
} from '../state.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
interface FileDetails {
|
||||
filePath: string;
|
||||
|
|
@ -82,6 +90,8 @@ let selectedPath = 'settings.json';
|
|||
export async function renderConfigView(
|
||||
root: HTMLElement,
|
||||
overview: ConfigOverview,
|
||||
state: ClientState,
|
||||
wsClient: MultiplexWsClient,
|
||||
onReloadOverview: () => Promise<void>,
|
||||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
|
|
@ -158,7 +168,7 @@ export async function renderConfigView(
|
|||
);
|
||||
btn.addEventListener('click', () => {
|
||||
selectedPath = f.filePath;
|
||||
void renderConfigView(root, overview, onReloadOverview);
|
||||
void renderConfigView(root, overview, state, wsClient, onReloadOverview);
|
||||
});
|
||||
fileList.append(el('li', {}, btn));
|
||||
}
|
||||
|
|
@ -249,6 +259,42 @@ export async function renderConfigView(
|
|||
});
|
||||
|
||||
const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn);
|
||||
if (isAiEnabled(state)) {
|
||||
const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]');
|
||||
aiBtn.addEventListener('click', async () => {
|
||||
const surface = details.filePath.startsWith('workflows/')
|
||||
? 'workflows'
|
||||
: details.filePath.startsWith('systems/')
|
||||
? 'systems'
|
||||
: details.filePath === 'snippets.json'
|
||||
? 'snippets'
|
||||
: 'setup';
|
||||
const defaultDraftKind =
|
||||
surface === 'workflows'
|
||||
? 'workflow'
|
||||
: surface === 'systems'
|
||||
? 'system'
|
||||
: surface === 'snippets'
|
||||
? 'snippet'
|
||||
: details.filePath.startsWith('servers/')
|
||||
? 'server'
|
||||
: details.filePath === 'alerts.json'
|
||||
? 'alerts'
|
||||
: 'settings';
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state,
|
||||
wsClient,
|
||||
surface,
|
||||
title: `AI Assist: ${details.filePath}`,
|
||||
contextText: editor.value,
|
||||
targetPath: details.filePath,
|
||||
defaultDraftKind,
|
||||
onApplied: onReloadOverview,
|
||||
});
|
||||
});
|
||||
actionRow.append(aiBtn);
|
||||
}
|
||||
if (details.filePath.includes('/')) {
|
||||
const delBtn = el(
|
||||
'button',
|
||||
|
|
|
|||
|
|
@ -5,7 +5,11 @@ import type {
|
|||
ServerRuntimeState,
|
||||
} from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { createSparklineSvg, updateSparklineSvg } from '../charts.js';
|
||||
import {
|
||||
createSparklineSvg,
|
||||
maxChartPointsForViewport,
|
||||
updateSparklineSvg,
|
||||
} from '../charts.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import {
|
||||
el,
|
||||
|
|
@ -30,7 +34,8 @@ function statusBadgeClass(status: string): string {
|
|||
function pushSparkPoint(serverId: string, cpuPct: number): number[] {
|
||||
const arr = sparkHistory.get(serverId) ?? [];
|
||||
arr.push(cpuPct);
|
||||
if (arr.length > 120) arr.shift();
|
||||
const cap = maxChartPointsForViewport();
|
||||
if (arr.length > cap) arr.splice(0, arr.length - cap);
|
||||
sparkHistory.set(serverId, arr);
|
||||
return arr;
|
||||
}
|
||||
|
|
@ -229,7 +234,20 @@ export async function renderDashboardView(
|
|||
state: ClientState,
|
||||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
const res = await apiFetch<{ servers: ServerEntry[] }>('/api/servers');
|
||||
const [res, pinnedRes] = await Promise.all([
|
||||
apiFetch<{ servers: ServerEntry[] }>('/api/servers'),
|
||||
apiFetch<{
|
||||
workflows: Array<{
|
||||
workflow: {
|
||||
id: string;
|
||||
name: string;
|
||||
inputs: Array<{ required?: boolean; default?: unknown }>;
|
||||
};
|
||||
latestRun: { runId: string; status: string; finishedAt: number | null } | null;
|
||||
latestStepLogs: Array<{ stepId: string; stdout: string; stderr: string }>;
|
||||
}>;
|
||||
}>('/api/workflows?pinnedOnly=1').catch(() => ({ workflows: [] })),
|
||||
]);
|
||||
const servers = res.servers;
|
||||
|
||||
const actionStatus = el('p', { class: 'form-msg' });
|
||||
|
|
@ -352,6 +370,92 @@ export async function renderDashboardView(
|
|||
);
|
||||
}
|
||||
|
||||
if (pinnedRes.workflows.length > 0) {
|
||||
const pinnedGrid = el('div', { class: 'grid-2' });
|
||||
for (const entry of pinnedRes.workflows) {
|
||||
const wf = entry.workflow;
|
||||
const runStatus = entry.latestRun?.status ?? 'idle';
|
||||
const badgeClass =
|
||||
runStatus === 'succeeded'
|
||||
? 'badge badge-ok'
|
||||
: runStatus === 'failed' || runStatus === 'cancelled'
|
||||
? 'badge badge-err'
|
||||
: runStatus === 'running' || runStatus === 'queued'
|
||||
? 'badge badge-warn'
|
||||
: 'badge';
|
||||
const rawOut = entry.latestStepLogs
|
||||
.map((l) => l.stdout || l.stderr)
|
||||
.filter((s) => s.length > 0)
|
||||
.join('\n')
|
||||
.trim();
|
||||
const previewText = rawOut
|
||||
? rawOut.length > 220
|
||||
? `${rawOut.slice(0, 220)}…`
|
||||
: rawOut
|
||||
: 'No output captured yet.';
|
||||
const statusNote = el('span', { class: 'muted mono' }, '');
|
||||
const needsPrompt = wf.inputs.some(
|
||||
(inp) => inp.required !== false && inp.default === undefined,
|
||||
);
|
||||
const runBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-primary' },
|
||||
needsPrompt ? 'Inputs…' : 'Run',
|
||||
);
|
||||
runBtn.addEventListener('click', async () => {
|
||||
if (needsPrompt) {
|
||||
window.location.hash = '#workflows';
|
||||
return;
|
||||
}
|
||||
runBtn.disabled = true;
|
||||
statusNote.textContent = 'Starting…';
|
||||
try {
|
||||
const started = await apiFetch<{ runId: string; status: string }>(
|
||||
`/api/workflows/${encodeURIComponent(wf.id)}/run`,
|
||||
{ method: 'POST', body: {} },
|
||||
);
|
||||
statusNote.textContent = `Run ${started.runId}: ${started.status}`;
|
||||
} catch (err) {
|
||||
statusNote.textContent = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
runBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
pinnedGrid.append(
|
||||
el(
|
||||
'article',
|
||||
{ class: 'panel' },
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('strong', {}, wf.name),
|
||||
el('span', { class: badgeClass }, runStatus.toUpperCase()),
|
||||
),
|
||||
el('pre', { class: 'terminal-preview muted' }, previewText),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('div', { class: 'row' }, runBtn, el('a', { href: '#workflows', class: 'btn btn-sm' }, 'Open')),
|
||||
statusNote,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
root.append(
|
||||
el(
|
||||
'section',
|
||||
{ class: 'panel' },
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('h2', {}, `Pinned Workflows (${pinnedRes.workflows.length})`),
|
||||
el('a', { href: '#workflows', class: 'btn btn-sm' }, 'All Workflows'),
|
||||
),
|
||||
pinnedGrid,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (servers.length === 0) {
|
||||
root.append(
|
||||
el(
|
||||
|
|
@ -363,6 +467,11 @@ export async function renderDashboardView(
|
|||
return;
|
||||
}
|
||||
|
||||
const activeIds = new Set(servers.map((s) => s.config.id));
|
||||
for (const key of sparkHistory.keys()) {
|
||||
if (!activeIds.has(key)) sparkHistory.delete(key);
|
||||
}
|
||||
|
||||
const grid = el('div', { class: 'grid-2' });
|
||||
for (const entry of servers) {
|
||||
const { config, runtime, telemetry } = entry;
|
||||
|
|
|
|||
|
|
@ -1,49 +0,0 @@
|
|||
import { el, type ConfigOverview, type RouteId } from '../state.js';
|
||||
|
||||
export function renderSectionShell(
|
||||
root: HTMLElement,
|
||||
route: 'workflows' | 'alerts',
|
||||
overview: ConfigOverview,
|
||||
): void {
|
||||
root.replaceChildren();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog, promptStepUp } from '../dialogs.js';
|
||||
import {
|
||||
CLIENT_THEME_IDS,
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
|
|
@ -54,10 +55,13 @@ export async function renderSettingsView(
|
|||
): Promise<void> {
|
||||
root.replaceChildren();
|
||||
|
||||
const [sessRes, auditRes, factorsRes] = await Promise.all([
|
||||
const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([
|
||||
apiFetch<{ sessions: SessionRow[] }>('/api/auth/sessions'),
|
||||
apiFetch<{ total: number; items: AuditRow[] }>('/api/audit?limit=40'),
|
||||
apiFetch<FactorsData>('/api/auth/factors'),
|
||||
apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>(
|
||||
'/api/vault/credentials',
|
||||
).catch(() => ({ credentials: [] })),
|
||||
]);
|
||||
|
||||
const sec = factorsRes.security;
|
||||
|
|
@ -71,8 +75,7 @@ export async function renderSettingsView(
|
|||
const themeSelect = el(
|
||||
'select',
|
||||
{},
|
||||
...['phosphor-green', 'amber-term', 'nord-dark', 'gruvbox-dark', 'paper-light'].map(
|
||||
(t) =>
|
||||
...CLIENT_THEME_IDS.map((t) =>
|
||||
el('option', { value: t, selected: state.theme === t ? true : undefined }, t),
|
||||
),
|
||||
);
|
||||
|
|
@ -318,6 +321,234 @@ export async function renderSettingsView(
|
|||
);
|
||||
root.append(policyPanel);
|
||||
|
||||
// 2b. Optional BYO-API AI Assistant (Strictly Opt-In)
|
||||
const rawAi = (state.overview?.settings?.ai ?? {}) as {
|
||||
enabled?: boolean;
|
||||
baseUrl?: string;
|
||||
model?: string;
|
||||
secretRef?: string;
|
||||
maxContextChars?: number;
|
||||
};
|
||||
const aiPanel = el('section', { class: 'panel panel-region' });
|
||||
aiPanel.append(
|
||||
el('h2', {}, 'Optional BYO-API AI Assistant'),
|
||||
el(
|
||||
'p',
|
||||
{ class: 'muted' },
|
||||
'Strictly opt-in. Uses any OpenAI-compatible v1 endpoint (Ollama, llama.cpp, vLLM, or cloud) with secret redaction and manual Apply confirmation.',
|
||||
),
|
||||
);
|
||||
const aiEnabledChk = el('input', { type: 'checkbox', checked: rawAi.enabled ? true : undefined });
|
||||
const aiBaseUrlInp = el('input', {
|
||||
value: rawAi.baseUrl ?? 'http://127.0.0.1:11434',
|
||||
placeholder: 'http://127.0.0.1:11434',
|
||||
});
|
||||
const aiModelInp = el('input', {
|
||||
value: rawAi.model ?? 'qwen2.5-coder:7b',
|
||||
placeholder: 'qwen2.5-coder:7b',
|
||||
});
|
||||
const aiSecretSel = el(
|
||||
'select',
|
||||
{},
|
||||
el('option', { value: '' }, '(None — local unauthenticated LLM)'),
|
||||
...credsRes.credentials.map((c) =>
|
||||
el(
|
||||
'option',
|
||||
{ value: c.id, selected: rawAi.secretRef === c.id ? true : undefined },
|
||||
`${c.id} (${c.type})`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const aiMaxCtxInp = el('input', {
|
||||
type: 'number',
|
||||
min: 1000,
|
||||
max: 128000,
|
||||
value: String(rawAi.maxContextChars ?? 16000),
|
||||
});
|
||||
const aiMsg = el('p', { class: 'form-msg' });
|
||||
const aiTestBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Test AI Endpoint');
|
||||
aiTestBtn.addEventListener('click', async () => {
|
||||
aiMsg.className = 'form-msg muted';
|
||||
aiMsg.textContent = 'Testing AI endpoint...';
|
||||
try {
|
||||
const r = await apiFetch<{ ok: boolean; latencyMs: number; replyPreview?: string; error?: string }>(
|
||||
'/api/ai/test',
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
baseUrl: aiBaseUrlInp.value.trim(),
|
||||
model: aiModelInp.value.trim(),
|
||||
secretRef: aiSecretSel.value,
|
||||
},
|
||||
},
|
||||
);
|
||||
aiMsg.className = r.ok ? 'form-msg ok-text' : 'form-msg err-text';
|
||||
aiMsg.textContent = r.ok
|
||||
? `Connected (${r.latencyMs}ms): ${r.replyPreview ?? 'OK'}`
|
||||
: `Endpoint test failed (${r.latencyMs}ms): ${r.error ?? 'error'}`;
|
||||
} catch (err) {
|
||||
aiMsg.className = 'form-msg err-text';
|
||||
aiMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
const aiSaveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Save AI Settings');
|
||||
aiSaveBtn.addEventListener('click', async () => {
|
||||
aiMsg.textContent = '';
|
||||
try {
|
||||
const nextSettings = {
|
||||
...(state.overview?.settings ?? {}),
|
||||
ai: {
|
||||
enabled: aiEnabledChk.checked,
|
||||
baseUrl: aiBaseUrlInp.value.trim(),
|
||||
model: aiModelInp.value.trim(),
|
||||
...(aiSecretSel.value ? { secretRef: aiSecretSel.value } : {}),
|
||||
maxContextChars: Number(aiMaxCtxInp.value || 16000),
|
||||
},
|
||||
};
|
||||
await apiFetch('/api/config/file', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
path: 'settings.json',
|
||||
content: `${JSON.stringify(nextSettings, null, 2)}\n`,
|
||||
summary: `AI Assistant -> ${aiEnabledChk.checked ? 'enabled' : 'disabled'}`,
|
||||
},
|
||||
});
|
||||
await onReloadState();
|
||||
} catch (err) {
|
||||
aiMsg.className = 'form-msg err-text';
|
||||
aiMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
aiPanel.append(
|
||||
el('label', { class: 'chk-row' }, aiEnabledChk, 'Enable AI Assistant Drawer Across UI Surfaces'),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'grid-2', style: 'margin-top:8px' },
|
||||
el('div', {}, el('label', {}, 'OpenAI-Compatible Base URL'), aiBaseUrlInp),
|
||||
el('div', {}, el('label', {}, 'Model Name'), aiModelInp),
|
||||
el('div', {}, el('label', {}, 'API Key Credential (Optional)'), aiSecretSel),
|
||||
el('div', {}, el('label', {}, 'Max Context Chars'), aiMaxCtxInp),
|
||||
),
|
||||
el('div', { class: 'row', style: 'margin-top:8px' }, aiTestBtn, aiSaveBtn),
|
||||
aiMsg,
|
||||
);
|
||||
root.append(aiPanel);
|
||||
|
||||
// 2c. Portable Encrypted Backup (.gcoord.enc)
|
||||
const portableBackupPanel = el('section', { class: 'panel panel-region' });
|
||||
portableBackupPanel.append(
|
||||
el('h2', {}, 'Portable Encrypted Backup (.gcoord.enc)'),
|
||||
el(
|
||||
'p',
|
||||
{ class: 'muted' },
|
||||
'Package /data/config, vault.enc, known_hosts, and active silences into a single AES-256-GCM authenticated bundle.',
|
||||
),
|
||||
);
|
||||
const expPassInp = el('input', {
|
||||
type: 'password',
|
||||
placeholder: 'Optional backup passphrase (blank = Vault master key)',
|
||||
});
|
||||
const expBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Export .gcoord.enc');
|
||||
const backupMsg = el('p', { class: 'form-msg' });
|
||||
expBtn.addEventListener('click', async () => {
|
||||
backupMsg.className = 'form-msg muted';
|
||||
backupMsg.textContent = 'Generating encrypted bundle...';
|
||||
try {
|
||||
const res = await apiFetch<{
|
||||
filename: string;
|
||||
bundleBase64: string;
|
||||
summary: { configFileCount: number; knownHostsCount: number; kdf: string };
|
||||
}>('/api/backup/export', {
|
||||
method: 'POST',
|
||||
body: { passphrase: expPassInp.value || undefined },
|
||||
});
|
||||
const bin = Uint8Array.from(atob(res.bundleBase64), (ch) => ch.charCodeAt(0));
|
||||
const url = URL.createObjectURL(new Blob([bin], { type: 'application/json' }));
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = res.filename;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
backupMsg.className = 'form-msg ok-text';
|
||||
backupMsg.textContent = `Downloaded ${res.filename} (${res.summary.configFileCount} configs, ${res.summary.knownHostsCount} known_hosts, kdf=${res.summary.kdf}).`;
|
||||
} catch (err) {
|
||||
backupMsg.className = 'form-msg err-text';
|
||||
backupMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
|
||||
const impFileInp = el('input', { type: 'file', accept: '.enc,.json,application/json' });
|
||||
const impPassInp = el('input', {
|
||||
type: 'password',
|
||||
placeholder: 'Passphrase or Master Key (if not runtime-ready)',
|
||||
});
|
||||
const readSelectedBase64 = async (): Promise<string> => {
|
||||
const file = impFileInp.files?.[0];
|
||||
if (!file) throw new Error('Select a .gcoord.enc file first');
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
let bin = '';
|
||||
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]!);
|
||||
return btoa(bin);
|
||||
};
|
||||
const verifyImpBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Verify Bundle');
|
||||
verifyImpBtn.addEventListener('click', async () => {
|
||||
backupMsg.className = 'form-msg muted';
|
||||
backupMsg.textContent = 'Verifying bundle integrity...';
|
||||
try {
|
||||
const bundleBase64 = await readSelectedBase64();
|
||||
const raw = impPassInp.value.trim();
|
||||
const isHexKey = /^[0-9a-fA-F]{64}$/.test(raw);
|
||||
const res = await apiFetch<{ summary: Record<string, unknown> }>('/api/backup/verify', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
bundleBase64,
|
||||
...(raw ? (isHexKey ? { masterKey: raw } : { passphrase: raw }) : {}),
|
||||
},
|
||||
});
|
||||
backupMsg.className = 'form-msg ok-text';
|
||||
backupMsg.textContent = `Verified cleanly: ${JSON.stringify(res.summary)}`;
|
||||
} catch (err) {
|
||||
backupMsg.className = 'form-msg err-text';
|
||||
backupMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
const restoreImpBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm mutating-action' }, 'Restore Bundle');
|
||||
restoreImpBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
const bundleBase64 = await readSelectedBase64();
|
||||
const ok = await confirmDialog(
|
||||
'dialog-confirm',
|
||||
'Atomically replace /data/config, vault.enc, and known_hosts from this backup bundle?',
|
||||
);
|
||||
if (!ok) return;
|
||||
const raw = impPassInp.value.trim();
|
||||
const isHexKey = /^[0-9a-fA-F]{64}$/.test(raw);
|
||||
const res = await apiFetch<{ summary: { configFileCount: number; knownHostsCount: number } }>(
|
||||
'/api/backup/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
body: {
|
||||
bundleBase64,
|
||||
...(raw ? (isHexKey ? { masterKey: raw } : { passphrase: raw }) : {}),
|
||||
},
|
||||
},
|
||||
);
|
||||
backupMsg.className = 'form-msg ok-text';
|
||||
backupMsg.textContent = `Restored ${res.summary.configFileCount} configs & ${res.summary.knownHostsCount} known_hosts.`;
|
||||
await onReloadState();
|
||||
} catch (err) {
|
||||
backupMsg.className = 'form-msg err-text';
|
||||
backupMsg.textContent = extractErrorMessage(err);
|
||||
}
|
||||
});
|
||||
portableBackupPanel.append(
|
||||
el('div', { class: 'grid-2' }, el('div', {}, el('label', {}, 'Export Passphrase (Optional)'), expPassInp), el('div', { style: 'align-self:end' }, expBtn)),
|
||||
el('div', { class: 'grid-2', style: 'margin-top:8px' }, el('div', {}, el('label', {}, 'Verify / Restore .gcoord.enc File'), impFileInp), el('div', {}, el('label', {}, 'Backup Passphrase / 64-Hex Master Key'), impPassInp)),
|
||||
el('div', { class: 'row', style: 'margin-top:8px' }, verifyImpBtn, restoreImpBtn),
|
||||
backupMsg,
|
||||
);
|
||||
root.append(portableBackupPanel);
|
||||
|
||||
// 3. Multi-Password & Multi-TOTP Factor Management
|
||||
const factorsGrid = el('div', { class: 'grid-2' });
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
|
||||
import {
|
||||
appendBoundedStreamText,
|
||||
el,
|
||||
extractErrorMessage,
|
||||
fmtTime,
|
||||
isAiEnabled,
|
||||
type ClientState,
|
||||
type ServerEntry,
|
||||
} from '../state.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
|
||||
interface SystemActionDef {
|
||||
|
|
@ -156,6 +164,7 @@ async function openAttachModal(
|
|||
}
|
||||
|
||||
async function runSystemAction(opts: {
|
||||
state: ClientState;
|
||||
systemId: string;
|
||||
serverId: string;
|
||||
action: SystemActionDef;
|
||||
|
|
@ -198,12 +207,34 @@ async function runSystemAction(opts: {
|
|||
}
|
||||
|
||||
if (res.mode === 'oneshot') {
|
||||
const outText = [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)';
|
||||
const debugBtn = isAiEnabled(opts.state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]')
|
||||
: null;
|
||||
if (debugBtn) {
|
||||
debugBtn.addEventListener('click', async () => {
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state: opts.state,
|
||||
wsClient: opts.wsClient,
|
||||
surface: 'logs',
|
||||
title: `AI Debug (${opts.systemId}: ${action.label})`,
|
||||
contextText: `Exit code: ${String(res.exitCode)}\n\n${outText}`,
|
||||
serverId: opts.serverId,
|
||||
});
|
||||
});
|
||||
}
|
||||
opts.outputHost.replaceChildren(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'panel' },
|
||||
el('div', { class: 'row-between' }, el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`)),
|
||||
el('pre', { class: 'stream-log mono' }, [res.stdout, res.stderr].filter(Boolean).join('\n') || '(no output)'),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('strong', {}, `${action.label} finished (exit ${String(res.exitCode)}, ${res.durationMs}ms)`),
|
||||
...(debugBtn ? [debugBtn] : []),
|
||||
),
|
||||
el('pre', { class: 'stream-log mono' }, outText),
|
||||
),
|
||||
);
|
||||
await opts.onFinished();
|
||||
|
|
@ -222,12 +253,33 @@ async function runSystemAction(opts: {
|
|||
await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' });
|
||||
stopBtn.disabled = true;
|
||||
});
|
||||
const streamAiBtn = isAiEnabled(opts.state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]')
|
||||
: null;
|
||||
if (streamAiBtn) {
|
||||
streamAiBtn.addEventListener('click', async () => {
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state: opts.state,
|
||||
wsClient: opts.wsClient,
|
||||
surface: 'logs',
|
||||
title: `AI Debug (${opts.systemId}: ${action.label})`,
|
||||
contextText: logPre.textContent ?? '',
|
||||
serverId: opts.serverId,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
opts.outputHost.replaceChildren(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'panel' },
|
||||
el('div', { class: 'row-between' }, el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`), stopBtn),
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('strong', {}, `Live Stream: ${action.label} (${res.jobId})`),
|
||||
el('div', { class: 'row' }, ...(streamAiBtn ? [streamAiBtn] : []), stopBtn),
|
||||
),
|
||||
logPre,
|
||||
),
|
||||
);
|
||||
|
|
@ -238,7 +290,7 @@ async function runSystemAction(opts: {
|
|||
try {
|
||||
const meta = JSON.parse(frame.data) as { event?: string; exitCode?: number | null };
|
||||
if (meta.event === 'exit') {
|
||||
logPre.textContent += `\n[Exited with code ${String(meta.exitCode)}]\n`;
|
||||
appendBoundedStreamText(logPre, `\n[Exited with code ${String(meta.exitCode)}]\n`);
|
||||
stopBtn.disabled = true;
|
||||
void opts.onFinished();
|
||||
}
|
||||
|
|
@ -246,7 +298,7 @@ async function runSystemAction(opts: {
|
|||
// Ignore meta parse errors
|
||||
}
|
||||
} else {
|
||||
logPre.textContent += frame.data;
|
||||
appendBoundedStreamText(logPre, frame.data);
|
||||
}
|
||||
logPre.scrollTop = logPre.scrollHeight;
|
||||
});
|
||||
|
|
@ -276,12 +328,29 @@ export async function renderSystemsView(
|
|||
}>;
|
||||
}>('/api/systems');
|
||||
|
||||
const aiSysBtn = isAiEnabled(state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Author System]')
|
||||
: null;
|
||||
if (aiSysBtn) {
|
||||
aiSysBtn.addEventListener('click', async () => {
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state,
|
||||
wsClient,
|
||||
surface: 'systems',
|
||||
title: 'AI Custom System Author',
|
||||
defaultDraftKind: 'system',
|
||||
onApplied: () => renderSystemsView(root, state, wsClient),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
root.append(
|
||||
el(
|
||||
'section',
|
||||
{ class: 'panel row-between' },
|
||||
el('div', {}, el('h1', {}, 'Custom Systems Engine'), el('p', { class: 'muted' }, 'Declarative service managers defined in /data/config/systems/*.json')),
|
||||
el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs'),
|
||||
el('div', { class: 'row' }, ...(aiSysBtn ? [aiSysBtn] : []), el('a', { href: '#config', class: 'btn btn-sm' }, 'Edit System JSONs')),
|
||||
),
|
||||
);
|
||||
|
||||
|
|
@ -350,6 +419,7 @@ export async function renderSystemsView(
|
|||
);
|
||||
btn.addEventListener('click', () => {
|
||||
void runSystemAction({
|
||||
state,
|
||||
systemId,
|
||||
serverId: targetServerId,
|
||||
action: act,
|
||||
|
|
@ -466,6 +536,7 @@ export async function renderSystemsView(
|
|||
const btn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
|
||||
btn.addEventListener('click', () => {
|
||||
void runSystemAction({
|
||||
state,
|
||||
systemId,
|
||||
serverId: targetServerId,
|
||||
action: act,
|
||||
|
|
@ -513,26 +584,191 @@ export async function renderSystemsView(
|
|||
}
|
||||
|
||||
// Per-Service Tasks & Cron workflows matching scope
|
||||
const scopedWfs = (state.overview?.workflows ?? []).filter((wf) => {
|
||||
const scope = wf.scope as { serverId?: string; systemId?: string; item?: string } | undefined;
|
||||
if (!scope) return false;
|
||||
if (scope.systemId && scope.systemId !== systemId) return false;
|
||||
if (scope.serverId && scope.serverId !== targetServerId) return false;
|
||||
if (scope.item && scope.item !== item.name) return false;
|
||||
return Boolean(scope.systemId);
|
||||
});
|
||||
const tasksPanel = el('section', { class: 'panel' });
|
||||
tasksPanel.append(
|
||||
el('div', { class: 'row-between' }, el('h2', {}, `Tasks & Cron (${scopedWfs.length})`), el('a', { href: '#config', class: 'btn btn-sm' }, 'Configure Workflows')),
|
||||
const tasksListHost = el('div', { class: 'stack' });
|
||||
const taskOutputPre = el('pre', { class: 'terminal-preview muted', hidden: true }, '');
|
||||
const scheduleFormWrap = el('form', { class: 'stack panel', hidden: true });
|
||||
|
||||
const taskActionInput = el('input', {
|
||||
type: 'text',
|
||||
value: 'restart',
|
||||
placeholder: 'restart / reload / status',
|
||||
required: true,
|
||||
});
|
||||
const taskNameInput = el('input', {
|
||||
type: 'text',
|
||||
value: `${item.name} scheduled task`,
|
||||
required: true,
|
||||
});
|
||||
const taskCronInput = el('input', {
|
||||
type: 'text',
|
||||
placeholder: '0 4 * * * (blank = manual)',
|
||||
});
|
||||
const taskTzInput = el('input', { type: 'text', value: 'UTC' });
|
||||
const taskFormErr = el('p', { class: 'err-text', hidden: true }, '');
|
||||
const toggleScheduleBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-primary' },
|
||||
'+ Schedule Service Task',
|
||||
);
|
||||
toggleScheduleBtn.addEventListener('click', () => {
|
||||
scheduleFormWrap.hidden = !scheduleFormWrap.hidden;
|
||||
});
|
||||
|
||||
const refreshScopedTasks = async (): Promise<void> => {
|
||||
const wfRes = await apiFetch<{
|
||||
workflows: Array<{
|
||||
workflow: {
|
||||
id: string;
|
||||
name: string;
|
||||
trigger: { type: string; expression?: string };
|
||||
scope?: { serverId?: string; systemId?: string; item?: string };
|
||||
};
|
||||
nextRunAt: number | null;
|
||||
latestRun: { runId: string; status: string } | null;
|
||||
}>;
|
||||
}>('/api/workflows').catch(() => ({ workflows: [] }));
|
||||
const scopedWfs = wfRes.workflows.filter((entry) => {
|
||||
const sc = entry.workflow.scope;
|
||||
if (!sc || sc.systemId !== systemId) return false;
|
||||
if (sc.serverId && sc.serverId !== targetServerId) return false;
|
||||
if (sc.item && sc.item !== item.name) return false;
|
||||
return true;
|
||||
});
|
||||
tasksListHost.replaceChildren();
|
||||
if (scopedWfs.length === 0) {
|
||||
tasksPanel.append(el('p', { class: 'muted' }, 'No scoped workflows yet. Phase 4 adds interactive scheduling and execution here.'));
|
||||
} else {
|
||||
for (const wf of scopedWfs) {
|
||||
tasksPanel.append(el('div', { class: 'mono' }, `• ${String(wf.name ?? wf.id)} (${String(wf.id)})`));
|
||||
tasksListHost.append(
|
||||
el('p', { class: 'muted' }, 'No scoped tasks or cron workflows for this service yet.'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
for (const entry of scopedWfs) {
|
||||
const wf = entry.workflow;
|
||||
const trigText =
|
||||
wf.trigger.type === 'cron'
|
||||
? `cron: ${wf.trigger.expression ?? ''}${entry.nextRunAt ? ` (next ${new Date(entry.nextRunAt).toISOString().slice(0, 19).replace('T', ' ')})` : ''}`
|
||||
: wf.trigger.type;
|
||||
const runStatus = entry.latestRun?.status ?? 'idle';
|
||||
const statusBadge = el(
|
||||
'span',
|
||||
{
|
||||
class:
|
||||
runStatus === 'succeeded'
|
||||
? 'badge badge-ok'
|
||||
: runStatus === 'failed' || runStatus === 'cancelled'
|
||||
? 'badge badge-err'
|
||||
: runStatus === 'running' || runStatus === 'queued'
|
||||
? 'badge badge-warn'
|
||||
: 'badge',
|
||||
},
|
||||
runStatus,
|
||||
);
|
||||
const runTaskBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Run Task');
|
||||
runTaskBtn.addEventListener('click', async () => {
|
||||
runTaskBtn.disabled = true;
|
||||
taskOutputPre.hidden = false;
|
||||
taskOutputPre.textContent = `Running ${wf.name}…`;
|
||||
try {
|
||||
const started = await apiFetch<{ runId: string; status: string }>(
|
||||
`/api/workflows/${encodeURIComponent(wf.id)}/run`,
|
||||
{ method: 'POST', body: {} },
|
||||
);
|
||||
taskOutputPre.textContent = `Run ${started.runId}: ${started.status}`;
|
||||
for (let i = 0; i < 15; i++) {
|
||||
await new Promise((r) => setTimeout(r, 400));
|
||||
const detail = await apiFetch<{
|
||||
run: { status: string };
|
||||
stepLogs: Array<{ stepId: string; exitCode: number | null; stdout: string; stderr: string }>;
|
||||
}>(`/api/workflows/runs/${encodeURIComponent(started.runId)}`);
|
||||
const logs = detail.stepLogs
|
||||
.map((l) => `[${l.stepId}] exit=${l.exitCode ?? '-'}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`)
|
||||
.join('\n');
|
||||
taskOutputPre.textContent = `Status: ${detail.run.status}\n${logs}`.trim();
|
||||
if (detail.run.status !== 'running' && detail.run.status !== 'queued') break;
|
||||
}
|
||||
await refreshScopedTasks();
|
||||
} catch (err) {
|
||||
taskOutputPre.textContent = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
runTaskBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
tasksListHost.append(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('div', {}, el('strong', {}, wf.name), el('span', { class: 'muted mono' }, ` (${trigText})`)),
|
||||
el('div', { class: 'row' }, statusBadge, runTaskBtn),
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const saveTaskBtn = el('button', { type: 'submit', class: 'btn btn-sm btn-primary' }, 'Create Task');
|
||||
scheduleFormWrap.append(
|
||||
el('label', {}, 'Task Name', taskNameInput),
|
||||
el('label', {}, 'System Action ID', taskActionInput),
|
||||
el('div', { class: 'grid-2' }, el('label', {}, 'Cron (optional)', taskCronInput), el('label', {}, 'Timezone', taskTzInput)),
|
||||
taskFormErr,
|
||||
el('div', { class: 'row' }, saveTaskBtn),
|
||||
);
|
||||
scheduleFormWrap.addEventListener('submit', async (ev) => {
|
||||
ev.preventDefault();
|
||||
taskFormErr.hidden = true;
|
||||
const slug = `${systemId}-${item.name}`
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 28);
|
||||
const id = `svc-${slug || 'task'}-${Date.now().toString(36)}`;
|
||||
const cronExpr = taskCronInput.value.trim();
|
||||
try {
|
||||
await apiFetch('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id,
|
||||
name: taskNameInput.value.trim() || `${item.name} task`,
|
||||
enabled: true,
|
||||
trigger: cronExpr
|
||||
? { type: 'cron', expression: cronExpr, timezone: taskTzInput.value.trim() || 'UTC' }
|
||||
: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log', pinToDashboard: false },
|
||||
scope: { serverId: targetServerId, systemId, item: item.name },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'service-action',
|
||||
type: 'system-action',
|
||||
target: { serverId: targetServerId },
|
||||
systemId,
|
||||
action: taskActionInput.value.trim() || 'status',
|
||||
item: item.name,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
scheduleFormWrap.hidden = true;
|
||||
await refreshScopedTasks();
|
||||
} catch (err) {
|
||||
taskFormErr.hidden = false;
|
||||
taskFormErr.textContent = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
});
|
||||
|
||||
tasksPanel.append(
|
||||
el(
|
||||
'div',
|
||||
{ class: 'row-between' },
|
||||
el('h2', {}, 'Tasks & Cron'),
|
||||
el('div', { class: 'row' }, toggleScheduleBtn, el('a', { href: '#workflows', class: 'btn btn-sm' }, 'All Workflows')),
|
||||
),
|
||||
scheduleFormWrap,
|
||||
tasksListHost,
|
||||
taskOutputPre,
|
||||
);
|
||||
root.append(tasksPanel);
|
||||
void refreshScopedTasks();
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -578,6 +814,7 @@ export async function renderSystemsView(
|
|||
);
|
||||
btn.addEventListener('click', () => {
|
||||
void runSystemAction({
|
||||
state,
|
||||
systemId,
|
||||
serverId: snap.serverId,
|
||||
action: act,
|
||||
|
|
@ -631,6 +868,7 @@ export async function renderSystemsView(
|
|||
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, act.label);
|
||||
b.addEventListener('click', () => {
|
||||
void runSystemAction({
|
||||
state,
|
||||
systemId,
|
||||
serverId: snap.serverId,
|
||||
action: act,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import type { FitAddon } from '@xterm/addon-fit';
|
|||
import type { ServerWsFrame } from '../../../shared/ws-protocol.js';
|
||||
import { apiFetch } from '../api.js';
|
||||
import { confirmDialog } from '../dialogs.js';
|
||||
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js';
|
||||
import { el, extractErrorMessage, fmtTime, isAiEnabled, type ClientState, type ServerEntry } from '../state.js';
|
||||
import type { MultiplexWsClient } from '../ws-client.js';
|
||||
import {
|
||||
clearTerminalComposition,
|
||||
|
|
@ -349,6 +349,39 @@ export async function renderTerminalView(
|
|||
const fontPlusBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'A+');
|
||||
const fitBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Fit');
|
||||
const snippetsBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Snippets');
|
||||
const aiTermBtn = isAiEnabled(state)
|
||||
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Helper]')
|
||||
: null;
|
||||
if (aiTermBtn) {
|
||||
aiTermBtn.addEventListener('click', async () => {
|
||||
let scrollbackTail = '';
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=plain`,
|
||||
{ credentials: 'same-origin' },
|
||||
);
|
||||
if (res.ok) {
|
||||
scrollbackTail = (await res.text()).slice(-4000);
|
||||
}
|
||||
} catch {
|
||||
// Ignore export errors
|
||||
}
|
||||
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
||||
await openAiAssistantDrawer({
|
||||
state,
|
||||
wsClient,
|
||||
surface: 'snippets',
|
||||
title: `AI Terminal Helper (${current.serverId})`,
|
||||
contextText: scrollbackTail,
|
||||
serverId: current.serverId,
|
||||
defaultDraftKind: 'snippet',
|
||||
onInsertTerminalText: (cmd) => {
|
||||
sendPtyInput(cmd.replace(/[\r\n]+/g, ' '));
|
||||
term?.focus();
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
const closeTabBtn = el(
|
||||
'button',
|
||||
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action' },
|
||||
|
|
@ -457,7 +490,7 @@ export async function renderTerminalView(
|
|||
{ class: 'mono muted' },
|
||||
`${current.title} | ${current.cols}x${current.rows} | opened ${fmtTime(current.createdAt)}`,
|
||||
),
|
||||
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, exportPlainBtn, exportAnsiBtn, closeTabBtn),
|
||||
el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn),
|
||||
),
|
||||
el('div', { class: 'term-shell' }, termContainer, touchBar),
|
||||
),
|
||||
|
|
|
|||
1246
src/client/ts/views/workflows-view.ts
Normal file
1246
src/client/ts/views/workflows-view.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -8,7 +8,7 @@ export class MultiplexWsClient {
|
|||
private reconnectTimer: number | null = null;
|
||||
private pingTimer: number | null = null;
|
||||
private shouldRun = false;
|
||||
private channels = new Set<string>(['config', 'alerts', 'metrics']);
|
||||
private channels = new Set<string>(['config', 'alerts', 'metrics', 'workflows']);
|
||||
private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>();
|
||||
private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>();
|
||||
|
||||
|
|
|
|||
624
src/server/ai/ai-service.ts
Normal file
624
src/server/ai/ai-service.ts
Normal file
|
|
@ -0,0 +1,624 @@
|
|||
import crypto from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
AlertsFileSchema,
|
||||
ServerConfigSchema,
|
||||
SettingsSchema,
|
||||
SnippetSchema,
|
||||
SnippetsFileSchema,
|
||||
SystemConfigSchema,
|
||||
WorkflowConfigSchema,
|
||||
} from '../../shared/schemas/index.js';
|
||||
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import { computeLineDiff, type DiffLine } from '../config/diff.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import {
|
||||
buildSurfaceGuideAndInventory,
|
||||
type AiDraftKind,
|
||||
type AiSurface,
|
||||
} from './guides.js';
|
||||
import { collectVaultSecretStrings, redactSecrets } from './redactor.js';
|
||||
|
||||
export class AiDisabledError extends Error {
|
||||
readonly code = 'AI_DISABLED';
|
||||
readonly status = 403;
|
||||
constructor() {
|
||||
super('AI Assistant is disabled in settings.json (settings.ai.enabled=false).');
|
||||
}
|
||||
}
|
||||
|
||||
export interface ChatMessageInput {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface ActiveAiChat {
|
||||
chatId: string;
|
||||
abortController: AbortController;
|
||||
frames: ServerWsFrame[];
|
||||
replayBytes: number;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
const MAX_REPLAY_BYTES = 128 * 1024;
|
||||
const MAX_RETAINED_CHATS = 25;
|
||||
|
||||
export function normalizeChatCompletionsUrl(baseUrl: string): string {
|
||||
const trimmed = baseUrl.trim().replace(/\/+$/, '');
|
||||
if (trimmed.endsWith('/chat/completions')) return trimmed;
|
||||
if (trimmed.endsWith('/v1')) return `${trimmed}/chat/completions`;
|
||||
return `${trimmed}/v1/chat/completions`;
|
||||
}
|
||||
|
||||
export class AiService {
|
||||
private readonly chats = new Map<string, ActiveAiChat>();
|
||||
private closed = false;
|
||||
|
||||
constructor(
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly vaultService: VaultService,
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
getReplayFrames(chatId: string): ServerWsFrame[] {
|
||||
return [...(this.chats.get(chatId)?.frames ?? [])];
|
||||
}
|
||||
|
||||
cancelChat(chatId: string): boolean {
|
||||
const chat = this.chats.get(chatId);
|
||||
if (!chat || chat.done) return false;
|
||||
chat.abortController.abort();
|
||||
return true;
|
||||
}
|
||||
|
||||
cancelAll(): void {
|
||||
for (const chat of this.chats.values()) {
|
||||
if (!chat.done) {
|
||||
chat.abortController.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.cancelAll();
|
||||
}
|
||||
|
||||
private resolveBearerToken(secretRef?: string): string | undefined {
|
||||
if (!secretRef || !this.vaultService.isRuntimeReady) return undefined;
|
||||
const cred = this.vaultService.getRuntimeSecret(secretRef);
|
||||
if (!cred) return undefined;
|
||||
if (cred.type === 'api-token') return cred.token;
|
||||
if (cred.type === 'webhook-secret') return cred.secret;
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
previewContext(opts: {
|
||||
surface: AiSurface;
|
||||
contextText?: string;
|
||||
serverId?: string;
|
||||
targetPath?: string;
|
||||
}): {
|
||||
enabled: boolean;
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
surface: AiSurface;
|
||||
defaultDraftKind?: AiDraftKind;
|
||||
systemPrompt: string;
|
||||
inventorySummary: string;
|
||||
sanitizedContext: string;
|
||||
redactedCount: number;
|
||||
truncated: boolean;
|
||||
} {
|
||||
const aiCfg = this.configManager.getSettings().ai;
|
||||
const knownSecrets = collectVaultSecretStrings(this.vaultService);
|
||||
const guide = buildSurfaceGuideAndInventory(
|
||||
opts.surface,
|
||||
{
|
||||
configManager: this.configManager,
|
||||
vaultService: this.vaultService,
|
||||
sshPool: this.sshPool,
|
||||
},
|
||||
{ serverId: opts.serverId, targetPath: opts.targetPath },
|
||||
);
|
||||
|
||||
const ctxRedacted = redactSecrets(
|
||||
opts.contextText ?? '',
|
||||
knownSecrets,
|
||||
aiCfg.maxContextChars,
|
||||
);
|
||||
const invRedacted = redactSecrets(guide.inventorySummary, knownSecrets, 12_000);
|
||||
|
||||
return {
|
||||
enabled: aiCfg.enabled,
|
||||
baseUrl: aiCfg.baseUrl,
|
||||
model: aiCfg.model,
|
||||
surface: opts.surface,
|
||||
defaultDraftKind: guide.defaultDraftKind,
|
||||
systemPrompt: guide.systemPrompt,
|
||||
inventorySummary: invRedacted.text,
|
||||
sanitizedContext: ctxRedacted.text,
|
||||
redactedCount: ctxRedacted.redactedCount + invRedacted.redactedCount,
|
||||
truncated: ctxRedacted.truncated || invRedacted.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
startChat(opts: {
|
||||
chatId?: string;
|
||||
surface: AiSurface;
|
||||
messages: ChatMessageInput[];
|
||||
contextText?: string;
|
||||
serverId?: string;
|
||||
targetPath?: string;
|
||||
actorIp: string;
|
||||
sessionIdHash: string | null;
|
||||
}): { chatId: string; redactedCount: number; truncated: boolean } {
|
||||
if (this.closed) {
|
||||
throw new Error('AiService is closed');
|
||||
}
|
||||
const aiCfg = this.configManager.getSettings().ai;
|
||||
if (!aiCfg.enabled) {
|
||||
throw new AiDisabledError();
|
||||
}
|
||||
|
||||
const knownSecrets = collectVaultSecretStrings(this.vaultService);
|
||||
const guide = buildSurfaceGuideAndInventory(
|
||||
opts.surface,
|
||||
{
|
||||
configManager: this.configManager,
|
||||
vaultService: this.vaultService,
|
||||
sshPool: this.sshPool,
|
||||
},
|
||||
{ serverId: opts.serverId, targetPath: opts.targetPath },
|
||||
);
|
||||
|
||||
let totalRedacted = 0;
|
||||
let anyTruncated = false;
|
||||
|
||||
const invRedacted = redactSecrets(guide.inventorySummary, knownSecrets, 12_000);
|
||||
totalRedacted += invRedacted.redactedCount;
|
||||
if (invRedacted.truncated) anyTruncated = true;
|
||||
|
||||
const ctxRedacted = redactSecrets(
|
||||
opts.contextText ?? '',
|
||||
knownSecrets,
|
||||
aiCfg.maxContextChars,
|
||||
);
|
||||
totalRedacted += ctxRedacted.redactedCount;
|
||||
if (ctxRedacted.truncated) anyTruncated = true;
|
||||
|
||||
const sanitizedMessages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }> = [
|
||||
{
|
||||
role: 'system',
|
||||
content: [
|
||||
guide.systemPrompt,
|
||||
'',
|
||||
'SANITIZED HUB INVENTORY:',
|
||||
invRedacted.text,
|
||||
...(ctxRedacted.text.trim()
|
||||
? ['', 'ATTACHED SANITIZED CONTEXT:', ctxRedacted.text]
|
||||
: []),
|
||||
].join('\n'),
|
||||
},
|
||||
];
|
||||
|
||||
for (const msg of opts.messages) {
|
||||
const mRedacted = redactSecrets(msg.content, knownSecrets, aiCfg.maxContextChars);
|
||||
totalRedacted += mRedacted.redactedCount;
|
||||
if (mRedacted.truncated) anyTruncated = true;
|
||||
sanitizedMessages.push({ role: msg.role, content: mRedacted.text });
|
||||
}
|
||||
|
||||
const chatId = opts.chatId?.trim() || `chat-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const abortController = new AbortController();
|
||||
const state: ActiveAiChat = {
|
||||
chatId,
|
||||
abortController,
|
||||
frames: [],
|
||||
replayBytes: 0,
|
||||
done: false,
|
||||
};
|
||||
this.chats.set(chatId, state);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'ai.chat',
|
||||
actorIp: opts.actorIp,
|
||||
sessionIdHash: opts.sessionIdHash,
|
||||
target: opts.surface,
|
||||
status: 'ok',
|
||||
details: {
|
||||
chatId,
|
||||
model: aiCfg.model,
|
||||
redactedCount: totalRedacted,
|
||||
},
|
||||
});
|
||||
|
||||
const endpointUrl = normalizeChatCompletionsUrl(aiCfg.baseUrl);
|
||||
const bearer = this.resolveBearerToken(aiCfg.secretRef);
|
||||
|
||||
void this.runStreamingRequest(state, endpointUrl, aiCfg.model, sanitizedMessages, bearer);
|
||||
|
||||
return {
|
||||
chatId,
|
||||
redactedCount: totalRedacted,
|
||||
truncated: anyTruncated,
|
||||
};
|
||||
}
|
||||
|
||||
private emitDelta(
|
||||
chat: ActiveAiChat,
|
||||
frame: { chunk: string; done?: boolean; error?: string },
|
||||
): void {
|
||||
const fullFrame: ServerWsFrame = {
|
||||
type: 'ai:delta',
|
||||
chatId: chat.chatId,
|
||||
chunk: frame.chunk,
|
||||
...(frame.done ? { done: true } : {}),
|
||||
...(frame.error ? { error: frame.error } : {}),
|
||||
};
|
||||
const bytes = Buffer.byteLength(JSON.stringify(fullFrame), 'utf8');
|
||||
chat.frames.push(fullFrame);
|
||||
chat.replayBytes += bytes;
|
||||
while (chat.replayBytes > MAX_REPLAY_BYTES && chat.frames.length > 0) {
|
||||
const dropped = chat.frames.shift()!;
|
||||
chat.replayBytes -= Buffer.byteLength(JSON.stringify(dropped), 'utf8');
|
||||
}
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.ai(chat.chatId), fullFrame);
|
||||
}
|
||||
|
||||
private async runStreamingRequest(
|
||||
chat: ActiveAiChat,
|
||||
endpointUrl: string,
|
||||
model: string,
|
||||
messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>,
|
||||
bearerToken?: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/event-stream, application/json',
|
||||
};
|
||||
if (bearerToken) {
|
||||
headers.Authorization = `Bearer ${bearerToken}`;
|
||||
}
|
||||
|
||||
const res = await fetch(endpointUrl, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ model, stream: true, messages }),
|
||||
signal: chat.abortController.signal,
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const errBody = await res.text().catch(() => '');
|
||||
this.emitDelta(chat, {
|
||||
chunk: '',
|
||||
done: true,
|
||||
error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = res.headers.get('content-type') ?? '';
|
||||
if (!contentType.includes('text/event-stream') || !res.body) {
|
||||
const jsonData = (await res.json().catch(() => ({}))) as {
|
||||
choices?: Array<{ message?: { content?: string }; text?: string }>;
|
||||
};
|
||||
const content =
|
||||
jsonData.choices?.[0]?.message?.content ?? jsonData.choices?.[0]?.text ?? '';
|
||||
if (content) {
|
||||
this.emitDelta(chat, { chunk: content });
|
||||
}
|
||||
this.emitDelta(chat, { chunk: '', done: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buf = '';
|
||||
let doneSent = false;
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
buf += decoder.decode(value, { stream: true });
|
||||
|
||||
let nlIdx: number;
|
||||
while ((nlIdx = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, nlIdx).trim();
|
||||
buf = buf.slice(nlIdx + 1);
|
||||
if (!line || !line.startsWith('data:')) continue;
|
||||
const payloadStr = line.slice(5).trim();
|
||||
if (payloadStr === '[DONE]') {
|
||||
doneSent = true;
|
||||
this.emitDelta(chat, { chunk: '', done: true });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(payloadStr) as {
|
||||
choices?: Array<{
|
||||
delta?: { content?: string };
|
||||
message?: { content?: string };
|
||||
}>;
|
||||
error?: { message?: string };
|
||||
};
|
||||
if (parsed.error?.message) {
|
||||
doneSent = true;
|
||||
this.emitDelta(chat, { chunk: '', done: true, error: parsed.error.message });
|
||||
return;
|
||||
}
|
||||
const chunk =
|
||||
parsed.choices?.[0]?.delta?.content ??
|
||||
parsed.choices?.[0]?.message?.content ??
|
||||
'';
|
||||
if (chunk) {
|
||||
this.emitDelta(chat, { chunk });
|
||||
}
|
||||
} catch {
|
||||
// Ignore partial/non-JSON keepalive lines
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!doneSent) {
|
||||
this.emitDelta(chat, { chunk: '', done: true });
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = chat.abortController.signal.aborted
|
||||
? 'Generation cancelled'
|
||||
: err instanceof Error
|
||||
? err.message
|
||||
: String(err);
|
||||
this.emitDelta(chat, {
|
||||
chunk: '',
|
||||
done: true,
|
||||
error: chat.abortController.signal.aborted ? undefined : msg,
|
||||
});
|
||||
} finally {
|
||||
chat.done = true;
|
||||
this.pruneChats();
|
||||
}
|
||||
}
|
||||
|
||||
private pruneChats(): void {
|
||||
const done = [...this.chats.values()].filter((c) => c.done);
|
||||
while (done.length > MAX_RETAINED_CHATS) {
|
||||
const oldest = done.shift()!;
|
||||
this.chats.delete(oldest.chatId);
|
||||
}
|
||||
}
|
||||
|
||||
async testEndpoint(override?: {
|
||||
baseUrl?: string;
|
||||
model?: string;
|
||||
secretRef?: string;
|
||||
}): Promise<{ ok: boolean; latencyMs: number; replyPreview?: string; error?: string }> {
|
||||
const saved = this.configManager.getSettings().ai;
|
||||
const baseUrl = override?.baseUrl?.trim() || saved.baseUrl;
|
||||
const model = override?.model?.trim() || saved.model;
|
||||
const secretRef =
|
||||
override && 'secretRef' in override ? override.secretRef?.trim() || undefined : saved.secretRef;
|
||||
const url = normalizeChatCompletionsUrl(baseUrl);
|
||||
const bearer = this.resolveBearerToken(secretRef);
|
||||
const started = Date.now();
|
||||
|
||||
try {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (bearer) headers.Authorization = `Bearer ${bearer}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
stream: false,
|
||||
max_tokens: 16,
|
||||
messages: [{ role: 'user', content: 'Reply with OK' }],
|
||||
}),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const latencyMs = Date.now() - started;
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => '');
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs,
|
||||
error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`,
|
||||
};
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as {
|
||||
choices?: Array<{ message?: { content?: string }; text?: string }>;
|
||||
};
|
||||
const preview =
|
||||
data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected';
|
||||
return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) };
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: Date.now() - started,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
validateDraft(opts: {
|
||||
kind: AiDraftKind;
|
||||
jsonText: string;
|
||||
targetId?: string;
|
||||
}):
|
||||
| {
|
||||
valid: true;
|
||||
kind: AiDraftKind;
|
||||
targetPath: string;
|
||||
id?: string;
|
||||
normalizedJson: string;
|
||||
diffLines: DiffLine[];
|
||||
}
|
||||
| {
|
||||
valid: false;
|
||||
issues: Array<{ path: string; message: string }>;
|
||||
} {
|
||||
let cleaned = opts.jsonText.trim();
|
||||
const fenceMatch = /^```(?:json)?\s*\r?\n([\s\S]*?)\r?\n```\s*$/i.exec(cleaned);
|
||||
if (fenceMatch?.[1]) {
|
||||
cleaned = fenceMatch[1].trim();
|
||||
}
|
||||
|
||||
let rawObj: unknown;
|
||||
try {
|
||||
rawObj = JSON.parse(cleaned);
|
||||
} catch (err) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: [
|
||||
{
|
||||
path: '(json)',
|
||||
message: err instanceof Error ? err.message : 'Invalid JSON syntax',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const withOptionalId = (obj: unknown) =>
|
||||
opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj)
|
||||
? { ...(obj as Record<string, unknown>), id: (obj as Record<string, unknown>).id ?? opts.targetId }
|
||||
: obj;
|
||||
|
||||
let targetPath: string;
|
||||
let normalizedJson: string;
|
||||
let entityId: string | undefined;
|
||||
|
||||
if (opts.kind === 'workflow') {
|
||||
const parsed = WorkflowConfigSchema.safeParse(withOptionalId(rawObj));
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
entityId = parsed.data.id;
|
||||
targetPath = `workflows/${entityId}.json`;
|
||||
normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`;
|
||||
} else if (opts.kind === 'system') {
|
||||
const parsed = SystemConfigSchema.safeParse(withOptionalId(rawObj));
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
entityId = parsed.data.id;
|
||||
targetPath = `systems/${entityId}.json`;
|
||||
normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`;
|
||||
} else if (opts.kind === 'server') {
|
||||
const parsed = ServerConfigSchema.safeParse(withOptionalId(rawObj));
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
entityId = parsed.data.id;
|
||||
targetPath = `servers/${entityId}.json`;
|
||||
normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`;
|
||||
} else if (opts.kind === 'snippet') {
|
||||
const parsed = SnippetSchema.safeParse(withOptionalId(rawObj));
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
entityId = parsed.data.id;
|
||||
targetPath = 'snippets.json';
|
||||
const current = this.configManager.getSnippets();
|
||||
const exists = current.snippets.some((s) => s.id === parsed.data.id);
|
||||
const nextSnippets = SnippetsFileSchema.parse({
|
||||
version: 1,
|
||||
snippets: exists
|
||||
? current.snippets.map((s) => (s.id === parsed.data.id ? parsed.data : s))
|
||||
: [...current.snippets, parsed.data],
|
||||
});
|
||||
normalizedJson = `${JSON.stringify(nextSnippets, null, 2)}\n`;
|
||||
} else if (opts.kind === 'alerts') {
|
||||
const candidate =
|
||||
rawObj && typeof rawObj === 'object' && !Array.isArray(rawObj)
|
||||
? { version: 1, ...(rawObj as Record<string, unknown>) }
|
||||
: rawObj;
|
||||
const parsed = AlertsFileSchema.safeParse(candidate);
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
targetPath = 'alerts.json';
|
||||
normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`;
|
||||
} else {
|
||||
const candidate =
|
||||
rawObj && typeof rawObj === 'object' && !Array.isArray(rawObj)
|
||||
? { version: 1, ...(rawObj as Record<string, unknown>) }
|
||||
: rawObj;
|
||||
const parsed = SettingsSchema.safeParse(candidate);
|
||||
if (!parsed.success) {
|
||||
return {
|
||||
valid: false,
|
||||
issues: parsed.error.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
};
|
||||
}
|
||||
targetPath = 'settings.json';
|
||||
normalizedJson = `${JSON.stringify(parsed.data, null, 2)}\n`;
|
||||
}
|
||||
|
||||
let currentContent = '';
|
||||
try {
|
||||
currentContent = this.configManager.readRawFile(targetPath).rawContent;
|
||||
} catch {
|
||||
currentContent = '';
|
||||
}
|
||||
const diff = computeLineDiff(currentContent, normalizedJson, 'existing', 'draft');
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
kind: opts.kind,
|
||||
targetPath,
|
||||
id: entityId,
|
||||
normalizedJson,
|
||||
diffLines: diff.lines,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const AiDraftKindSchema = z.enum([
|
||||
'workflow',
|
||||
'system',
|
||||
'snippet',
|
||||
'server',
|
||||
'alerts',
|
||||
'settings',
|
||||
]);
|
||||
159
src/server/ai/guides.ts
Normal file
159
src/server/ai/guides.ts
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
import { z } from 'zod';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
|
||||
export const AiSurfaceSchema = z.enum(['workflows', 'systems', 'snippets', 'logs', 'setup']);
|
||||
export type AiSurface = z.infer<typeof AiSurfaceSchema>;
|
||||
|
||||
export type AiDraftKind = 'workflow' | 'system' | 'snippet' | 'server' | 'alerts' | 'settings';
|
||||
|
||||
export interface SurfaceGuideResult {
|
||||
systemPrompt: string;
|
||||
inventorySummary: string;
|
||||
defaultDraftKind?: AiDraftKind;
|
||||
}
|
||||
|
||||
export function buildSurfaceGuideAndInventory(
|
||||
surface: AiSurface,
|
||||
deps: {
|
||||
configManager: ConfigManager;
|
||||
vaultService: VaultService;
|
||||
sshPool: SSHPool;
|
||||
},
|
||||
opts: {
|
||||
serverId?: string;
|
||||
targetPath?: string;
|
||||
} = {},
|
||||
): SurfaceGuideResult {
|
||||
const { configManager, vaultService, sshPool } = deps;
|
||||
const servers = configManager.listServers();
|
||||
const systems = configManager.listSystems();
|
||||
const snippets = configManager.getSnippets().snippets;
|
||||
const workflows = configManager.listWorkflows();
|
||||
const alerts = configManager.getAlerts();
|
||||
|
||||
const serverSummary = servers.map((s) => ({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
tags: s.tags,
|
||||
os: sshPool.getState(s.id)?.osDetected ?? s.osHint,
|
||||
enabled: s.enabled,
|
||||
systems: s.systems.map((a) => a.systemId),
|
||||
probes: s.probes.map((p) => p.id),
|
||||
tunnels: s.tunnels.map((t) => ({ id: t.id, mode: t.mode, targetPort: t.targetPort })),
|
||||
}));
|
||||
|
||||
const systemSummary = systems.map((sys) => ({
|
||||
id: sys.id,
|
||||
name: sys.name,
|
||||
discoveryType: sys.discovery.type,
|
||||
actions: sys.actions.map((a) => ({ id: a.id, scope: a.scope, mode: a.mode })),
|
||||
}));
|
||||
|
||||
const credMeta = vaultService.isRuntimeReady
|
||||
? vaultService.listMetadata().map((c) => ({ id: c.id, name: c.name, type: c.type }))
|
||||
: [];
|
||||
|
||||
const targetSrv = opts.serverId ? configManager.getServer(opts.serverId) : undefined;
|
||||
const targetSrvOs = opts.serverId
|
||||
? sshPool.getState(opts.serverId)?.osDetected ?? targetSrv?.osHint ?? 'unknown'
|
||||
: undefined;
|
||||
|
||||
const inventorySummary = JSON.stringify(
|
||||
{
|
||||
servers: serverSummary,
|
||||
systems: systemSummary,
|
||||
existingWorkflowIds: workflows.map((w) => w.id),
|
||||
existingSnippetIds: snippets.map((s) => s.id),
|
||||
alertChannelIds: alerts.channels.map((c) => c.id),
|
||||
vaultCredentialRefs: credMeta,
|
||||
...(opts.serverId ? { focusedServer: { id: opts.serverId, os: targetSrvOs } } : {}),
|
||||
...(opts.targetPath ? { focusedConfigPath: opts.targetPath } : {}),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
|
||||
const commonRules = [
|
||||
'You are the built-in assistant for GCoordinator, a single-admin agentless SSH hub.',
|
||||
'STRICT GUARDRAILS: Never assume auto-execution. Output config JSON inside a ```json code block so the user can inspect, Zod-validate, diff, and confirm before saving.',
|
||||
'Never invent secret values; always reference existing Vault credential IDs via credentialId/secretRef.',
|
||||
].join('\n');
|
||||
|
||||
switch (surface) {
|
||||
case 'workflows':
|
||||
return {
|
||||
defaultDraftKind: 'workflow',
|
||||
inventorySummary,
|
||||
systemPrompt: [
|
||||
commonRules,
|
||||
'SURFACE: Workflows DAG Editor.',
|
||||
'Schema rules (workflows/<id>.json):',
|
||||
'- Required fields: id (slug [a-zA-Z0-9._-]), name, enabled (boolean), trigger ({type:"manual"} | {type:"cron",expression,timezone} | {type:"event",event:"server.offline"|"server.online"|"probe.failed"|"system.unhealthy"|"alert.fired"}), overlapPolicy ("skip"|"queue"|"cancel-previous"), display ({mode:"log"|"file-view"|"json"|"table"|"summary",pinToDashboard:boolean}), inputs ([]), steps ([] non-empty DAG).',
|
||||
'- Step types: "exec" (target:{serverId|tags|all}, command), "read-file" (target, path, tailLines?), "system-action" (target, systemId, action, item), "transfer" (mode:"hub-relayed"|"direct", source:{serverId,path}, destination:{serverId,path}).',
|
||||
'- DAG edges: dependsOn uses string stepIds or {stepId, on:"success"|"failure"|"always"}; must be acyclic.',
|
||||
'- Safety: Use {{inputs.x}}, {{steps.id.stdout}}, {{captures.alias}} (auto single-quoted in shell) or $GCOORD_INPUT_X env vars.',
|
||||
].join('\n'),
|
||||
};
|
||||
|
||||
case 'systems':
|
||||
return {
|
||||
defaultDraftKind: 'system',
|
||||
inventorySummary,
|
||||
systemPrompt: [
|
||||
commonRules,
|
||||
'SURFACE: Custom Systems Editor.',
|
||||
'Schema rules (systems/<id>.json):',
|
||||
'- Fields: id (slug), name, cacheTtlSec, params ([{name,type:"string"|"number"|"boolean"|"string[]",default?,required?}]), discovery ({type:"folder-scan",rootsParam,maxDepth,matchFiles,selectableFiles?} | {type:"command",command,parser:"lines"|"json"|"json-lines"}), status ({command,parser:"json-lines"|"json"|"lines"|"regex"|"exit-code",subItemField?,regexPattern?,health?}), actions ([{id,label,scope:"system"|"item"|"subitem",mode:"oneshot"|"stream"|"interactive",command,sudo,confirm}]), editableFiles ([".env", ...]).',
|
||||
'- Runtime env vars injected safely: $GCOORD_ITEM_NAME, $GCOORD_ITEM_DIR, $GCOORD_SUBITEM, $GCOORD_ACTIVE_FILES, $GCOORD_PARAM_<NAME>. Never interpolate untrusted strings unquoted.',
|
||||
].join('\n'),
|
||||
};
|
||||
|
||||
case 'snippets':
|
||||
return {
|
||||
defaultDraftKind: 'snippet',
|
||||
inventorySummary,
|
||||
systemPrompt: [
|
||||
commonRules,
|
||||
'SURFACE: Terminal Commands & Reusable Snippets.',
|
||||
'- When generating a reusable Snippet JSON block (for snippets.json entry), follow:',
|
||||
' { id (slug), name, description?, command, tags: string[], inputs: [{name,type:"string"|"number"|"boolean"|"server"|"select",label?,required,default?,options?}], sudo: boolean, confirm: boolean }.',
|
||||
'- If answering an interactive terminal request with a one-off shell command, also provide a ```sh block (without destructive auto-execution).',
|
||||
targetSrvOs ? `- Target host OS hint: ${targetSrvOs}. Tailor flags/utilities accordingly.` : '',
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join('\n'),
|
||||
};
|
||||
|
||||
case 'logs':
|
||||
return {
|
||||
inventorySummary,
|
||||
systemPrompt: [
|
||||
commonRules,
|
||||
'SURFACE: Log & Alert Debugger.',
|
||||
'- Analyze the sanitized log tail, exit code, or alert incident.',
|
||||
'- Explain the likely root cause concisely in monospace-friendly plain text/bullet points.',
|
||||
'- Propose safe read-only verification commands (e.g. checking status/journal/logs) before any mutating fix.',
|
||||
].join('\n'),
|
||||
};
|
||||
|
||||
case 'setup':
|
||||
return {
|
||||
defaultDraftKind: opts.targetPath?.startsWith('servers/')
|
||||
? 'server'
|
||||
: opts.targetPath === 'alerts.json'
|
||||
? 'alerts'
|
||||
: opts.targetPath === 'settings.json'
|
||||
? 'settings'
|
||||
: 'alerts',
|
||||
inventorySummary,
|
||||
systemPrompt: [
|
||||
commonRules,
|
||||
'SURFACE: Infrastructure Setup, Probes, Jump Hosts & Alerting Helper.',
|
||||
'- Help configure servers/<id>.json (credentialId, jumpHostId, sudoCredentialId, probes[], tunnels[]), alerts.json (channels[], rules[] with kind "metric"|"disk"|"offline"|"probe"|"system", maintenanceWindows[]), or settings.json.',
|
||||
'- Reference existing Vault secretRef/credentialId IDs from inventory.',
|
||||
].join('\n'),
|
||||
};
|
||||
}
|
||||
}
|
||||
129
src/server/ai/redactor.ts
Normal file
129
src/server/ai/redactor.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import type { VaultService } from '../security/vault.js';
|
||||
|
||||
export interface RedactionResult {
|
||||
text: string;
|
||||
redactedCount: number;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
function escapeRegExp(literal: string): string {
|
||||
return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
export function collectVaultSecretStrings(vaultService: VaultService): string[] {
|
||||
if (!vaultService.isRuntimeReady) return [];
|
||||
|
||||
const collected = new Set<string>();
|
||||
try {
|
||||
const creds = vaultService.exportAllCredentials();
|
||||
for (const cred of Object.values(creds)) {
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') {
|
||||
if (cred.password.length >= 6) collected.add(cred.password);
|
||||
} else if (cred.type === 'webhook-secret') {
|
||||
if (cred.secret.length >= 6) collected.add(cred.secret);
|
||||
} else if (cred.type === 'api-token') {
|
||||
if (cred.token.length >= 6) collected.add(cred.token);
|
||||
} else if (cred.type === 'ssh-key') {
|
||||
const trimmed = cred.privateKey.trim();
|
||||
if (trimmed.length >= 6) collected.add(trimmed);
|
||||
for (const line of trimmed.split(/\r?\n/)) {
|
||||
const l = line.trim();
|
||||
if (l.length >= 12 && !l.startsWith('-----')) {
|
||||
collected.add(l);
|
||||
}
|
||||
}
|
||||
if (cred.passphrase && cred.passphrase.length >= 6) {
|
||||
collected.add(cred.passphrase);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [...collected].sort((a, b) => b.length - a.length);
|
||||
}
|
||||
|
||||
export function redactSecrets(
|
||||
input: string,
|
||||
knownSecrets: string[] = [],
|
||||
maxChars = 16_000,
|
||||
): RedactionResult {
|
||||
let redactedCount = 0;
|
||||
let text = input ?? '';
|
||||
|
||||
// 1. Strip PEM / OpenSSH private key blocks
|
||||
const keyBlockRe =
|
||||
/-----BEGIN [A-Z0-9 -]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 -]*PRIVATE KEY-----/g;
|
||||
text = text.replace(keyBlockRe, () => {
|
||||
redactedCount += 1;
|
||||
return '[REDACTED_PRIVATE_KEY]';
|
||||
});
|
||||
|
||||
// 2. Strip known secrets currently held in Vault
|
||||
for (const secret of knownSecrets) {
|
||||
if (secret.length < 6) continue;
|
||||
const re = new RegExp(escapeRegExp(secret), 'g');
|
||||
text = text.replace(re, () => {
|
||||
redactedCount += 1;
|
||||
return '[REDACTED_VAULT_SECRET]';
|
||||
});
|
||||
}
|
||||
|
||||
// 3. Strip HTTP Authorization / Bearer / custom secret headers
|
||||
text = text.replace(
|
||||
/\b(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\r\n]+)/gi,
|
||||
(_m, prefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${prefix}[REDACTED_TOKEN]`;
|
||||
},
|
||||
);
|
||||
text = text.replace(
|
||||
/\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g,
|
||||
(_m, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return 'Bearer [REDACTED_TOKEN]';
|
||||
},
|
||||
);
|
||||
text = text.replace(
|
||||
/\b(X-(?:API-Key|Telegram-Bot-Token|Auth-Token)\s*:\s*)([^\s\r\n]+)/gi,
|
||||
(_m, prefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${prefix}[REDACTED_TOKEN]`;
|
||||
},
|
||||
);
|
||||
|
||||
// 4. Strip .env / shell KEY=value secret assignments
|
||||
text = text.replace(
|
||||
/(^|[\s;|&])([A-Za-z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE)[A-Za-z0-9_]*)=("[^"\n]*"|'[^'\n]*'|[^\s\r\n]+)/gim,
|
||||
(_m, lead: string, key: string, rawVal: string) => {
|
||||
if (rawVal.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${lead}${key}=[REDACTED_SECRET]`;
|
||||
},
|
||||
);
|
||||
|
||||
// 5. Strip JSON "key": "secret" string properties
|
||||
text = text.replace(
|
||||
/("(?:[A-Za-z0-9_-]*(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase)[A-Za-z0-9_-]*)"\s*:\s*)"([^"\\]*(?:\\.[^"\\]*)*)"/gi,
|
||||
(_m, keyPrefix: string, val: string) => {
|
||||
if (val.includes('[REDACTED')) return _m;
|
||||
redactedCount += 1;
|
||||
return `${keyPrefix}"[REDACTED_SECRET]"`;
|
||||
},
|
||||
);
|
||||
|
||||
const cap = Math.max(256, maxChars);
|
||||
let truncated = false;
|
||||
if (text.length > cap) {
|
||||
truncated = true;
|
||||
const prefix = '...[truncated older context]...\n';
|
||||
const tailLen = Math.max(64, cap - prefix.length);
|
||||
text = `${prefix}${text.slice(-tailLen)}`;
|
||||
}
|
||||
|
||||
return { text, redactedCount, truncated };
|
||||
}
|
||||
869
src/server/alerts/alert-engine.ts
Normal file
869
src/server/alerts/alert-engine.ts
Normal file
|
|
@ -0,0 +1,869 @@
|
|||
import crypto from 'node:crypto';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { Cron } from 'croner';
|
||||
import type {
|
||||
AlertChannel,
|
||||
AlertRule,
|
||||
AlertRuleTargetSchema,
|
||||
} from '../../shared/schemas/alerts.schema.js';
|
||||
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
||||
import type { z } from 'zod';
|
||||
import { WS_CHANNELS, type DiskSample, type ProbeSample } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { WorkflowEngine } from '../automation/workflow-engine.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type {
|
||||
MonitoringService,
|
||||
MonitoringTickEvent,
|
||||
} from '../monitoring/monitoring-service.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import type {
|
||||
CustomSystemsEngine,
|
||||
ServerSystemSnapshot,
|
||||
} from '../systems/systems-engine.js';
|
||||
|
||||
type AlertRuleTarget = z.infer<typeof AlertRuleTargetSchema>;
|
||||
|
||||
export interface AlertEventRecord {
|
||||
id: string;
|
||||
ruleId: string;
|
||||
serverId: string | null;
|
||||
state: 'firing' | 'resolved';
|
||||
severity: 'warn' | 'critical';
|
||||
message: string;
|
||||
webhookStatus: string | null;
|
||||
triggeredAt: number;
|
||||
resolvedAt: number | null;
|
||||
incidentKey?: string | null;
|
||||
}
|
||||
|
||||
export interface AlertSilenceRecord {
|
||||
id: string;
|
||||
scopeType: 'all' | 'rule' | 'server' | 'tag';
|
||||
targetId: string;
|
||||
reason: string | null;
|
||||
createdAt: number;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface IncidentRuntimeState {
|
||||
consecutiveFailures: number;
|
||||
firingEventId?: string;
|
||||
lastNotifiedAt?: number;
|
||||
}
|
||||
|
||||
const OFFLINE_SWEEP_MS = 5000;
|
||||
|
||||
export class AlertEngine {
|
||||
private readonly incidents = new Map<string, IncidentRuntimeState>();
|
||||
private readonly disconnectedSince = new Map<string, number>();
|
||||
private readonly prevOnlineState = new Map<string, boolean>();
|
||||
private readonly emittedOffline = new Set<string>();
|
||||
private readonly prevProbeOk = new Map<string, boolean>();
|
||||
private readonly prevSystemDown = new Set<string>();
|
||||
private readonly unsubs: Array<() => void> = [];
|
||||
private sweepTimer: NodeJS.Timeout | null = null;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly db: Database.Database,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly vaultService: VaultService,
|
||||
private readonly monitoringService: MonitoringService,
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly customSystemsEngine: CustomSystemsEngine,
|
||||
private readonly workflowEngine: WorkflowEngine,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
start(): void {
|
||||
this.stopped = false;
|
||||
this.hydrateOpenIncidents();
|
||||
|
||||
this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => {
|
||||
await this.sendDirectChannelMessage(channelId, {
|
||||
severity: 'critical',
|
||||
title: 'Workflow Execution Failure',
|
||||
message,
|
||||
state: 'firing',
|
||||
});
|
||||
});
|
||||
|
||||
this.unsubs.push(
|
||||
this.monitoringService.onTick((ev) => {
|
||||
void this.evaluateTick(ev);
|
||||
}),
|
||||
);
|
||||
this.unsubs.push(
|
||||
this.monitoringService.onProbe(({ serverId, probe }) => {
|
||||
void this.evaluateProbe(serverId, probe);
|
||||
}),
|
||||
);
|
||||
this.unsubs.push(
|
||||
this.customSystemsEngine.onHealthSnapshot((snapshot) => {
|
||||
void this.evaluateSystemSnapshot(snapshot);
|
||||
}),
|
||||
);
|
||||
this.unsubs.push(
|
||||
this.sshPool.onStateChange((states) => {
|
||||
const now = Date.now();
|
||||
for (const st of states) {
|
||||
const srv = this.configManager.getServer(st.serverId);
|
||||
if (!srv || !srv.enabled) {
|
||||
this.disconnectedSince.delete(st.serverId);
|
||||
this.emittedOffline.delete(st.serverId);
|
||||
this.prevOnlineState.delete(st.serverId);
|
||||
continue;
|
||||
}
|
||||
const wasOnline = this.prevOnlineState.get(st.serverId);
|
||||
if (st.status === 'connected') {
|
||||
this.disconnectedSince.delete(st.serverId);
|
||||
if (wasOnline === false || this.emittedOffline.has(st.serverId)) {
|
||||
this.emittedOffline.delete(st.serverId);
|
||||
void this.workflowEngine.handleSystemEvent({
|
||||
event: 'server.online',
|
||||
serverId: st.serverId,
|
||||
});
|
||||
}
|
||||
this.prevOnlineState.set(st.serverId, true);
|
||||
} else {
|
||||
if (!this.disconnectedSince.has(st.serverId)) {
|
||||
this.disconnectedSince.set(st.serverId, now);
|
||||
}
|
||||
if (wasOnline === true && !this.emittedOffline.has(st.serverId)) {
|
||||
this.emittedOffline.add(st.serverId);
|
||||
void this.workflowEngine.handleSystemEvent({
|
||||
event: 'server.offline',
|
||||
serverId: st.serverId,
|
||||
message: st.lastError,
|
||||
});
|
||||
}
|
||||
this.prevOnlineState.set(st.serverId, false);
|
||||
}
|
||||
}
|
||||
void this.sweepOfflineRules(now);
|
||||
}),
|
||||
);
|
||||
|
||||
this.sweepTimer = setInterval(() => {
|
||||
if (!this.stopped) {
|
||||
void this.sweepOfflineRules(Date.now());
|
||||
}
|
||||
}, OFFLINE_SWEEP_MS);
|
||||
this.sweepTimer.unref();
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.stopped = true;
|
||||
while (this.unsubs.length > 0) {
|
||||
try {
|
||||
this.unsubs.pop()!();
|
||||
} catch {
|
||||
// Ignore unsub error
|
||||
}
|
||||
}
|
||||
if (this.sweepTimer) {
|
||||
clearInterval(this.sweepTimer);
|
||||
this.sweepTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
handlePanicLock(): void {
|
||||
this.disconnectedSince.clear();
|
||||
}
|
||||
|
||||
listSilences(nowMs = Date.now()): AlertSilenceRecord[] {
|
||||
this.db.prepare('DELETE FROM alert_silences WHERE expires_at <= ?').run(nowMs);
|
||||
return this.db
|
||||
.prepare(
|
||||
`SELECT id, scope_type AS scopeType, target_id AS targetId, reason,
|
||||
created_at AS createdAt, expires_at AS expiresAt
|
||||
FROM alert_silences
|
||||
WHERE expires_at > ?
|
||||
ORDER BY created_at DESC`,
|
||||
)
|
||||
.all(nowMs) as AlertSilenceRecord[];
|
||||
}
|
||||
|
||||
createSilence(opts: {
|
||||
scopeType: 'all' | 'rule' | 'server' | 'tag';
|
||||
targetId: string;
|
||||
durationMinutes: number;
|
||||
reason?: string;
|
||||
actorIp?: string;
|
||||
sessionIdHash?: string | null;
|
||||
}): AlertSilenceRecord {
|
||||
const id = `sil-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const createdAt = Date.now();
|
||||
const expiresAt = createdAt + Math.max(1, Math.min(opts.durationMinutes, 43_200)) * 60_000;
|
||||
const targetId = opts.scopeType === 'all' ? '*' : opts.targetId.trim();
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO alert_silences (id, scope_type, target_id, reason, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.run(id, opts.scopeType, targetId, opts.reason ?? null, createdAt, expiresAt);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'alert.silence_create',
|
||||
actorIp: opts.actorIp ?? 'system',
|
||||
sessionIdHash: opts.sessionIdHash ?? null,
|
||||
target: `${opts.scopeType}:${targetId}`,
|
||||
status: 'ok',
|
||||
details: { id, durationMinutes: opts.durationMinutes },
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
scopeType: opts.scopeType,
|
||||
targetId,
|
||||
reason: opts.reason ?? null,
|
||||
createdAt,
|
||||
expiresAt,
|
||||
};
|
||||
}
|
||||
|
||||
deleteSilence(id: string): boolean {
|
||||
const info = this.db.prepare('DELETE FROM alert_silences WHERE id = ?').run(id);
|
||||
return info.changes > 0;
|
||||
}
|
||||
|
||||
getActiveCount(): number {
|
||||
const row = this.db
|
||||
.prepare(`SELECT COUNT(*) AS cnt FROM alert_events WHERE state = 'firing'`)
|
||||
.get() as { cnt: number };
|
||||
return row.cnt;
|
||||
}
|
||||
|
||||
getActiveMaintenanceWindowIds(nowMs = Date.now()): string[] {
|
||||
const windows = this.configManager.getAlerts().maintenanceWindows;
|
||||
const activeIds: string[] = [];
|
||||
for (const win of windows) {
|
||||
if (!win.enabled) continue;
|
||||
if (this.isCronWindowActiveNow(win.cron, win.timezone, win.durationMinutes, nowMs)) {
|
||||
activeIds.push(win.id);
|
||||
}
|
||||
}
|
||||
return activeIds;
|
||||
}
|
||||
|
||||
getSummary(limit = 50): {
|
||||
activeCount: number;
|
||||
activeEvents: AlertEventRecord[];
|
||||
recentEvents: AlertEventRecord[];
|
||||
silences: AlertSilenceRecord[];
|
||||
activeMaintenanceWindowIds: string[];
|
||||
} {
|
||||
const activeEvents = this.db
|
||||
.prepare(
|
||||
`SELECT id, rule_id AS ruleId, server_id AS serverId, state, severity, message,
|
||||
webhook_status AS webhookStatus, triggered_at AS triggeredAt, resolved_at AS resolvedAt,
|
||||
incident_key AS incidentKey
|
||||
FROM alert_events
|
||||
WHERE state = 'firing'
|
||||
ORDER BY triggered_at DESC`,
|
||||
)
|
||||
.all() as AlertEventRecord[];
|
||||
|
||||
const recentEvents = this.db
|
||||
.prepare(
|
||||
`SELECT id, rule_id AS ruleId, server_id AS serverId, state, severity, message,
|
||||
webhook_status AS webhookStatus, triggered_at AS triggeredAt, resolved_at AS resolvedAt,
|
||||
incident_key AS incidentKey
|
||||
FROM alert_events
|
||||
ORDER BY triggered_at DESC
|
||||
LIMIT ?`,
|
||||
)
|
||||
.all(Math.max(1, Math.min(limit, 200))) as AlertEventRecord[];
|
||||
|
||||
return {
|
||||
activeCount: activeEvents.length,
|
||||
activeEvents,
|
||||
recentEvents,
|
||||
silences: this.listSilences(),
|
||||
activeMaintenanceWindowIds: this.getActiveMaintenanceWindowIds(),
|
||||
};
|
||||
}
|
||||
|
||||
async sendTestAlert(
|
||||
channelId: string,
|
||||
actor: { ip: string; sessionIdHash: string | null },
|
||||
): Promise<{ ok: boolean; statusCode?: number; error?: string }> {
|
||||
const ch = this.configManager.getAlerts().channels.find((c) => c.id === channelId);
|
||||
if (!ch) {
|
||||
throw new Error(`Unknown alert channel "${channelId}"`);
|
||||
}
|
||||
|
||||
const res = await this.dispatchToChannel(ch, {
|
||||
id: `test-${crypto.randomBytes(4).toString('hex')}`,
|
||||
ruleId: 'test-alert',
|
||||
serverId: 'hub',
|
||||
severity: 'warn',
|
||||
title: '[TEST] GCoordinator Alert Channel Verification',
|
||||
message: `Test notification dispatched to "${ch.name}" (${ch.type}) at ${new Date().toISOString()}.`,
|
||||
state: 'firing',
|
||||
ts: Date.now(),
|
||||
});
|
||||
|
||||
this.auditService.log({
|
||||
action: 'alert.test_channel',
|
||||
actorIp: actor.ip,
|
||||
sessionIdHash: actor.sessionIdHash,
|
||||
target: channelId,
|
||||
status: res.ok ? 'ok' : 'error',
|
||||
details: res,
|
||||
});
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
async evaluateTick(event: MonitoringTickEvent, nowMs = Date.now()): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const server = this.configManager.getServer(event.serverId);
|
||||
if (!server || !server.enabled) return;
|
||||
|
||||
const rules = this.configManager.getAlerts().rules.filter((r) => r.enabled);
|
||||
for (const rule of rules) {
|
||||
if (!this.matchesTarget(rule.target, server)) continue;
|
||||
|
||||
if (rule.kind === 'metric') {
|
||||
const val =
|
||||
rule.metric === 'cpuPct'
|
||||
? event.sample.cpuPct
|
||||
: rule.metric === 'load1m'
|
||||
? event.sample.load1m
|
||||
: event.sample.memTotalMb > 0
|
||||
? (event.sample.memUsedMb / event.sample.memTotalMb) * 100
|
||||
: 0;
|
||||
const breached = compareOp(val, rule.operator, rule.threshold);
|
||||
const key = `${rule.id}::${server.id}::metric`;
|
||||
const msg = `${rule.name} on ${server.name}: ${rule.metric}=${val.toFixed(1)} (${rule.operator} ${rule.threshold})`;
|
||||
await this.evaluateIncident(key, breached, rule, server, msg, nowMs);
|
||||
} else if (rule.kind === 'disk') {
|
||||
const matchedDisks: DiskSample[] = rule.mountPoint
|
||||
? event.disks.filter((d) => d.mountPoint === rule.mountPoint)
|
||||
: event.disks;
|
||||
for (const d of matchedDisks) {
|
||||
const breached = d.usedPct >= rule.thresholdPct;
|
||||
const key = `${rule.id}::${server.id}::disk::${d.mountPoint}`;
|
||||
const msg = `${rule.name} on ${server.name}: ${d.mountPoint} at ${d.usedPct}% (>= ${rule.thresholdPct}%)`;
|
||||
await this.evaluateIncident(key, breached, rule, server, msg, nowMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const probe of event.probes) {
|
||||
await this.evaluateProbe(server.id, probe, nowMs);
|
||||
}
|
||||
}
|
||||
|
||||
async evaluateProbe(
|
||||
serverId: string,
|
||||
probe: ProbeSample,
|
||||
nowMs = Date.now(),
|
||||
): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server || !server.enabled) return;
|
||||
|
||||
const pKey = `${server.id}::${probe.probeId}`;
|
||||
const prevOk = this.prevProbeOk.get(pKey);
|
||||
this.prevProbeOk.set(pKey, probe.ok);
|
||||
if (!probe.ok && prevOk !== false) {
|
||||
void this.workflowEngine.handleSystemEvent({
|
||||
event: 'probe.failed',
|
||||
serverId: server.id,
|
||||
probeId: probe.probeId,
|
||||
message: probe.error ?? `HTTP ${String(probe.statusCode ?? 'err')}`,
|
||||
});
|
||||
}
|
||||
|
||||
const rules = this.configManager
|
||||
.getAlerts()
|
||||
.rules.filter((r) => r.enabled && r.kind === 'probe');
|
||||
for (const rule of rules) {
|
||||
if (rule.kind !== 'probe') continue;
|
||||
if (!this.matchesTarget(rule.target, server)) continue;
|
||||
if (rule.probeId && rule.probeId !== probe.probeId) continue;
|
||||
|
||||
const key = `${rule.id}::${server.id}::probe::${probe.probeId}`;
|
||||
const msg = `${rule.name} on ${server.name}: probe "${probe.probeId}" failed${probe.error ? ` (${probe.error})` : ''}`;
|
||||
await this.evaluateIncident(key, !probe.ok, rule, server, msg, nowMs);
|
||||
}
|
||||
}
|
||||
|
||||
async evaluateSystemSnapshot(
|
||||
snapshot: ServerSystemSnapshot,
|
||||
nowMs = Date.now(),
|
||||
): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const server = this.configManager.getServer(snapshot.serverId);
|
||||
if (!server || !server.enabled) return;
|
||||
|
||||
const sysKey = `${server.id}::${snapshot.systemId}`;
|
||||
const wasDown = this.prevSystemDown.has(sysKey);
|
||||
if (snapshot.systemHealth === 'down' && !wasDown) {
|
||||
this.prevSystemDown.add(sysKey);
|
||||
void this.workflowEngine.handleSystemEvent({
|
||||
event: 'system.unhealthy',
|
||||
serverId: server.id,
|
||||
systemId: snapshot.systemId,
|
||||
message: snapshot.error,
|
||||
});
|
||||
} else if (snapshot.systemHealth === 'ok') {
|
||||
this.prevSystemDown.delete(sysKey);
|
||||
}
|
||||
|
||||
const rules = this.configManager
|
||||
.getAlerts()
|
||||
.rules.filter(
|
||||
(r) => r.enabled && r.kind === 'system' && r.systemId === snapshot.systemId,
|
||||
);
|
||||
|
||||
for (const rule of rules) {
|
||||
if (rule.kind !== 'system') continue;
|
||||
if (!this.matchesTarget(rule.target, server)) continue;
|
||||
|
||||
const items = rule.item
|
||||
? snapshot.items.filter((i) => i.name === rule.item)
|
||||
: snapshot.items;
|
||||
|
||||
if (items.length === 0 && snapshot.error) {
|
||||
const key = `${rule.id}::${server.id}::system::${snapshot.systemId}::__error`;
|
||||
await this.evaluateIncident(
|
||||
key,
|
||||
true,
|
||||
rule,
|
||||
server,
|
||||
`${rule.name} on ${server.name}: ${snapshot.systemId} error (${snapshot.error})`,
|
||||
nowMs,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const item of items) {
|
||||
const breached =
|
||||
rule.severity === 'warn'
|
||||
? item.status.health === 'down' || item.status.health === 'warn'
|
||||
: item.status.health === 'down';
|
||||
const key = `${rule.id}::${server.id}::system::${snapshot.systemId}::${item.name}`;
|
||||
const msg = `${rule.name} on ${server.name}: ${snapshot.systemId}/${item.name} is ${item.status.health.toUpperCase()}`;
|
||||
await this.evaluateIncident(key, breached, rule, server, msg, nowMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async sweepOfflineRules(nowMs = Date.now()): Promise<void> {
|
||||
if (this.stopped || !this.vaultService.isRuntimeReady) return;
|
||||
const rules = this.configManager
|
||||
.getAlerts()
|
||||
.rules.filter((r) => r.enabled && r.kind === 'offline');
|
||||
if (rules.length === 0) return;
|
||||
|
||||
const servers = this.configManager.listServers().filter((s) => s.enabled);
|
||||
for (const srv of servers) {
|
||||
const st = this.sshPool.getState(srv.id);
|
||||
const isConnected = st?.status === 'connected';
|
||||
if (!isConnected && !this.disconnectedSince.has(srv.id)) {
|
||||
this.disconnectedSince.set(srv.id, nowMs);
|
||||
}
|
||||
const since = this.disconnectedSince.get(srv.id);
|
||||
|
||||
for (const rule of rules) {
|
||||
if (rule.kind !== 'offline') continue;
|
||||
if (!this.matchesTarget(rule.target, srv)) continue;
|
||||
|
||||
const breached = !isConnected && since !== undefined && nowMs - since >= rule.offlineSec * 1000;
|
||||
const key = `${rule.id}::${srv.id}::offline`;
|
||||
const msg = `${rule.name}: ${srv.name} (${srv.host}) unreachable for >= ${rule.offlineSec}s`;
|
||||
await this.evaluateIncident(key, breached, rule, srv, msg, nowMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async evaluateIncident(
|
||||
incidentKey: string,
|
||||
breached: boolean,
|
||||
rule: AlertRule,
|
||||
server: ServerConfig,
|
||||
message: string,
|
||||
nowMs: number,
|
||||
): Promise<void> {
|
||||
let state = this.incidents.get(incidentKey);
|
||||
if (!state) {
|
||||
state = { consecutiveFailures: 0 };
|
||||
this.incidents.set(incidentKey, state);
|
||||
}
|
||||
|
||||
if (breached) {
|
||||
state.consecutiveFailures += 1;
|
||||
if (state.consecutiveFailures < rule.forConsecutivePolls) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!state.firingEventId) {
|
||||
const suppressed = this.isSuppressed(rule, server, nowMs);
|
||||
const eventId = `evt-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const initialWebhookStatus = suppressed ? 'suppressed' : 'pending';
|
||||
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO alert_events (id, rule_id, server_id, state, severity, message, webhook_status, triggered_at, resolved_at, incident_key)
|
||||
VALUES (?, ?, ?, 'firing', ?, ?, ?, ?, NULL, ?)`,
|
||||
)
|
||||
.run(
|
||||
eventId,
|
||||
rule.id,
|
||||
server.id,
|
||||
rule.severity,
|
||||
message,
|
||||
initialWebhookStatus,
|
||||
nowMs,
|
||||
incidentKey,
|
||||
);
|
||||
|
||||
state.firingEventId = eventId;
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, {
|
||||
type: 'alerts:update',
|
||||
activeCount: this.getActiveCount(),
|
||||
event: {
|
||||
id: eventId,
|
||||
ruleId: rule.id,
|
||||
serverId: server.id,
|
||||
severity: rule.severity,
|
||||
message,
|
||||
ts: nowMs,
|
||||
},
|
||||
});
|
||||
|
||||
if (!suppressed) {
|
||||
const inCooldown =
|
||||
state.lastNotifiedAt !== undefined &&
|
||||
nowMs - state.lastNotifiedAt < rule.cooldownSec * 1000;
|
||||
|
||||
if (!inCooldown) {
|
||||
state.lastNotifiedAt = nowMs;
|
||||
const statusText = await this.dispatchRuleChannels(rule.channelIds, {
|
||||
id: eventId,
|
||||
ruleId: rule.id,
|
||||
serverId: server.id,
|
||||
severity: rule.severity,
|
||||
title: `[${rule.severity.toUpperCase()}] ${rule.name}`,
|
||||
message,
|
||||
state: 'firing',
|
||||
ts: nowMs,
|
||||
});
|
||||
this.db
|
||||
.prepare('UPDATE alert_events SET webhook_status = ? WHERE id = ?')
|
||||
.run(statusText, eventId);
|
||||
} else {
|
||||
this.db
|
||||
.prepare(`UPDATE alert_events SET webhook_status = 'cooldown' WHERE id = ?`)
|
||||
.run(eventId);
|
||||
}
|
||||
|
||||
if (rule.remediationWorkflowId && this.vaultService.isRuntimeReady) {
|
||||
const remWf = this.configManager.getWorkflow(rule.remediationWorkflowId);
|
||||
const autoInputs =
|
||||
remWf && remWf.inputs.some((i) => i.name === 'serverId')
|
||||
? { serverId: server.id }
|
||||
: undefined;
|
||||
void this.workflowEngine
|
||||
.triggerWorkflow(rule.remediationWorkflowId, {
|
||||
triggerSource: `alert:${rule.id}`,
|
||||
inputs: autoInputs,
|
||||
eventMeta: { ruleId: rule.id, serverId: server.id, message },
|
||||
})
|
||||
.catch(() => undefined);
|
||||
}
|
||||
|
||||
void this.workflowEngine.handleSystemEvent({
|
||||
event: 'alert.fired',
|
||||
serverId: server.id,
|
||||
ruleId: rule.id,
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Healthy sample -> resolve open incident if firing
|
||||
state.consecutiveFailures = 0;
|
||||
if (state.firingEventId) {
|
||||
const eventId = state.firingEventId;
|
||||
state.firingEventId = undefined;
|
||||
this.db
|
||||
.prepare(`UPDATE alert_events SET state = 'resolved', resolved_at = ? WHERE id = ?`)
|
||||
.run(nowMs, eventId);
|
||||
|
||||
const resolvedMsg = `RESOLVED: ${rule.name} on ${server.name}`;
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, {
|
||||
type: 'alerts:update',
|
||||
activeCount: this.getActiveCount(),
|
||||
event: {
|
||||
id: eventId,
|
||||
ruleId: rule.id,
|
||||
serverId: server.id,
|
||||
severity: 'resolved',
|
||||
message: resolvedMsg,
|
||||
ts: nowMs,
|
||||
},
|
||||
});
|
||||
|
||||
if (!this.isSuppressed(rule, server, nowMs) && rule.channelIds.length > 0) {
|
||||
await this.dispatchRuleChannels(rule.channelIds, {
|
||||
id: eventId,
|
||||
ruleId: rule.id,
|
||||
serverId: server.id,
|
||||
severity: rule.severity,
|
||||
title: `[RESOLVED] ${rule.name}`,
|
||||
message: resolvedMsg,
|
||||
state: 'resolved',
|
||||
ts: nowMs,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private hydrateOpenIncidents(): void {
|
||||
const rows = this.db
|
||||
.prepare(
|
||||
`SELECT id, incident_key AS incidentKey, triggered_at AS triggeredAt
|
||||
FROM alert_events
|
||||
WHERE state = 'firing' AND incident_key IS NOT NULL`,
|
||||
)
|
||||
.all() as Array<{ id: string; incidentKey: string; triggeredAt: number }>;
|
||||
|
||||
for (const row of rows) {
|
||||
this.incidents.set(row.incidentKey, {
|
||||
consecutiveFailures: 99,
|
||||
firingEventId: row.id,
|
||||
lastNotifiedAt: row.triggeredAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private isSuppressed(rule: AlertRule, server: ServerConfig, nowMs: number): boolean {
|
||||
const silences = this.listSilences(nowMs);
|
||||
for (const s of silences) {
|
||||
if (s.scopeType === 'all') return true;
|
||||
if (s.scopeType === 'rule' && s.targetId === rule.id) return true;
|
||||
if (s.scopeType === 'server' && s.targetId === server.id) return true;
|
||||
if (s.scopeType === 'tag' && server.tags.includes(s.targetId)) return true;
|
||||
}
|
||||
|
||||
const windows = this.configManager.getAlerts().maintenanceWindows;
|
||||
for (const win of windows) {
|
||||
if (!win.enabled) continue;
|
||||
if (!this.matchesTarget(win.target, server)) continue;
|
||||
if (this.isCronWindowActiveNow(win.cron, win.timezone, win.durationMinutes, nowMs)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private isCronWindowActiveNow(
|
||||
expression: string,
|
||||
timezone: string,
|
||||
durationMinutes: number,
|
||||
nowMs: number,
|
||||
): boolean {
|
||||
try {
|
||||
const cron = new Cron(expression, { timezone, paused: true });
|
||||
const durMs = durationMinutes * 60_000;
|
||||
let cand = cron.nextRun(new Date(nowMs - durMs));
|
||||
while (cand && cand.getTime() <= nowMs) {
|
||||
if (nowMs < cand.getTime() + durMs) return true;
|
||||
cand = cron.nextRun(cand);
|
||||
}
|
||||
return false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private matchesTarget(target: AlertRuleTarget, server: ServerConfig): boolean {
|
||||
if (target.serverId && target.serverId !== server.id) return false;
|
||||
if (target.tags && target.tags.length > 0) {
|
||||
if (!server.tags.some((t) => target.tags!.includes(t))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private async sendDirectChannelMessage(
|
||||
channelId: string,
|
||||
opts: {
|
||||
severity: 'warn' | 'critical';
|
||||
title: string;
|
||||
message: string;
|
||||
state: 'firing' | 'resolved';
|
||||
},
|
||||
): Promise<void> {
|
||||
const ch = this.configManager.getAlerts().channels.find((c) => c.id === channelId);
|
||||
if (!ch || !ch.enabled) return;
|
||||
await this.dispatchToChannel(ch, {
|
||||
id: `notify-${crypto.randomBytes(4).toString('hex')}`,
|
||||
ruleId: 'workflow-on-failure',
|
||||
serverId: 'hub',
|
||||
severity: opts.severity,
|
||||
title: opts.title,
|
||||
message: opts.message,
|
||||
state: opts.state,
|
||||
ts: Date.now(),
|
||||
});
|
||||
}
|
||||
|
||||
private async dispatchRuleChannels(
|
||||
channelIds: string[],
|
||||
payload: {
|
||||
id: string;
|
||||
ruleId: string;
|
||||
serverId: string;
|
||||
severity: 'warn' | 'critical';
|
||||
title: string;
|
||||
message: string;
|
||||
state: 'firing' | 'resolved';
|
||||
ts: number;
|
||||
},
|
||||
): Promise<string> {
|
||||
if (channelIds.length === 0) return 'none';
|
||||
const channels = this.configManager.getAlerts().channels;
|
||||
const statuses: string[] = [];
|
||||
|
||||
for (const cid of channelIds) {
|
||||
const ch = channels.find((c) => c.id === cid);
|
||||
if (!ch || !ch.enabled) {
|
||||
statuses.push(`${cid}:skipped`);
|
||||
continue;
|
||||
}
|
||||
const res = await this.dispatchToChannel(ch, payload);
|
||||
statuses.push(res.ok ? `${cid}:ok` : `${cid}:err(${res.error ?? res.statusCode})`);
|
||||
}
|
||||
return statuses.join(', ');
|
||||
}
|
||||
|
||||
private readChannelSecret(secretRef: string): string | null {
|
||||
if (!this.vaultService.isRuntimeReady) return null;
|
||||
const cred = this.vaultService.getRuntimeSecret(secretRef);
|
||||
if (!cred) return null;
|
||||
if (cred.type === 'webhook-secret') return cred.secret;
|
||||
if (cred.type === 'api-token') return cred.token;
|
||||
if (cred.type === 'ssh-password' || cred.type === 'sudo-password') return cred.password;
|
||||
return null;
|
||||
}
|
||||
|
||||
private async dispatchToChannel(
|
||||
channel: AlertChannel,
|
||||
payload: {
|
||||
id: string;
|
||||
ruleId: string;
|
||||
serverId: string;
|
||||
severity: 'warn' | 'critical';
|
||||
title: string;
|
||||
message: string;
|
||||
state: 'firing' | 'resolved';
|
||||
ts: number;
|
||||
},
|
||||
): Promise<{ ok: boolean; statusCode?: number; error?: string }> {
|
||||
const secret = this.readChannelSecret(channel.secretRef);
|
||||
if (!secret && !channel.url) {
|
||||
return { ok: false, error: `Missing vault secret "${channel.secretRef}"` };
|
||||
}
|
||||
|
||||
try {
|
||||
let targetUrl = channel.url ?? '';
|
||||
let method = 'POST';
|
||||
const headers: Record<string, string> = {};
|
||||
let body: string;
|
||||
|
||||
if (channel.type === 'discord') {
|
||||
targetUrl = targetUrl || (secret && /^https?:\/\//.test(secret) ? secret : '');
|
||||
if (!targetUrl) return { ok: false, error: 'Missing Discord webhook URL' };
|
||||
headers['Content-Type'] = 'application/json';
|
||||
if (secret && secret !== targetUrl) {
|
||||
headers.Authorization = `Bearer ${secret}`;
|
||||
}
|
||||
body = JSON.stringify({
|
||||
content: `**${payload.title}**\n${payload.message}`,
|
||||
});
|
||||
} else if (channel.type === 'telegram') {
|
||||
if (!secret) return { ok: false, error: 'Missing Telegram bot token in Vault' };
|
||||
if (!channel.chatId) return { ok: false, error: 'Missing Telegram chatId' };
|
||||
targetUrl = targetUrl
|
||||
? `${targetUrl.replace(/\/$/, '')}/sendMessage`
|
||||
: `https://api.telegram.org/bot${secret}/sendMessage`;
|
||||
headers['Content-Type'] = 'application/json';
|
||||
headers['X-Telegram-Bot-Token'] = secret;
|
||||
body = JSON.stringify({
|
||||
chat_id: channel.chatId,
|
||||
text: `${payload.title}\n${payload.message}`,
|
||||
});
|
||||
} else if (channel.type === 'ntfy') {
|
||||
const topic = channel.topic || 'gcoordinator';
|
||||
targetUrl = targetUrl
|
||||
? targetUrl.endsWith(`/${topic}`)
|
||||
? targetUrl
|
||||
: `${targetUrl.replace(/\/$/, '')}/${encodeURIComponent(topic)}`
|
||||
: `https://ntfy.sh/${encodeURIComponent(topic)}`;
|
||||
headers['Content-Type'] = 'text/plain; charset=utf-8';
|
||||
headers.Title = payload.title;
|
||||
headers.Priority =
|
||||
payload.state === 'resolved'
|
||||
? '3'
|
||||
: payload.severity === 'critical'
|
||||
? '5'
|
||||
: '4';
|
||||
if (secret) headers.Authorization = `Bearer ${secret}`;
|
||||
body = payload.message;
|
||||
} else {
|
||||
targetUrl = targetUrl || (secret && /^https?:\/\//.test(secret) ? secret : '');
|
||||
if (!targetUrl) return { ok: false, error: 'Missing generic webhook URL' };
|
||||
headers['Content-Type'] = 'application/json';
|
||||
if (secret && secret !== targetUrl) {
|
||||
headers.Authorization = `Bearer ${secret}`;
|
||||
}
|
||||
body = JSON.stringify(payload);
|
||||
}
|
||||
|
||||
const res = await fetch(targetUrl, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
return {
|
||||
ok: res.ok,
|
||||
statusCode: res.status,
|
||||
error: res.ok ? undefined : `HTTP ${res.status}`,
|
||||
};
|
||||
} catch (err) {
|
||||
return {
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function compareOp(
|
||||
actual: number,
|
||||
op: 'gt' | 'gte' | 'lt' | 'lte',
|
||||
threshold: number,
|
||||
): boolean {
|
||||
switch (op) {
|
||||
case 'gt':
|
||||
return actual > threshold;
|
||||
case 'gte':
|
||||
return actual >= threshold;
|
||||
case 'lt':
|
||||
return actual < threshold;
|
||||
case 'lte':
|
||||
return actual <= threshold;
|
||||
}
|
||||
}
|
||||
127
src/server/api/routes/ai.routes.ts
Normal file
127
src/server/api/routes/ai.routes.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js';
|
||||
import { AiSurfaceSchema } from '../../ai/guides.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface AiRouterDeps {
|
||||
authService: AuthService;
|
||||
aiService: AiService;
|
||||
}
|
||||
|
||||
export function createAiRouter(deps: AiRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, aiService } = deps;
|
||||
|
||||
// Read-only context redaction & preview (Safe-Mode exempt)
|
||||
router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
surface: AiSurfaceSchema,
|
||||
contextText: z.string().max(256_000).optional(),
|
||||
serverId: EntityIdSchema.optional(),
|
||||
targetPath: z.string().max(200).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(aiService.previewContext(parsed.data));
|
||||
});
|
||||
|
||||
// Read-only Zod schema check + diff preview for AI-generated drafts (Safe-Mode exempt)
|
||||
router.post('/validate-draft', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
kind: AiDraftKindSchema,
|
||||
jsonText: z.string().min(1).max(256_000),
|
||||
targetId: EntityIdSchema.optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(aiService.validateDraft(parsed.data));
|
||||
});
|
||||
|
||||
// Strictly read-only draft streaming: never auto-executes commands (Safe-Mode exempt)
|
||||
router.post('/chat', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
chatId: z.string().min(1).max(64).optional(),
|
||||
surface: AiSurfaceSchema,
|
||||
messages: z
|
||||
.array(
|
||||
z.object({
|
||||
role: z.enum(['user', 'assistant']),
|
||||
content: z.string().min(1).max(64_000),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(24),
|
||||
contextText: z.string().max(256_000).optional(),
|
||||
serverId: EntityIdSchema.optional(),
|
||||
targetPath: z.string().max(200).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const started = aiService.startChat({
|
||||
...parsed.data,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.status(202).json(started);
|
||||
} catch (err) {
|
||||
if (err instanceof AiDisabledError) {
|
||||
res.status(403).json({ error: err.code, message: err.message });
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'AI_CHAT_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to start AI chat',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/chat/:chatId/cancel', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const chatId = String(req.params.chatId ?? '');
|
||||
res.json({ cancelled: aiService.cancelChat(chatId) });
|
||||
});
|
||||
|
||||
router.post('/test', requireAuth(authService), requireCsrf, enforceSafeMode, async (req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
baseUrl: z.string().url().optional(),
|
||||
model: z.string().min(1).optional(),
|
||||
secretRef: z.string().max(64).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json(await aiService.testEndpoint(parsed.data));
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
143
src/server/api/routes/alerts.routes.ts
Normal file
143
src/server/api/routes/alerts.routes.ts
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { Router } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js';
|
||||
import type { AlertEngine } from '../../alerts/alert-engine.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface AlertsRouterDeps {
|
||||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
alertEngine: AlertEngine;
|
||||
}
|
||||
|
||||
export function createAlertsRouter(deps: AlertsRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, configManager, auditService, alertEngine } = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (req, res) => {
|
||||
const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50;
|
||||
res.json({
|
||||
alertsConfig: configManager.getAlerts(),
|
||||
...alertEngine.getSummary(Number.isFinite(limit) ? limit : 50),
|
||||
});
|
||||
});
|
||||
|
||||
router.put('/config', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = AlertsFileSchema.parse({ version: 1, ...(req.body ?? {}) });
|
||||
const saved = configManager.saveConfigText(
|
||||
'alerts.json',
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated alerts configuration via UI',
|
||||
);
|
||||
auditService.log({
|
||||
action: 'alerts.config_update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'alerts.json',
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ alertsConfig: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid alerts configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'ALERTS_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save alerts configuration',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/silences',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
scopeType: z.enum(['all', 'rule', 'server', 'tag']),
|
||||
targetId: z.string().default('*'),
|
||||
durationMinutes: z.number().int().min(1).max(43_200),
|
||||
reason: z.string().max(240).optional(),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const silence = alertEngine.createSilence({
|
||||
...parsed.data,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.status(201).json({ silence });
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/silences/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const deleted = alertEngine.deleteSilence(id);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SILENCE_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'alert.silence_delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/channels/:id/test',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const result = await alertEngine.sendTestAlert(id, {
|
||||
ip: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.json(result);
|
||||
} catch (err) {
|
||||
res.status(404).json({
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : 'Channel test failed',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
216
src/server/api/routes/backup.routes.ts
Normal file
216
src/server/api/routes/backup.routes.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
import type Database from 'better-sqlite3';
|
||||
import { Router, type RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
createBackupBundle,
|
||||
restoreBackupBundle,
|
||||
verifyBackupSummaryOnly,
|
||||
type BackupInnerPayload,
|
||||
type BackupVerificationSummary,
|
||||
} from '../../security/backup.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
import type { VaultService } from '../../security/vault.js';
|
||||
|
||||
export interface BackupRouterDeps {
|
||||
dataDir: string;
|
||||
db: Database.Database;
|
||||
authService: AuthService;
|
||||
vaultService: VaultService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
stepUpGuard: RequestHandler;
|
||||
onRestored: (info: {
|
||||
summary: BackupVerificationSummary;
|
||||
inner: BackupInnerPayload;
|
||||
vaultKeyCandidate?: string;
|
||||
}) => void | Promise<void>;
|
||||
}
|
||||
|
||||
const ExportBackupBodySchema = z.object({
|
||||
passphrase: z.string().max(256).optional(),
|
||||
});
|
||||
|
||||
const VerifyBackupBodySchema = z.object({
|
||||
bundleBase64: z.string().min(1),
|
||||
passphrase: z.string().max(256).optional(),
|
||||
masterKey: z.string().max(256).optional(),
|
||||
vaultMasterKey: z.string().max(256).optional(),
|
||||
});
|
||||
|
||||
export function createBackupRouter(deps: BackupRouterDeps): Router {
|
||||
const router = Router();
|
||||
const {
|
||||
dataDir,
|
||||
db,
|
||||
authService,
|
||||
vaultService,
|
||||
configManager,
|
||||
auditService,
|
||||
stepUpGuard,
|
||||
onRestored,
|
||||
} = deps;
|
||||
|
||||
router.post(
|
||||
'/export',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const parsed = ExportBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const passphrase = parsed.data.passphrase?.trim() || undefined;
|
||||
const masterKey = vaultService.exportMasterKeyHex() ?? undefined;
|
||||
if (!passphrase && !masterKey) {
|
||||
res.status(423).json({
|
||||
error: 'VAULT_LOCKED',
|
||||
message: 'Vault is sealed; unlock Vault or provide a backup passphrase.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = createBackupBundle({
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
});
|
||||
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
|
||||
const filename = `gcoordinator-backup-${stamp}.gcoord.enc`;
|
||||
|
||||
auditService.log({
|
||||
action: 'backup.export',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: filename,
|
||||
status: 'ok',
|
||||
details: {
|
||||
kdf: result.summary.kdf,
|
||||
configFileCount: result.summary.configFileCount,
|
||||
knownHostsCount: result.summary.knownHostsCount,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({
|
||||
filename,
|
||||
bundleBase64: Buffer.from(result.serialized, 'utf8').toString('base64'),
|
||||
summary: result.summary,
|
||||
});
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_EXPORT_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to create backup bundle',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Read-only verification: exempt from enforceSafeMode
|
||||
router.post('/verify', requireAuth(authService), requireCsrf, (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
const summary = verifyBackupSummaryOnly(rawBuf, {
|
||||
masterKey:
|
||||
parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined,
|
||||
passphrase: parsed.data.passphrase?.trim() || undefined,
|
||||
vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined,
|
||||
});
|
||||
res.json({ summary });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_INVALID',
|
||||
message: err instanceof Error ? err.message : 'Backup verification failed',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/restore',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const parsed = VerifyBackupBodySchema.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64');
|
||||
const passphrase = parsed.data.passphrase?.trim() || undefined;
|
||||
const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined;
|
||||
const masterKey = parsed.data.masterKey?.trim() || runtimeKey;
|
||||
const vaultMasterKey = parsed.data.vaultMasterKey?.trim() || undefined;
|
||||
|
||||
const wasWatching = await configManager.pauseWatcher();
|
||||
try {
|
||||
const restored = restoreBackupBundle(rawBuf, {
|
||||
dataDir,
|
||||
db,
|
||||
masterKey,
|
||||
passphrase,
|
||||
vaultMasterKey,
|
||||
});
|
||||
|
||||
await onRestored({
|
||||
summary: restored.summary,
|
||||
inner: restored.inner,
|
||||
vaultKeyCandidate: vaultMasterKey || masterKey,
|
||||
});
|
||||
|
||||
auditService.log({
|
||||
action: 'backup.restore',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'data',
|
||||
status: 'ok',
|
||||
details: {
|
||||
configFileCount: restored.summary.configFileCount,
|
||||
knownHostsCount: restored.summary.knownHostsCount,
|
||||
vaultVerified: restored.summary.vaultVerified,
|
||||
},
|
||||
});
|
||||
|
||||
res.json({ restored: true, summary: restored.summary });
|
||||
} catch (err) {
|
||||
auditService.log({
|
||||
action: 'backup.restore',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: 'data',
|
||||
status: 'error',
|
||||
details: { message: err instanceof Error ? err.message : String(err) },
|
||||
});
|
||||
res.status(400).json({
|
||||
error: 'BACKUP_RESTORE_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Backup restore failed',
|
||||
});
|
||||
} finally {
|
||||
if (wasWatching) {
|
||||
await configManager.resumeWatcher();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
120
src/server/api/routes/snippets.routes.ts
Normal file
120
src/server/api/routes/snippets.routes.ts
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
import { Router } from 'express';
|
||||
import { SnippetSchema, SnippetsFileSchema } from '../../../shared/schemas/snippets.schema.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface SnippetsRouterDeps {
|
||||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
}
|
||||
|
||||
export function createSnippetsRouter(deps: SnippetsRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, configManager, auditService } = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (_req, res) => {
|
||||
res.json(configManager.getSnippets());
|
||||
});
|
||||
|
||||
router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const parsed = SnippetSchema.safeParse(req.body);
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const current = configManager.getSnippets();
|
||||
if (current.snippets.some((s) => s.id === parsed.data.id)) {
|
||||
res.status(409).json({
|
||||
error: 'SNIPPET_EXISTS',
|
||||
message: `Snippet "${parsed.data.id}" already exists`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const next = SnippetsFileSchema.parse({
|
||||
version: 1,
|
||||
snippets: [...current.snippets, parsed.data],
|
||||
});
|
||||
configManager.saveConfigText(
|
||||
'snippets.json',
|
||||
JSON.stringify(next, null, 2),
|
||||
'ui',
|
||||
`Added snippet ${parsed.data.id}`,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'snippet.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.data.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ snippet: parsed.data, snippets: next.snippets });
|
||||
});
|
||||
|
||||
router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = SnippetSchema.safeParse({ ...(req.body ?? {}), id });
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const current = configManager.getSnippets();
|
||||
const exists = current.snippets.some((s) => s.id === id);
|
||||
const nextList = exists
|
||||
? current.snippets.map((s) => (s.id === id ? parsed.data : s))
|
||||
: [...current.snippets, parsed.data];
|
||||
|
||||
const next = SnippetsFileSchema.parse({ version: 1, snippets: nextList });
|
||||
configManager.saveConfigText(
|
||||
'snippets.json',
|
||||
JSON.stringify(next, null, 2),
|
||||
'ui',
|
||||
`Updated snippet ${id}`,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'snippet.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ snippet: parsed.data, snippets: next.snippets });
|
||||
});
|
||||
|
||||
router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const current = configManager.getSnippets();
|
||||
const filtered = current.snippets.filter((s) => s.id !== id);
|
||||
if (filtered.length === current.snippets.length) {
|
||||
res.status(404).json({ error: 'SNIPPET_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
|
||||
const next = SnippetsFileSchema.parse({ version: 1, snippets: filtered });
|
||||
configManager.saveConfigText(
|
||||
'snippets.json',
|
||||
JSON.stringify(next, null, 2),
|
||||
'ui',
|
||||
`Deleted snippet ${id}`,
|
||||
);
|
||||
auditService.log({
|
||||
action: 'snippet.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true, snippets: next.snippets });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
293
src/server/api/routes/workflows.routes.ts
Normal file
293
src/server/api/routes/workflows.routes.ts
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
import { Router } from 'express';
|
||||
import { ZodError, z } from 'zod';
|
||||
import { EntityIdSchema } from '../../../shared/schemas/common.js';
|
||||
import { WorkflowConfigSchema } from '../../../shared/schemas/workflow.schema.js';
|
||||
import type { BroadcastService } from '../../automation/broadcast-service.js';
|
||||
import type { WorkflowEngine } from '../../automation/workflow-engine.js';
|
||||
import type { ConfigManager } from '../../config/config-manager.js';
|
||||
import type { AuditService } from '../../security/audit.js';
|
||||
import type { AuthService } from '../../security/auth.js';
|
||||
import {
|
||||
enforceSafeMode,
|
||||
requireAuth,
|
||||
requireCsrf,
|
||||
} from '../../security/guards.js';
|
||||
|
||||
export interface WorkflowsRouterDeps {
|
||||
authService: AuthService;
|
||||
configManager: ConfigManager;
|
||||
auditService: AuditService;
|
||||
workflowEngine: WorkflowEngine;
|
||||
broadcastService: BroadcastService;
|
||||
}
|
||||
|
||||
export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router {
|
||||
const router = Router();
|
||||
const { authService, configManager, auditService, workflowEngine, broadcastService } = deps;
|
||||
|
||||
router.get('/', requireAuth(authService), (req, res) => {
|
||||
const pinnedOnly = req.query.pinnedOnly === '1' || req.query.pinnedOnly === 'true';
|
||||
let items = workflowEngine.listWorkflowsWithSummary();
|
||||
if (pinnedOnly) {
|
||||
items = items.filter(
|
||||
(x) => Boolean(x.workflow.display.pinToDashboard || x.workflow.pinToDashboard),
|
||||
);
|
||||
}
|
||||
res.json({ workflows: items });
|
||||
});
|
||||
|
||||
router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = WorkflowConfigSchema.parse(req.body);
|
||||
const saved = configManager.saveConfigText(
|
||||
`workflows/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Created workflow via UI',
|
||||
);
|
||||
auditService.log({
|
||||
action: 'workflow.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({ workflow: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid workflow configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'WORKFLOW_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save workflow',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = WorkflowConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
const saved = configManager.saveConfigText(
|
||||
`workflows/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated workflow via UI',
|
||||
);
|
||||
auditService.log({
|
||||
action: 'workflow.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ workflow: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid workflow configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'WORKFLOW_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update workflow',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`workflows/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'WORKFLOW_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
auditService.log({
|
||||
action: 'workflow.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'WORKFLOW_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete workflow',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/runs', requireAuth(authService), (req, res) => {
|
||||
const workflowId = typeof req.query.workflowId === 'string' ? req.query.workflowId : undefined;
|
||||
const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50;
|
||||
res.json({
|
||||
runs: workflowEngine.listRuns(
|
||||
workflowId,
|
||||
Number.isFinite(limit) ? limit : 50,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/runs/:runId', requireAuth(authService), (req, res) => {
|
||||
const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''));
|
||||
if (!detail) {
|
||||
res.status(404).json({ error: 'RUN_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
res.json(detail);
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/runs/:runId/cancel',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const runId = String(req.params.runId ?? '');
|
||||
const cancelled = workflowEngine.cancelRun(runId, 'admin');
|
||||
auditService.log({
|
||||
action: 'workflow.cancel',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: runId,
|
||||
status: cancelled ? 'ok' : 'error',
|
||||
});
|
||||
res.json({ cancelled });
|
||||
},
|
||||
);
|
||||
|
||||
// Dry-run is read-only preview -> exempt from enforceSafeMode
|
||||
router.post('/:id/dry-run', requireAuth(authService), requireCsrf, async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z
|
||||
.object({ inputs: z.record(z.unknown()).default({}) })
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const plan = await workflowEngine.previewDryRun(id, parsed.data.inputs);
|
||||
res.json({ plan });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'DRY_RUN_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to compute workflow dry-run',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/:id/run',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z
|
||||
.object({ inputs: z.record(z.unknown()).default({}) })
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await workflowEngine.triggerWorkflow(id, {
|
||||
triggerSource: 'manual',
|
||||
inputs: parsed.data.inputs,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.status(result.status === 'skipped' ? 200 : 202).json(result);
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'WORKFLOW_RUN_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to trigger workflow',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/broadcast',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
snippetId: EntityIdSchema.optional(),
|
||||
command: z.string().min(1).optional(),
|
||||
inputs: z.record(z.unknown()).optional(),
|
||||
sudo: z.boolean().optional(),
|
||||
concurrency: z.number().int().min(1).max(32).optional(),
|
||||
timeoutSec: z.number().int().min(1).max(3600).optional(),
|
||||
target: z.object({
|
||||
serverId: z.string().optional(),
|
||||
serverIds: z.array(EntityIdSchema).optional(),
|
||||
tags: z.array(z.string().min(1)).optional(),
|
||||
all: z.boolean().optional(),
|
||||
}),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const job = broadcastService.startBroadcast({
|
||||
...parsed.data,
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
});
|
||||
res.status(202).json({ job });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'BROADCAST_FAILED',
|
||||
message: err instanceof Error ? err.message : 'Unable to start fleet broadcast',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => {
|
||||
const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? ''));
|
||||
if (!job) {
|
||||
res.status(404).json({ error: 'BROADCAST_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
res.json({ job });
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/broadcast/:jobId/cancel',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
(req, res) => {
|
||||
const jobId = String(req.params.jobId ?? '');
|
||||
res.json({ cancelled: broadcastService.cancelBroadcast(jobId) });
|
||||
},
|
||||
);
|
||||
|
||||
return router;
|
||||
}
|
||||
|
|
@ -37,6 +37,10 @@ export interface WsPtyHandlers {
|
|||
onResize: (sessionId: string, cols: number, rows: number) => void;
|
||||
}
|
||||
|
||||
export interface WsAiHandlers {
|
||||
onCancel: (chatId: string) => void;
|
||||
}
|
||||
|
||||
export class WsHub {
|
||||
private readonly wss = new WebSocketServer({ noServer: true });
|
||||
private readonly clients = new Set<WsClientMeta>();
|
||||
|
|
@ -44,6 +48,7 @@ export class WsHub {
|
|||
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
|
||||
private readonly subscribeListeners = new Set<WsSubscribeListener>();
|
||||
private ptyHandlers: WsPtyHandlers | null = null;
|
||||
private aiHandlers: WsAiHandlers | null = null;
|
||||
|
||||
constructor(
|
||||
httpServer: HttpServer,
|
||||
|
|
@ -83,6 +88,10 @@ export class WsHub {
|
|||
this.ptyHandlers = handlers;
|
||||
}
|
||||
|
||||
attachAiHandlers(handlers: WsAiHandlers): void {
|
||||
this.aiHandlers = handlers;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
clearInterval(this.pingTimer);
|
||||
for (const client of this.clients) {
|
||||
|
|
@ -295,7 +304,7 @@ export class WsHub {
|
|||
break;
|
||||
}
|
||||
case 'ai:cancel':
|
||||
// Wired in Phase 5
|
||||
this.aiHandlers?.onCancel(frame.chatId);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,11 @@ import http from 'node:http';
|
|||
import path from 'node:path';
|
||||
import type Database from 'better-sqlite3';
|
||||
import express, { type Express } from 'express';
|
||||
import { AiService } from './ai/ai-service.js';
|
||||
import { AlertEngine } from './alerts/alert-engine.js';
|
||||
import { BroadcastService } from './automation/broadcast-service.js';
|
||||
import { TransferEngine } from './automation/transfer-engine.js';
|
||||
import { WorkflowEngine } from './automation/workflow-engine.js';
|
||||
import { ConfigManager } from './config/config-manager.js';
|
||||
import { openDatabase } from './db/database.js';
|
||||
import { ServerInspector } from './monitoring/inspector.js';
|
||||
|
|
@ -24,15 +29,20 @@ import { SftpService } from './ssh/sftp-service.js';
|
|||
import { SSHPool } from './ssh/ssh-pool.js';
|
||||
import { TunnelManager } from './ssh/tunnel-manager.js';
|
||||
import { CustomSystemsEngine } from './systems/systems-engine.js';
|
||||
import { createAiRouter } from './api/routes/ai.routes.js';
|
||||
import { createAlertsRouter } from './api/routes/alerts.routes.js';
|
||||
import { createAuditRouter } from './api/routes/audit.routes.js';
|
||||
import { createAuthRouter } from './api/routes/auth.routes.js';
|
||||
import { createBackupRouter } from './api/routes/backup.routes.js';
|
||||
import { createConfigRouter } from './api/routes/config.routes.js';
|
||||
import { createServersRouter } from './api/routes/servers.routes.js';
|
||||
import { createSftpRouter } from './api/routes/sftp.routes.js';
|
||||
import { createSnippetsRouter } from './api/routes/snippets.routes.js';
|
||||
import { createSystemsRouter } from './api/routes/systems.routes.js';
|
||||
import { createTerminalRouter } from './api/routes/terminal.routes.js';
|
||||
import { createProxyRouter, createTunnelsRouter } from './api/routes/tunnels.routes.js';
|
||||
import { createVaultRouter } from './api/routes/vault.routes.js';
|
||||
import { createWorkflowsRouter } from './api/routes/workflows.routes.js';
|
||||
import { WsHub } from './api/ws-hub.js';
|
||||
|
||||
export interface ServerOptions {
|
||||
|
|
@ -64,6 +74,11 @@ export interface GCoordinatorInstance {
|
|||
customSystemsEngine: CustomSystemsEngine;
|
||||
serverInspector: ServerInspector;
|
||||
monitoringService: MonitoringService;
|
||||
transferEngine: TransferEngine;
|
||||
workflowEngine: WorkflowEngine;
|
||||
broadcastService: BroadcastService;
|
||||
alertEngine: AlertEngine;
|
||||
aiService: AiService;
|
||||
wsHub: WsHub;
|
||||
port: number;
|
||||
close(): Promise<void>;
|
||||
|
|
@ -144,6 +159,43 @@ export async function createGCoordinatorServer(
|
|||
sshPool,
|
||||
probeRunner,
|
||||
);
|
||||
const transferEngine = new TransferEngine(sshPool, sftpService, configManager);
|
||||
const workflowEngine = new WorkflowEngine(
|
||||
db,
|
||||
configManager,
|
||||
vaultService,
|
||||
sshPool,
|
||||
sftpService,
|
||||
customSystemsEngine,
|
||||
transferEngine,
|
||||
wsHub,
|
||||
auditService,
|
||||
);
|
||||
const broadcastService = new BroadcastService(
|
||||
configManager,
|
||||
vaultService,
|
||||
sshPool,
|
||||
wsHub,
|
||||
auditService,
|
||||
);
|
||||
const alertEngine = new AlertEngine(
|
||||
db,
|
||||
configManager,
|
||||
vaultService,
|
||||
monitoringService,
|
||||
sshPool,
|
||||
customSystemsEngine,
|
||||
workflowEngine,
|
||||
wsHub,
|
||||
auditService,
|
||||
);
|
||||
const aiService = new AiService(
|
||||
configManager,
|
||||
vaultService,
|
||||
sshPool,
|
||||
wsHub,
|
||||
auditService,
|
||||
);
|
||||
|
||||
wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => {
|
||||
tunnelManager.handleWsProxyUpgrade(req, socket, head);
|
||||
|
|
@ -156,6 +208,11 @@ export async function createGCoordinatorServer(
|
|||
ptyManager.resize(sessionId, cols, rows);
|
||||
},
|
||||
});
|
||||
wsHub.attachAiHandlers({
|
||||
onCancel: (chatId) => {
|
||||
aiService.cancelChat(chatId);
|
||||
},
|
||||
});
|
||||
wsHub.onChannelSubscribe((ctx, channel) => {
|
||||
if (channel.startsWith('pty:')) {
|
||||
const sessionId = channel.slice('pty:'.length);
|
||||
|
|
@ -178,7 +235,17 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
} else if (channel.startsWith('stream:')) {
|
||||
const jobId = channel.slice('stream:'.length);
|
||||
for (const frame of customSystemsEngine.getStreamReplayFrames(jobId)) {
|
||||
const replay = jobId.startsWith('wf:')
|
||||
? workflowEngine.getStreamReplayFrames(jobId)
|
||||
: jobId.startsWith('bcast-')
|
||||
? broadcastService.getStreamReplayFrames(jobId)
|
||||
: customSystemsEngine.getStreamReplayFrames(jobId);
|
||||
for (const frame of replay) {
|
||||
ctx.send(frame);
|
||||
}
|
||||
} else if (channel.startsWith('ai:')) {
|
||||
const chatId = channel.slice('ai:'.length);
|
||||
for (const frame of aiService.getReplayFrames(chatId)) {
|
||||
ctx.send(frame);
|
||||
}
|
||||
} else if (channel === 'metrics') {
|
||||
|
|
@ -218,7 +285,8 @@ export async function createGCoordinatorServer(
|
|||
if (s.hostKeyMismatch) {
|
||||
wsHub.broadcastChannel('alerts', {
|
||||
type: 'alerts:update',
|
||||
activeCount: knownHosts.listPendingMismatches().length,
|
||||
activeCount:
|
||||
alertEngine.getActiveCount() + knownHosts.listPendingMismatches().length,
|
||||
hostKeyMismatch: s.hostKeyMismatch,
|
||||
});
|
||||
}
|
||||
|
|
@ -238,8 +306,14 @@ export async function createGCoordinatorServer(
|
|||
monitoringService.start();
|
||||
void tunnelManager.syncAutoStart();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.start();
|
||||
alertEngine.start();
|
||||
|
||||
vaultService.onPanicLock(() => {
|
||||
aiService.cancelAll();
|
||||
alertEngine.handlePanicLock();
|
||||
workflowEngine.handlePanicLock();
|
||||
broadcastService.cancelAll();
|
||||
monitoringService.stopAll();
|
||||
customSystemsEngine.stopBackgroundChecks();
|
||||
customSystemsEngine.cancelAllStreams();
|
||||
|
|
@ -261,6 +335,7 @@ export async function createGCoordinatorServer(
|
|||
if (
|
||||
event.entityType === 'server' ||
|
||||
event.entityType === 'system' ||
|
||||
event.entityType === 'workflow' ||
|
||||
event.entityType === 'settings' ||
|
||||
event.entityType === 'all'
|
||||
) {
|
||||
|
|
@ -279,6 +354,7 @@ export async function createGCoordinatorServer(
|
|||
}
|
||||
monitoringService.syncServers();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.syncCronJobs();
|
||||
void tunnelManager.syncAutoStart();
|
||||
}
|
||||
});
|
||||
|
|
@ -320,6 +396,7 @@ export async function createGCoordinatorServer(
|
|||
onVaultUnlocked: () => {
|
||||
monitoringService.syncServers();
|
||||
customSystemsEngine.syncBackgroundChecks();
|
||||
workflowEngine.syncCronJobs();
|
||||
void tunnelManager.syncAutoStart();
|
||||
},
|
||||
onVaultChanged: (snapshotReason) => {
|
||||
|
|
@ -329,6 +406,39 @@ export async function createGCoordinatorServer(
|
|||
|
||||
app.use('/api/vault', vaultRouter);
|
||||
app.use('/api/security', panicLockHandler);
|
||||
app.use(
|
||||
'/api/backup',
|
||||
createBackupRouter({
|
||||
dataDir,
|
||||
db,
|
||||
authService,
|
||||
vaultService,
|
||||
configManager,
|
||||
auditService,
|
||||
stepUpGuard,
|
||||
onRestored: async ({ inner, vaultKeyCandidate }) => {
|
||||
if (inner.vaultEnvelopeRaw !== null) {
|
||||
try {
|
||||
vaultService.reloadFromDisk(vaultKeyCandidate);
|
||||
} catch {
|
||||
// Keep existing runtime state untouched if backup vault used a different key
|
||||
}
|
||||
}
|
||||
knownHosts.replaceAllKnownHosts(inner.knownHosts);
|
||||
configManager.reloadAllFromDisk();
|
||||
sshPool.syncWithConfig();
|
||||
if (authService.isBootstrapped() && vaultService.isRuntimeReady) {
|
||||
authService.syncRecovery({ snapshotReason: 'backup-restore' });
|
||||
}
|
||||
wsHub.broadcastAll({
|
||||
type: 'vault:state',
|
||||
vaultState: vaultService.state,
|
||||
vaultRuntimeReady: vaultService.isRuntimeReady,
|
||||
isPanicLocked: vaultService.isPanicLocked,
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use('/api/terminal', createTerminalRouter({ authService, configManager, auditService, ptyManager }));
|
||||
app.use(
|
||||
'/api/tunnels',
|
||||
|
|
@ -338,6 +448,25 @@ export async function createGCoordinatorServer(
|
|||
'/api/systems',
|
||||
createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }),
|
||||
);
|
||||
app.use(
|
||||
'/api/workflows',
|
||||
createWorkflowsRouter({
|
||||
authService,
|
||||
configManager,
|
||||
auditService,
|
||||
workflowEngine,
|
||||
broadcastService,
|
||||
}),
|
||||
);
|
||||
app.use(
|
||||
'/api/snippets',
|
||||
createSnippetsRouter({ authService, configManager, auditService }),
|
||||
);
|
||||
app.use(
|
||||
'/api/alerts',
|
||||
createAlertsRouter({ authService, configManager, auditService, alertEngine }),
|
||||
);
|
||||
app.use('/api/ai', createAiRouter({ authService, aiService }));
|
||||
app.use(
|
||||
'/api/servers/:id/sftp',
|
||||
createSftpRouter({ authService, configManager, auditService, sftpService }),
|
||||
|
|
@ -409,9 +538,18 @@ export async function createGCoordinatorServer(
|
|||
customSystemsEngine,
|
||||
serverInspector,
|
||||
monitoringService,
|
||||
transferEngine,
|
||||
workflowEngine,
|
||||
broadcastService,
|
||||
alertEngine,
|
||||
aiService,
|
||||
wsHub,
|
||||
port: actualPort,
|
||||
async close() {
|
||||
aiService.close();
|
||||
alertEngine.close();
|
||||
workflowEngine.close();
|
||||
broadcastService.cancelAll();
|
||||
monitoringService.close();
|
||||
customSystemsEngine.close();
|
||||
tunnelManager.stopAll();
|
||||
|
|
|
|||
354
src/server/automation/broadcast-service.ts
Normal file
354
src/server/automation/broadcast-service.ts
Normal file
|
|
@ -0,0 +1,354 @@
|
|||
import crypto from 'node:crypto';
|
||||
import type { ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import type { VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from '../ssh/ssh-pool.js';
|
||||
import { BufferedStreamEmitter } from './stream-buffer.js';
|
||||
import {
|
||||
buildWorkflowEnv,
|
||||
interpolateShellCommandSafe,
|
||||
resolveTargetServers,
|
||||
validateAndResolveInputs,
|
||||
} from './template.js';
|
||||
|
||||
export interface BroadcastTargetResult {
|
||||
serverId: string;
|
||||
serverName: string;
|
||||
status: 'pending' | 'running' | 'ok' | 'error' | 'cancelled';
|
||||
exitCode: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
durationMs: number;
|
||||
}
|
||||
|
||||
export interface BroadcastJobSummary {
|
||||
jobId: string;
|
||||
snippetId?: string;
|
||||
command: string;
|
||||
sudo: boolean;
|
||||
createdAt: number;
|
||||
finishedAt: number | null;
|
||||
cancelled: boolean;
|
||||
done: boolean;
|
||||
targets: BroadcastTargetResult[];
|
||||
}
|
||||
|
||||
interface ActiveBroadcastJob extends BroadcastJobSummary {
|
||||
emitter: BufferedStreamEmitter;
|
||||
abortController: AbortController;
|
||||
}
|
||||
|
||||
const MAX_RETAINED_BROADCASTS = 25;
|
||||
const MAX_OUTPUT_PER_SERVER = 256 * 1024;
|
||||
|
||||
async function runPool<T>(
|
||||
items: T[],
|
||||
concurrency: number,
|
||||
worker: (item: T) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const limit = Math.max(1, Math.min(concurrency, items.length || 1));
|
||||
let idx = 0;
|
||||
const runners = Array.from({ length: limit }, async () => {
|
||||
while (idx < items.length) {
|
||||
const current = items[idx++]!;
|
||||
await worker(current);
|
||||
}
|
||||
});
|
||||
await Promise.all(runners);
|
||||
}
|
||||
|
||||
export class BroadcastService {
|
||||
private readonly jobs = new Map<string, ActiveBroadcastJob>();
|
||||
|
||||
constructor(
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly vaultService: VaultService,
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly wsHub: WsHub,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
getStreamReplayFrames(jobId: string): ServerWsFrame[] {
|
||||
return this.jobs.get(jobId)?.emitter.getReplayFrames() ?? [];
|
||||
}
|
||||
|
||||
getBroadcastResult(jobId: string): BroadcastJobSummary | undefined {
|
||||
const job = this.jobs.get(jobId);
|
||||
if (!job) return undefined;
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
snippetId: job.snippetId,
|
||||
command: job.command,
|
||||
sudo: job.sudo,
|
||||
createdAt: job.createdAt,
|
||||
finishedAt: job.finishedAt,
|
||||
cancelled: job.cancelled,
|
||||
done: job.done,
|
||||
targets: job.targets.map((t) => ({ ...t })),
|
||||
};
|
||||
}
|
||||
|
||||
cancelBroadcast(jobId: string): boolean {
|
||||
const job = this.jobs.get(jobId);
|
||||
if (!job || job.done) return false;
|
||||
job.cancelled = true;
|
||||
job.abortController.abort();
|
||||
return true;
|
||||
}
|
||||
|
||||
cancelAll(): void {
|
||||
for (const job of this.jobs.values()) {
|
||||
if (!job.done) {
|
||||
job.cancelled = true;
|
||||
job.abortController.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
startBroadcast(opts: {
|
||||
snippetId?: string;
|
||||
command?: string;
|
||||
inputs?: Record<string, unknown>;
|
||||
sudo?: boolean;
|
||||
concurrency?: number;
|
||||
timeoutSec?: number;
|
||||
target: { serverId?: string; serverIds?: string[]; tags?: string[]; all?: boolean };
|
||||
actorIp: string;
|
||||
sessionIdHash: string | null;
|
||||
}): BroadcastJobSummary {
|
||||
if (!this.vaultService.isRuntimeReady) {
|
||||
throw new Error('Vault is sealed; unseal Vault before running Fleet Broadcast');
|
||||
}
|
||||
|
||||
let rawCommand = opts.command?.trim() ?? '';
|
||||
let sudo = Boolean(opts.sudo);
|
||||
let resolvedInputs: Record<string, string> = {};
|
||||
|
||||
if (opts.snippetId) {
|
||||
const snip = this.configManager
|
||||
.getSnippets()
|
||||
.snippets.find((s) => s.id === opts.snippetId);
|
||||
if (!snip) {
|
||||
throw new Error(`Unknown command snippet "${opts.snippetId}"`);
|
||||
}
|
||||
resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {});
|
||||
rawCommand = snip.command;
|
||||
sudo = opts.sudo ?? snip.sudo;
|
||||
} else {
|
||||
if (!rawCommand) {
|
||||
throw new Error('Command or snippetId is required for Fleet Broadcast');
|
||||
}
|
||||
if (opts.inputs) {
|
||||
for (const [k, v] of Object.entries(opts.inputs)) {
|
||||
if (v !== undefined && v !== null) resolvedInputs[k] = String(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const baseCtx = { inputs: resolvedInputs };
|
||||
const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx);
|
||||
const allServers = this.configManager.listServers();
|
||||
|
||||
let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx);
|
||||
if (opts.target.serverIds && opts.target.serverIds.length > 0) {
|
||||
const byId = new Set(matchedServers.map((s) => s.id));
|
||||
const wanted = new Set(opts.target.serverIds);
|
||||
for (const s of allServers) {
|
||||
if (s.enabled && wanted.has(s.id) && !byId.has(s.id)) {
|
||||
byId.add(s.id);
|
||||
matchedServers.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (matchedServers.length === 0) {
|
||||
throw new Error('No enabled target servers matched broadcast filter');
|
||||
}
|
||||
|
||||
const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`;
|
||||
const emitter = new BufferedStreamEmitter(this.wsHub, jobId);
|
||||
const abortController = new AbortController();
|
||||
|
||||
const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({
|
||||
serverId: s.id,
|
||||
serverName: s.name,
|
||||
status: 'pending',
|
||||
exitCode: null,
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
durationMs: 0,
|
||||
}));
|
||||
|
||||
const job: ActiveBroadcastJob = {
|
||||
jobId,
|
||||
snippetId: opts.snippetId,
|
||||
command: renderedCommand,
|
||||
sudo,
|
||||
createdAt: Date.now(),
|
||||
finishedAt: null,
|
||||
cancelled: false,
|
||||
done: false,
|
||||
targets,
|
||||
emitter,
|
||||
abortController,
|
||||
};
|
||||
this.jobs.set(jobId, job);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'broadcast.start',
|
||||
actorIp: opts.actorIp,
|
||||
sessionIdHash: opts.sessionIdHash,
|
||||
target: opts.snippetId ?? 'adhoc',
|
||||
status: 'ok',
|
||||
details: {
|
||||
jobId,
|
||||
serverIds: matchedServers.map((s) => s.id),
|
||||
},
|
||||
});
|
||||
|
||||
emitter.pushMeta({
|
||||
event: 'start',
|
||||
jobId,
|
||||
command: renderedCommand,
|
||||
targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })),
|
||||
});
|
||||
|
||||
const timeoutMs = (opts.timeoutSec ?? 120) * 1000;
|
||||
const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32));
|
||||
|
||||
void runPool(matchedServers, concurrency, async (srv) => {
|
||||
const targetEntry = job.targets.find((t) => t.serverId === srv.id)!;
|
||||
if (abortController.signal.aborted) {
|
||||
targetEntry.status = 'cancelled';
|
||||
emitter.pushMeta({
|
||||
event: 'server-exit',
|
||||
serverId: srv.id,
|
||||
exitCode: null,
|
||||
durationMs: 0,
|
||||
status: 'cancelled',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const started = Date.now();
|
||||
targetEntry.status = 'running';
|
||||
emitter.pushMeta({ event: 'server-start', serverId: srv.id });
|
||||
|
||||
const env = buildWorkflowEnv({
|
||||
inputs: resolvedInputs,
|
||||
serverId: srv.id,
|
||||
});
|
||||
|
||||
try {
|
||||
const handle = await this.sshPool.execStream(srv.id, renderedCommand, {
|
||||
env,
|
||||
sudo,
|
||||
});
|
||||
|
||||
const outChunks: Buffer[] = [];
|
||||
const errChunks: Buffer[] = [];
|
||||
let outBytes = 0;
|
||||
let errBytes = 0;
|
||||
|
||||
handle.channel.on('data', (chunk: Buffer) => {
|
||||
const text = chunk.toString('utf8');
|
||||
if (outBytes < MAX_OUTPUT_PER_SERVER) {
|
||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - outBytes);
|
||||
outChunks.push(slice);
|
||||
outBytes += slice.length;
|
||||
}
|
||||
emitter.push('stdout', `[${srv.id}] ${text}`);
|
||||
emitter.pushMeta({
|
||||
event: 'server-output',
|
||||
serverId: srv.id,
|
||||
channel: 'stdout',
|
||||
data: text,
|
||||
});
|
||||
});
|
||||
|
||||
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
||||
const text = chunk.toString('utf8');
|
||||
if (errBytes < MAX_OUTPUT_PER_SERVER) {
|
||||
const slice = chunk.subarray(0, MAX_OUTPUT_PER_SERVER - errBytes);
|
||||
errChunks.push(slice);
|
||||
errBytes += slice.length;
|
||||
}
|
||||
emitter.push('stderr', `[${srv.id}] ${text}`);
|
||||
emitter.pushMeta({
|
||||
event: 'server-output',
|
||||
serverId: srv.id,
|
||||
channel: 'stderr',
|
||||
data: text,
|
||||
});
|
||||
});
|
||||
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
handle.abort();
|
||||
}, timeoutMs);
|
||||
timer.unref();
|
||||
|
||||
const onAbort = () => handle.abort();
|
||||
abortController.signal.addEventListener('abort', onAbort, { once: true });
|
||||
|
||||
try {
|
||||
const { exitCode } = await handle.done;
|
||||
targetEntry.stdout = Buffer.concat(outChunks).toString('utf8');
|
||||
targetEntry.stderr = Buffer.concat(errChunks).toString('utf8');
|
||||
targetEntry.durationMs = Date.now() - started;
|
||||
targetEntry.exitCode = exitCode;
|
||||
|
||||
if (job.cancelled || abortController.signal.aborted) {
|
||||
targetEntry.status = 'cancelled';
|
||||
} else if (timedOut) {
|
||||
targetEntry.status = 'error';
|
||||
targetEntry.stderr += `\nTimed out after ${timeoutMs}ms`;
|
||||
} else {
|
||||
targetEntry.status = exitCode === 0 ? 'ok' : 'error';
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
abortController.signal.removeEventListener('abort', onAbort);
|
||||
}
|
||||
} catch (err) {
|
||||
targetEntry.durationMs = Date.now() - started;
|
||||
targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error';
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg;
|
||||
emitter.push('stderr', `[${srv.id}] ${msg}\n`);
|
||||
}
|
||||
|
||||
emitter.pushMeta({
|
||||
event: 'server-exit',
|
||||
serverId: srv.id,
|
||||
exitCode: targetEntry.exitCode,
|
||||
durationMs: targetEntry.durationMs,
|
||||
status: targetEntry.status,
|
||||
});
|
||||
}).finally(() => {
|
||||
job.done = true;
|
||||
job.finishedAt = Date.now();
|
||||
const okCount = job.targets.filter((t) => t.status === 'ok').length;
|
||||
emitter.pushMeta({
|
||||
event: 'done',
|
||||
cancelled: job.cancelled,
|
||||
okCount,
|
||||
total: job.targets.length,
|
||||
});
|
||||
this.pruneJobs();
|
||||
});
|
||||
|
||||
return this.getBroadcastResult(jobId)!;
|
||||
}
|
||||
|
||||
private pruneJobs(): void {
|
||||
const done = [...this.jobs.values()].filter((j) => j.done);
|
||||
while (done.length > MAX_RETAINED_BROADCASTS) {
|
||||
const oldest = done.shift()!;
|
||||
this.jobs.delete(oldest.jobId);
|
||||
}
|
||||
}
|
||||
}
|
||||
44
src/server/automation/stream-buffer.ts
Normal file
44
src/server/automation/stream-buffer.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
|
||||
import type { WsHub } from '../api/ws-hub.js';
|
||||
|
||||
const DEFAULT_MAX_REPLAY_BYTES = 128 * 1024;
|
||||
|
||||
export class BufferedStreamEmitter {
|
||||
private readonly frames: ServerWsFrame[] = [];
|
||||
private bufferBytes = 0;
|
||||
|
||||
constructor(
|
||||
private readonly wsHub: WsHub,
|
||||
public readonly jobId: string,
|
||||
private readonly maxReplayBytes = DEFAULT_MAX_REPLAY_BYTES,
|
||||
) {}
|
||||
|
||||
push(stream: 'stdout' | 'stderr' | 'meta', data: string): void {
|
||||
const frame: ServerWsFrame = {
|
||||
type: 'stream:chunk',
|
||||
jobId: this.jobId,
|
||||
stream,
|
||||
data,
|
||||
};
|
||||
const bytes = Buffer.byteLength(data, 'utf8');
|
||||
this.frames.push(frame);
|
||||
this.bufferBytes += bytes;
|
||||
|
||||
while (this.bufferBytes > this.maxReplayBytes && this.frames.length > 0) {
|
||||
const dropped = this.frames.shift()!;
|
||||
if (dropped.type === 'stream:chunk') {
|
||||
this.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
this.wsHub.broadcastChannel(WS_CHANNELS.stream(this.jobId), frame);
|
||||
}
|
||||
|
||||
pushMeta(payload: Record<string, unknown>): void {
|
||||
this.push('meta', JSON.stringify(payload));
|
||||
}
|
||||
|
||||
getReplayFrames(): ServerWsFrame[] {
|
||||
return [...this.frames];
|
||||
}
|
||||
}
|
||||
192
src/server/automation/template.ts
Normal file
192
src/server/automation/template.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import type { InputDef } from '../../shared/schemas/common.js';
|
||||
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
||||
import { posixSingleQuote } from '../ssh/sudo.js';
|
||||
|
||||
export interface StepOutputSummary {
|
||||
stdout: string;
|
||||
exitCode: number | null;
|
||||
}
|
||||
|
||||
export interface TemplateContext {
|
||||
workflowId?: string;
|
||||
runId?: string;
|
||||
serverId?: string;
|
||||
inputs: Record<string, string>;
|
||||
stepOutputs?: Map<string, StepOutputSummary>;
|
||||
captures?: Map<string, string>;
|
||||
eventMeta?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function toEnvIdent(raw: string): string {
|
||||
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
|
||||
}
|
||||
|
||||
export function validateAndResolveInputs(
|
||||
defs: InputDef[],
|
||||
supplied: Record<string, unknown> = {},
|
||||
): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
|
||||
for (const def of defs) {
|
||||
const raw = supplied[def.name];
|
||||
const hasSupplied = raw !== undefined && raw !== null && raw !== '';
|
||||
const candidate = hasSupplied ? raw : def.default;
|
||||
|
||||
if (candidate === undefined || candidate === null || candidate === '') {
|
||||
if (def.required) {
|
||||
throw new Error(`Missing required input "${def.label ?? def.name}"`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (def.type === 'number') {
|
||||
const n = Number(candidate);
|
||||
if (!Number.isFinite(n)) {
|
||||
throw new Error(`Input "${def.name}" must be a valid number`);
|
||||
}
|
||||
out[def.name] = String(n);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (def.type === 'boolean') {
|
||||
if (typeof candidate === 'boolean') {
|
||||
out[def.name] = candidate ? 'true' : 'false';
|
||||
} else {
|
||||
const lower = String(candidate).trim().toLowerCase();
|
||||
if (lower === 'true' || lower === '1' || lower === 'yes') out[def.name] = 'true';
|
||||
else if (lower === 'false' || lower === '0' || lower === 'no') out[def.name] = 'false';
|
||||
else throw new Error(`Input "${def.name}" must be true or false`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const strVal = String(candidate);
|
||||
if (def.type === 'select' && def.options && def.options.length > 0) {
|
||||
if (!def.options.includes(strVal)) {
|
||||
throw new Error(
|
||||
`Input "${def.name}" must be one of: ${def.options.join(', ')}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
out[def.name] = strVal;
|
||||
}
|
||||
|
||||
for (const [k, v] of Object.entries(supplied)) {
|
||||
if (!(k in out) && v !== undefined && v !== null) {
|
||||
out[k] = String(v);
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
|
||||
if (ctx.runId) env.GCOORD_RUN_ID = ctx.runId;
|
||||
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
|
||||
|
||||
for (const [k, v] of Object.entries(ctx.inputs)) {
|
||||
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
|
||||
}
|
||||
|
||||
if (ctx.stepOutputs) {
|
||||
for (const [stepId, res] of ctx.stepOutputs.entries()) {
|
||||
const keyBase = `GCOORD_STEP_${toEnvIdent(stepId)}`;
|
||||
env[`${keyBase}_STDOUT`] = res.stdout.slice(0, 32 * 1024);
|
||||
env[`${keyBase}_EXIT`] = res.exitCode === null ? '' : String(res.exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.captures) {
|
||||
for (const [alias, val] of ctx.captures.entries()) {
|
||||
env[`GCOORD_CAPTURE_${toEnvIdent(alias)}`] = val.slice(0, 32 * 1024);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx.eventMeta) {
|
||||
for (const [k, v] of Object.entries(ctx.eventMeta)) {
|
||||
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
|
||||
}
|
||||
}
|
||||
|
||||
return env;
|
||||
}
|
||||
|
||||
function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string {
|
||||
const expr = rawExpr.trim();
|
||||
if (expr.startsWith('inputs.')) {
|
||||
const key = expr.slice('inputs.'.length);
|
||||
return ctx.inputs[key] ?? '';
|
||||
}
|
||||
if (expr.startsWith('steps.')) {
|
||||
const rest = expr.slice('steps.'.length);
|
||||
const dot = rest.lastIndexOf('.');
|
||||
if (dot > 0) {
|
||||
const stepId = rest.slice(0, dot);
|
||||
const field = rest.slice(dot + 1);
|
||||
const out = ctx.stepOutputs?.get(stepId);
|
||||
if (!out) return '';
|
||||
if (field === 'stdout') return out.stdout.trim();
|
||||
if (field === 'exitCode') return out.exitCode === null ? '' : String(out.exitCode);
|
||||
}
|
||||
}
|
||||
if (expr.startsWith('captures.')) {
|
||||
const key = expr.slice('captures.'.length);
|
||||
return (ctx.captures?.get(key) ?? '').trim();
|
||||
}
|
||||
if (expr.startsWith('event.')) {
|
||||
const key = expr.slice('event.'.length);
|
||||
return ctx.eventMeta?.[key] ?? '';
|
||||
}
|
||||
return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim();
|
||||
}
|
||||
|
||||
export function interpolateValuePlain(template: string, ctx: TemplateContext): string {
|
||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
||||
resolveTemplateToken(expr, ctx),
|
||||
);
|
||||
}
|
||||
|
||||
export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string {
|
||||
return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) =>
|
||||
posixSingleQuote(resolveTemplateToken(expr, ctx)),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveTargetServers(
|
||||
target: { serverId?: string; tags?: string[]; all?: boolean },
|
||||
servers: ServerConfig[],
|
||||
ctx: TemplateContext,
|
||||
): ServerConfig[] {
|
||||
const enabled = servers.filter((s) => s.enabled);
|
||||
|
||||
if (target.all) {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
const out: ServerConfig[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
if (target.serverId) {
|
||||
const resolvedId = interpolateValuePlain(target.serverId, ctx).trim();
|
||||
const match = enabled.find((s) => s.id === resolvedId);
|
||||
if (match) {
|
||||
seen.add(match.id);
|
||||
out.push(match);
|
||||
}
|
||||
}
|
||||
|
||||
if (target.tags && target.tags.length > 0) {
|
||||
const wanted = new Set(target.tags);
|
||||
for (const s of enabled) {
|
||||
if (seen.has(s.id)) continue;
|
||||
if (s.tags.some((t) => wanted.has(t))) {
|
||||
seen.add(s.id);
|
||||
out.push(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
|
@ -86,6 +86,9 @@ export class TransferEngine {
|
|||
|
||||
const errBuf: Buffer[] = [];
|
||||
let errLen = 0;
|
||||
handle.channel.on('data', (chunk: Buffer) => {
|
||||
opts.onProgress?.(chunk.toString('utf8'));
|
||||
});
|
||||
handle.channel.stderr?.on('data', (chunk: Buffer) => {
|
||||
if (errLen < 16_384) {
|
||||
errBuf.push(chunk);
|
||||
|
|
|
|||
1438
src/server/automation/workflow-engine.ts
Normal file
1438
src/server/automation/workflow-engine.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -133,6 +133,58 @@ export class ConfigManager {
|
|||
}
|
||||
}
|
||||
|
||||
get configDirPath(): string {
|
||||
return this.configDir;
|
||||
}
|
||||
|
||||
async pauseWatcher(): Promise<boolean> {
|
||||
const wasWatching = this.watcher !== null;
|
||||
for (const timer of this.debounceTimers.values()) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
this.debounceTimers.clear();
|
||||
|
||||
if (this.watcher) {
|
||||
await this.watcher.close();
|
||||
this.watcher = null;
|
||||
}
|
||||
return wasWatching;
|
||||
}
|
||||
|
||||
async resumeWatcher(): Promise<void> {
|
||||
if (!this.watcher) {
|
||||
await this.startWatcher();
|
||||
}
|
||||
}
|
||||
|
||||
reloadAllFromDisk(): void {
|
||||
this.servers.clear();
|
||||
this.systems.clear();
|
||||
this.workflows.clear();
|
||||
this.errors.clear();
|
||||
this.knownFiles.clear();
|
||||
this.snippets = SnippetsFileSchema.parse({});
|
||||
this.alerts = AlertsFileSchema.parse({});
|
||||
this.settings = SettingsSchema.parse({});
|
||||
|
||||
const seeded = seedDefaultConfigs(this.configDir);
|
||||
const seededSet = new Set(seeded);
|
||||
|
||||
const files = this.discoverAllConfigPaths();
|
||||
for (const relPath of files) {
|
||||
this.knownFiles.add(relPath);
|
||||
this.loadFileFromDisk(relPath, seededSet.has(relPath) ? 'seed' : 'disk', false);
|
||||
}
|
||||
|
||||
this.recomputeWarnings();
|
||||
this.emitChange({
|
||||
entityType: 'all',
|
||||
relPath: '*',
|
||||
warnings: structuredClone(this.warnings),
|
||||
errors: [...this.errors.values()].map((e) => structuredClone(e)),
|
||||
});
|
||||
}
|
||||
|
||||
onChange(listener: (event: ConfigChangeEvent) => void): () => void {
|
||||
this.changeListeners.add(listener);
|
||||
return () => {
|
||||
|
|
|
|||
534
src/server/security/backup.ts
Normal file
534
src/server/security/backup.ts
Normal file
|
|
@ -0,0 +1,534 @@
|
|||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
AlertsFileSchema,
|
||||
ServerConfigSchema,
|
||||
SettingsSchema,
|
||||
SnippetsFileSchema,
|
||||
SystemConfigSchema,
|
||||
WorkflowConfigSchema,
|
||||
} from '../../shared/schemas/index.js';
|
||||
import { openDatabase } from '../db/database.js';
|
||||
import { parseMasterKey, verifyVaultEnvelopeText } from './vault.js';
|
||||
|
||||
export const BackupEnvelopeSchema = z.object({
|
||||
magic: z.literal('GCOORD_BACKUP_V1'),
|
||||
version: z.literal(1),
|
||||
alg: z.literal('aes-256-gcm'),
|
||||
kdf: z.enum(['raw-master-key', 'scrypt']),
|
||||
salt: z.string().optional(),
|
||||
iv: z.string().min(1),
|
||||
tag: z.string().min(1),
|
||||
ciphertext: z.string().min(1),
|
||||
createdAt: z.string(),
|
||||
});
|
||||
|
||||
export type BackupEnvelope = z.infer<typeof BackupEnvelopeSchema>;
|
||||
|
||||
const KnownHostRowSchema = z.object({
|
||||
hostPort: z.string().min(1),
|
||||
algorithm: z.string().min(1),
|
||||
fingerprint: z.string().min(1),
|
||||
trustedAt: z.number().int(),
|
||||
updatedAt: z.number().int(),
|
||||
});
|
||||
|
||||
const AlertSilenceRowSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
scopeType: z.enum(['all', 'rule', 'server', 'tag']),
|
||||
targetId: z.string().min(1),
|
||||
reason: z.string().nullable(),
|
||||
createdAt: z.number().int(),
|
||||
expiresAt: z.number().int(),
|
||||
});
|
||||
|
||||
export const BackupInnerPayloadSchema = z.object({
|
||||
format: z.literal('gcoord-backup'),
|
||||
version: z.literal(1),
|
||||
createdAt: z.string(),
|
||||
configFiles: z.record(z.string(), z.string()),
|
||||
vaultEnvelopeRaw: z.string().nullable(),
|
||||
knownHosts: z.array(KnownHostRowSchema).default([]),
|
||||
dbMeta: z
|
||||
.object({
|
||||
alertSilences: z.array(AlertSilenceRowSchema).default([]),
|
||||
})
|
||||
.default({ alertSilences: [] }),
|
||||
});
|
||||
|
||||
export type BackupInnerPayload = z.infer<typeof BackupInnerPayloadSchema>;
|
||||
|
||||
export interface BackupVerificationSummary {
|
||||
valid: true;
|
||||
createdAt: string;
|
||||
kdf: 'raw-master-key' | 'scrypt';
|
||||
configFileCount: number;
|
||||
configFiles: string[];
|
||||
hasVault: boolean;
|
||||
vaultVerified: boolean;
|
||||
vaultCredentialCount?: number;
|
||||
knownHostsCount: number;
|
||||
alertSilenceCount: number;
|
||||
overlayCount: number;
|
||||
}
|
||||
|
||||
const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
|
||||
const MAX_GUNZIP_BYTES = 32 * 1024 * 1024;
|
||||
const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const;
|
||||
|
||||
function validateAndParseConfigEntry(
|
||||
relPath: string,
|
||||
rawJson: string,
|
||||
): { overlayCount: number } {
|
||||
if (!relPath || relPath.includes('\\') || relPath.includes('..') || relPath.startsWith('/')) {
|
||||
throw new Error(`Unsafe config path inside backup: ${relPath}`);
|
||||
}
|
||||
const obj = JSON.parse(rawJson);
|
||||
|
||||
if (relPath === 'settings.json') {
|
||||
SettingsSchema.parse(obj);
|
||||
return { overlayCount: 0 };
|
||||
}
|
||||
if (relPath === 'alerts.json') {
|
||||
AlertsFileSchema.parse(obj);
|
||||
return { overlayCount: 0 };
|
||||
}
|
||||
if (relPath === 'snippets.json') {
|
||||
SnippetsFileSchema.parse(obj);
|
||||
return { overlayCount: 0 };
|
||||
}
|
||||
|
||||
const parts = relPath.split('/');
|
||||
if (parts.length !== 2 || !parts[1]?.endsWith('.json')) {
|
||||
throw new Error(`Unrecognized config path in backup: ${relPath}`);
|
||||
}
|
||||
const [folder, fileName] = parts;
|
||||
const expectedId = fileName.slice(0, -5);
|
||||
if (!SLUG_ID_RE.test(expectedId)) {
|
||||
throw new Error(`Invalid config entity ID in path: ${relPath}`);
|
||||
}
|
||||
|
||||
if (folder === 'servers') {
|
||||
const parsed = ServerConfigSchema.parse(obj);
|
||||
if (parsed.id !== expectedId) {
|
||||
throw new Error(`Config server id "${parsed.id}" does not match filename "${relPath}"`);
|
||||
}
|
||||
let overlayCount = 0;
|
||||
for (const sys of parsed.systems) {
|
||||
overlayCount += Object.keys(sys.itemOverrides).length;
|
||||
}
|
||||
return { overlayCount };
|
||||
}
|
||||
if (folder === 'systems') {
|
||||
const parsed = SystemConfigSchema.parse(obj);
|
||||
if (parsed.id !== expectedId) {
|
||||
throw new Error(`Config system id "${parsed.id}" does not match filename "${relPath}"`);
|
||||
}
|
||||
return { overlayCount: 0 };
|
||||
}
|
||||
if (folder === 'workflows') {
|
||||
const parsed = WorkflowConfigSchema.parse(obj);
|
||||
if (parsed.id !== expectedId) {
|
||||
throw new Error(`Config workflow id "${parsed.id}" does not match filename "${relPath}"`);
|
||||
}
|
||||
return { overlayCount: 0 };
|
||||
}
|
||||
|
||||
throw new Error(`Unsupported config folder "${folder}" inside backup`);
|
||||
}
|
||||
|
||||
function collectConfigFilesFromDisk(configDir: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
if (!fs.existsSync(configDir)) return out;
|
||||
|
||||
for (const name of ['settings.json', 'alerts.json', 'snippets.json']) {
|
||||
const abs = path.join(configDir, name);
|
||||
if (fs.existsSync(abs)) {
|
||||
out[name] = fs.readFileSync(abs, 'utf8');
|
||||
}
|
||||
}
|
||||
for (const folder of ['servers', 'systems', 'workflows']) {
|
||||
const dir = path.join(configDir, folder);
|
||||
if (!fs.existsSync(dir)) continue;
|
||||
for (const entry of fs.readdirSync(dir).sort()) {
|
||||
if (!entry.endsWith('.json') || entry.includes('.tmp')) continue;
|
||||
const rel = `${folder}/${entry}`;
|
||||
const abs = path.join(dir, entry);
|
||||
if (fs.statSync(abs).isFile()) {
|
||||
out[rel] = fs.readFileSync(abs, 'utf8');
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function deriveEnvelopeKeyForEncrypt(opts: {
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
}): {
|
||||
key: Buffer;
|
||||
kdf: 'raw-master-key' | 'scrypt';
|
||||
saltB64?: string;
|
||||
} {
|
||||
const pass = opts.passphrase?.trim();
|
||||
if (pass && pass.length > 0) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS);
|
||||
return { key, kdf: 'scrypt', saltB64: salt.toString('base64') };
|
||||
}
|
||||
if (!opts.masterKey || !opts.masterKey.trim()) {
|
||||
throw new Error('Either Vault master key or backup passphrase is required');
|
||||
}
|
||||
return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' };
|
||||
}
|
||||
|
||||
function deriveEnvelopeKeyForDecrypt(
|
||||
envelope: BackupEnvelope,
|
||||
opts: { masterKey?: string; passphrase?: string },
|
||||
): Buffer {
|
||||
if (envelope.kdf === 'scrypt') {
|
||||
const pass = opts.passphrase?.trim();
|
||||
if (!pass) {
|
||||
throw new Error('This backup is encrypted with a passphrase; provide backup passphrase');
|
||||
}
|
||||
if (!envelope.salt) {
|
||||
throw new Error('Backup envelope is missing scrypt salt');
|
||||
}
|
||||
const salt = Buffer.from(envelope.salt, 'base64');
|
||||
if (salt.length < 8) {
|
||||
throw new Error('Backup envelope contains an invalid scrypt salt');
|
||||
}
|
||||
return crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS);
|
||||
}
|
||||
|
||||
if (!opts.masterKey || !opts.masterKey.trim()) {
|
||||
throw new Error('This backup requires the 32-byte Vault master key to decrypt');
|
||||
}
|
||||
return parseMasterKey(opts.masterKey);
|
||||
}
|
||||
|
||||
export function createBackupBundle(opts: {
|
||||
dataDir: string;
|
||||
db?: Database.Database;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
}): {
|
||||
serialized: string;
|
||||
envelope: BackupEnvelope;
|
||||
summary: BackupVerificationSummary;
|
||||
} {
|
||||
const dataDir = path.resolve(opts.dataDir);
|
||||
const configDir = path.join(dataDir, 'config');
|
||||
const vaultPath = path.join(dataDir, 'vault.enc');
|
||||
const dbPath = path.join(dataDir, 'gcoord.db');
|
||||
|
||||
const configFiles = collectConfigFilesFromDisk(configDir);
|
||||
let overlayCount = 0;
|
||||
for (const [relPath, rawJson] of Object.entries(configFiles)) {
|
||||
overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount;
|
||||
}
|
||||
|
||||
const vaultEnvelopeRaw = fs.existsSync(vaultPath)
|
||||
? fs.readFileSync(vaultPath, 'utf8')
|
||||
: null;
|
||||
let vaultVerified = false;
|
||||
let vaultCredentialCount: number | undefined;
|
||||
if (vaultEnvelopeRaw) {
|
||||
const vCheck = verifyVaultEnvelopeText(
|
||||
vaultEnvelopeRaw,
|
||||
opts.masterKey?.trim() || undefined,
|
||||
);
|
||||
vaultVerified = vCheck.decrypted;
|
||||
vaultCredentialCount = vCheck.credentialCount;
|
||||
}
|
||||
|
||||
let localDb: Database.Database | null = null;
|
||||
const db =
|
||||
opts.db ??
|
||||
(fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null);
|
||||
|
||||
let knownHosts: Array<z.infer<typeof KnownHostRowSchema>> = [];
|
||||
let alertSilences: Array<z.infer<typeof AlertSilenceRowSchema>> = [];
|
||||
try {
|
||||
if (db) {
|
||||
knownHosts = db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC',
|
||||
)
|
||||
.all() as Array<z.infer<typeof KnownHostRowSchema>>;
|
||||
|
||||
const nowMs = Date.now();
|
||||
alertSilences = db
|
||||
.prepare(
|
||||
`SELECT id, scope_type AS scopeType, target_id AS targetId, reason,
|
||||
created_at AS createdAt, expires_at AS expiresAt
|
||||
FROM alert_silences
|
||||
WHERE expires_at > ?
|
||||
ORDER BY created_at DESC`,
|
||||
)
|
||||
.all(nowMs) as Array<z.infer<typeof AlertSilenceRowSchema>>;
|
||||
}
|
||||
} finally {
|
||||
localDb?.close();
|
||||
}
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const inner: BackupInnerPayload = {
|
||||
format: 'gcoord-backup',
|
||||
version: 1,
|
||||
createdAt,
|
||||
configFiles,
|
||||
vaultEnvelopeRaw,
|
||||
knownHosts,
|
||||
dbMeta: { alertSilences },
|
||||
};
|
||||
|
||||
const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({
|
||||
masterKey: opts.masterKey,
|
||||
passphrase: opts.passphrase,
|
||||
});
|
||||
|
||||
const plaintextJson = Buffer.from(JSON.stringify(inner), 'utf8');
|
||||
const compressed = zlib.gzipSync(plaintextJson, { level: 9 });
|
||||
try {
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
|
||||
const envelope: BackupEnvelope = {
|
||||
magic: 'GCOORD_BACKUP_V1',
|
||||
version: 1,
|
||||
alg: 'aes-256-gcm',
|
||||
kdf,
|
||||
...(saltB64 ? { salt: saltB64 } : {}),
|
||||
iv: iv.toString('base64'),
|
||||
tag: tag.toString('base64'),
|
||||
ciphertext: ciphertext.toString('base64'),
|
||||
createdAt,
|
||||
};
|
||||
|
||||
const fileList = Object.keys(configFiles).sort();
|
||||
return {
|
||||
serialized: `${JSON.stringify(envelope, null, 2)}\n`,
|
||||
envelope,
|
||||
summary: {
|
||||
valid: true,
|
||||
createdAt,
|
||||
kdf,
|
||||
configFileCount: fileList.length,
|
||||
configFiles: fileList,
|
||||
hasVault: vaultEnvelopeRaw !== null,
|
||||
vaultVerified,
|
||||
vaultCredentialCount,
|
||||
knownHostsCount: knownHosts.length,
|
||||
alertSilenceCount: alertSilences.length,
|
||||
overlayCount,
|
||||
},
|
||||
};
|
||||
} finally {
|
||||
key.fill(0);
|
||||
plaintextJson.fill(0);
|
||||
compressed.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyBackupBundle(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const rawStr = typeof rawTextOrBuf === 'string' ? rawTextOrBuf : rawTextOrBuf.toString('utf8');
|
||||
const envelope = BackupEnvelopeSchema.parse(JSON.parse(rawStr));
|
||||
|
||||
const iv = Buffer.from(envelope.iv, 'base64');
|
||||
const tag = Buffer.from(envelope.tag, 'base64');
|
||||
const ciphertext = Buffer.from(envelope.ciphertext, 'base64');
|
||||
if (iv.length !== 12 || tag.length !== 16) {
|
||||
throw new Error('Invalid AES-256-GCM parameters inside backup envelope');
|
||||
}
|
||||
|
||||
const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts);
|
||||
let compressed: Buffer | null = null;
|
||||
let plaintext: Buffer | null = null;
|
||||
let inner: BackupInnerPayload;
|
||||
|
||||
try {
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAuthTag(tag);
|
||||
compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
plaintext = zlib.gunzipSync(compressed, { maxOutputLength: MAX_GUNZIP_BYTES });
|
||||
inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8')));
|
||||
} finally {
|
||||
key.fill(0);
|
||||
compressed?.fill(0);
|
||||
plaintext?.fill(0);
|
||||
}
|
||||
|
||||
let overlayCount = 0;
|
||||
for (const [relPath, rawJson] of Object.entries(inner.configFiles)) {
|
||||
overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount;
|
||||
}
|
||||
|
||||
let vaultVerified = false;
|
||||
let vaultCredentialCount: number | undefined;
|
||||
if (inner.vaultEnvelopeRaw !== null) {
|
||||
const effectiveVaultKey = keyOpts.vaultMasterKey?.trim() || keyOpts.masterKey?.trim();
|
||||
const res = verifyVaultEnvelopeText(inner.vaultEnvelopeRaw, effectiveVaultKey || undefined);
|
||||
vaultVerified = res.decrypted;
|
||||
vaultCredentialCount = res.credentialCount;
|
||||
if (envelope.kdf === 'raw-master-key' && !keyOpts.vaultMasterKey && !vaultVerified) {
|
||||
throw new Error('Vault integrity check failed with master key');
|
||||
}
|
||||
}
|
||||
|
||||
const configFiles = Object.keys(inner.configFiles).sort();
|
||||
return {
|
||||
inner,
|
||||
summary: {
|
||||
valid: true,
|
||||
createdAt: inner.createdAt,
|
||||
kdf: envelope.kdf,
|
||||
configFileCount: configFiles.length,
|
||||
configFiles,
|
||||
hasVault: inner.vaultEnvelopeRaw !== null,
|
||||
vaultVerified,
|
||||
vaultCredentialCount,
|
||||
knownHostsCount: inner.knownHosts.length,
|
||||
alertSilenceCount: inner.dbMeta.alertSilences.length,
|
||||
overlayCount,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyBackupSummaryOnly(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string },
|
||||
): BackupVerificationSummary {
|
||||
return verifyBackupBundle(rawTextOrBuf, keyOpts).summary;
|
||||
}
|
||||
|
||||
function writeAtomicPrivateFile(targetPath: string, content: string): void {
|
||||
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
||||
const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
||||
const fd = fs.openSync(tmpPath, 'w', 0o600);
|
||||
try {
|
||||
fs.writeFileSync(fd, content, 'utf8');
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmpPath, targetPath);
|
||||
fs.chmodSync(targetPath, 0o600);
|
||||
} catch (err) {
|
||||
try {
|
||||
fs.unlinkSync(tmpPath);
|
||||
} catch {
|
||||
// Ignore cleanup error
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function swapConfigDirectoryAtomic(configDir: string, configFiles: Record<string, string>): void {
|
||||
const parent = path.dirname(configDir);
|
||||
const rand = crypto.randomBytes(5).toString('hex');
|
||||
const stageDir = path.join(parent, `config.restore-${rand}`);
|
||||
const bakDir = path.join(parent, `config.bak-${rand}`);
|
||||
|
||||
fs.mkdirSync(stageDir, { recursive: true, mode: 0o700 });
|
||||
try {
|
||||
for (const [relPath, content] of Object.entries(configFiles)) {
|
||||
const dest = path.resolve(stageDir, relPath);
|
||||
if (!dest.startsWith(`${stageDir}${path.sep}`)) {
|
||||
throw new Error(`Unsafe restore target path: ${relPath}`);
|
||||
}
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(dest, content, { encoding: 'utf8', mode: 0o600 });
|
||||
}
|
||||
|
||||
const hadExisting = fs.existsSync(configDir);
|
||||
if (hadExisting) {
|
||||
fs.renameSync(configDir, bakDir);
|
||||
}
|
||||
try {
|
||||
fs.renameSync(stageDir, configDir);
|
||||
} catch (err) {
|
||||
if (hadExisting && fs.existsSync(bakDir) && !fs.existsSync(configDir)) {
|
||||
fs.renameSync(bakDir, configDir);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (hadExisting && fs.existsSync(bakDir)) {
|
||||
fs.rmSync(bakDir, { recursive: true, force: true });
|
||||
}
|
||||
} catch (err) {
|
||||
if (fs.existsSync(stageDir)) {
|
||||
fs.rmSync(stageDir, { recursive: true, force: true });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function restoreBackupBundle(
|
||||
rawTextOrBuf: string | Buffer,
|
||||
opts: {
|
||||
dataDir: string;
|
||||
masterKey?: string;
|
||||
passphrase?: string;
|
||||
vaultMasterKey?: string;
|
||||
db?: Database.Database;
|
||||
},
|
||||
): { summary: BackupVerificationSummary; inner: BackupInnerPayload } {
|
||||
const verified = verifyBackupBundle(rawTextOrBuf, {
|
||||
masterKey: opts.masterKey,
|
||||
passphrase: opts.passphrase,
|
||||
vaultMasterKey: opts.vaultMasterKey,
|
||||
});
|
||||
|
||||
const dataDir = path.resolve(opts.dataDir);
|
||||
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
||||
|
||||
swapConfigDirectoryAtomic(path.join(dataDir, 'config'), verified.inner.configFiles);
|
||||
|
||||
const vaultPath = path.join(dataDir, 'vault.enc');
|
||||
if (verified.inner.vaultEnvelopeRaw !== null) {
|
||||
writeAtomicPrivateFile(vaultPath, verified.inner.vaultEnvelopeRaw);
|
||||
if (verified.summary.vaultVerified) {
|
||||
fs.rmSync(`${vaultPath}.panic-locked`, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
let localDb: Database.Database | null = null;
|
||||
const db = opts.db ?? (localDb = openDatabase(path.join(dataDir, 'gcoord.db')));
|
||||
try {
|
||||
const tx = db.transaction(() => {
|
||||
db.prepare('DELETE FROM known_hosts').run();
|
||||
const insHost = db.prepare(
|
||||
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const h of verified.inner.knownHosts) {
|
||||
insHost.run(h.hostPort, h.algorithm, h.fingerprint, h.trustedAt, h.updatedAt);
|
||||
}
|
||||
|
||||
db.prepare('DELETE FROM alert_silences').run();
|
||||
const insSilence = db.prepare(
|
||||
`INSERT INTO alert_silences (id, scope_type, target_id, reason, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const s of verified.inner.dbMeta.alertSilences) {
|
||||
insSilence.run(s.id, s.scopeType, s.targetId, s.reason, s.createdAt, s.expiresAt);
|
||||
}
|
||||
});
|
||||
tx();
|
||||
} finally {
|
||||
localDb?.close();
|
||||
}
|
||||
|
||||
return verified;
|
||||
}
|
||||
|
|
@ -12,7 +12,7 @@ import {
|
|||
} from '../../shared/schemas/vault.schema.js';
|
||||
import type { VaultState } from '../../shared/ws-protocol.js';
|
||||
|
||||
const VaultEnvelopeSchema = z.object({
|
||||
export const VaultEnvelopeSchema = z.object({
|
||||
version: z.literal(1),
|
||||
alg: z.literal('aes-256-gcm'),
|
||||
iv: z.string().min(1),
|
||||
|
|
@ -21,7 +21,7 @@ const VaultEnvelopeSchema = z.object({
|
|||
updatedAt: z.string(),
|
||||
});
|
||||
|
||||
type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
|
||||
export type VaultEnvelope = z.infer<typeof VaultEnvelopeSchema>;
|
||||
|
||||
export function parseMasterKey(raw: string): Buffer {
|
||||
const trimmed = raw.trim();
|
||||
|
|
@ -77,6 +77,37 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload {
|
|||
}
|
||||
}
|
||||
|
||||
export function verifyVaultEnvelopeText(
|
||||
rawText: string,
|
||||
masterKeyInput?: string,
|
||||
): {
|
||||
envelopeValid: boolean;
|
||||
decrypted: boolean;
|
||||
credentialCount?: number;
|
||||
updatedAt: string;
|
||||
} {
|
||||
const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText));
|
||||
if (!masterKeyInput || !masterKeyInput.trim()) {
|
||||
return {
|
||||
envelopeValid: true,
|
||||
decrypted: false,
|
||||
updatedAt: envelope.updatedAt,
|
||||
};
|
||||
}
|
||||
const keyBuf = parseMasterKey(masterKeyInput);
|
||||
try {
|
||||
const payload = decryptEnvelope(envelope, keyBuf);
|
||||
return {
|
||||
envelopeValid: true,
|
||||
decrypted: true,
|
||||
credentialCount: Object.keys(payload.credentials).length,
|
||||
updatedAt: envelope.updatedAt,
|
||||
};
|
||||
} finally {
|
||||
keyBuf.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function computeOpenSshFingerprint(publicKeyLine: string): string {
|
||||
const parsed = ssh2.utils.parseKey(publicKeyLine.trim());
|
||||
if (parsed instanceof Error) {
|
||||
|
|
@ -91,6 +122,37 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string {
|
|||
return `SHA256:${hash}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString
|
||||
* leading-zero stripping bug when a generated public key starts with 0x00.
|
||||
*/
|
||||
export function generateValidEd25519KeyPair(opts: {
|
||||
comment: string;
|
||||
passphrase?: string;
|
||||
}): { privateKey: string; publicKey: string; fingerprint: string } {
|
||||
let lastErr: unknown;
|
||||
for (let attempt = 0; attempt < 16; attempt++) {
|
||||
const kp = opts.passphrase
|
||||
? ssh2.utils.generateKeyPairSync('ed25519', {
|
||||
comment: opts.comment,
|
||||
passphrase: opts.passphrase,
|
||||
cipher: 'aes256-ctr',
|
||||
rounds: 16,
|
||||
})
|
||||
: ssh2.utils.generateKeyPairSync('ed25519', {
|
||||
comment: opts.comment,
|
||||
});
|
||||
const publicKey = kp.public.trim();
|
||||
try {
|
||||
const fingerprint = computeOpenSshFingerprint(publicKey);
|
||||
return { privateKey: kp.private, publicKey, fingerprint };
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
}
|
||||
}
|
||||
throw lastErr instanceof Error ? lastErr : new Error('Failed to generate valid Ed25519 keypair');
|
||||
}
|
||||
|
||||
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
||||
|
||||
export type VaultCredentialInput = DistributiveOmit<
|
||||
|
|
@ -344,6 +406,40 @@ export class VaultService {
|
|||
this.writeUnlocked = false;
|
||||
}
|
||||
|
||||
reloadFromDisk(masterKeyInput?: string): boolean {
|
||||
if (!fs.existsSync(this.vaultFilePath)) {
|
||||
this.credentials.clear();
|
||||
return false;
|
||||
}
|
||||
|
||||
let candidateKey: Buffer | null = null;
|
||||
if (masterKeyInput && masterKeyInput.trim().length > 0) {
|
||||
candidateKey = parseMasterKey(masterKeyInput);
|
||||
} else if (this.masterKey !== null) {
|
||||
candidateKey = Buffer.from(this.masterKey);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const rawText = fs.readFileSync(this.vaultFilePath, 'utf8');
|
||||
const envelope = VaultEnvelopeSchema.parse(JSON.parse(rawText));
|
||||
const payload = decryptEnvelope(envelope, candidateKey);
|
||||
const wasUnlocked = this.writeUnlocked;
|
||||
this.zeroizeMasterKey();
|
||||
this.masterKey = candidateKey;
|
||||
this.credentials = new Map(Object.entries(payload.credentials));
|
||||
this.writeUnlocked = wasUnlocked;
|
||||
this.autoInitializedEmpty = false;
|
||||
this.setPanicLockMarker(false);
|
||||
this.persistKeyFileIfConfigured(candidateKey);
|
||||
return true;
|
||||
} catch (err) {
|
||||
candidateKey.fill(0);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
panicLock(): void {
|
||||
this.zeroizeMasterKey();
|
||||
this.credentials.clear();
|
||||
|
|
@ -483,25 +579,16 @@ export class VaultService {
|
|||
this.assertWriteUnlocked();
|
||||
this.autoInitializedEmpty = false;
|
||||
|
||||
const keyPair = options.passphrase
|
||||
? ssh2.utils.generateKeyPairSync('ed25519', {
|
||||
const { privateKey, publicKey, fingerprint } = generateValidEd25519KeyPair({
|
||||
comment: options.comment ?? options.id,
|
||||
passphrase: options.passphrase,
|
||||
cipher: 'aes256-ctr',
|
||||
rounds: 16,
|
||||
})
|
||||
: ssh2.utils.generateKeyPairSync('ed25519', {
|
||||
comment: options.comment ?? options.id,
|
||||
});
|
||||
|
||||
const publicKey = keyPair.public.trim();
|
||||
const fingerprint = computeOpenSshFingerprint(publicKey);
|
||||
|
||||
return this.upsertCredential({
|
||||
id: options.id,
|
||||
name: options.name,
|
||||
type: 'ssh-key',
|
||||
privateKey: keyPair.private,
|
||||
privateKey,
|
||||
publicKey,
|
||||
passphrase: options.passphrase || undefined,
|
||||
fingerprint,
|
||||
|
|
|
|||
|
|
@ -243,6 +243,35 @@ export class KnownHostsService {
|
|||
.all() as KnownHostRecord[];
|
||||
}
|
||||
|
||||
replaceAllKnownHosts(
|
||||
records: Array<
|
||||
Pick<KnownHostRecord, 'hostPort' | 'algorithm' | 'fingerprint'> &
|
||||
Partial<Pick<KnownHostRecord, 'trustedAt' | 'updatedAt'>>
|
||||
>,
|
||||
): void {
|
||||
const now = Date.now();
|
||||
const tx = this.db.transaction(() => {
|
||||
this.db.prepare('DELETE FROM known_hosts').run();
|
||||
const ins = this.db.prepare(
|
||||
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
);
|
||||
for (const r of records) {
|
||||
ins.run(
|
||||
r.hostPort,
|
||||
r.algorithm,
|
||||
r.fingerprint,
|
||||
r.trustedAt ?? now,
|
||||
r.updatedAt ?? now,
|
||||
);
|
||||
}
|
||||
});
|
||||
tx();
|
||||
this.pendingTofu.clear();
|
||||
this.pendingMismatches.clear();
|
||||
this.emitChange();
|
||||
}
|
||||
|
||||
deleteKnownHost(hostPort: string): boolean {
|
||||
const res = this.db
|
||||
.prepare('DELETE FROM known_hosts WHERE host_port = ?')
|
||||
|
|
|
|||
|
|
@ -7,8 +7,13 @@ export const ThemeIdSchema = z.enum([
|
|||
'nord-dark',
|
||||
'gruvbox-dark',
|
||||
'paper-light',
|
||||
'solarized-dark',
|
||||
'tokyo-night',
|
||||
'high-contrast',
|
||||
]);
|
||||
|
||||
export const THEME_IDS = ThemeIdSchema.options;
|
||||
|
||||
export const StepUpPolicySchema = z.enum([
|
||||
'off',
|
||||
'every-action',
|
||||
|
|
|
|||
414
tests/ai-assistant.test.ts
Normal file
414
tests/ai-assistant.test.ts
Normal file
|
|
@ -0,0 +1,414 @@
|
|||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
class CookieJar {
|
||||
private cookies = new Map<string, string>();
|
||||
updateFrom(res: Response): void {
|
||||
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
|
||||
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
|
||||
for (const line of rawList) {
|
||||
const first = line.split(';')[0] ?? '';
|
||||
const eq = first.indexOf('=');
|
||||
if (eq > 0) {
|
||||
const name = first.slice(0, eq).trim();
|
||||
const val = first.slice(eq + 1).trim();
|
||||
if (val === '') this.cookies.delete(name);
|
||||
else this.cookies.set(name, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
header(): string {
|
||||
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
}
|
||||
}
|
||||
|
||||
async function openWs(url: string, headers: Record<string, string>) {
|
||||
return new Promise<{ ws: WebSocket; frames: Array<Record<string, unknown>> }>((resolve, reject) => {
|
||||
const frames: Array<Record<string, unknown>> = [];
|
||||
const ws = new WebSocket(url, { headers });
|
||||
ws.on('message', (raw) => frames.push(JSON.parse(raw.toString())));
|
||||
ws.once('open', () => resolve({ ws, frames }));
|
||||
ws.once('unexpected-response', (_req, res) =>
|
||||
reject(new Error(`WS_HTTP_${res.statusCode}`)),
|
||||
);
|
||||
ws.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function waitFor<T>(
|
||||
fn: () => T | undefined | null | false,
|
||||
timeoutMs = 5000,
|
||||
intervalMs = 25,
|
||||
): Promise<T> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const val = fn();
|
||||
if (val) return val;
|
||||
await new Promise((r) => setTimeout(r, intervalMs));
|
||||
}
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
|
||||
interface MockAiReq {
|
||||
url: string;
|
||||
authorization?: string;
|
||||
rawBody: string;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guides, WS Streaming & Zod Validation', () => {
|
||||
it('stays disabled by default, redacts all secrets across all 5 surfaces, streams/cancels over /ws while Vault is write-locked, and validates Zod drafts', async () => {
|
||||
const recorded: MockAiReq[] = [];
|
||||
let abortedSlowCount = 0;
|
||||
const openSlowResponses = new Set<http.ServerResponse>();
|
||||
|
||||
const mockAiServer = http.createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on('data', (c: Buffer) => chunks.push(c));
|
||||
req.on('end', () => {
|
||||
const rawBody = Buffer.concat(chunks).toString('utf8');
|
||||
recorded.push({
|
||||
url: req.url ?? '',
|
||||
authorization:
|
||||
typeof req.headers.authorization === 'string' ? req.headers.authorization : undefined,
|
||||
rawBody,
|
||||
});
|
||||
|
||||
const bodyObj = JSON.parse(rawBody) as {
|
||||
stream?: boolean;
|
||||
messages?: Array<{ role: string; content: string }>;
|
||||
};
|
||||
const userText = bodyObj.messages?.map((m) => m.content).join('\n') ?? '';
|
||||
|
||||
if (!bodyObj.stream) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(
|
||||
JSON.stringify({
|
||||
choices: [{ message: { content: 'OK' } }],
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
Connection: 'keep-alive',
|
||||
});
|
||||
|
||||
if (userText.includes('SLOW_STREAM')) {
|
||||
openSlowResponses.add(res);
|
||||
res.write(
|
||||
`data: ${JSON.stringify({ choices: [{ delta: { content: 'Starting slow analysis ' } }] })}\n\n`,
|
||||
);
|
||||
req.on('close', () => {
|
||||
openSlowResponses.delete(res);
|
||||
abortedSlowCount += 1;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const draftJson = JSON.stringify({
|
||||
id: 'ai-health-check',
|
||||
name: 'AI Health Check',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log', pinToDashboard: false },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'check-uptime',
|
||||
type: 'exec',
|
||||
target: { all: true },
|
||||
command: 'uptime',
|
||||
},
|
||||
],
|
||||
});
|
||||
const chunksOut = [
|
||||
'Here is a validated workflow draft:\n',
|
||||
'```json\n',
|
||||
draftJson,
|
||||
'\n```',
|
||||
];
|
||||
let idx = 0;
|
||||
const timer = setInterval(() => {
|
||||
if (idx < chunksOut.length) {
|
||||
res.write(
|
||||
`data: ${JSON.stringify({ choices: [{ delta: { content: chunksOut[idx++] } }] })}\n\n`,
|
||||
);
|
||||
} else {
|
||||
clearInterval(timer);
|
||||
res.write('data: [DONE]\n\n');
|
||||
res.end();
|
||||
}
|
||||
}, 10);
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => mockAiServer.listen(0, '127.0.0.1', resolve));
|
||||
const aiAddr = mockAiServer.address() as { port: number };
|
||||
const aiBaseUrl = `http://127.0.0.1:${aiAddr.port}`;
|
||||
cleanups.push(async () => {
|
||||
for (const r of openSlowResponses) r.destroy();
|
||||
await new Promise<void>((resolve) => mockAiServer.close(() => resolve()));
|
||||
});
|
||||
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-ai-'));
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const wsUrl = `ws://127.0.0.1:${server.port}/ws`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
|
||||
const api = async (
|
||||
pathname: string,
|
||||
opts: { method?: string; body?: unknown; safeMode?: boolean } = {},
|
||||
) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1';
|
||||
|
||||
const res = await fetch(`${baseUrl}${pathname}`, {
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
jar.updateFrom(res);
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
const boot = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'phase5-ai-password',
|
||||
totpCode: totp.generate(),
|
||||
secretBase32,
|
||||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'ai-api-key',
|
||||
name: 'AI LLM Key',
|
||||
type: 'api-token',
|
||||
token: 'sk-vault-ai-secret-55555',
|
||||
},
|
||||
});
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'prod-sudo',
|
||||
name: 'Prod Sudo',
|
||||
type: 'sudo-password',
|
||||
password: 'VaultSudoLeakCheck!99',
|
||||
},
|
||||
});
|
||||
|
||||
// 1. Strictly opt-in: disabled by default -> 403 AI_DISABLED, zero outbound requests
|
||||
const disabledChat = await api('/api/ai/chat', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
surface: 'workflows',
|
||||
messages: [{ role: 'user', content: 'Draft a ping workflow' }],
|
||||
},
|
||||
});
|
||||
expect(disabledChat.status).toBe(403);
|
||||
expect(disabledChat.data.error).toBe('AI_DISABLED');
|
||||
expect(recorded).toHaveLength(0);
|
||||
|
||||
// 2. Enable AI in settings.json referencing vaulted secretRef, then write-lock Vault
|
||||
const settingsRes = await api('/api/config/file?path=settings.json');
|
||||
const settingsObj = JSON.parse(String(settingsRes.data.rawContent));
|
||||
settingsObj.ai = {
|
||||
enabled: true,
|
||||
baseUrl: aiBaseUrl,
|
||||
model: 'qwen2.5-coder:7b',
|
||||
secretRef: 'ai-api-key',
|
||||
maxContextChars: 4000,
|
||||
};
|
||||
expect(
|
||||
(
|
||||
await api('/api/config/file', {
|
||||
method: 'PUT',
|
||||
body: { path: 'settings.json', content: JSON.stringify(settingsObj, null, 2) },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
// Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret
|
||||
expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked');
|
||||
|
||||
const testEp = await api('/api/ai/test', { method: 'POST', body: {} });
|
||||
expect(testEp.status).toBe(200);
|
||||
expect(testEp.data.ok).toBe(true);
|
||||
expect(testEp.data.replyPreview).toBe('OK');
|
||||
expect(recorded[0]?.url).toBe('/v1/chat/completions');
|
||||
expect(recorded[0]?.authorization).toBe('Bearer sk-vault-ai-secret-55555');
|
||||
|
||||
// 3. Context preview & strict secret redaction across all 5 surfaces
|
||||
const dirtyContext = [
|
||||
'-----BEGIN OPENSSH PRIVATE KEY-----',
|
||||
'b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAA=',
|
||||
'-----END OPENSSH PRIVATE KEY-----',
|
||||
'Authorization: Bearer super-secret-jwt-token-987654',
|
||||
'DB_PASSWORD="my-inline-db-password"',
|
||||
'Detected password value: VaultSudoLeakCheck!99',
|
||||
].join('\n');
|
||||
|
||||
for (const surface of ['workflows', 'systems', 'snippets', 'logs', 'setup'] as const) {
|
||||
const prev = await api('/api/ai/context-preview', {
|
||||
method: 'POST',
|
||||
body: { surface, contextText: dirtyContext },
|
||||
safeMode: true,
|
||||
});
|
||||
expect(prev.status).toBe(200);
|
||||
expect(Number(prev.data.redactedCount)).toBeGreaterThanOrEqual(4);
|
||||
const sanitized = String(prev.data.sanitizedContext);
|
||||
expect(sanitized).toContain('[REDACTED_PRIVATE_KEY]');
|
||||
expect(sanitized).toContain('[REDACTED_VAULT_SECRET]');
|
||||
expect(sanitized).toContain('[REDACTED_TOKEN]');
|
||||
expect(sanitized).toContain('[REDACTED_SECRET]');
|
||||
expect(sanitized).not.toContain('b3BlbnNzaC1rZXktdjE');
|
||||
expect(sanitized).not.toContain('super-secret-jwt-token-987654');
|
||||
expect(sanitized).not.toContain('my-inline-db-password');
|
||||
expect(sanitized).not.toContain('VaultSudoLeakCheck!99');
|
||||
}
|
||||
|
||||
// 4. Multiplexed /ws ai:<chatId> streaming (Safe Mode exempt) + draft Zod validation
|
||||
const { ws, frames } = await openWs(wsUrl, {
|
||||
Cookie: jar.header(),
|
||||
Host: `127.0.0.1:${server.port}`,
|
||||
Origin: baseUrl,
|
||||
});
|
||||
cleanups.push(() => ws.close());
|
||||
|
||||
recorded.length = 0;
|
||||
const chatRes = await api('/api/ai/chat', {
|
||||
method: 'POST',
|
||||
safeMode: true,
|
||||
body: {
|
||||
surface: 'workflows',
|
||||
messages: [{ role: 'user', content: 'Draft workflow using DB_PASSWORD=inline_pw' }],
|
||||
contextText: dirtyContext,
|
||||
},
|
||||
});
|
||||
expect(chatRes.status).toBe(202);
|
||||
const chatId = String(chatRes.data.chatId);
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: [`ai:${chatId}`] }));
|
||||
|
||||
await waitFor(() =>
|
||||
frames.some((f) => f.type === 'ai:delta' && f.chatId === chatId && f.done === true),
|
||||
);
|
||||
const fullStreamText = frames
|
||||
.filter((f) => f.type === 'ai:delta' && f.chatId === chatId)
|
||||
.map((f) => String(f.chunk ?? ''))
|
||||
.join('');
|
||||
expect(fullStreamText).toContain('ai-health-check');
|
||||
|
||||
// Outbound LLM payload must contain zero raw secrets
|
||||
const sentRaw = recorded[0]?.rawBody ?? '';
|
||||
expect(sentRaw).not.toContain('VaultSudoLeakCheck!99');
|
||||
expect(sentRaw).not.toContain('super-secret-jwt-token-987654');
|
||||
expect(sentRaw).not.toContain('my-inline-db-password');
|
||||
expect(sentRaw).not.toContain('inline_pw');
|
||||
expect(sentRaw).not.toContain('b3BlbnNzaC1rZXktdjE');
|
||||
|
||||
// Draft validation: reject cyclic DAG, accept generated workflow draft
|
||||
const invalidDraft = await api('/api/ai/validate-draft', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
kind: 'workflow',
|
||||
jsonText: JSON.stringify({
|
||||
id: 'bad-cycle',
|
||||
name: 'Cycle',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{ id: 'a', type: 'exec', dependsOn: ['b'], target: { all: true }, command: 'id' },
|
||||
{ id: 'b', type: 'exec', dependsOn: ['a'], target: { all: true }, command: 'id' },
|
||||
],
|
||||
}),
|
||||
},
|
||||
});
|
||||
expect(invalidDraft.status).toBe(200);
|
||||
expect(invalidDraft.data.valid).toBe(false);
|
||||
expect((invalidDraft.data.issues as unknown[]).length).toBeGreaterThan(0);
|
||||
|
||||
const fenceMatch = /```json\s*\n([\s\S]*?)\n```/.exec(fullStreamText);
|
||||
const validDraft = await api('/api/ai/validate-draft', {
|
||||
method: 'POST',
|
||||
safeMode: true,
|
||||
body: { kind: 'workflow', jsonText: fenceMatch![1]! },
|
||||
});
|
||||
expect(validDraft.status).toBe(200);
|
||||
expect(validDraft.data.valid).toBe(true);
|
||||
expect(validDraft.data.targetPath).toBe('workflows/ai-health-check.json');
|
||||
expect((validDraft.data.diffLines as unknown[]).length).toBeGreaterThan(0);
|
||||
|
||||
// 5. Cancel slow SSE generation mid-stream via WS { type: 'ai:cancel', chatId }
|
||||
const slowRes = await api('/api/ai/chat', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
surface: 'logs',
|
||||
messages: [{ role: 'user', content: 'SLOW_STREAM please' }],
|
||||
},
|
||||
});
|
||||
const slowId = String(slowRes.data.chatId);
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: [`ai:${slowId}`] }));
|
||||
await waitFor(() =>
|
||||
frames.some((f) => f.type === 'ai:delta' && f.chatId === slowId && String(f.chunk).includes('Starting slow')),
|
||||
);
|
||||
ws.send(JSON.stringify({ type: 'ai:cancel', chatId: slowId }));
|
||||
await waitFor(
|
||||
() =>
|
||||
frames.some((f) => f.type === 'ai:delta' && f.chatId === slowId && f.done === true) &&
|
||||
abortedSlowCount >= 1,
|
||||
);
|
||||
});
|
||||
});
|
||||
664
tests/alerts-engine.test.ts
Normal file
664
tests/alerts-engine.test.ts
Normal file
|
|
@ -0,0 +1,664 @@
|
|||
import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
class CookieJar {
|
||||
private cookies = new Map<string, string>();
|
||||
updateFrom(res: Response): void {
|
||||
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
|
||||
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
|
||||
for (const line of rawList) {
|
||||
const first = line.split(';')[0] ?? '';
|
||||
const eq = first.indexOf('=');
|
||||
if (eq > 0) {
|
||||
const name = first.slice(0, eq).trim();
|
||||
const val = first.slice(eq + 1).trim();
|
||||
if (val === '') this.cookies.delete(name);
|
||||
else this.cookies.set(name, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
header(): string {
|
||||
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
}
|
||||
}
|
||||
|
||||
async function openWs(url: string, headers: Record<string, string>) {
|
||||
return new Promise<{ ws: WebSocket; frames: Array<Record<string, unknown>> }>((resolve, reject) => {
|
||||
const frames: Array<Record<string, unknown>> = [];
|
||||
const ws = new WebSocket(url, { headers });
|
||||
ws.on('message', (raw) => frames.push(JSON.parse(raw.toString())));
|
||||
ws.once('open', () => resolve({ ws, frames }));
|
||||
ws.once('unexpected-response', (_req, res) =>
|
||||
reject(new Error(`WS_HTTP_${res.statusCode}`)),
|
||||
);
|
||||
ws.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function waitFor<T>(
|
||||
fn: () => T | undefined | null | false,
|
||||
timeoutMs = 5000,
|
||||
intervalMs = 30,
|
||||
): Promise<T> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const val = fn();
|
||||
if (val) return val;
|
||||
await new Promise((r) => setTimeout(r, intervalMs));
|
||||
}
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
|
||||
interface RecordedWebhook {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: http.IncomingHttpHeaders;
|
||||
body: string;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => {
|
||||
it(
|
||||
'evaluates all 5 rule kinds with hysteresis/cooldown/recovery, dispatches all 4 webhook formats while Vault is write-locked, triggers remediation & event workflows, and honours silences & cron maintenance windows',
|
||||
{ timeout: 25_000 },
|
||||
async () => {
|
||||
const webhooks: RecordedWebhook[] = [];
|
||||
const webhookServer = http.createServer((req, res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
req.on('data', (c: Buffer) => chunks.push(c));
|
||||
req.on('end', () => {
|
||||
webhooks.push({
|
||||
url: req.url ?? '/',
|
||||
method: req.method ?? 'POST',
|
||||
headers: req.headers,
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
});
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => webhookServer.listen(0, '127.0.0.1', resolve));
|
||||
const whAddr = webhookServer.address() as { port: number };
|
||||
const whBase = `http://127.0.0.1:${whAddr.port}`;
|
||||
cleanups.push(
|
||||
() => new Promise<void>((resolve) => webhookServer.close(() => resolve())),
|
||||
);
|
||||
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-alerts-'));
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const wsUrl = `ws://127.0.0.1:${server.port}/ws`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
|
||||
const api = async (pathname: string, opts: { method?: string; body?: unknown } = {}) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
|
||||
const res = await fetch(`${baseUrl}${pathname}`, {
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
jar.updateFrom(res);
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
const boot = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'phase4-alert-password',
|
||||
totpCode: totp.generate(),
|
||||
secretBase32,
|
||||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'alert-key', name: 'Alert Key' },
|
||||
});
|
||||
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
|
||||
|
||||
for (const [id, secret] of [
|
||||
['wh-discord', 'discord-bearer-secret'],
|
||||
['wh-tg', '123456:telegram-bot-token'],
|
||||
['wh-ntfy', 'ntfy-secret-token'],
|
||||
['wh-generic', 'generic-hmac-bearer'],
|
||||
] as const) {
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: { id, name: id, type: 'webhook-secret', secret },
|
||||
});
|
||||
}
|
||||
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
authorizedKeys: [pubKey],
|
||||
onExec: (cmd) => {
|
||||
if (cmd.includes('REMEDIATE:')) {
|
||||
return { stdout: 'remediated-ok\n', exitCode: 0 };
|
||||
}
|
||||
return { stdout: 'event-ok\n', exitCode: 0 };
|
||||
},
|
||||
});
|
||||
const sshPort = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'srv-1',
|
||||
name: 'Prod 1',
|
||||
host: '127.0.0.1',
|
||||
port: sshPort,
|
||||
username: 'ops',
|
||||
credentialId: 'alert-key',
|
||||
tags: ['prod'],
|
||||
pollIntervalSec: 3600,
|
||||
},
|
||||
});
|
||||
await api('/api/servers/srv-1/reconnect', { method: 'POST' });
|
||||
const approveRes = await api('/api/servers/srv-1/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mock.hostFingerprint },
|
||||
});
|
||||
expect(approveRes.status).toBe(200);
|
||||
await waitFor(() => server.sshPool.getState('srv-1')?.status === 'connected');
|
||||
|
||||
// Remediation + Event workflows
|
||||
for (const wf of [
|
||||
{
|
||||
id: 'wf-remediate',
|
||||
name: 'Auto Remediate',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [{ name: 'serverId', type: 'string', required: false }],
|
||||
steps: [
|
||||
{
|
||||
id: 'rem',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-1' },
|
||||
command: 'echo REMEDIATE: {{inputs.serverId}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'wf-on-alert',
|
||||
name: 'On Alert Fired',
|
||||
enabled: true,
|
||||
trigger: { type: 'event', event: 'alert.fired' },
|
||||
overlapPolicy: 'queue',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'evt',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-1' },
|
||||
command: 'echo ALERT_EVT {{event.ruleId}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'wf-on-probe',
|
||||
name: 'On Probe Failed',
|
||||
enabled: true,
|
||||
trigger: { type: 'event', event: 'probe.failed' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'evt',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-1' },
|
||||
command: 'echo PROBE_EVT {{event.probeId}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'wf-on-sys',
|
||||
name: 'On System Unhealthy',
|
||||
enabled: true,
|
||||
trigger: { type: 'event', event: 'system.unhealthy' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'evt',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-1' },
|
||||
command: 'echo SYS_EVT {{event.systemId}}',
|
||||
},
|
||||
],
|
||||
},
|
||||
]) {
|
||||
expect((await api('/api/workflows', { method: 'POST', body: wf })).status).toBe(201);
|
||||
}
|
||||
|
||||
// Configure 4 channels + 5 rule kinds + scheduled maintenance window
|
||||
const alertsCfgRes = await api('/api/alerts/config', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
channels: [
|
||||
{
|
||||
id: 'ch-discord',
|
||||
name: 'Discord Ops',
|
||||
type: 'discord',
|
||||
url: `${whBase}/discord`,
|
||||
secretRef: 'wh-discord',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'ch-tg',
|
||||
name: 'Telegram Ops',
|
||||
type: 'telegram',
|
||||
url: `${whBase}/tg`,
|
||||
secretRef: 'wh-tg',
|
||||
chatId: '-1009988',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'ch-ntfy',
|
||||
name: 'Ntfy Ops',
|
||||
type: 'ntfy',
|
||||
url: `${whBase}/ntfy`,
|
||||
secretRef: 'wh-ntfy',
|
||||
topic: 'ops-alerts',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'ch-generic',
|
||||
name: 'Generic Ops',
|
||||
type: 'generic',
|
||||
url: `${whBase}/generic`,
|
||||
secretRef: 'wh-generic',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
rules: [
|
||||
{
|
||||
id: 'rule-cpu',
|
||||
name: 'High CPU',
|
||||
kind: 'metric',
|
||||
metric: 'cpuPct',
|
||||
operator: 'gt',
|
||||
threshold: 80,
|
||||
severity: 'critical',
|
||||
target: { tags: ['prod'] },
|
||||
forConsecutivePolls: 2,
|
||||
cooldownSec: 300,
|
||||
channelIds: ['ch-discord', 'ch-generic'],
|
||||
remediationWorkflowId: 'wf-remediate',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'rule-disk',
|
||||
name: 'Root Disk High',
|
||||
kind: 'disk',
|
||||
mountPoint: '/',
|
||||
thresholdPct: 90,
|
||||
severity: 'warn',
|
||||
target: { serverId: 'srv-1' },
|
||||
forConsecutivePolls: 1,
|
||||
cooldownSec: 60,
|
||||
channelIds: ['ch-ntfy'],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'rule-offline',
|
||||
name: 'Server Offline',
|
||||
kind: 'offline',
|
||||
offlineSec: 10,
|
||||
severity: 'critical',
|
||||
target: { all: true },
|
||||
forConsecutivePolls: 1,
|
||||
cooldownSec: 60,
|
||||
channelIds: ['ch-tg'],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'rule-probe',
|
||||
name: 'Probe Failed',
|
||||
kind: 'probe',
|
||||
probeId: 'http-root',
|
||||
severity: 'warn',
|
||||
target: { all: true },
|
||||
forConsecutivePolls: 1,
|
||||
cooldownSec: 60,
|
||||
channelIds: ['ch-generic'],
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
id: 'rule-sys',
|
||||
name: 'Nginx Unhealthy',
|
||||
kind: 'system',
|
||||
systemId: 'systemd',
|
||||
item: 'nginx.service',
|
||||
severity: 'critical',
|
||||
target: { serverId: 'srv-1' },
|
||||
forConsecutivePolls: 1,
|
||||
cooldownSec: 60,
|
||||
channelIds: ['ch-discord'],
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
maintenanceWindows: [
|
||||
{
|
||||
id: 'mw-nightly',
|
||||
name: 'Nightly Maint',
|
||||
cron: `0 ${(new Date().getUTCHours() + 3) % 24} * * *`,
|
||||
timezone: 'UTC',
|
||||
durationMinutes: 60,
|
||||
target: { tags: ['prod'] },
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(alertsCfgRes.status).toBe(200);
|
||||
|
||||
// Lock Vault for modifications -> write-only lock must still allow webhook tests using established secrets
|
||||
const lockRes = await api('/api/vault/lock', { method: 'POST' });
|
||||
expect(lockRes.data.state).toBe('locked');
|
||||
expect(lockRes.data.runtimeReady).toBe(true);
|
||||
|
||||
// --- 1. Send Test Alert for all 4 channel types while Vault is write-locked ---
|
||||
for (const chId of ['ch-discord', 'ch-tg', 'ch-ntfy', 'ch-generic']) {
|
||||
const tRes = await api(`/api/alerts/channels/${chId}/test`, { method: 'POST' });
|
||||
expect(tRes.status).toBe(200);
|
||||
expect(tRes.data.ok).toBe(true);
|
||||
expect(tRes.data.statusCode).toBe(200);
|
||||
}
|
||||
expect(webhooks).toHaveLength(4);
|
||||
const byUrl = new Map(webhooks.map((w) => [w.url, w]));
|
||||
expect(JSON.parse(byUrl.get('/discord')!.body).content).toContain('[TEST]');
|
||||
expect(byUrl.get('/discord')!.headers.authorization).toBe('Bearer discord-bearer-secret');
|
||||
expect(byUrl.get('/tg/sendMessage')!.headers['x-telegram-bot-token']).toBe(
|
||||
'123456:telegram-bot-token',
|
||||
);
|
||||
expect(JSON.parse(byUrl.get('/tg/sendMessage')!.body).chat_id).toBe('-1009988');
|
||||
expect(byUrl.get('/ntfy/ops-alerts')!.headers.authorization).toBe('Bearer ntfy-secret-token');
|
||||
expect(byUrl.get('/ntfy/ops-alerts')!.headers.title).toContain('[TEST]');
|
||||
expect(byUrl.get('/generic')!.headers.authorization).toBe('Bearer generic-hmac-bearer');
|
||||
|
||||
webhooks.length = 0;
|
||||
|
||||
// Subscribe WS to alerts channel
|
||||
const { ws, frames } = await openWs(wsUrl, {
|
||||
Cookie: jar.header(),
|
||||
Host: `127.0.0.1:${server.port}`,
|
||||
Origin: baseUrl,
|
||||
});
|
||||
cleanups.push(() => ws.close());
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: ['alerts'] }));
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
|
||||
const makeTick = (cpuPct: number, diskUsedPct: number, ts: number) => ({
|
||||
serverId: 'srv-1',
|
||||
sample: {
|
||||
ts,
|
||||
cpuPct,
|
||||
memUsedMb: 1000,
|
||||
memTotalMb: 16000,
|
||||
netRxBps: 100,
|
||||
netTxBps: 50,
|
||||
load1m: 0.5,
|
||||
uptimeSec: 1000,
|
||||
},
|
||||
disks: [
|
||||
{
|
||||
mountPoint: '/',
|
||||
fsType: 'ext4',
|
||||
usedMb: diskUsedPct * 100,
|
||||
totalMb: 10000,
|
||||
usedPct: diskUsedPct,
|
||||
},
|
||||
],
|
||||
probes: [],
|
||||
});
|
||||
|
||||
// Use monotonic timestamps outside maintenance window
|
||||
const t0 = Date.now();
|
||||
const mwHour = (new Date(t0).getUTCHours() + 3) % 24;
|
||||
|
||||
// --- 2. Metric hysteresis (forConsecutivePolls: 2), remediation + alert.fired, recovery & cooldown ---
|
||||
await server.alertEngine.evaluateTick(makeTick(95, 40, t0), t0);
|
||||
expect((await api('/api/alerts')).data.activeCount).toBe(0);
|
||||
expect(webhooks).toHaveLength(0);
|
||||
|
||||
await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 5000), t0 + 5000);
|
||||
expect((await api('/api/alerts')).data.activeCount).toBe(1);
|
||||
expect(webhooks.map((w) => w.url).sort()).toEqual(['/discord', '/generic']);
|
||||
await waitFor(() =>
|
||||
frames.some((f) => f.type === 'alerts:update' && f.activeCount === 1),
|
||||
);
|
||||
await waitFor(() => server.workflowEngine.listRuns('wf-remediate')[0]?.status === 'succeeded');
|
||||
await waitFor(() => server.workflowEngine.listRuns('wf-on-alert')[0]?.status === 'succeeded');
|
||||
|
||||
webhooks.length = 0;
|
||||
|
||||
// Healthy poll resolves metric incident and sends recovery notice
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 10_000), t0 + 10_000);
|
||||
expect((await api('/api/alerts')).data.activeCount).toBe(0);
|
||||
expect(webhooks.map((w) => w.url).sort()).toEqual(['/discord', '/generic']);
|
||||
expect(JSON.parse(webhooks.find((w) => w.url === '/discord')!.body).content).toContain(
|
||||
'RESOLVED',
|
||||
);
|
||||
|
||||
webhooks.length = 0;
|
||||
|
||||
// Re-breach inside cooldownSec (300s): incident fires with webhookStatus='cooldown', zero webhook spam
|
||||
await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 15_000), t0 + 15_000);
|
||||
await server.alertEngine.evaluateTick(makeTick(95, 40, t0 + 20_000), t0 + 20_000);
|
||||
const cooldownSummary = await api('/api/alerts?limit=10');
|
||||
expect(cooldownSummary.data.activeCount).toBe(1);
|
||||
expect(
|
||||
(cooldownSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>)[0]
|
||||
?.webhookStatus,
|
||||
).toBe('cooldown');
|
||||
expect(webhooks).toHaveLength(0);
|
||||
// Resolve metric incident cleanly
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 25_000), t0 + 25_000);
|
||||
webhooks.length = 0;
|
||||
|
||||
// --- 3. Disk, Probe, System, and Offline rule kinds ---
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 95, t0 + 30_000), t0 + 30_000);
|
||||
expect(webhooks.some((w) => w.url === '/ntfy/ops-alerts')).toBe(true);
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 40, t0 + 35_000), t0 + 35_000);
|
||||
webhooks.length = 0;
|
||||
|
||||
await server.alertEngine.evaluateProbe(
|
||||
'srv-1',
|
||||
{ probeId: 'http-root', ok: false, statusCode: 502, latencyMs: 120, error: 'Bad Gateway' },
|
||||
t0 + 40_000,
|
||||
);
|
||||
expect(webhooks.some((w) => w.url === '/generic')).toBe(true);
|
||||
await waitFor(() => server.workflowEngine.listRuns('wf-on-probe')[0]?.status === 'succeeded');
|
||||
await server.alertEngine.evaluateProbe(
|
||||
'srv-1',
|
||||
{ probeId: 'http-root', ok: true, statusCode: 200, latencyMs: 12 },
|
||||
t0 + 45_000,
|
||||
);
|
||||
webhooks.length = 0;
|
||||
|
||||
await server.alertEngine.evaluateSystemSnapshot(
|
||||
{
|
||||
serverId: 'srv-1',
|
||||
systemId: 'systemd',
|
||||
params: {},
|
||||
fetchedAt: t0 + 50_000,
|
||||
cached: false,
|
||||
systemHealth: 'down',
|
||||
items: [
|
||||
{
|
||||
name: 'nginx.service',
|
||||
dir: '',
|
||||
activeFiles: [],
|
||||
selectableFiles: [],
|
||||
editableFiles: [],
|
||||
status: { health: 'down', rawSummary: 'failed', exitCode: 1, subItems: [] },
|
||||
},
|
||||
],
|
||||
},
|
||||
t0 + 50_000,
|
||||
);
|
||||
expect(webhooks.some((w) => w.url === '/discord')).toBe(true);
|
||||
await waitFor(() => server.workflowEngine.listRuns('wf-on-sys')[0]?.status === 'succeeded');
|
||||
await server.alertEngine.evaluateSystemSnapshot(
|
||||
{
|
||||
serverId: 'srv-1',
|
||||
systemId: 'systemd',
|
||||
params: {},
|
||||
fetchedAt: t0 + 55_000,
|
||||
cached: false,
|
||||
systemHealth: 'ok',
|
||||
items: [
|
||||
{
|
||||
name: 'nginx.service',
|
||||
dir: '',
|
||||
activeFiles: [],
|
||||
selectableFiles: [],
|
||||
editableFiles: [],
|
||||
status: { health: 'ok', rawSummary: 'active', exitCode: 0, subItems: [] },
|
||||
},
|
||||
],
|
||||
},
|
||||
t0 + 55_000,
|
||||
);
|
||||
webhooks.length = 0;
|
||||
|
||||
// Offline rule check via sshPool closeServer + sweepOfflineRules
|
||||
server.sshPool.closeServer('srv-1');
|
||||
const tOffline = Date.now();
|
||||
await server.alertEngine.sweepOfflineRules(tOffline + 100);
|
||||
expect(webhooks).toHaveLength(0);
|
||||
await server.alertEngine.sweepOfflineRules(tOffline + 15_000);
|
||||
expect(webhooks.some((w) => w.url === '/tg/sendMessage')).toBe(true);
|
||||
await api('/api/servers/srv-1/reconnect', { method: 'POST' });
|
||||
await waitFor(() => server.sshPool.getState('srv-1')?.status === 'connected');
|
||||
await server.alertEngine.sweepOfflineRules(Date.now() + 20_000);
|
||||
webhooks.length = 0;
|
||||
|
||||
// --- 4. Alert Silences + Cron Maintenance Windows (verified strictly monotonically in future UTC) ---
|
||||
const silRes = await api('/api/alerts/silences', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
scopeType: 'rule',
|
||||
targetId: 'rule-disk',
|
||||
durationMinutes: 2880,
|
||||
reason: 'Disk rebalance',
|
||||
},
|
||||
});
|
||||
expect(silRes.status).toBe(201);
|
||||
const silenceId = String((silRes.data.silence as { id: string }).id);
|
||||
|
||||
const d1 = new Date(Date.now() + 86_400_000);
|
||||
const dayPlusOneSafe = Date.UTC(
|
||||
d1.getUTCFullYear(),
|
||||
d1.getUTCMonth(),
|
||||
d1.getUTCDate(),
|
||||
(mwHour + 6) % 24,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 95, dayPlusOneSafe), dayPlusOneSafe);
|
||||
const silencedSummary = await api('/api/alerts?limit=5');
|
||||
expect(
|
||||
(silencedSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>).find(
|
||||
(e) => e.ruleId === 'rule-disk',
|
||||
)?.webhookStatus,
|
||||
).toBe('suppressed');
|
||||
expect(webhooks).toHaveLength(0);
|
||||
|
||||
await server.alertEngine.evaluateTick(
|
||||
makeTick(20, 40, dayPlusOneSafe + 5000),
|
||||
dayPlusOneSafe + 5000,
|
||||
);
|
||||
expect((await api(`/api/alerts/silences/${silenceId}`, { method: 'DELETE' })).status).toBe(
|
||||
200,
|
||||
);
|
||||
webhooks.length = 0;
|
||||
|
||||
// Scheduled cron maintenance window (0 <mwHour> * * * UTC for 60 minutes)
|
||||
const d2 = new Date(Date.now() + 2 * 86_400_000);
|
||||
const insideWindowMs = Date.UTC(
|
||||
d2.getUTCFullYear(),
|
||||
d2.getUTCMonth(),
|
||||
d2.getUTCDate(),
|
||||
mwHour,
|
||||
30,
|
||||
0,
|
||||
);
|
||||
const outsideWindowMs = insideWindowMs + 3_600_000;
|
||||
expect(server.alertEngine.getActiveMaintenanceWindowIds(insideWindowMs)).toContain(
|
||||
'mw-nightly',
|
||||
);
|
||||
expect(server.alertEngine.getActiveMaintenanceWindowIds(outsideWindowMs)).toEqual([]);
|
||||
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 95, insideWindowMs), insideWindowMs);
|
||||
const mwSummary = await api('/api/alerts?limit=5');
|
||||
expect(
|
||||
(mwSummary.data.activeEvents as Array<{ ruleId: string; webhookStatus: string }>).find(
|
||||
(e) => e.ruleId === 'rule-disk',
|
||||
)?.webhookStatus,
|
||||
).toBe('suppressed');
|
||||
expect(webhooks).toHaveLength(0);
|
||||
|
||||
await server.alertEngine.evaluateTick(
|
||||
makeTick(20, 40, insideWindowMs + 1000),
|
||||
insideWindowMs + 1000,
|
||||
);
|
||||
webhooks.length = 0;
|
||||
|
||||
await server.alertEngine.evaluateTick(makeTick(20, 95, outsideWindowMs), outsideWindowMs);
|
||||
expect(webhooks.some((w) => w.url === '/ntfy/ops-alerts')).toBe(true);
|
||||
},
|
||||
);
|
||||
});
|
||||
320
tests/backup-and-cli.test.ts
Normal file
320
tests/backup-and-cli.test.ts
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createGCoordinatorServer } from '../src/server/app.js';
|
||||
import { openDatabase } from '../src/server/db/database.js';
|
||||
import { VaultService } from '../src/server/security/vault.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const CLI_PATH = path.resolve('dist/cli/gcoord.js');
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
class CookieJar {
|
||||
private cookies = new Map<string, string>();
|
||||
updateFrom(res: Response): void {
|
||||
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
|
||||
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
|
||||
for (const line of rawList) {
|
||||
const first = line.split(';')[0] ?? '';
|
||||
const eq = first.indexOf('=');
|
||||
if (eq > 0) {
|
||||
const name = first.slice(0, eq).trim();
|
||||
const val = first.slice(eq + 1).trim();
|
||||
if (val === '') this.cookies.delete(name);
|
||||
else this.cookies.set(name, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
header(): string {
|
||||
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord CLI)', () => {
|
||||
it('creates, verifies, and restores AES-256-GCM bundles across master-key API and scrypt CLI modes', async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-bkp-src-'));
|
||||
const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p5-bkp-work-'));
|
||||
const freshRestoreDir = path.join(workDir, 'restored-data');
|
||||
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
|
||||
const api = async (
|
||||
pathname: string,
|
||||
opts: { method?: string; body?: unknown; safeMode?: boolean } = {},
|
||||
) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1';
|
||||
|
||||
const res = await fetch(`${baseUrl}${pathname}`, {
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
jar.updateFrom(res);
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
const boot = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'phase5-backup-password',
|
||||
totpCode: totp.generate(),
|
||||
secretBase32,
|
||||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'bkp-ssh-key', name: 'Backup SSH Key' },
|
||||
});
|
||||
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: { id: 'bkp-api-tok', name: 'Backup API Token', type: 'api-token', token: 'tok-restore-999' },
|
||||
});
|
||||
|
||||
const mock = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
authorizedKeys: [pubKey],
|
||||
});
|
||||
const sshPort = await mock.start();
|
||||
cleanups.push(() => mock.close());
|
||||
|
||||
// Register server with itemOverrides activeFiles overlay and approve TOFU -> populates config + known_hosts
|
||||
const reg = await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'app1',
|
||||
name: 'App Backup Server',
|
||||
host: '127.0.0.1',
|
||||
port: sshPort,
|
||||
username: 'ops',
|
||||
credentialId: 'bkp-ssh-key',
|
||||
pollIntervalSec: 3600,
|
||||
systems: [
|
||||
{
|
||||
systemId: 'docker-compose',
|
||||
enabled: true,
|
||||
params: { rootDirs: ['/opt/stacks'] },
|
||||
itemOverrides: {
|
||||
webapp: { activeFiles: ['compose.yml', 'compose.prod.yml'] },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(reg.status).toBe(201);
|
||||
await api('/api/servers/app1/reconnect', { method: 'POST' });
|
||||
const approve = await api('/api/servers/app1/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mock.hostFingerprint },
|
||||
});
|
||||
expect(approve.status).toBe(200);
|
||||
|
||||
// Add active alert silence
|
||||
const silRes = await api('/api/alerts/silences', {
|
||||
method: 'POST',
|
||||
body: { scopeType: 'server', targetId: 'app1', durationMinutes: 120, reason: 'Backup test' },
|
||||
});
|
||||
expect(silRes.status).toBe(201);
|
||||
|
||||
// Checkpoint WAL so external CLI sees all SQLite rows cleanly
|
||||
server.db.pragma('wal_checkpoint(TRUNCATE)');
|
||||
|
||||
// Re-lock Vault for modifications -> Master-Key export still works via runtime key
|
||||
const relock = await api('/api/vault/lock', { method: 'POST' });
|
||||
expect(relock.status).toBe(200);
|
||||
expect(relock.data.state).toBe('locked');
|
||||
expect(relock.data.runtimeReady).toBe(true);
|
||||
|
||||
// Safe Mode blocks export/restore (423), exempts verify (200)
|
||||
expect(
|
||||
(await api('/api/backup/export', { method: 'POST', body: {}, safeMode: true })).status,
|
||||
).toBe(423);
|
||||
|
||||
const exported = await api('/api/backup/export', { method: 'POST', body: {} });
|
||||
expect(exported.status).toBe(200);
|
||||
const masterBundleB64 = String(exported.data.bundleBase64);
|
||||
const expSummary = exported.data.summary as {
|
||||
valid: boolean;
|
||||
kdf: string;
|
||||
vaultVerified: boolean;
|
||||
knownHostsCount: number;
|
||||
alertSilenceCount: number;
|
||||
overlayCount: number;
|
||||
};
|
||||
expect(expSummary.valid).toBe(true);
|
||||
expect(expSummary.kdf).toBe('raw-master-key');
|
||||
expect(expSummary.vaultVerified).toBe(true);
|
||||
expect(expSummary.knownHostsCount).toBe(1);
|
||||
expect(expSummary.alertSilenceCount).toBe(1);
|
||||
expect(expSummary.overlayCount).toBe(1);
|
||||
|
||||
const verifySafe = await api('/api/backup/verify', {
|
||||
method: 'POST',
|
||||
body: { bundleBase64: masterBundleB64 },
|
||||
safeMode: true,
|
||||
});
|
||||
expect(verifySafe.status).toBe(200);
|
||||
expect((verifySafe.data.summary as { valid: boolean }).valid).toBe(true);
|
||||
|
||||
// --- CLI Passphrase (scrypt) Backup, Verify-Backup, Tamper Reject & Cold Restore ---
|
||||
const passFile = path.join(workDir, 'backup.pass');
|
||||
fs.writeFileSync(passFile, 'portable-backup-passphrase-2026!\n', { mode: 0o600 });
|
||||
const passBundlePath = path.join(workDir, 'portable.gcoord.enc');
|
||||
const vaultKeyPath = path.join(dataDir, 'vault.key');
|
||||
|
||||
const bkpOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'backup',
|
||||
'--data-dir',
|
||||
dataDir,
|
||||
'--out',
|
||||
passBundlePath,
|
||||
'--passphrase-file',
|
||||
passFile,
|
||||
]);
|
||||
expect(bkpOut.stdout).toContain('kdf=scrypt');
|
||||
expect(fs.existsSync(passBundlePath)).toBe(true);
|
||||
|
||||
const verOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'verify-backup',
|
||||
passBundlePath,
|
||||
'--passphrase-file',
|
||||
passFile,
|
||||
'--vault-key-file',
|
||||
vaultKeyPath,
|
||||
'--json',
|
||||
]);
|
||||
const cliSummary = JSON.parse(verOut.stdout) as typeof expSummary;
|
||||
expect(cliSummary.valid).toBe(true);
|
||||
expect(cliSummary.kdf).toBe('scrypt');
|
||||
expect(cliSummary.vaultVerified).toBe(true);
|
||||
expect(cliSummary.overlayCount).toBe(1);
|
||||
|
||||
// Tamper 1 character in GCM tag -> must fail verification
|
||||
const tamperedPath = path.join(workDir, 'tampered.gcoord.enc');
|
||||
const envObj = JSON.parse(fs.readFileSync(passBundlePath, 'utf8')) as {
|
||||
tag: string;
|
||||
[k: string]: unknown;
|
||||
};
|
||||
const origTag = Buffer.from(envObj.tag, 'base64');
|
||||
origTag[0] = origTag[0]! ^ 0xff;
|
||||
envObj.tag = origTag.toString('base64');
|
||||
fs.writeFileSync(tamperedPath, JSON.stringify(envObj), 'utf8');
|
||||
|
||||
await expect(
|
||||
execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'verify-backup',
|
||||
tamperedPath,
|
||||
'--passphrase-file',
|
||||
passFile,
|
||||
]),
|
||||
).rejects.toThrow();
|
||||
|
||||
// Restore scrypt bundle into an empty fresh directory
|
||||
const restOut = await execFileAsync(process.execPath, [
|
||||
CLI_PATH,
|
||||
'restore',
|
||||
passBundlePath,
|
||||
'--data-dir',
|
||||
freshRestoreDir,
|
||||
'--passphrase-file',
|
||||
passFile,
|
||||
]);
|
||||
expect(restOut.stdout).toContain('Restored GCoordinator state');
|
||||
|
||||
const restoredSrvJson = JSON.parse(
|
||||
fs.readFileSync(path.join(freshRestoreDir, 'config', 'servers', 'app1.json'), 'utf8'),
|
||||
) as { systems: Array<{ itemOverrides: Record<string, { activeFiles?: string[] }> }> };
|
||||
expect(restoredSrvJson.systems[0]?.itemOverrides.webapp?.activeFiles).toEqual([
|
||||
'compose.yml',
|
||||
'compose.prod.yml',
|
||||
]);
|
||||
|
||||
const restoredVault = new VaultService(path.join(freshRestoreDir, 'vault.enc'));
|
||||
restoredVault.unlock(fs.readFileSync(vaultKeyPath, 'utf8').trim());
|
||||
expect(restoredVault.getSecret('bkp-api-tok')).toMatchObject({ token: 'tok-restore-999' });
|
||||
|
||||
const restoredDb = openDatabase(path.join(freshRestoreDir, 'gcoord.db'));
|
||||
try {
|
||||
const hosts = restoredDb.prepare('SELECT host_port, fingerprint FROM known_hosts').all() as Array<{
|
||||
host_port: string;
|
||||
fingerprint: string;
|
||||
}>;
|
||||
expect(hosts).toHaveLength(1);
|
||||
expect(hosts[0]?.fingerprint).toBe(mock.hostFingerprint);
|
||||
|
||||
const sils = restoredDb.prepare('SELECT target_id FROM alert_silences').all() as Array<{
|
||||
target_id: string;
|
||||
}>;
|
||||
expect(sils.some((s) => s.target_id === 'app1')).toBe(true);
|
||||
} finally {
|
||||
restoredDb.close();
|
||||
}
|
||||
|
||||
// --- Live API Restore hot-reloads ConfigManager & KnownHosts ---
|
||||
expect((await api('/api/servers/app1', { method: 'DELETE' })).status).toBe(200);
|
||||
expect((await api('/api/servers')).data.servers).toHaveLength(0);
|
||||
expect(
|
||||
(await api('/api/backup/restore', { method: 'POST', body: { bundleBase64: masterBundleB64 }, safeMode: true })).status,
|
||||
).toBe(423);
|
||||
|
||||
const liveRestore = await api('/api/backup/restore', {
|
||||
method: 'POST',
|
||||
body: { bundleBase64: masterBundleB64 },
|
||||
});
|
||||
expect(liveRestore.status).toBe(200);
|
||||
expect(liveRestore.data.restored).toBe(true);
|
||||
|
||||
const serversAfter = (await api('/api/servers')).data.servers as Array<{ config: { id: string } }>;
|
||||
expect(serversAfter.map((s) => s.config.id)).toEqual(['app1']);
|
||||
});
|
||||
});
|
||||
|
|
@ -4,7 +4,10 @@ import net from 'node:net';
|
|||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import ssh2, { type Attributes, type Connection, type Server } from 'ssh2';
|
||||
import { computeOpenSshFingerprint } from '../../src/server/security/vault.js';
|
||||
import {
|
||||
computeOpenSshFingerprint,
|
||||
generateValidEd25519KeyPair,
|
||||
} from '../../src/server/security/vault.js';
|
||||
|
||||
export interface MockSshOptions {
|
||||
username: string;
|
||||
|
|
@ -77,9 +80,9 @@ export class MockSshServer {
|
|||
this.sftpRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mock-ssh-sftp-'));
|
||||
this.ownsSftpRoot = true;
|
||||
}
|
||||
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' });
|
||||
this.hostPrivateKey = kp.private;
|
||||
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
|
||||
const kp = generateValidEd25519KeyPair({ comment: 'mock-host' });
|
||||
this.hostPrivateKey = kp.privateKey;
|
||||
this.hostFingerprint = kp.fingerprint;
|
||||
}
|
||||
|
||||
private resolveVirtualPath(vPath: string): { normPosix: string; absPath: string } {
|
||||
|
|
@ -129,9 +132,9 @@ export class MockSshServer {
|
|||
async swapHostKey(): Promise<string> {
|
||||
const prevPort = this.port;
|
||||
await this.close();
|
||||
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mitm-host' });
|
||||
this.hostPrivateKey = kp.private;
|
||||
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
|
||||
const kp = generateValidEd25519KeyPair({ comment: 'mitm-host' });
|
||||
this.hostPrivateKey = kp.privateKey;
|
||||
this.hostFingerprint = kp.fingerprint;
|
||||
await this.start(prevPort);
|
||||
return this.hostFingerprint;
|
||||
}
|
||||
|
|
|
|||
78
tests/mobile-and-themes.test.ts
Normal file
78
tests/mobile-and-themes.test.ts
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import zlib from 'node:zlib';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { appendBoundedStreamText } from '../src/client/ts/state.js';
|
||||
import { SettingsSchema, THEME_IDS } from '../src/shared/schemas/settings.schema.js';
|
||||
|
||||
describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Optimization', () => {
|
||||
it('supports all 8 theme presets in SettingsSchema and dist/public/themes.css', () => {
|
||||
expect(THEME_IDS).toEqual([
|
||||
'phosphor-green',
|
||||
'amber-term',
|
||||
'nord-dark',
|
||||
'gruvbox-dark',
|
||||
'paper-light',
|
||||
'solarized-dark',
|
||||
'tokyo-night',
|
||||
'high-contrast',
|
||||
]);
|
||||
|
||||
const themesCss = fs.readFileSync(path.resolve('dist/public/themes.css'), 'utf8');
|
||||
for (const id of THEME_IDS) {
|
||||
const parsed = SettingsSchema.parse({ theme: id });
|
||||
expect(parsed.theme).toBe(id);
|
||||
expect(themesCss).toMatch(new RegExp(`\\[data-theme="?${id}"?\\]`));
|
||||
}
|
||||
});
|
||||
|
||||
it('meets <50KB core gzipped bundle, splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => {
|
||||
const publicDir = path.resolve('dist/public');
|
||||
const coreFiles = ['index.html', 'themes.css', 'base.css', 'main.js'];
|
||||
let totalCoreGzip = 0;
|
||||
|
||||
for (const f of coreFiles) {
|
||||
const buf = fs.readFileSync(path.join(publicDir, f));
|
||||
totalCoreGzip += zlib.gzipSync(buf, { level: 9 }).length;
|
||||
}
|
||||
expect(totalCoreGzip).toBeLessThan(50 * 1024);
|
||||
|
||||
// Heavy/optional UI stays code-split out of main.js
|
||||
const mainJs = fs.readFileSync(path.join(publicDir, 'main.js'), 'utf8');
|
||||
expect(mainJs).not.toContain('ai-drawer-dialog');
|
||||
expect(mainJs).not.toContain('xterm-helper-textarea');
|
||||
|
||||
const chunks = fs.readdirSync(path.join(publicDir, 'chunks'));
|
||||
expect(chunks.some((c) => c.startsWith('ai-drawer-') && c.endsWith('.js'))).toBe(true);
|
||||
expect(chunks.some((c) => c.startsWith('terminal-view-') && c.endsWith('.js'))).toBe(true);
|
||||
expect(chunks.some((c) => c.startsWith('workflows-view-') && c.endsWith('.js'))).toBe(true);
|
||||
expect(chunks.some((c) => c.startsWith('alerts-view-') && c.endsWith('.js'))).toBe(true);
|
||||
|
||||
for (const c of chunks) {
|
||||
if (c.startsWith('terminal-view-')) continue;
|
||||
const gzLen = zlib.gzipSync(fs.readFileSync(path.join(publicDir, 'chunks', c)), {
|
||||
level: 9,
|
||||
}).length;
|
||||
expect(gzLen).toBeLessThan(20 * 1024);
|
||||
}
|
||||
|
||||
const manifest = JSON.parse(fs.readFileSync(path.join(publicDir, 'manifest.json'), 'utf8')) as {
|
||||
display: string;
|
||||
};
|
||||
expect(manifest.display).toBe('standalone');
|
||||
|
||||
const baseCss = fs.readFileSync(path.join(publicDir, 'base.css'), 'utf8');
|
||||
expect(baseCss).toContain('overscroll-behavior:contain');
|
||||
expect(baseCss).toContain('content-visibility:auto');
|
||||
expect(baseCss).toContain('min-height:44px');
|
||||
|
||||
// Long-running log stream buffer remains strictly bounded
|
||||
const mockPre = { textContent: '' };
|
||||
for (let i = 0; i < 40; i++) {
|
||||
appendBoundedStreamText(mockPre, `line-${i}:${'x'.repeat(200)}\n`, 1024);
|
||||
}
|
||||
expect(mockPre.textContent.length).toBeLessThanOrEqual(1024);
|
||||
expect(mockPre.textContent).toContain('[truncated older stream output]');
|
||||
expect(mockPre.textContent).toContain('line-39:');
|
||||
});
|
||||
});
|
||||
790
tests/workflows-and-transfer.test.ts
Normal file
790
tests/workflows-and-transfer.test.ts
Normal file
|
|
@ -0,0 +1,790 @@
|
|||
import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import * as OTPAuth from 'otpauth';
|
||||
import type { ClientChannel } from 'ssh2';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import WebSocket from 'ws';
|
||||
import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
|
||||
import { MockSshServer } from './helpers/mock-ssh-server.js';
|
||||
|
||||
const cleanups: Array<() => Promise<void> | void> = [];
|
||||
|
||||
class CookieJar {
|
||||
private cookies = new Map<string, string>();
|
||||
updateFrom(res: Response): void {
|
||||
const getSetCookie = (res.headers as unknown as { getSetCookie?: () => string[] }).getSetCookie;
|
||||
const rawList = typeof getSetCookie === 'function' ? getSetCookie.call(res.headers) : [];
|
||||
for (const line of rawList) {
|
||||
const first = line.split(';')[0] ?? '';
|
||||
const eq = first.indexOf('=');
|
||||
if (eq > 0) {
|
||||
const name = first.slice(0, eq).trim();
|
||||
const val = first.slice(eq + 1).trim();
|
||||
if (val === '') this.cookies.delete(name);
|
||||
else this.cookies.set(name, val);
|
||||
}
|
||||
}
|
||||
}
|
||||
header(): string {
|
||||
return [...this.cookies.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
|
||||
}
|
||||
}
|
||||
|
||||
async function openWs(url: string, headers: Record<string, string>) {
|
||||
return new Promise<{ ws: WebSocket; frames: Array<Record<string, unknown>> }>((resolve, reject) => {
|
||||
const frames: Array<Record<string, unknown>> = [];
|
||||
const ws = new WebSocket(url, { headers });
|
||||
ws.on('message', (raw) => frames.push(JSON.parse(raw.toString())));
|
||||
ws.once('open', () => resolve({ ws, frames }));
|
||||
ws.once('unexpected-response', (_req, res) =>
|
||||
reject(new Error(`WS_HTTP_${res.statusCode}`)),
|
||||
);
|
||||
ws.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function waitFor<T>(
|
||||
fn: () => Promise<T | undefined | null | false> | T | undefined | null | false,
|
||||
timeoutMs = 5000,
|
||||
intervalMs = 30,
|
||||
): Promise<T> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const val = await fn();
|
||||
if (val) return val;
|
||||
await new Promise((r) => setTimeout(r, intervalMs));
|
||||
}
|
||||
throw new Error('Timed out waiting for condition');
|
||||
}
|
||||
|
||||
async function waitForWorkflowRun(server: GCoordinatorInstance, runId: string, timeoutMs = 4000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const detail = server.workflowEngine.getRunDetail(runId);
|
||||
if (detail && detail.run.status !== 'running' && detail.run.status !== 'queued') {
|
||||
return detail;
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
}
|
||||
const latest = server.workflowEngine.getRunDetail(runId);
|
||||
const streamFrames = server.workflowEngine.getStreamReplayFrames(`wf:${runId}`);
|
||||
throw new Error(
|
||||
`Workflow run ${runId} timed out: run=${JSON.stringify(latest?.run)} steps=${JSON.stringify(latest?.stepLogs)} frames=${JSON.stringify(streamFrames.slice(-10))}`,
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
while (cleanups.length > 0) {
|
||||
await cleanups.pop()!();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers', () => {
|
||||
it(
|
||||
'supports Snippets CRUD, Safe Mode blocks, Ad-Hoc Fleet Broadcast with safe shell quoting, WS streaming & cancel, Full DAG + steps + transfers, Overlap policies, Timeouts, and Cron',
|
||||
{ timeout: 25_000 },
|
||||
async () => {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-wf-'));
|
||||
const sftpRootA = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpa-'));
|
||||
const sftpRootB = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-p4-sftpb-'));
|
||||
|
||||
fs.mkdirSync(path.join(sftpRootA, 'logs'), { recursive: true });
|
||||
fs.writeFileSync(path.join(sftpRootA, 'logs', 'app.log'), 'l1\nl2\nl3\nl4\n');
|
||||
fs.writeFileSync(path.join(sftpRootA, 'single.txt'), 'single-file-payload\n');
|
||||
fs.mkdirSync(path.join(sftpRootA, 'bundle', 'nested'), { recursive: true });
|
||||
fs.writeFileSync(path.join(sftpRootA, 'bundle', 'top.txt'), 'top-content');
|
||||
fs.writeFileSync(path.join(sftpRootA, 'bundle', 'nested', 'deep.txt'), 'deep-content');
|
||||
|
||||
const seenExecA: string[] = [];
|
||||
const seenExecB: string[] = [];
|
||||
const directRsyncCmds: string[] = [];
|
||||
|
||||
const server = await createGCoordinatorServer({
|
||||
dataDir,
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
publicDir: path.resolve('dist/public'),
|
||||
watchConfig: false,
|
||||
});
|
||||
cleanups.push(async () => {
|
||||
await server.close();
|
||||
fs.rmSync(dataDir, { recursive: true, force: true });
|
||||
fs.rmSync(sftpRootA, { recursive: true, force: true });
|
||||
fs.rmSync(sftpRootB, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const baseUrl = `http://127.0.0.1:${server.port}`;
|
||||
const wsUrl = `ws://127.0.0.1:${server.port}/ws`;
|
||||
const jar = new CookieJar();
|
||||
let csrfToken = '';
|
||||
|
||||
const api = async (
|
||||
pathname: string,
|
||||
opts: { method?: string; body?: unknown; safeMode?: boolean } = {},
|
||||
) => {
|
||||
const headers: Record<string, string> = {};
|
||||
if (jar.header()) headers.Cookie = jar.header();
|
||||
if (opts.body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (csrfToken) headers['X-CSRF-Token'] = csrfToken;
|
||||
if (opts.safeMode) headers['X-GCoord-Safe-Mode'] = '1';
|
||||
|
||||
const res = await fetch(`${baseUrl}${pathname}`, {
|
||||
method: opts.method ?? 'GET',
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
jar.updateFrom(res);
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
return { status: res.status, data };
|
||||
};
|
||||
|
||||
const bootInfo = await api('/api/auth/bootstrap');
|
||||
const secretBase32 = String(bootInfo.data.secretBase32);
|
||||
const totp = new OTPAuth.TOTP({
|
||||
issuer: 'GCoordinator',
|
||||
label: 'admin',
|
||||
algorithm: 'SHA1',
|
||||
digits: 6,
|
||||
period: 30,
|
||||
secret: OTPAuth.Secret.fromBase32(secretBase32),
|
||||
});
|
||||
const boot = await api('/api/auth/bootstrap', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
username: 'admin',
|
||||
password: 'phase4-workflow-password',
|
||||
totpCode: totp.generate(),
|
||||
secretBase32,
|
||||
initialSafeMode: false,
|
||||
},
|
||||
});
|
||||
csrfToken = String(boot.data.csrfToken);
|
||||
|
||||
await api('/api/vault/init', { method: 'POST', body: {} });
|
||||
const keyRes = await api('/api/vault/generate-ed25519', {
|
||||
method: 'POST',
|
||||
body: { id: 'wf-key', name: 'Workflow Key' },
|
||||
});
|
||||
const pubKey = String((keyRes.data.credential as { publicKey: string }).publicKey);
|
||||
await api('/api/vault/credentials', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-sudo',
|
||||
name: 'WF Sudo',
|
||||
type: 'sudo-password',
|
||||
password: 'sudo-wf-pw',
|
||||
},
|
||||
});
|
||||
|
||||
const makeMockExec =
|
||||
(serverTag: 'A' | 'B', sink: string[]) => (cmd: string) => {
|
||||
sink.push(cmd);
|
||||
if (cmd.includes('REAL_SH_QUOTE_TEST')) {
|
||||
const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' });
|
||||
return { stdout: out, exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('systemctl list-units')) {
|
||||
return { stdout: 'nginx.service\n', exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('systemctl show')) {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
Id: 'nginx.service',
|
||||
LoadState: 'loaded',
|
||||
ActiveState: 'active',
|
||||
SubState: 'running',
|
||||
}),
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
if (cmd.includes('systemctl restart')) {
|
||||
return { stdout: `restarted nginx on ${serverTag}\n`, exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('rsync -az ')) {
|
||||
directRsyncCmds.push(cmd);
|
||||
return { stdout: 'sent 128 bytes\n', exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('FAIL_NOW')) {
|
||||
return { stdout: '', stderr: 'intentional step failure', exitCode: 42 };
|
||||
}
|
||||
if (cmd.includes('PRINT_CAP')) {
|
||||
const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' });
|
||||
return { stdout: out, exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('CRON_TICK')) {
|
||||
return { stdout: `cron-ok-${serverTag}\n`, exitCode: 0 };
|
||||
}
|
||||
if (cmd.includes('ECHO_STEP')) {
|
||||
const out = execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8' });
|
||||
return { stdout: out, exitCode: 0 };
|
||||
}
|
||||
return { stdout: `ok:${serverTag}\n`, exitCode: 0 };
|
||||
};
|
||||
|
||||
const mockA = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
sudoPassword: 'sudo-wf-pw',
|
||||
authorizedKeys: [pubKey],
|
||||
sftpRootDir: sftpRootA,
|
||||
onExec: makeMockExec('A', seenExecA),
|
||||
});
|
||||
const mockB = new MockSshServer({
|
||||
username: 'ops',
|
||||
os: 'Linux',
|
||||
sudoPassword: 'sudo-wf-pw',
|
||||
authorizedKeys: [pubKey],
|
||||
sftpRootDir: sftpRootB,
|
||||
onExec: makeMockExec('B', seenExecB),
|
||||
});
|
||||
|
||||
const portA = await mockA.start();
|
||||
const portB = await mockB.start();
|
||||
cleanups.push(async () => {
|
||||
await mockA.close();
|
||||
await mockB.close();
|
||||
});
|
||||
|
||||
await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'srv-a',
|
||||
name: 'Server A',
|
||||
host: '127.0.0.1',
|
||||
port: portA,
|
||||
username: 'ops',
|
||||
credentialId: 'wf-key',
|
||||
sudoCredentialId: 'wf-sudo',
|
||||
tags: ['web'],
|
||||
pollIntervalSec: 3600,
|
||||
},
|
||||
});
|
||||
await api('/api/servers', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'srv-b',
|
||||
name: 'Server B',
|
||||
host: '127.0.0.1',
|
||||
port: portB,
|
||||
username: 'ops',
|
||||
credentialId: 'wf-key',
|
||||
sudoCredentialId: 'wf-sudo',
|
||||
tags: ['backup'],
|
||||
pollIntervalSec: 3600,
|
||||
},
|
||||
});
|
||||
await api('/api/servers/srv-a/reconnect', { method: 'POST' });
|
||||
await api('/api/servers/srv-b/reconnect', { method: 'POST' });
|
||||
expect(
|
||||
(
|
||||
await api('/api/servers/srv-a/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mockA.hostFingerprint },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
expect(
|
||||
(
|
||||
await api('/api/servers/srv-b/tofu/approve', {
|
||||
method: 'POST',
|
||||
body: { fingerprint: mockB.hostFingerprint },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
await waitFor(
|
||||
() =>
|
||||
server.sshPool.getState('srv-a')?.status === 'connected' &&
|
||||
server.sshPool.getState('srv-b')?.status === 'connected',
|
||||
);
|
||||
|
||||
// Attach systemd to srv-a for system-action step
|
||||
expect(
|
||||
(
|
||||
await api('/api/systems/systemd/servers/srv-a/attach', {
|
||||
method: 'PUT',
|
||||
body: { params: { unitFilter: 'nginx' } },
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
|
||||
// Wrap execStream ONLY for deterministic slow steps (__SLOW_250__ / __SLOW_2S__)
|
||||
const origExecStream = server.sshPool.execStream.bind(server.sshPool);
|
||||
vi.spyOn(server.sshPool, 'execStream').mockImplementation(async (serverId, cmd, opts) => {
|
||||
if (!cmd.includes('__SLOW_')) {
|
||||
return origExecStream(serverId, cmd, opts);
|
||||
}
|
||||
const ch = new PassThrough() as PassThrough & { stderr: PassThrough; close: () => void };
|
||||
const stderrStream = new PassThrough();
|
||||
ch.stderr = stderrStream;
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
let settled = false;
|
||||
let resolveDone!: (res: { exitCode: number | null; signal?: string }) => void;
|
||||
const done = new Promise<{ exitCode: number | null; signal?: string }>((resolve) => {
|
||||
resolveDone = resolve;
|
||||
});
|
||||
const finish = (res: { exitCode: number | null; signal?: string }) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
ch.end();
|
||||
stderrStream.end();
|
||||
resolveDone(res);
|
||||
};
|
||||
const abort = () => {
|
||||
finish({ exitCode: null, signal: 'TERM' });
|
||||
};
|
||||
ch.close = abort;
|
||||
const delayMs = cmd.includes('__SLOW_2S__') ? 2500 : 300;
|
||||
ch.write(`slow-start:${serverId}\n`);
|
||||
timer = setTimeout(() => {
|
||||
ch.write(`slow-end:${serverId}\n`);
|
||||
finish({ exitCode: 0 });
|
||||
}, delayMs);
|
||||
return { channel: ch as unknown as ClientChannel, done, abort };
|
||||
});
|
||||
|
||||
// --- 1. Snippets CRUD & Safe Mode enforcement ---
|
||||
const safeBlocked = await api('/api/snippets', {
|
||||
method: 'POST',
|
||||
safeMode: true,
|
||||
body: { id: 'snip-safe', name: 'Safe', command: 'echo hi' },
|
||||
});
|
||||
expect(safeBlocked.status).toBe(423);
|
||||
expect(safeBlocked.data.error).toBe('SAFE_MODE_ACTIVE');
|
||||
|
||||
const snipCreate = await api('/api/snippets', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'snip-quote',
|
||||
name: 'Safe Quoting Check',
|
||||
command:
|
||||
'echo REAL_SH_QUOTE_TEST && printf "ARG=%s ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"',
|
||||
tags: ['diagnostics'],
|
||||
inputs: [{ name: 'arg', type: 'string', required: true }],
|
||||
sudo: false,
|
||||
confirm: false,
|
||||
},
|
||||
});
|
||||
expect(snipCreate.status).toBe(201);
|
||||
|
||||
const snipDup = await api('/api/snippets', {
|
||||
method: 'POST',
|
||||
body: { id: 'snip-quote', name: 'Dup', command: 'echo dup' },
|
||||
});
|
||||
expect(snipDup.status).toBe(409);
|
||||
|
||||
const snipUpd = await api('/api/snippets/snip-quote', {
|
||||
method: 'PUT',
|
||||
body: {
|
||||
name: 'Safe Quoting Updated',
|
||||
command:
|
||||
'echo REAL_SH_QUOTE_TEST && printf "ARG=%s|ENV=%s" {{inputs.arg}} "$GCOORD_INPUT_ARG"',
|
||||
tags: ['diagnostics'],
|
||||
inputs: [{ name: 'arg', type: 'string', required: true }],
|
||||
sudo: false,
|
||||
confirm: false,
|
||||
},
|
||||
});
|
||||
expect(snipUpd.status).toBe(200);
|
||||
expect(
|
||||
((await api('/api/snippets')).data.snippets as Array<{ id: string }>).some(
|
||||
(s) => s.id === 'snip-quote',
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
// Temporary snippet to verify DELETE
|
||||
await api('/api/snippets', {
|
||||
method: 'POST',
|
||||
body: { id: 'snip-del', name: 'Temp', command: 'echo bye' },
|
||||
});
|
||||
expect((await api('/api/snippets/snip-del', { method: 'DELETE' })).status).toBe(200);
|
||||
|
||||
// --- 2. Ad-Hoc Fleet Broadcast (safe quoting, WS replay, cancellation) ---
|
||||
const dangerousArg = "hello'; touch /tmp/should-not-run; echo INJECTED";
|
||||
const { ws, frames } = await openWs(wsUrl, {
|
||||
Cookie: jar.header(),
|
||||
Host: `127.0.0.1:${server.port}`,
|
||||
Origin: baseUrl,
|
||||
});
|
||||
cleanups.push(() => ws.close());
|
||||
|
||||
const bcastRes = await api('/api/workflows/broadcast', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
snippetId: 'snip-quote',
|
||||
inputs: { arg: dangerousArg },
|
||||
concurrency: 2,
|
||||
target: { all: true },
|
||||
},
|
||||
});
|
||||
expect(bcastRes.status).toBe(202);
|
||||
const jobId = String((bcastRes.data.job as { jobId: string }).jobId);
|
||||
|
||||
const bcastDone = await waitFor(async () => {
|
||||
const g = await api(`/api/workflows/broadcast/${jobId}`);
|
||||
const j = g.data.job as {
|
||||
done: boolean;
|
||||
targets: Array<{ serverId: string; stdout: string; exitCode: number | null; status: string }>;
|
||||
};
|
||||
return j?.done ? j : undefined;
|
||||
});
|
||||
expect(bcastDone.targets).toHaveLength(2);
|
||||
for (const t of bcastDone.targets) {
|
||||
expect(t.status).toBe('ok');
|
||||
expect(t.exitCode).toBe(0);
|
||||
// POSIX single-quoting prevents shell injection; literal payload reaches printf unchanged
|
||||
expect(t.stdout).toContain(`ARG=${dangerousArg}|ENV=${dangerousArg}`);
|
||||
expect(t.stdout).not.toContain('\nINJECTED');
|
||||
}
|
||||
|
||||
// Subscribe AFTER broadcast finished to verify BufferedStreamEmitter replay frames
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: [`stream:${jobId}`] }));
|
||||
await waitFor(() =>
|
||||
frames.some((f) => {
|
||||
if (f.type !== 'stream:chunk' || f.jobId !== jobId || f.stream !== 'meta') return false;
|
||||
try {
|
||||
return (JSON.parse(String(f.data)) as { event?: string }).event === 'done';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// Broadcast cancellation
|
||||
const slowBcast = await api('/api/workflows/broadcast', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
command: 'echo __SLOW_2S__',
|
||||
target: { serverId: 'srv-a' },
|
||||
},
|
||||
});
|
||||
expect(slowBcast.status).toBe(202);
|
||||
const slowJobId = String((slowBcast.data.job as { jobId: string }).jobId);
|
||||
const cancelBcast = await api(`/api/workflows/broadcast/${slowJobId}/cancel`, {
|
||||
method: 'POST',
|
||||
});
|
||||
expect(cancelBcast.status).toBe(200);
|
||||
expect(cancelBcast.data.cancelled).toBe(true);
|
||||
const abortedJob = await waitFor(() => {
|
||||
const j = server.broadcastService.getBroadcastResult(slowJobId);
|
||||
return j?.done ? j : undefined;
|
||||
});
|
||||
expect(abortedJob.cancelled).toBe(true);
|
||||
expect(abortedJob.targets[0]?.status).toBe('cancelled');
|
||||
|
||||
// --- 3. Workflow Dry-Run, Pinned summary, Full DAG + failure/always + read-file + system-action + hub-relayed & direct transfers ---
|
||||
const dagWf = {
|
||||
id: 'wf-dag-full',
|
||||
name: 'Full DAG Verification',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
stopOnError: false,
|
||||
concurrency: 2,
|
||||
display: { mode: 'summary', pinToDashboard: true },
|
||||
inputs: [{ name: 'tag', type: 'string', required: true }],
|
||||
steps: [
|
||||
{
|
||||
id: 'gen-token',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-a' },
|
||||
command: ': ECHO_STEP; printf "tok-%s" {{inputs.tag}}',
|
||||
captureAs: 'tok',
|
||||
},
|
||||
{
|
||||
id: 'tail-log',
|
||||
type: 'read-file',
|
||||
target: { serverId: 'srv-a' },
|
||||
path: '/logs/app.log',
|
||||
tailLines: 2,
|
||||
},
|
||||
{
|
||||
id: 'svc-restart',
|
||||
type: 'system-action',
|
||||
dependsOn: ['gen-token'],
|
||||
target: { serverId: 'srv-a' },
|
||||
systemId: 'systemd',
|
||||
action: 'restart',
|
||||
item: 'nginx.service',
|
||||
},
|
||||
{
|
||||
id: 'xfer-file',
|
||||
type: 'transfer',
|
||||
dependsOn: ['gen-token'],
|
||||
mode: 'hub-relayed',
|
||||
source: { serverId: 'srv-a', path: '/single.txt' },
|
||||
destination: { serverId: 'srv-b', path: '/dst-single.txt' },
|
||||
},
|
||||
{
|
||||
id: 'xfer-dir',
|
||||
type: 'transfer',
|
||||
dependsOn: ['xfer-file'],
|
||||
mode: 'hub-relayed',
|
||||
source: { serverId: 'srv-a', path: '/bundle' },
|
||||
destination: { serverId: 'srv-b', path: '/dst-bundle' },
|
||||
},
|
||||
{
|
||||
id: 'xfer-direct',
|
||||
type: 'transfer',
|
||||
dependsOn: ['gen-token'],
|
||||
mode: 'direct',
|
||||
source: { serverId: 'srv-a', path: '/single.txt' },
|
||||
destination: { serverId: 'srv-b', path: '/direct-copy.txt' },
|
||||
},
|
||||
{
|
||||
id: 'will-fail',
|
||||
type: 'exec',
|
||||
dependsOn: ['gen-token'],
|
||||
target: { serverId: 'srv-b' },
|
||||
command: 'echo FAIL_NOW',
|
||||
onFailure: 'continue',
|
||||
},
|
||||
{
|
||||
id: 'on-fail-branch',
|
||||
type: 'exec',
|
||||
dependsOn: [{ stepId: 'will-fail', on: 'failure' }],
|
||||
target: { serverId: 'srv-a' },
|
||||
command: ': PRINT_CAP; printf "CAP=%s|STEP=%s" {{captures.tok}} {{steps.gen-token.stdout}}',
|
||||
},
|
||||
{
|
||||
id: 'on-always-cleanup',
|
||||
type: 'exec',
|
||||
dependsOn: [
|
||||
{ stepId: 'on-fail-branch', on: 'always' },
|
||||
{ stepId: 'xfer-dir', on: 'success' },
|
||||
],
|
||||
target: { serverId: 'srv-b' },
|
||||
command: 'echo cleanup-done',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(
|
||||
(await api('/api/workflows', { method: 'POST', body: dagWf })).status,
|
||||
).toBe(201);
|
||||
|
||||
const pinnedRes = await api('/api/workflows?pinnedOnly=1');
|
||||
expect(pinnedRes.status).toBe(200);
|
||||
expect(
|
||||
(pinnedRes.data.workflows as Array<{ workflow: { id: string } }>).map(
|
||||
(w) => w.workflow.id,
|
||||
),
|
||||
).toEqual(['wf-dag-full']);
|
||||
|
||||
// Dry-run works even under Safe Mode
|
||||
const dryRes = await api('/api/workflows/wf-dag-full/dry-run', {
|
||||
method: 'POST',
|
||||
safeMode: true,
|
||||
body: { inputs: { tag: 'v42' } },
|
||||
});
|
||||
expect(dryRes.status).toBe(200);
|
||||
const plan = dryRes.data.plan as {
|
||||
steps: Array<{
|
||||
stepId: string;
|
||||
wave: number;
|
||||
renderedCommand?: string;
|
||||
renderedPath?: string;
|
||||
}>;
|
||||
};
|
||||
const tailPlan = plan.steps.find((s) => s.stepId === 'tail-log');
|
||||
expect(tailPlan?.renderedPath).toBe('/logs/app.log');
|
||||
const genPlan = plan.steps.find((s) => s.stepId === 'gen-token');
|
||||
expect(genPlan?.renderedCommand).toContain("'v42'");
|
||||
|
||||
const dagStart = await api('/api/workflows/wf-dag-full/run', {
|
||||
method: 'POST',
|
||||
body: { inputs: { tag: 'v42' } },
|
||||
});
|
||||
expect(dagStart.status).toBe(202);
|
||||
const dagRunId = String(dagStart.data.runId);
|
||||
const dagDetail = await waitForWorkflowRun(server, dagRunId, 10_000);
|
||||
expect(dagDetail.run.status).toBe('succeeded');
|
||||
|
||||
const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l]));
|
||||
expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42');
|
||||
expect(logByStep.get('tail-log')?.stdout.trim()).toBe('l3\nl4');
|
||||
expect(logByStep.get('svc-restart')?.stdout).toContain('restarted nginx on A');
|
||||
expect(logByStep.get('will-fail')?.exitCode).toBe(42);
|
||||
expect(logByStep.get('on-fail-branch')?.stdout).toBe('CAP=tok-v42|STEP=tok-v42');
|
||||
expect(logByStep.get('on-always-cleanup')?.exitCode).toBe(0);
|
||||
|
||||
// Verify hub-relayed SFTP transfer files landed on srvB without touching local disk
|
||||
expect(fs.readFileSync(path.join(sftpRootB, 'dst-single.txt'), 'utf8')).toBe(
|
||||
'single-file-payload\n',
|
||||
);
|
||||
expect(fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'top.txt'), 'utf8')).toBe(
|
||||
'top-content',
|
||||
);
|
||||
expect(
|
||||
fs.readFileSync(path.join(sftpRootB, 'dst-bundle', 'nested', 'deep.txt'), 'utf8'),
|
||||
).toBe('deep-content');
|
||||
expect(directRsyncCmds.some((c) => c.includes(`ops@127.0.0.1:/direct-copy.txt`))).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
// Verify WS workflow:run + stream:wf:<runId> replay frames
|
||||
ws.send(JSON.stringify({ type: 'sub', channels: [`stream:wf:${dagRunId}`] }));
|
||||
await waitFor(() =>
|
||||
frames.some((f) => {
|
||||
if (f.type !== 'stream:chunk' || f.jobId !== `wf:${dagRunId}` || f.stream !== 'meta') {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return (JSON.parse(String(f.data)) as { event?: string }).event === 'done';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// --- 4. Overlap Policies ('skip', 'queue', 'cancel-previous'), Timeout & Manual Cancel ---
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-overlap-skip',
|
||||
name: 'Overlap Skip',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }],
|
||||
},
|
||||
});
|
||||
const rSkip1 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} });
|
||||
expect(rSkip1.status).toBe(202);
|
||||
const rSkip2 = await api('/api/workflows/wf-overlap-skip/run', { method: 'POST', body: {} });
|
||||
expect(rSkip2.status).toBe(200);
|
||||
expect(rSkip2.data.status).toBe('skipped');
|
||||
expect((await waitForWorkflowRun(server, String(rSkip1.data.runId))).run.status).toBe('succeeded');
|
||||
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-overlap-queue',
|
||||
name: 'Overlap Queue',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'queue',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }],
|
||||
},
|
||||
});
|
||||
const rQ1 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} });
|
||||
const rQ2 = await api('/api/workflows/wf-overlap-queue/run', { method: 'POST', body: {} });
|
||||
expect(rQ1.status).toBe(202);
|
||||
expect(rQ2.status).toBe(202);
|
||||
expect(rQ2.data.status).toBe('queued');
|
||||
expect((await waitForWorkflowRun(server, String(rQ1.data.runId))).run.status).toBe('succeeded');
|
||||
expect((await waitForWorkflowRun(server, String(rQ2.data.runId))).run.status).toBe('succeeded');
|
||||
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-overlap-cancel',
|
||||
name: 'Overlap Cancel Prev',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'cancel-previous',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [{ id: 's1', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_250__' }],
|
||||
},
|
||||
});
|
||||
const rC1 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} });
|
||||
const rC2 = await api('/api/workflows/wf-overlap-cancel/run', { method: 'POST', body: {} });
|
||||
expect(rC2.status).toBe(202);
|
||||
expect((await waitForWorkflowRun(server, String(rC1.data.runId))).run.status).toBe('cancelled');
|
||||
expect((await waitForWorkflowRun(server, String(rC2.data.runId))).run.status).toBe('succeeded');
|
||||
|
||||
// Step timeoutSec: 1 + manual run cancel
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-timeout',
|
||||
name: 'Timeout Test',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [
|
||||
{
|
||||
id: 'slow',
|
||||
type: 'exec',
|
||||
target: { serverId: 'srv-a' },
|
||||
command: 'echo __SLOW_2S__',
|
||||
timeoutSec: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const rTimeout = await api('/api/workflows/wf-timeout/run', { method: 'POST', body: {} });
|
||||
const dTimeout = await waitForWorkflowRun(server, String(rTimeout.data.runId));
|
||||
expect(dTimeout.run.status).toBe('failed');
|
||||
expect(dTimeout.stepLogs[0]?.stderr).toMatch(/timed out/i);
|
||||
|
||||
const rToCancel = await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-manual-cancel',
|
||||
name: 'Manual Cancel',
|
||||
enabled: true,
|
||||
trigger: { type: 'manual' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [{ id: 'slow', type: 'exec', target: { serverId: 'srv-a' }, command: 'echo __SLOW_2S__' }],
|
||||
},
|
||||
});
|
||||
expect(rToCancel.status).toBe(201);
|
||||
const rManStart = await api('/api/workflows/wf-manual-cancel/run', { method: 'POST', body: {} });
|
||||
const manCancelRes = await api(`/api/workflows/runs/${String(rManStart.data.runId)}/cancel`, {
|
||||
method: 'POST',
|
||||
});
|
||||
expect(manCancelRes.data.cancelled).toBe(true);
|
||||
const dCancelled = await waitForWorkflowRun(server, String(rManStart.data.runId));
|
||||
expect(dCancelled.run.status).toBe('cancelled');
|
||||
expect(dCancelled.run.cancelledBy).toBe('admin');
|
||||
|
||||
// --- 5. Cron Workflow Scheduling ---
|
||||
await api('/api/workflows', {
|
||||
method: 'POST',
|
||||
body: {
|
||||
id: 'wf-cron-sec',
|
||||
name: 'Every Second Cron',
|
||||
enabled: true,
|
||||
trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' },
|
||||
overlapPolicy: 'skip',
|
||||
display: { mode: 'log' },
|
||||
inputs: [],
|
||||
steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }],
|
||||
},
|
||||
});
|
||||
|
||||
const listSummary = await api('/api/workflows');
|
||||
const cronSummary = (
|
||||
listSummary.data.workflows as Array<{
|
||||
workflow: { id: string };
|
||||
nextRunAt: number | null;
|
||||
}>
|
||||
).find((w) => w.workflow.id === 'wf-cron-sec');
|
||||
expect(typeof cronSummary?.nextRunAt).toBe('number');
|
||||
expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000);
|
||||
|
||||
const cronRun = await waitFor(
|
||||
() => {
|
||||
const runs = server.workflowEngine.listRuns('wf-cron-sec');
|
||||
return runs.find((r) => r.triggerSource === 'cron' && r.status === 'succeeded');
|
||||
},
|
||||
5000,
|
||||
);
|
||||
expect(cronRun.triggerSource).toBe('cron');
|
||||
await api('/api/workflows/wf-cron-sec', { method: 'DELETE' });
|
||||
},
|
||||
);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue