feat(alerts,api): implement AlertEngine, webhooks, silences, and Phase 4 REST/WS routes

This commit is contained in:
tyuXX 2026-11-27 06:15:07 +00:00
parent f21699963f
commit 7272ad58bd
5 changed files with 1507 additions and 2 deletions

View 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;
}
}

View 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;
}

View 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;
}

View 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;
}

View file

@ -3,6 +3,10 @@ import http from 'node:http';
import path from 'node:path'; import path from 'node:path';
import type Database from 'better-sqlite3'; import type Database from 'better-sqlite3';
import express, { type Express } from 'express'; import express, { type Express } from 'express';
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 { ConfigManager } from './config/config-manager.js';
import { openDatabase } from './db/database.js'; import { openDatabase } from './db/database.js';
import { ServerInspector } from './monitoring/inspector.js'; import { ServerInspector } from './monitoring/inspector.js';
@ -24,15 +28,18 @@ import { SftpService } from './ssh/sftp-service.js';
import { SSHPool } from './ssh/ssh-pool.js'; import { SSHPool } from './ssh/ssh-pool.js';
import { TunnelManager } from './ssh/tunnel-manager.js'; import { TunnelManager } from './ssh/tunnel-manager.js';
import { CustomSystemsEngine } from './systems/systems-engine.js'; import { CustomSystemsEngine } from './systems/systems-engine.js';
import { createAlertsRouter } from './api/routes/alerts.routes.js';
import { createAuditRouter } from './api/routes/audit.routes.js'; import { createAuditRouter } from './api/routes/audit.routes.js';
import { createAuthRouter } from './api/routes/auth.routes.js'; import { createAuthRouter } from './api/routes/auth.routes.js';
import { createConfigRouter } from './api/routes/config.routes.js'; import { createConfigRouter } from './api/routes/config.routes.js';
import { createServersRouter } from './api/routes/servers.routes.js'; import { createServersRouter } from './api/routes/servers.routes.js';
import { createSftpRouter } from './api/routes/sftp.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 { createSystemsRouter } from './api/routes/systems.routes.js';
import { createTerminalRouter } from './api/routes/terminal.routes.js'; import { createTerminalRouter } from './api/routes/terminal.routes.js';
import { createProxyRouter, createTunnelsRouter } from './api/routes/tunnels.routes.js'; import { createProxyRouter, createTunnelsRouter } from './api/routes/tunnels.routes.js';
import { createVaultRouter } from './api/routes/vault.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'; import { WsHub } from './api/ws-hub.js';
export interface ServerOptions { export interface ServerOptions {
@ -64,6 +71,10 @@ export interface GCoordinatorInstance {
customSystemsEngine: CustomSystemsEngine; customSystemsEngine: CustomSystemsEngine;
serverInspector: ServerInspector; serverInspector: ServerInspector;
monitoringService: MonitoringService; monitoringService: MonitoringService;
transferEngine: TransferEngine;
workflowEngine: WorkflowEngine;
broadcastService: BroadcastService;
alertEngine: AlertEngine;
wsHub: WsHub; wsHub: WsHub;
port: number; port: number;
close(): Promise<void>; close(): Promise<void>;
@ -144,6 +155,36 @@ export async function createGCoordinatorServer(
sshPool, sshPool,
probeRunner, 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,
);
wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => {
tunnelManager.handleWsProxyUpgrade(req, socket, head); tunnelManager.handleWsProxyUpgrade(req, socket, head);
@ -178,7 +219,12 @@ export async function createGCoordinatorServer(
} }
} else if (channel.startsWith('stream:')) { } else if (channel.startsWith('stream:')) {
const jobId = channel.slice('stream:'.length); 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); ctx.send(frame);
} }
} else if (channel === 'metrics') { } else if (channel === 'metrics') {
@ -218,7 +264,8 @@ export async function createGCoordinatorServer(
if (s.hostKeyMismatch) { if (s.hostKeyMismatch) {
wsHub.broadcastChannel('alerts', { wsHub.broadcastChannel('alerts', {
type: 'alerts:update', type: 'alerts:update',
activeCount: knownHosts.listPendingMismatches().length, activeCount:
alertEngine.getActiveCount() + knownHosts.listPendingMismatches().length,
hostKeyMismatch: s.hostKeyMismatch, hostKeyMismatch: s.hostKeyMismatch,
}); });
} }
@ -238,8 +285,13 @@ export async function createGCoordinatorServer(
monitoringService.start(); monitoringService.start();
void tunnelManager.syncAutoStart(); void tunnelManager.syncAutoStart();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
workflowEngine.start();
alertEngine.start();
vaultService.onPanicLock(() => { vaultService.onPanicLock(() => {
alertEngine.handlePanicLock();
workflowEngine.handlePanicLock();
broadcastService.cancelAll();
monitoringService.stopAll(); monitoringService.stopAll();
customSystemsEngine.stopBackgroundChecks(); customSystemsEngine.stopBackgroundChecks();
customSystemsEngine.cancelAllStreams(); customSystemsEngine.cancelAllStreams();
@ -261,6 +313,7 @@ export async function createGCoordinatorServer(
if ( if (
event.entityType === 'server' || event.entityType === 'server' ||
event.entityType === 'system' || event.entityType === 'system' ||
event.entityType === 'workflow' ||
event.entityType === 'settings' || event.entityType === 'settings' ||
event.entityType === 'all' event.entityType === 'all'
) { ) {
@ -279,6 +332,7 @@ export async function createGCoordinatorServer(
} }
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
workflowEngine.syncCronJobs();
void tunnelManager.syncAutoStart(); void tunnelManager.syncAutoStart();
} }
}); });
@ -320,6 +374,7 @@ export async function createGCoordinatorServer(
onVaultUnlocked: () => { onVaultUnlocked: () => {
monitoringService.syncServers(); monitoringService.syncServers();
customSystemsEngine.syncBackgroundChecks(); customSystemsEngine.syncBackgroundChecks();
workflowEngine.syncCronJobs();
void tunnelManager.syncAutoStart(); void tunnelManager.syncAutoStart();
}, },
onVaultChanged: (snapshotReason) => { onVaultChanged: (snapshotReason) => {
@ -338,6 +393,24 @@ export async function createGCoordinatorServer(
'/api/systems', '/api/systems',
createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }), 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( app.use(
'/api/servers/:id/sftp', '/api/servers/:id/sftp',
createSftpRouter({ authService, configManager, auditService, sftpService }), createSftpRouter({ authService, configManager, auditService, sftpService }),
@ -409,9 +482,16 @@ export async function createGCoordinatorServer(
customSystemsEngine, customSystemsEngine,
serverInspector, serverInspector,
monitoringService, monitoringService,
transferEngine,
workflowEngine,
broadcastService,
alertEngine,
wsHub, wsHub,
port: actualPort, port: actualPort,
async close() { async close() {
alertEngine.close();
workflowEngine.close();
broadcastService.cancelAll();
monitoringService.close(); monitoringService.close();
customSystemsEngine.close(); customSystemsEngine.close();
tunnelManager.stopAll(); tunnelManager.stopAll();