From f21699963ff0b736033a222d20aa8103ead87116 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:12:51 +0000 Subject: [PATCH 01/10] feat(automation): implement DAG WorkflowEngine, cron/event triggers, dry-run, and BroadcastService --- src/server/automation/broadcast-service.ts | 354 +++++ src/server/automation/stream-buffer.ts | 44 + src/server/automation/template.ts | 192 +++ src/server/automation/workflow-engine.ts | 1438 ++++++++++++++++++++ 4 files changed, 2028 insertions(+) create mode 100644 src/server/automation/broadcast-service.ts create mode 100644 src/server/automation/stream-buffer.ts create mode 100644 src/server/automation/template.ts create mode 100644 src/server/automation/workflow-engine.ts diff --git a/src/server/automation/broadcast-service.ts b/src/server/automation/broadcast-service.ts new file mode 100644 index 0000000..4909164 --- /dev/null +++ b/src/server/automation/broadcast-service.ts @@ -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( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + 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(); + + 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; + 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 = {}; + + 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); + } + } +} diff --git a/src/server/automation/stream-buffer.ts b/src/server/automation/stream-buffer.ts new file mode 100644 index 0000000..bc26e55 --- /dev/null +++ b/src/server/automation/stream-buffer.ts @@ -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): void { + this.push('meta', JSON.stringify(payload)); + } + + getReplayFrames(): ServerWsFrame[] { + return [...this.frames]; + } +} diff --git a/src/server/automation/template.ts b/src/server/automation/template.ts new file mode 100644 index 0000000..a890e2f --- /dev/null +++ b/src/server/automation/template.ts @@ -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; + stepOutputs?: Map; + captures?: Map; + eventMeta?: Record; +} + +export function toEnvIdent(raw: string): string { + return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); +} + +export function validateAndResolveInputs( + defs: InputDef[], + supplied: Record = {}, +): Record { + const out: Record = {}; + + 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 { + const env: Record = {}; + 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(); + + 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; +} diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts new file mode 100644 index 0000000..8d3a181 --- /dev/null +++ b/src/server/automation/workflow-engine.ts @@ -0,0 +1,1438 @@ +import crypto from 'node:crypto'; +import type Database from 'better-sqlite3'; +import { Cron } from 'croner'; +import type { ServerConfig } from '../../shared/schemas/server.schema.js'; +import type { + StepDependencySchema, + WorkflowConfig, + WorkflowStep, +} from '../../shared/schemas/workflow.schema.js'; +import type { z } from 'zod'; +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 type { AuditService } from '../security/audit.js'; +import type { VaultService } from '../security/vault.js'; +import type { SftpService } from '../ssh/sftp-service.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import { posixSingleQuote } from '../ssh/sudo.js'; +import type { CustomSystemsEngine } from '../systems/systems-engine.js'; +import { BufferedStreamEmitter } from './stream-buffer.js'; +import { + buildWorkflowEnv, + interpolateShellCommandSafe, + interpolateValuePlain, + resolveTargetServers, + validateAndResolveInputs, + type StepOutputSummary, + type TemplateContext, +} from './template.js'; +import type { TransferEngine } from './transfer-engine.js'; + +type StepDependency = z.infer; + +export type WorkflowRunStatus = + | 'queued' + | 'running' + | 'succeeded' + | 'failed' + | 'cancelled' + | 'skipped'; + +export interface WorkflowRunRecord { + runId: string; + workflowId: string; + triggerSource: string; + status: WorkflowRunStatus; + startedAt: number; + finishedAt: number | null; + cancelledBy: string | null; + inputsJson?: string | null; +} + +export interface WorkflowStepLogRecord { + id: number; + runId: string; + stepId: string; + serverId: string; + exitCode: number | null; + durationMs: number; + stdout: string; + stderr: string; + createdAt: number; +} + +export interface DryRunStepPlan { + stepId: string; + type: WorkflowStep['type']; + wave: number; + dependsOn: Array<{ stepId: string; on: 'success' | 'failure' | 'always' }>; + targets: Array<{ serverId: string; serverName: string }>; + renderedCommand?: string; + renderedPath?: string; + systemId?: string; + actionId?: string; + discoveredItems?: Record; + transferPreview?: { + mode: 'hub-relayed' | 'direct'; + sourceServerId: string; + sourcePath: string; + destinationServerId: string; + destinationPath: string; + }; + envKeys: string[]; +} + +export interface SystemTriggerEvent { + event: + | 'server.offline' + | 'server.online' + | 'probe.failed' + | 'system.unhealthy' + | 'alert.fired'; + serverId?: string; + systemId?: string; + item?: string; + probeId?: string; + ruleId?: string; + message?: string; +} + +interface ActiveRunControl { + runId: string; + workflowId: string; + status: WorkflowRunStatus; + abortController: AbortController; + emitter: BufferedStreamEmitter; + done: boolean; + cancelledBy?: string; +} + +interface QueuedRunRequest { + runId: string; + workflow: WorkflowConfig; + triggerSource: string; + inputs: Record; + eventMeta?: Record; + actorIp: string; + sessionIdHash: string | null; + startedAt: number; + onFailureDepth: number; +} + +export type FailureNotifierFn = ( + channelId: string, + message: string, + workflowId: string, +) => Promise; + +const MAX_OUTPUT_CHARS = 256 * 1024; +const MAX_RETAINED_STREAM_RUNS = 30; + +function normalizeDep(dep: StepDependency): { + stepId: string; + on: 'success' | 'failure' | 'always'; +} { + if (typeof dep === 'string') return { stepId: dep, on: 'success' }; + return { stepId: dep.stepId, on: dep.on }; +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + const limit = Math.max(1, Math.min(concurrency, items.length || 1)); + let idx = 0; + const workers = Array.from({ length: limit }, async () => { + while (idx < items.length) { + const item = items[idx++]!; + await worker(item); + } + }); + await Promise.all(workers); +} + +export class WorkflowEngine { + private readonly cronJobs = new Map(); + private readonly activeByWorkflow = new Map(); + private readonly queueByWorkflow = new Map(); + private readonly runsById = new Map(); + private failureNotifier: FailureNotifierFn | null = null; + private closed = false; + + constructor( + private readonly db: Database.Database, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sshPool: SSHPool, + private readonly sftpService: SftpService, + private readonly customSystemsEngine: CustomSystemsEngine, + private readonly transferEngine: TransferEngine, + private readonly wsHub: WsHub, + private readonly auditService: AuditService, + ) {} + + setFailureNotifier(fn: FailureNotifierFn): void { + this.failureNotifier = fn; + } + + getStreamReplayFrames(jobId: string): ServerWsFrame[] { + if (!jobId.startsWith('wf:')) return []; + const runId = jobId.slice(3); + return this.runsById.get(runId)?.emitter.getReplayFrames() ?? []; + } + + start(): void { + this.closed = false; + this.syncCronJobs(); + } + + syncCronJobs(): void { + this.stopCronJobs(); + if (this.closed || !this.vaultService.isRuntimeReady) return; + + for (const wf of this.configManager.listWorkflows()) { + if (!wf.enabled || wf.trigger.type !== 'cron') continue; + const wfId = wf.id; + const cron = new Cron( + wf.trigger.expression, + { + timezone: wf.trigger.timezone, + protect: true, + unref: true, + }, + () => { + if (this.closed || !this.vaultService.isRuntimeReady) return; + void this.triggerWorkflow(wfId, { + triggerSource: 'cron', + }).catch(() => undefined); + }, + ); + this.cronJobs.set(wfId, cron); + } + } + + stopCronJobs(): void { + for (const job of this.cronJobs.values()) { + job.stop(); + } + this.cronJobs.clear(); + } + + handlePanicLock(): void { + this.stopCronJobs(); + for (const [wfId, q] of this.queueByWorkflow.entries()) { + for (const req of q) { + this.markRunFinished(req.runId, wfId, 'cancelled', 'cron', Date.now(), 'panic_lock'); + } + } + this.queueByWorkflow.clear(); + for (const run of this.activeByWorkflow.values()) { + this.cancelRun(run.runId, 'panic_lock'); + } + } + + close(): void { + this.closed = true; + this.handlePanicLock(); + } + + getNextCronRun(workflowId: string): number | null { + const job = this.cronJobs.get(workflowId); + if (!job) return null; + const next = job.nextRun(); + return next ? next.getTime() : null; + } + + listWorkflowsWithSummary(): Array<{ + workflow: WorkflowConfig; + nextRunAt: number | null; + activeRunId: string | null; + queuedCount: number; + latestRun: WorkflowRunRecord | null; + latestStepLogs: WorkflowStepLogRecord[]; + }> { + const workflows = this.configManager.listWorkflows(); + return workflows.map((workflow) => { + const latestRun = + (this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE workflow_id = ? + ORDER BY started_at DESC + LIMIT 1`, + ) + .get(workflow.id) as WorkflowRunRecord | undefined) ?? null; + + const latestStepLogs = latestRun + ? (this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(latestRun.runId) as WorkflowStepLogRecord[]) + : []; + + const active = this.activeByWorkflow.get(workflow.id); + const queued = this.queueByWorkflow.get(workflow.id)?.length ?? 0; + + return { + workflow, + nextRunAt: this.getNextCronRun(workflow.id), + activeRunId: active && !active.done ? active.runId : null, + queuedCount: queued, + latestRun, + latestStepLogs, + }; + }); + } + + listRuns(workflowId?: string, limit = 50): WorkflowRunRecord[] { + const capped = Math.max(1, Math.min(limit, 200)); + if (workflowId) { + return this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE workflow_id = ? + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(workflowId, capped) as WorkflowRunRecord[]; + } + return this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(capped) as WorkflowRunRecord[]; + } + + getRunDetail(runId: string): { + run: WorkflowRunRecord; + stepLogs: WorkflowStepLogRecord[]; + workflow: WorkflowConfig | null; + } | null { + const run = this.db + .prepare( + `SELECT run_id AS runId, workflow_id AS workflowId, trigger_source AS triggerSource, + status, started_at AS startedAt, finished_at AS finishedAt, + cancelled_by AS cancelledBy, inputs_json AS inputsJson + FROM workflow_runs + WHERE run_id = ?`, + ) + .get(runId) as WorkflowRunRecord | undefined; + if (!run) return null; + + const stepLogs = this.db + .prepare( + `SELECT id, run_id AS runId, step_id AS stepId, server_id AS serverId, + exit_code AS exitCode, duration_ms AS durationMs, stdout, stderr, + created_at AS createdAt + FROM workflow_step_logs + WHERE run_id = ? + ORDER BY id ASC`, + ) + .all(runId) as WorkflowStepLogRecord[]; + + return { + run, + stepLogs, + workflow: this.configManager.getWorkflow(run.workflowId) ?? null, + }; + } + + async handleSystemEvent(ev: SystemTriggerEvent): Promise { + if (this.closed || !this.vaultService.isRuntimeReady) return []; + + const triggeredRunIds: string[] = []; + const srv = ev.serverId ? this.configManager.getServer(ev.serverId) : undefined; + const workflows = this.configManager.listWorkflows(); + + for (const wf of workflows) { + if (!wf.enabled || wf.trigger.type !== 'event') continue; + if (wf.trigger.event !== ev.event) continue; + + const filter = wf.trigger.filter; + if (filter) { + if (filter.serverId && filter.serverId !== ev.serverId) continue; + if (filter.systemId && filter.systemId !== ev.systemId) continue; + if (filter.tags && filter.tags.length > 0) { + if (!srv || !srv.tags.some((t) => filter.tags!.includes(t))) continue; + } + } + + const autoInputs: Record = {}; + if (ev.serverId && wf.inputs.some((i) => i.name === 'serverId')) { + autoInputs.serverId = ev.serverId; + } + + const eventMeta: Record = { type: ev.event }; + if (ev.serverId) eventMeta.serverId = ev.serverId; + if (ev.systemId) eventMeta.systemId = ev.systemId; + if (ev.item) eventMeta.item = ev.item; + if (ev.probeId) eventMeta.probeId = ev.probeId; + if (ev.ruleId) eventMeta.ruleId = ev.ruleId; + if (ev.message) eventMeta.message = ev.message; + + try { + const res = await this.triggerWorkflow(wf.id, { + triggerSource: `event:${ev.event}`, + inputs: autoInputs, + eventMeta, + }); + triggeredRunIds.push(res.runId); + } catch { + // Isolate event-triggered workflow failures + } + } + + return triggeredRunIds; + } + + async triggerWorkflow( + workflowId: string, + opts: { + triggerSource: string; + inputs?: Record; + eventMeta?: Record; + actorIp?: string; + sessionIdHash?: string | null; + onFailureDepth?: number; + }, + ): Promise<{ runId: string; status: WorkflowRunStatus; skippedReason?: string }> { + if (this.closed) { + throw new Error('WorkflowEngine is closed'); + } + if (!this.vaultService.isRuntimeReady) { + throw new Error('Vault is sealed; unseal Vault before running workflows'); + } + + const wf = this.configManager.getWorkflow(workflowId); + if (!wf) { + throw new Error(`Unknown workflow "${workflowId}"`); + } + + const inputs = validateAndResolveInputs(wf.inputs, opts.inputs ?? {}); + const runId = `run-${crypto.randomBytes(6).toString('hex')}`; + const now = Date.now(); + const depth = opts.onFailureDepth ?? 0; + const actorIp = opts.actorIp ?? 'scheduler'; + const sessionIdHash = opts.sessionIdHash ?? null; + + const existingActive = this.activeByWorkflow.get(wf.id); + if (existingActive && !existingActive.done) { + if (wf.overlapPolicy === 'skip') { + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'skipped', ?, ?, 'overlap:skip', ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, now, JSON.stringify(inputs)); + + this.broadcastRunFrame({ + runId, + workflowId: wf.id, + status: 'skipped', + triggerSource: opts.triggerSource, + startedAt: now, + finishedAt: now, + }); + return { runId, status: 'skipped', skippedReason: 'overlap' }; + } + + if (wf.overlapPolicy === 'queue') { + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'queued', ?, NULL, NULL, ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + + const q = this.queueByWorkflow.get(wf.id) ?? []; + q.push({ + runId, + workflow: wf, + triggerSource: opts.triggerSource, + inputs, + eventMeta: opts.eventMeta, + actorIp, + sessionIdHash, + startedAt: now, + onFailureDepth: depth, + }); + this.queueByWorkflow.set(wf.id, q); + + this.broadcastRunFrame({ + runId, + workflowId: wf.id, + status: 'queued', + triggerSource: opts.triggerSource, + startedAt: now, + }); + return { runId, status: 'queued' }; + } + + if (wf.overlapPolicy === 'cancel-previous') { + const queued = this.queueByWorkflow.get(wf.id); + if (queued) { + for (const item of queued) { + this.markRunFinished( + item.runId, + wf.id, + 'cancelled', + item.triggerSource, + item.startedAt, + 'overlap:cancel-previous', + ); + } + this.queueByWorkflow.delete(wf.id); + } + this.cancelRun(existingActive.runId, 'overlap:cancel-previous'); + } + } + + this.db + .prepare( + `INSERT INTO workflow_runs (run_id, workflow_id, trigger_source, status, started_at, finished_at, cancelled_by, inputs_json) + VALUES (?, ?, ?, 'running', ?, NULL, NULL, ?)`, + ) + .run(runId, wf.id, opts.triggerSource, now, JSON.stringify(inputs)); + + this.startExecution({ + runId, + workflow: wf, + triggerSource: opts.triggerSource, + inputs, + eventMeta: opts.eventMeta, + actorIp, + sessionIdHash, + startedAt: now, + onFailureDepth: depth, + }); + + return { runId, status: 'running' }; + } + + cancelRun(runId: string, actor = 'admin'): boolean { + for (const [wfId, queue] of this.queueByWorkflow.entries()) { + const idx = queue.findIndex((q) => q.runId === runId); + if (idx >= 0) { + const [removed] = queue.splice(idx, 1); + if (queue.length === 0) this.queueByWorkflow.delete(wfId); + if (removed) { + this.markRunFinished( + removed.runId, + removed.workflow.id, + 'cancelled', + removed.triggerSource, + removed.startedAt, + actor, + ); + } + return true; + } + } + + const active = this.runsById.get(runId); + if (!active || active.done) return false; + + active.cancelledBy = actor; + active.status = 'cancelled'; + active.abortController.abort(); + active.emitter.pushMeta({ event: 'cancelled', actor }); + return true; + } + + async previewDryRun( + workflowInput: string | WorkflowConfig, + suppliedInputs: Record = {}, + ): Promise<{ workflowId: string; workflowName: string; inputs: Record; steps: DryRunStepPlan[] }> { + const wf = + typeof workflowInput === 'string' + ? this.configManager.getWorkflow(workflowInput) + : workflowInput; + if (!wf) { + throw new Error(`Unknown workflow "${String(workflowInput)}"`); + } + + const inputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const allServers = this.configManager.listServers(); + const baseCtx: TemplateContext = { workflowId: wf.id, inputs }; + const envKeys = Object.keys(buildWorkflowEnv(baseCtx)); + + // Compute topological waves matching WorkflowConfigSchema DAG + const waveMap = new Map(); + const stepById = new Map(wf.steps.map((s) => [s.id, s])); + const computeWave = (stepId: string): number => { + if (waveMap.has(stepId)) return waveMap.get(stepId)!; + const step = stepById.get(stepId)!; + if (step.dependsOn.length === 0) { + waveMap.set(stepId, 0); + return 0; + } + let maxDep = 0; + for (const d of step.dependsOn) { + const depId = normalizeDep(d).stepId; + maxDep = Math.max(maxDep, computeWave(depId) + 1); + } + waveMap.set(stepId, maxDep); + return maxDep; + }; + for (const s of wf.steps) computeWave(s.id); + + const ordered = [...wf.steps].sort( + (a, b) => (waveMap.get(a.id) ?? 0) - (waveMap.get(b.id) ?? 0), + ); + + const steps: DryRunStepPlan[] = []; + for (const step of ordered) { + const deps = step.dependsOn.map(normalizeDep); + const wave = waveMap.get(step.id) ?? 0; + + if (step.type === 'transfer') { + const srcId = interpolateValuePlain(step.source.serverId, baseCtx); + const dstId = interpolateValuePlain(step.destination.serverId, baseCtx); + const srcSrv = allServers.find((s) => s.id === srcId && s.enabled); + const dstSrv = allServers.find((s) => s.id === dstId && s.enabled); + const targets: Array<{ serverId: string; serverName: string }> = []; + if (srcSrv) targets.push({ serverId: srcSrv.id, serverName: srcSrv.name }); + if (dstSrv && dstSrv.id !== srcSrv?.id) { + targets.push({ serverId: dstSrv.id, serverName: dstSrv.name }); + } + steps.push({ + stepId: step.id, + type: step.type, + wave, + dependsOn: deps, + targets, + transferPreview: { + mode: step.mode, + sourceServerId: srcId, + sourcePath: interpolateValuePlain(step.source.path, baseCtx), + destinationServerId: dstId, + destinationPath: interpolateValuePlain(step.destination.path, baseCtx), + }, + envKeys, + }); + continue; + } + + const matched = resolveTargetServers(step.target, allServers, baseCtx); + const plan: DryRunStepPlan = { + stepId: step.id, + type: step.type, + wave, + dependsOn: deps, + targets: matched.map((s) => ({ serverId: s.id, serverName: s.name })), + envKeys, + }; + + if (step.type === 'exec') { + plan.renderedCommand = interpolateShellCommandSafe(step.command, baseCtx); + } else if (step.type === 'read-file') { + plan.renderedPath = interpolateValuePlain(step.path, baseCtx); + } else if (step.type === 'system-action') { + plan.systemId = step.systemId; + plan.actionId = step.action; + const discoveredItems: Record = {}; + if (this.vaultService.isRuntimeReady && step.item === '*') { + for (const srv of matched) { + if (!srv.systems.some((a) => a.systemId === step.systemId)) continue; + try { + const snap = await this.customSystemsEngine.getServerSystem(srv.id, step.systemId); + discoveredItems[srv.id] = snap.items.map((i) => i.name); + } catch { + discoveredItems[srv.id] = []; + } + } + } + plan.discoveredItems = discoveredItems; + } + + steps.push(plan); + } + + return { + workflowId: wf.id, + workflowName: wf.name, + inputs, + steps, + }; + } + + private startExecution(req: QueuedRunRequest): void { + const emitter = new BufferedStreamEmitter(this.wsHub, `wf:${req.runId}`); + const abortController = new AbortController(); + const control: ActiveRunControl = { + runId: req.runId, + workflowId: req.workflow.id, + status: 'running', + abortController, + emitter, + done: false, + }; + + this.activeByWorkflow.set(req.workflow.id, control); + this.runsById.set(req.runId, control); + + this.auditService.log({ + action: 'workflow.start', + actorIp: req.actorIp, + sessionIdHash: req.sessionIdHash, + target: `${req.workflow.id}:${req.runId}`, + status: 'ok', + details: { triggerSource: req.triggerSource }, + }); + + this.broadcastRunFrame({ + runId: req.runId, + workflowId: req.workflow.id, + status: 'running', + triggerSource: req.triggerSource, + startedAt: req.startedAt, + }); + + emitter.pushMeta({ + event: 'start', + runId: req.runId, + workflowId: req.workflow.id, + triggerSource: req.triggerSource, + }); + + void this.executeDag(req, control) + .then((finalStatus) => { + control.done = true; + control.status = finalStatus; + this.markRunFinished( + req.runId, + req.workflow.id, + finalStatus, + req.triggerSource, + req.startedAt, + control.cancelledBy ?? null, + ); + emitter.pushMeta({ event: 'done', runId: req.runId, status: finalStatus }); + }) + .catch((err) => { + control.done = true; + const msg = err instanceof Error ? err.message : String(err); + emitter.push('stderr', `${msg}\n`); + control.status = abortController.signal.aborted ? 'cancelled' : 'failed'; + this.markRunFinished( + req.runId, + req.workflow.id, + control.status, + req.triggerSource, + req.startedAt, + control.cancelledBy ?? null, + ); + emitter.pushMeta({ event: 'done', runId: req.runId, status: control.status }); + }) + .finally(() => { + if (this.activeByWorkflow.get(req.workflow.id)?.runId === req.runId) { + this.activeByWorkflow.delete(req.workflow.id); + } + this.pruneRetainedStreams(); + this.pumpQueue(req.workflow.id); + }); + } + + private pumpQueue(workflowId: string): void { + if (this.closed || !this.vaultService.isRuntimeReady) return; + if (this.activeByWorkflow.has(workflowId)) return; + + const queue = this.queueByWorkflow.get(workflowId); + if (!queue || queue.length === 0) return; + const next = queue.shift()!; + if (queue.length === 0) this.queueByWorkflow.delete(workflowId); + + this.db + .prepare(`UPDATE workflow_runs SET status = 'running' WHERE run_id = ?`) + .run(next.runId); + this.startExecution(next); + } + + private async executeDag( + req: QueuedRunRequest, + control: ActiveRunControl, + ): Promise { + const wf = req.workflow; + const allServers = this.configManager.listServers(); + const stepOutputs = new Map(); + const captures = new Map(); + const terminalState = new Map(); + const runningPromises = new Map>(); + + let abortUnrelated = false; + let hasFatalFailure = false; + + while (terminalState.size < wf.steps.length) { + if (control.abortController.signal.aborted) { + if (runningPromises.size > 0) { + await Promise.allSettled(runningPromises.values()); + } + return 'cancelled'; + } + + let madeProgress = false; + + for (const step of wf.steps) { + if (terminalState.has(step.id) || runningPromises.has(step.id)) continue; + + const deps = step.dependsOn.map(normalizeDep); + if (!deps.every((d) => terminalState.has(d.stepId))) continue; + + let eligible = true; + if (deps.length === 0) { + if (abortUnrelated) eligible = false; + } else { + for (const d of deps) { + const depSt = terminalState.get(d.stepId)!; + if (d.on === 'success') { + if (depSt !== 'succeeded' || abortUnrelated) { + eligible = false; + break; + } + } else if (d.on === 'failure') { + if (depSt !== 'failed') { + eligible = false; + break; + } + } + } + + if (eligible) { + const allAlways = deps.every((d) => d.on === 'always'); + const anyNonSkipped = deps.some((d) => terminalState.get(d.stepId) !== 'skipped'); + if (allAlways && !anyNonSkipped) { + eligible = false; + } + if (abortUnrelated && deps.every((d) => d.on === 'success')) { + eligible = false; + } + } + } + + if (!eligible) { + terminalState.set(step.id, 'skipped'); + madeProgress = true; + continue; + } + + madeProgress = true; + const p = (async () => { + const ok = await this.runSingleStep( + wf, + step, + allServers, + req, + control, + stepOutputs, + captures, + ); + terminalState.set(step.id, ok ? 'succeeded' : 'failed'); + if (!ok && !control.abortController.signal.aborted) { + await this.handleStepFailure(wf, step, req, control); + const continueOnErr = + step.onFailure === 'continue' || + (typeof step.onFailure === 'object' && step.onFailure.action === 'continue'); + const forceAbort = + step.onFailure === 'abort' || + (typeof step.onFailure === 'object' && step.onFailure.action === 'abort'); + if (!continueOnErr) { + hasFatalFailure = true; + } + if (forceAbort || (wf.stopOnError && !continueOnErr)) { + abortUnrelated = true; + } + } + })() + .catch(() => { + terminalState.set(step.id, 'failed'); + hasFatalFailure = true; + if (wf.stopOnError && step.onFailure !== 'continue') { + abortUnrelated = true; + } + }) + .finally(() => { + runningPromises.delete(step.id); + }); + + runningPromises.set(step.id, p); + } + + if (runningPromises.size > 0) { + await Promise.race(runningPromises.values()); + } else if (!madeProgress) { + break; + } + } + + if (runningPromises.size > 0) { + await Promise.allSettled(runningPromises.values()); + } + + if (control.abortController.signal.aborted) { + return 'cancelled'; + } + return hasFatalFailure ? 'failed' : 'succeeded'; + } + + private async handleStepFailure( + wf: WorkflowConfig, + step: WorkflowStep, + req: QueuedRunRequest, + control: ActiveRunControl, + ): Promise { + const onFail = step.onFailure; + if (!onFail || onFail === 'abort' || onFail === 'continue') return; + + if (typeof onFail === 'string') { + const targetWf = this.configManager.getWorkflow(onFail); + if (targetWf) { + if (req.onFailureDepth < 1) { + await this.triggerWorkflow(targetWf.id, { + triggerSource: `onFailure:${wf.id}:${step.id}`, + onFailureDepth: req.onFailureDepth + 1, + }).catch(() => undefined); + } + } else if (this.failureNotifier) { + await this.failureNotifier( + onFail, + `Workflow "${wf.name}" (${wf.id}) failed at step "${step.id}" (run ${req.runId})`, + wf.id, + ).catch(() => undefined); + } + return; + } + + if (onFail.action === 'notify' && onFail.channelId && this.failureNotifier) { + await this.failureNotifier( + onFail.channelId, + `Workflow "${wf.name}" (${wf.id}) failed at step "${step.id}" (run ${req.runId})`, + wf.id, + ).catch(() => undefined); + } else if ( + onFail.action === 'run-workflow' && + onFail.workflowId && + req.onFailureDepth < 1 + ) { + await this.triggerWorkflow(onFail.workflowId, { + triggerSource: `onFailure:${wf.id}:${step.id}`, + onFailureDepth: req.onFailureDepth + 1, + }).catch(() => undefined); + } else { + void control; + } + } + + private async runSingleStep( + wf: WorkflowConfig, + step: WorkflowStep, + allServers: ServerConfig[], + req: QueuedRunRequest, + control: ActiveRunControl, + stepOutputs: Map, + captures: Map, + ): Promise { + const timeoutMs = (step.timeoutSec ?? 300) * 1000; + const stepAbort = new AbortController(); + const onParentAbort = () => stepAbort.abort(); + if (control.abortController.signal.aborted) { + return false; + } + control.abortController.signal.addEventListener('abort', onParentAbort, { once: true }); + + let timedOut = false; + const stepTimer = setTimeout(() => { + timedOut = true; + stepAbort.abort(); + }, timeoutMs); + stepTimer.unref(); + + const makeCtx = (serverId?: string): TemplateContext => ({ + workflowId: wf.id, + runId: req.runId, + serverId, + inputs: req.inputs, + stepOutputs, + captures, + eventMeta: req.eventMeta, + }); + + control.emitter.pushMeta({ event: 'step-start', stepId: step.id, type: step.type }); + + try { + if (step.type === 'transfer') { + const ctx = makeCtx(); + const srcServerId = interpolateValuePlain(step.source.serverId, ctx); + const srcPath = interpolateValuePlain(step.source.path, ctx); + const dstServerId = interpolateValuePlain(step.destination.serverId, ctx); + const dstPath = interpolateValuePlain(step.destination.path, ctx); + + const started = Date.now(); + try { + const xfer = await this.transferEngine.transfer({ + mode: step.mode, + source: { serverId: srcServerId, path: srcPath }, + destination: { serverId: dstServerId, path: dstPath }, + sudo: step.sudo, + timeoutMs, + signal: stepAbort.signal, + onProgress: (msg) => { + control.emitter.push('stdout', `[${step.id}] ${msg}\n`); + }, + }); + const summaryJson = JSON.stringify(xfer); + this.recordStepLog( + req.runId, + step.id, + `${srcServerId}->${dstServerId}`, + 0, + xfer.durationMs, + summaryJson, + '', + ); + stepOutputs.set(step.id, { stdout: xfer.destinationPath, exitCode: 0 }); + if (step.captureAs) captures.set(step.captureAs, xfer.destinationPath); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); + return true; + } catch (err) { + const msg = timedOut + ? `Step "${step.id}" timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err); + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + `${srcServerId}->${dstServerId}`, + 1, + Date.now() - started, + '', + msg, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + } + + const targets = resolveTargetServers(step.target, allServers, makeCtx()); + if (targets.length === 0) { + const msg = `No enabled target servers matched step "${step.id}"`; + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + + if (step.type === 'exec') { + let allOk = true; + const stdouts: string[] = []; + let lastExit: number | null = 0; + + await runWithConcurrency(targets, step.concurrency ?? wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const env = buildWorkflowEnv(ctx); + const cmd = interpolateShellCommandSafe(step.command, ctx); + try { + const res = await this.execStreamAbortable(srv.id, cmd, { + env, + sudo: step.sudo, + signal: stepAbort.signal, + onStdout: (txt) => control.emitter.push('stdout', `[${step.id}@${srv.id}] ${txt}`), + onStderr: (txt) => control.emitter.push('stderr', `[${step.id}@${srv.id}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + srv.id, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + stdouts.push(res.stdout); + lastExit = res.exitCode; + if (res.exitCode !== 0) allOk = false; + } catch (err) { + allOk = false; + lastExit = 1; + const msg = timedOut + ? `Timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = stdouts.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: lastExit }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } + + if (step.type === 'read-file') { + let allOk = true; + const contents: string[] = []; + + await runWithConcurrency(targets, wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const remotePath = interpolateValuePlain(step.path, ctx); + const tailRaw = + typeof step.tailLines === 'number' + ? step.tailLines + : typeof step.tailLines === 'string' + ? Number(interpolateValuePlain(step.tailLines, ctx)) + : undefined; + + try { + let text = ''; + try { + const fileRes = await this.sftpService.readTextFile(srv.id, remotePath, { + sudo: step.sudo, + }); + text = fileRes.content; + if (tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { + const lines = text.replace(/\n$/, '').split(/\r?\n/); + text = `${lines.slice(-Math.floor(tailRaw)).join('\n')}\n`; + } + } catch (readErr) { + const code = (readErr as { code?: string }).code; + if (code === 'FILE_TOO_LARGE' && tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { + const execRes = await this.execStreamAbortable( + srv.id, + `tail -n ${Math.floor(tailRaw)} -- ${posixSingleQuote(remotePath)}`, + { sudo: step.sudo, signal: stepAbort.signal }, + ); + if (execRes.exitCode !== 0) { + throw new Error(execRes.stderr.trim() || `tail failed for ${remotePath}`); + } + text = execRes.stdout; + } else { + throw readErr; + } + } + + control.emitter.push('stdout', `[${step.id}@${srv.id}] ${text}`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 0, + Date.now() - started, + text, + '', + ); + contents.push(text); + } catch (err) { + allOk = false; + const msg = err instanceof Error ? err.message : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = contents.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } + + // system-action step + const attachedTargets = targets.filter((s) => + s.systems.some((a) => a.systemId === step.systemId), + ); + if (attachedTargets.length === 0) { + const msg = `No matched server has system "${step.systemId}" attached`; + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return false; + } + + const system = this.configManager.getSystem(step.systemId); + const actionDef = system?.actions.find((a) => a.id === step.action); + let allOk = true; + const sysOutputs: string[] = []; + + await runWithConcurrency(attachedTargets, step.concurrency ?? wf.concurrency, async (srv) => { + const started = Date.now(); + const ctx = makeCtx(srv.id); + const itemSpec = interpolateValuePlain(step.item, ctx); + const subItemVal = step.subItem ? interpolateValuePlain(step.subItem, ctx) : undefined; + + try { + if (actionDef?.scope === 'system') { + const res = await this.customSystemsEngine.executeActionBlocking({ + serverId: srv.id, + systemId: step.systemId, + actionId: step.action, + timeoutMs, + signal: stepAbort.signal, + onChunk: (st, txt) => control.emitter.push(st, `[${step.id}@${srv.id}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + srv.id, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + sysOutputs.push(res.stdout); + if (res.exitCode !== 0) allOk = false; + return; + } + + let itemNames: string[]; + if (itemSpec === '*') { + const snap = await this.customSystemsEngine.getServerSystem(srv.id, step.systemId, { + forceRefresh: true, + }); + itemNames = snap.items.map((i) => i.name); + } else { + itemNames = [itemSpec]; + } + + if (itemNames.length === 0) { + this.recordStepLog( + req.runId, + step.id, + srv.id, + 0, + Date.now() - started, + `No discovered items for ${step.systemId}`, + '', + ); + return; + } + + for (const itemName of itemNames) { + const res = await this.customSystemsEngine.executeActionBlocking({ + serverId: srv.id, + systemId: step.systemId, + actionId: step.action, + itemName, + subItemName: subItemVal, + timeoutMs, + signal: stepAbort.signal, + onChunk: (st, txt) => + control.emitter.push(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), + }); + this.recordStepLog( + req.runId, + step.id, + `${srv.id}:${itemName}`, + res.exitCode, + res.durationMs, + res.stdout, + res.stderr, + ); + sysOutputs.push(res.stdout); + if (res.exitCode !== 0) allOk = false; + } + } catch (err) { + allOk = false; + const msg = err instanceof Error ? err.message : String(err); + control.emitter.push('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, srv.id, 1, Date.now() - started, '', msg); + } + }); + + const joined = sysOutputs.join('\n'); + stepOutputs.set(step.id, { stdout: joined, exitCode: allOk ? 0 : 1 }); + if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); + return allOk; + } finally { + clearTimeout(stepTimer); + control.abortController.signal.removeEventListener('abort', onParentAbort); + } + } + + private async execStreamAbortable( + serverId: string, + command: string, + opts: { + env?: Record; + sudo?: boolean; + signal: AbortSignal; + onStdout?: (text: string) => void; + onStderr?: (text: string) => void; + }, + ): Promise<{ exitCode: number | null; stdout: string; stderr: string; durationMs: number }> { + if (opts.signal.aborted) { + throw new Error('Workflow step aborted'); + } + + const started = Date.now(); + const handle = await this.sshPool.execStream(serverId, command, { + env: opts.env, + sudo: opts.sudo, + }); + + const outChunks: Buffer[] = []; + const errChunks: Buffer[] = []; + let outLen = 0; + let errLen = 0; + + return new Promise((resolve, reject) => { + let settled = false; + const cleanup = () => { + opts.signal.removeEventListener('abort', onAbort); + }; + const onAbort = () => { + handle.abort(); + if (!settled) { + settled = true; + cleanup(); + reject(new Error('Workflow step aborted')); + } + }; + + if (opts.signal.aborted) { + onAbort(); + return; + } + opts.signal.addEventListener('abort', onAbort, { once: true }); + + handle.channel.on('data', (chunk: Buffer) => { + if (outLen < MAX_OUTPUT_CHARS) { + outChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - outLen)); + outLen += chunk.length; + } + opts.onStdout?.(chunk.toString('utf8')); + }); + handle.channel.stderr?.on('data', (chunk: Buffer) => { + if (errLen < MAX_OUTPUT_CHARS) { + errChunks.push(chunk.subarray(0, MAX_OUTPUT_CHARS - errLen)); + errLen += chunk.length; + } + opts.onStderr?.(chunk.toString('utf8')); + }); + + handle.done + .then(({ exitCode }) => { + if (!settled) { + settled = true; + cleanup(); + resolve({ + exitCode, + stdout: Buffer.concat(outChunks).toString('utf8'), + stderr: Buffer.concat(errChunks).toString('utf8'), + durationMs: Date.now() - started, + }); + } + }) + .catch((err) => { + if (!settled) { + settled = true; + cleanup(); + reject(err); + } + }); + }); + } + + private recordStepLog( + runId: string, + stepId: string, + serverId: string, + exitCode: number | null, + durationMs: number, + stdout: string, + stderr: string, + ): void { + this.db + .prepare( + `INSERT INTO workflow_step_logs (run_id, step_id, server_id, exit_code, duration_ms, stdout, stderr, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + ) + .run( + runId, + stepId, + serverId, + exitCode, + Math.max(0, Math.round(durationMs)), + stdout.slice(0, MAX_OUTPUT_CHARS), + stderr.slice(0, MAX_OUTPUT_CHARS), + Date.now(), + ); + } + + private markRunFinished( + runId: string, + workflowId: string, + status: WorkflowRunStatus, + triggerSource: string, + startedAt: number, + cancelledBy: string | null, + ): void { + const finishedAt = Date.now(); + this.db + .prepare( + `UPDATE workflow_runs + SET status = ?, finished_at = ?, cancelled_by = ? + WHERE run_id = ?`, + ) + .run(status, finishedAt, cancelledBy, runId); + + this.broadcastRunFrame({ + runId, + workflowId, + status, + triggerSource, + startedAt, + finishedAt, + }); + } + + private broadcastRunFrame(frame: { + runId: string; + workflowId: string; + status: WorkflowRunStatus; + triggerSource: string; + startedAt: number; + finishedAt?: number | null; + }): void { + this.wsHub.broadcastChannel(WS_CHANNELS.WORKFLOWS, { + type: 'workflow:run', + ...frame, + }); + } + + private pruneRetainedStreams(): void { + const doneRuns = [...this.runsById.values()].filter((r) => r.done); + while (doneRuns.length > MAX_RETAINED_STREAM_RUNS) { + const oldest = doneRuns.shift()!; + this.runsById.delete(oldest.runId); + } + } +} From 7272ad58bd89189a2accdb88c82e8dc2210327fc Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:15:07 +0000 Subject: [PATCH 02/10] feat(alerts,api): implement AlertEngine, webhooks, silences, and Phase 4 REST/WS routes --- src/server/alerts/alert-engine.ts | 869 ++++++++++++++++++++++ src/server/api/routes/alerts.routes.ts | 143 ++++ src/server/api/routes/snippets.routes.ts | 120 +++ src/server/api/routes/workflows.routes.ts | 293 ++++++++ src/server/app.ts | 84 ++- 5 files changed, 1507 insertions(+), 2 deletions(-) create mode 100644 src/server/alerts/alert-engine.ts create mode 100644 src/server/api/routes/alerts.routes.ts create mode 100644 src/server/api/routes/snippets.routes.ts create mode 100644 src/server/api/routes/workflows.routes.ts diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts new file mode 100644 index 0000000..7dfc025 --- /dev/null +++ b/src/server/alerts/alert-engine.ts @@ -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; + +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(); + private readonly disconnectedSince = new Map(); + private readonly prevOnlineState = new Map(); + private readonly emittedOffline = new Set(); + private readonly prevProbeOk = new Map(); + private readonly prevSystemDown = new Set(); + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 = {}; + 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; + } +} diff --git a/src/server/api/routes/alerts.routes.ts b/src/server/api/routes/alerts.routes.ts new file mode 100644 index 0000000..bfb82f7 --- /dev/null +++ b/src/server/api/routes/alerts.routes.ts @@ -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; +} diff --git a/src/server/api/routes/snippets.routes.ts b/src/server/api/routes/snippets.routes.ts new file mode 100644 index 0000000..3696398 --- /dev/null +++ b/src/server/api/routes/snippets.routes.ts @@ -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; +} diff --git a/src/server/api/routes/workflows.routes.ts b/src/server/api/routes/workflows.routes.ts new file mode 100644 index 0000000..34c7809 --- /dev/null +++ b/src/server/api/routes/workflows.routes.ts @@ -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; +} diff --git a/src/server/app.ts b/src/server/app.ts index 524590a..54358a6 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -3,6 +3,10 @@ import http from 'node:http'; import path from 'node:path'; import type Database from 'better-sqlite3'; 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 { openDatabase } from './db/database.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 { TunnelManager } from './ssh/tunnel-manager.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 { createAuthRouter } from './api/routes/auth.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 +71,10 @@ export interface GCoordinatorInstance { customSystemsEngine: CustomSystemsEngine; serverInspector: ServerInspector; monitoringService: MonitoringService; + transferEngine: TransferEngine; + workflowEngine: WorkflowEngine; + broadcastService: BroadcastService; + alertEngine: AlertEngine; wsHub: WsHub; port: number; close(): Promise; @@ -144,6 +155,36 @@ 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, + ); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); @@ -178,7 +219,12 @@ 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 === 'metrics') { @@ -218,7 +264,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 +285,13 @@ export async function createGCoordinatorServer( monitoringService.start(); void tunnelManager.syncAutoStart(); customSystemsEngine.syncBackgroundChecks(); + workflowEngine.start(); + alertEngine.start(); vaultService.onPanicLock(() => { + alertEngine.handlePanicLock(); + workflowEngine.handlePanicLock(); + broadcastService.cancelAll(); monitoringService.stopAll(); customSystemsEngine.stopBackgroundChecks(); customSystemsEngine.cancelAllStreams(); @@ -261,6 +313,7 @@ export async function createGCoordinatorServer( if ( event.entityType === 'server' || event.entityType === 'system' || + event.entityType === 'workflow' || event.entityType === 'settings' || event.entityType === 'all' ) { @@ -279,6 +332,7 @@ export async function createGCoordinatorServer( } monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); + workflowEngine.syncCronJobs(); void tunnelManager.syncAutoStart(); } }); @@ -320,6 +374,7 @@ export async function createGCoordinatorServer( onVaultUnlocked: () => { monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); + workflowEngine.syncCronJobs(); void tunnelManager.syncAutoStart(); }, onVaultChanged: (snapshotReason) => { @@ -338,6 +393,24 @@ 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/servers/:id/sftp', createSftpRouter({ authService, configManager, auditService, sftpService }), @@ -409,9 +482,16 @@ export async function createGCoordinatorServer( customSystemsEngine, serverInspector, monitoringService, + transferEngine, + workflowEngine, + broadcastService, + alertEngine, wsHub, port: actualPort, async close() { + alertEngine.close(); + workflowEngine.close(); + broadcastService.cancelAll(); monitoringService.close(); customSystemsEngine.close(); tunnelManager.stopAll(); From 41e79c3df3aa9dd26a739c9c5585e1a003c95056 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:19:37 +0000 Subject: [PATCH 03/10] feat(client): add code-split Workflows, Broadcast, Snippets, Alerts views, pinned widgets, and service cron tasks --- src/client/index.html | 1 + src/client/ts/main.ts | 34 +- src/client/ts/state.ts | 1 + src/client/ts/views/alerts-view.ts | 430 +++++++++ src/client/ts/views/dashboard-view.ts | 101 ++- src/client/ts/views/section-shells.ts | 49 - src/client/ts/views/systems-view.ts | 194 +++- src/client/ts/views/workflows-view.ts | 1185 +++++++++++++++++++++++++ src/client/ts/ws-client.ts | 2 +- 9 files changed, 1925 insertions(+), 72 deletions(-) create mode 100644 src/client/ts/views/alerts-view.ts delete mode 100644 src/client/ts/views/section-shells.ts create mode 100644 src/client/ts/views/workflows-view.ts diff --git a/src/client/index.html b/src/client/index.html index 03dc22b..f58ec26 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -19,6 +19,7 @@ [OFFLINE] [VAULT] +
diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index 471210b..8f1f14d 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -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 { - state.overview = await apiFetch('/api/config/overview'); + const [overview, alertsSummary] = await Promise.all([ + apiFetch('/api/config/overview'), + apiFetch<{ activeCount: number }>('/api/alerts?limit=1').catch(() => ({ activeCount: 0 })), + ]); + state.overview = overview; + state.activeAlertCount = alertsSummary.activeCount ?? 0; updateTopBarUi(); } @@ -233,9 +246,14 @@ async function renderCurrentView(): Promise { 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); } } @@ -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(); + } } }); diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index ab52baa..cd0f705 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -103,6 +103,7 @@ export interface ClientState { safeMode: boolean; defaultMobileSafeMode: boolean; elevatedUntil: number | null; + activeAlertCount: number; theme: string; route: RouteId; selectedServerId?: string; diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts new file mode 100644 index 0000000..90cbec1 --- /dev/null +++ b/src/client/ts/views/alerts-view.ts @@ -0,0 +1,430 @@ +import { apiFetch } from '../api.js'; +import { confirmDialog } from '../dialogs.js'; +import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.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, +): Promise { + root.replaceChildren(); + const [data, credsRes] = await Promise.all([ + apiFetch('/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); + }); + + 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.`)), + 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); + }); + return b; + }); + 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)), + 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); + }); + 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); + }); + 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); + }; + + 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); +} diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts index 84a1b3f..2e4c106 100644 --- a/src/client/ts/views/dashboard-view.ts +++ b/src/client/ts/views/dashboard-view.ts @@ -229,7 +229,20 @@ export async function renderDashboardView( state: ClientState, ): Promise { 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 +365,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 === 'success' + ? 'badge badge-ok' + : runStatus === 'failed' || runStatus === 'timed-out' + ? '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( diff --git a/src/client/ts/views/section-shells.ts b/src/client/ts/views/section-shells.ts deleted file mode 100644 index d6f2b7e..0000000 --- a/src/client/ts/views/section-shells.ts +++ /dev/null @@ -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/.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); -} diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index be72041..7491f6f 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -513,26 +513,188 @@ 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', ); - 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)})`)); + toggleScheduleBtn.addEventListener('click', () => { + scheduleFormWrap.hidden = !scheduleFormWrap.hidden; + }); + + const refreshScopedTasks = async (): Promise => { + 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) { + 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 statusBadge = el( + 'span', + { + class: + entry.latestRun?.status === 'success' + ? 'badge badge-ok' + : entry.latestRun?.status === 'failed' + ? 'badge badge-err' + : 'badge', + }, + entry.latestRun?.status ?? 'idle', + ); + 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; } diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts new file mode 100644 index 0000000..52030d8 --- /dev/null +++ b/src/client/ts/views/workflows-view.ts @@ -0,0 +1,1185 @@ +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 type { MultiplexWsClient } from '../ws-client.js'; + +type WfSubTab = 'workflows' | 'broadcast' | 'snippets'; + +interface WorkflowInputDef { + name: string; + type: 'string' | 'number' | 'boolean' | 'server' | 'select'; + label?: string; + description?: string; + required?: boolean; + default?: string | number | boolean; + options?: string[]; +} + +interface WorkflowStepDef { + id: string; + type: 'exec' | 'read-file' | 'system-action' | 'transfer'; + dependsOn?: Array; + target?: { serverId?: string; tags?: string[]; all?: boolean }; + command?: string; + path?: string; + tailLines?: number | string; + systemId?: string; + action?: string; + item?: string; + subItem?: string; + mode?: 'hub-relayed' | 'direct'; + source?: { serverId: string; path: string }; + destination?: { serverId: string; path: string }; + timeoutSec?: number; + sudo?: boolean; + captureAs?: string; + onFailure?: string | { action: string; channelId?: string; workflowId?: string }; +} + +interface WorkflowConfigItem { + id: string; + name: string; + description?: string; + enabled: boolean; + trigger: + | { type: 'manual' } + | { type: 'cron'; expression: string; timezone: string } + | { type: 'event'; event: string }; + overlapPolicy: 'skip' | 'queue' | 'cancel-previous'; + stopOnError?: boolean; + concurrency?: number; + display: { mode: 'log' | 'file-view' | 'json' | 'table' | 'summary'; syntax?: string; pinToDashboard?: boolean }; + pinToDashboard?: boolean; + inputs: WorkflowInputDef[]; + steps: WorkflowStepDef[]; +} + +interface WorkflowRunItem { + runId: string; + workflowId: string; + triggerSource: string; + status: string; + startedAt: number; + finishedAt: number | null; + cancelledBy: string | null; +} + +interface WorkflowStepLogItem { + id: number; + runId: string; + stepId: string; + serverId: string; + exitCode: number | null; + durationMs: number; + stdout: string; + stderr: string; +} + +interface WorkflowSummaryEntry { + workflow: WorkflowConfigItem; + nextRunAt: number | null; + activeRunId: string | null; + queuedCount: number; + latestRun: WorkflowRunItem | null; + latestStepLogs: WorkflowStepLogItem[]; +} + +interface SnippetItem { + id: string; + name: string; + description?: string; + command: string; + tags: string[]; + inputs: WorkflowInputDef[]; + sudo: boolean; + confirm: boolean; +} + +let activeSubTab: WfSubTab = 'workflows'; +let selectedRunDetailId: string | null = null; +let broadcastPresetSnippetId: string | null = null; +let unsubWfWs: (() => void) | null = null; + +function statusBadgeClass(status: string): string { + if (status === 'succeeded' || status === 'ok') return 'badge badge-ok'; + if (status === 'running' || status === 'queued' || status === 'pending') return 'badge badge-warn'; + if (status === 'failed' || status === 'error' || status === 'cancelled') return 'badge badge-err'; + return 'badge'; +} + +function renderStructuredOutput( + host: HTMLElement, + wf: WorkflowConfigItem | null, + run: WorkflowRunItem, + stepLogs: WorkflowStepLogItem[], +): void { + host.replaceChildren(); + const mode = wf?.display?.mode ?? 'log'; + const hdr = el( + 'div', + { class: 'row-between' }, + el('strong', {}, `Run ${run.runId} (${run.workflowId}) — Display: ${mode}`), + el('span', { class: statusBadgeClass(run.status) }, `[${run.status.toUpperCase()}]`), + ); + host.append(hdr); + + if (stepLogs.length === 0) { + host.append(el('p', { class: 'muted' }, 'No step logs recorded for this run yet.')); + return; + } + + if (mode === 'summary') { + const okCount = stepLogs.filter((l) => l.exitCode === 0).length; + const failCount = stepLogs.length - okCount; + const totalMs = stepLogs.reduce((acc, l) => acc + l.durationMs, 0); + host.append( + el( + 'div', + { class: 'metric-grid', style: 'margin-top:8px' }, + el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'PASSED'), el('div', { class: 'metric-val ok-text' }, String(okCount))), + el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'FAILED'), el('div', { class: 'metric-val err-text' }, String(failCount))), + el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'TOTAL STEPS'), el('div', { class: 'metric-val' }, String(stepLogs.length))), + el('div', { class: 'metric-cell' }, el('div', { class: 'metric-label' }, 'DURATION'), el('div', { class: 'metric-val mono' }, `${totalMs}ms`)), + ), + ); + const last = stepLogs[stepLogs.length - 1]; + if (last?.stdout) { + host.append(el('pre', { class: 'stream-log mono', style: 'margin-top:8px' }, last.stdout.trim().slice(-2000))); + } + return; + } + + if (mode === 'json') { + const outObj = stepLogs.map((l) => { + let parsed: unknown = l.stdout.trim(); + try { + parsed = JSON.parse(l.stdout); + } catch { + // Leave as text + } + return { + stepId: l.stepId, + serverId: l.serverId, + exitCode: l.exitCode, + durationMs: l.durationMs, + stdout: parsed, + stderr: l.stderr.trim() || undefined, + }; + }); + host.append(el('pre', { class: 'diff-body mono', style: 'margin-top:8px' }, JSON.stringify(outObj, null, 2))); + return; + } + + if (mode === 'table') { + const tbl = el('table'); + tbl.append( + el('thead', {}, el('tr', {}, el('th', {}, 'Step'), el('th', {}, 'Server'), el('th', {}, 'Exit'), el('th', {}, 'Time'), el('th', {}, 'Output'))), + ); + const tbody = el('tbody'); + for (const l of stepLogs) { + tbody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, l.stepId), + el('td', { class: 'mono' }, l.serverId), + el('td', {}, el('span', { class: statusBadgeClass(l.exitCode === 0 ? 'ok' : 'error') }, String(l.exitCode ?? '—'))), + el('td', { class: 'mono' }, `${l.durationMs}ms`), + el('td', { class: 'mono' }, (l.stdout || l.stderr || '—').trim().slice(0, 140)), + ), + ); + } + tbl.append(tbody); + host.append(el('div', { class: 'table-wrap', style: 'margin-top:8px' }, tbl)); + return; + } + + if (mode === 'file-view') { + const combined = stepLogs + .map((l) => `# === ${l.stepId} @ ${l.serverId} ===\n${l.stdout}${l.stderr ? `\n[stderr] ${l.stderr}` : ''}`) + .join('\n'); + host.append(el('pre', { class: 'diff-body mono', style: 'margin-top:8px', 'data-syntax': wf?.display?.syntax ?? 'log' }, combined)); + return; + } + + // Default 'log' mode + const logText = stepLogs + .map((l) => `[${l.stepId} @ ${l.serverId}] exit=${String(l.exitCode)} (${l.durationMs}ms)\n${l.stdout}${l.stderr ? `[stderr]\n${l.stderr}\n` : ''}`) + .join('\n'); + host.append(el('pre', { class: 'stream-log mono', style: 'margin-top:8px' }, logText)); +} + +async function promptWorkflowInputs( + wfName: string, + defs: WorkflowInputDef[], + servers: ServerEntry[], +): Promise | null> { + if (defs.length === 0) return {}; + + return new Promise((resolve) => { + const dialog = document.createElement('dialog'); + dialog.className = 'dialog-wide'; + dialog.setAttribute('aria-labelledby', 'wf-inputs-title'); + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel'); + const fields = new Map(); + const formFields = el('div', { class: 'stack' }); + + for (const def of defs) { + let ctrl: HTMLInputElement | HTMLSelectElement; + if (def.type === 'server') { + const sel = el('select', { required: def.required }); + for (const s of servers) { + sel.append(el('option', { value: s.config.id, selected: def.default === s.config.id }, `${s.config.name} (${s.config.id})`)); + } + ctrl = sel; + } else if (def.type === 'select' && def.options) { + const sel = el('select', { required: def.required }); + for (const o of def.options) { + sel.append(el('option', { value: o, selected: def.default === o }, o)); + } + ctrl = sel; + } else if (def.type === 'boolean') { + ctrl = el('input', { type: 'checkbox', checked: Boolean(def.default) }); + } else { + ctrl = el('input', { + type: def.type === 'number' ? 'number' : 'text', + value: def.default !== undefined ? String(def.default) : '', + required: def.required, + placeholder: def.description ?? def.name, + }); + } + fields.set(def.name, ctrl); + formFields.append(el('label', {}, `${def.label ?? def.name} (${def.type})`), ctrl); + } + + const form = el( + 'form', + { class: 'stack' }, + formFields, + el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Execute')), + ); + + let done = false; + const finish = (val: Record | null) => { + if (done) return; + done = true; + if (dialog.open) dialog.close(); + dialog.remove(); + resolve(val); + }; + + closeBtn.addEventListener('click', () => finish(null)); + dialog.addEventListener('close', () => finish(null)); + form.addEventListener('submit', (ev) => { + ev.preventDefault(); + const values: Record = {}; + for (const def of defs) { + const node = fields.get(def.name)!; + if (def.type === 'boolean') values[def.name] = (node as HTMLInputElement).checked; + else if (def.type === 'number') values[def.name] = Number(node.value); + else values[def.name] = node.value; + } + finish(values); + }); + + dialog.append(el('h1', { id: 'wf-inputs-title' }, `Inputs: ${wfName}`), form); + document.body.append(dialog); + dialog.showModal(); + }); +} + +function openWorkflowEditorDialog( + existing: WorkflowConfigItem | null, + servers: ServerEntry[], + systems: Array<{ system: { id: string; name: string; actions: Array<{ id: string; label: string }> } }>, + onSaved: () => Promise, +): void { + const dialog = document.createElement('dialog'); + dialog.className = 'dialog-wide'; + dialog.setAttribute('aria-labelledby', 'wf-edit-title'); + + const idInput = el('input', { + value: existing?.id ?? '', + placeholder: 'nightly-health-check', + readonly: Boolean(existing), + required: true, + }); + const nameInput = el('input', { + value: existing?.name ?? '', + placeholder: 'Nightly Health Check', + required: true, + }); + const descInput = el('input', { + value: existing?.description ?? '', + placeholder: 'Optional description', + }); + const enabledChk = el('input', { + type: 'checkbox', + checked: existing ? existing.enabled : true, + }); + const trigSel = el( + 'select', + {}, + el('option', { value: 'manual', selected: !existing || existing.trigger.type === 'manual' }, 'manual'), + el('option', { value: 'cron', selected: existing?.trigger.type === 'cron' }, 'cron'), + el('option', { value: 'event', selected: existing?.trigger.type === 'event' }, 'event'), + ); + const cronExprInput = el('input', { + value: existing?.trigger.type === 'cron' ? existing.trigger.expression : '0 * * * *', + placeholder: '0 3 * * *', + }); + const cronTzInput = el('input', { + value: existing?.trigger.type === 'cron' ? existing.trigger.timezone : 'UTC', + placeholder: 'UTC', + }); + const eventSel = el( + 'select', + {}, + ...['server.offline', 'server.online', 'probe.failed', 'system.unhealthy', 'alert.fired'].map( + (evName) => + el( + 'option', + { + value: evName, + selected: existing?.trigger.type === 'event' && existing.trigger.event === evName, + }, + evName, + ), + ), + ); + const trigDetailBox = el('div', { class: 'grid-2' }); + const redrawTrigDetail = () => { + trigDetailBox.replaceChildren(); + if (trigSel.value === 'cron') { + trigDetailBox.append( + el('div', {}, el('label', {}, 'Cron Expression'), cronExprInput), + el('div', {}, el('label', {}, 'Timezone'), cronTzInput), + ); + } else if (trigSel.value === 'event') { + trigDetailBox.append(el('div', {}, el('label', {}, 'System Event'), eventSel)); + } + }; + trigSel.addEventListener('change', redrawTrigDetail); + redrawTrigDetail(); + + const overlapSel = el( + 'select', + {}, + el('option', { value: 'skip', selected: !existing || existing.overlapPolicy === 'skip' }, 'skip'), + el('option', { value: 'queue', selected: existing?.overlapPolicy === 'queue' }, 'queue'), + el('option', { value: 'cancel-previous', selected: existing?.overlapPolicy === 'cancel-previous' }, 'cancel-previous'), + ); + const displaySel = el( + 'select', + {}, + ...(['log', 'file-view', 'json', 'table', 'summary'] as const).map((m) => + el('option', { value: m, selected: (existing?.display.mode ?? 'log') === m }, m), + ), + ); + const stopOnErrChk = el('input', { + type: 'checkbox', + checked: existing ? existing.stopOnError !== false : true, + }); + const pinChk = el('input', { + type: 'checkbox', + checked: Boolean(existing?.display.pinToDashboard || existing?.pinToDashboard), + }); + + const draftSteps: WorkflowStepDef[] = existing?.steps + ? existing.steps.map((s) => ({ ...s })) + : [ + { + id: 'step-1', + type: 'exec', + target: { all: true }, + command: 'uname -a', + sudo: false, + }, + ]; + + const stepsHost = el('div', { class: 'stack' }); + const redrawSteps = () => { + stepsHost.replaceChildren(); + draftSteps.forEach((step, idx) => { + const card = el('div', { class: 'panel' }); + const sId = el('input', { class: 'input-sm', value: step.id, placeholder: 'step-id' }); + sId.addEventListener('input', () => { + step.id = sId.value.trim(); + }); + + const sType = el( + 'select', + { class: 'input-sm' }, + ...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) => + el('option', { value: t, selected: step.type === t }, t), + ), + ); + sType.addEventListener('change', () => { + step.type = sType.value as WorkflowStepDef['type']; + if (step.type === 'transfer' && !step.source) { + step.mode = 'hub-relayed'; + step.source = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file' }; + step.destination = { serverId: servers[0]?.config.id ?? 'srv-1', path: '/tmp/file.bak' }; + } + redrawSteps(); + }); + + const depsVal = (step.dependsOn ?? []) + .map((d) => (typeof d === 'string' ? d : d.on === 'success' ? d.stepId : `${d.stepId}:${d.on}`)) + .join(', '); + const sDeps = el('input', { + class: 'input-sm', + value: depsVal, + placeholder: 'dependsOn (e.g. step-1, step-2:failure)', + }); + sDeps.addEventListener('input', () => { + const tokens = sDeps.value + .split(',') + .map((x) => x.trim()) + .filter(Boolean); + step.dependsOn = tokens.map((tok) => { + const [stepId, onRaw] = tok.split(':'); + if (onRaw === 'failure' || onRaw === 'always' || onRaw === 'success') { + return { stepId: stepId!, on: onRaw }; + } + return stepId!; + }); + }); + + const rmBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Remove'); + rmBtn.addEventListener('click', () => { + if (draftSteps.length <= 1) return; + draftSteps.splice(idx, 1); + redrawSteps(); + }); + + card.append( + el( + 'div', + { class: 'row-between' }, + el('strong', {}, `Step #${idx + 1}`), + el('div', { class: 'row' }, sId, sType, rmBtn), + ), + sDeps, + ); + + if (step.type === 'transfer') { + const modeSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: 'hub-relayed', selected: (step.mode ?? 'hub-relayed') === 'hub-relayed' }, 'hub-relayed'), + el('option', { value: 'direct', selected: step.mode === 'direct' }, 'direct (rsync)'), + ); + const srcSrv = el('input', { class: 'input-sm', value: step.source?.serverId ?? '', placeholder: 'Source Server ID' }); + const srcPath = el('input', { class: 'input-sm', value: step.source?.path ?? '', placeholder: 'Source Path' }); + const dstSrv = el('input', { class: 'input-sm', value: step.destination?.serverId ?? '', placeholder: 'Dest Server ID' }); + const dstPath = el('input', { class: 'input-sm', value: step.destination?.path ?? '', placeholder: 'Dest Path' }); + const syncXfer = () => { + step.mode = modeSel.value as 'hub-relayed' | 'direct'; + step.source = { serverId: srcSrv.value.trim(), path: srcPath.value.trim() }; + step.destination = { serverId: dstSrv.value.trim(), path: dstPath.value.trim() }; + }; + [modeSel, srcSrv, srcPath, dstSrv, dstPath].forEach((n) => n.addEventListener('input', syncXfer)); + card.append( + el('div', { class: 'grid-2', style: 'margin-top:6px' }, srcSrv, srcPath, dstSrv, dstPath), + el('div', { class: 'row', style: 'margin-top:6px' }, el('span', { class: 'muted' }, 'Mode:'), modeSel), + ); + } else { + const tgtVal = step.target?.all + ? 'all' + : step.target?.tags?.length + ? `tags:${step.target.tags.join(',')}` + : step.target?.serverId ?? 'all'; + const tgtInput = el('input', { + class: 'input-sm', + value: tgtVal, + placeholder: 'all | server-id | tags:prod,web', + }); + tgtInput.addEventListener('input', () => { + const v = tgtInput.value.trim(); + if (!v || v === 'all') step.target = { all: true }; + else if (v.startsWith('tags:')) { + step.target = { tags: v.slice(5).split(',').map((t) => t.trim()).filter(Boolean) }; + } else { + step.target = { serverId: v }; + } + }); + + const sudoChk = el('input', { type: 'checkbox', checked: Boolean(step.sudo) }); + sudoChk.addEventListener('change', () => { + step.sudo = sudoChk.checked; + }); + + const capInput = el('input', { + class: 'input-sm', + value: step.captureAs ?? '', + placeholder: 'captureAs (optional)', + }); + capInput.addEventListener('input', () => { + step.captureAs = capInput.value.trim() || undefined; + }); + + card.append( + el('div', { class: 'row', style: 'margin-top:6px' }, el('span', { class: 'muted' }, 'Target:'), tgtInput, el('label', { class: 'chk-row' }, sudoChk, 'sudo'), capInput), + ); + + if (step.type === 'exec') { + const cmdArea = el('textarea', { rows: 2, placeholder: 'Shell command (e.g. df -h)' }, step.command ?? ''); + cmdArea.value = step.command ?? ''; + cmdArea.addEventListener('input', () => { + step.command = cmdArea.value; + }); + card.append(cmdArea); + } else if (step.type === 'read-file') { + const pIn = el('input', { class: 'input-sm', value: step.path ?? '/var/log/syslog', placeholder: 'Remote file path' }); + const tailIn = el('input', { class: 'input-sm', value: step.tailLines !== undefined ? String(step.tailLines) : '', placeholder: 'tailLines (optional)' }); + pIn.addEventListener('input', () => { + step.path = pIn.value.trim(); + }); + tailIn.addEventListener('input', () => { + const raw = tailIn.value.trim(); + step.tailLines = !raw ? undefined : /^\d+$/.test(raw) ? Number(raw) : raw; + }); + card.append(el('div', { class: 'grid-2', style: 'margin-top:6px' }, pIn, tailIn)); + } else { + const sysIn = el('input', { + class: 'input-sm', + value: step.systemId ?? systems[0]?.system.id ?? 'docker-compose', + placeholder: 'systemId', + }); + const actIn = el('input', { + class: 'input-sm', + value: step.action ?? systems[0]?.system.actions[0]?.id ?? 'restart', + placeholder: 'action', + }); + const itemIn = el('input', { + class: 'input-sm', + value: step.item ?? '*', + placeholder: 'item or *', + }); + const syncSys = () => { + step.systemId = sysIn.value.trim(); + step.action = actIn.value.trim(); + step.item = itemIn.value.trim() || '*'; + }; + [sysIn, actIn, itemIn].forEach((n) => n.addEventListener('input', syncSys)); + syncSys(); + card.append(el('div', { class: 'grid-3', style: 'margin-top:6px' }, sysIn, actIn, itemIn)); + } + } + stepsHost.append(card); + }); + }; + redrawSteps(); + + const addStepBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '+ Add Step'); + addStepBtn.addEventListener('click', () => { + draftSteps.push({ + id: `step-${draftSteps.length + 1}`, + type: 'exec', + target: { all: true }, + command: 'echo ok', + sudo: false, + }); + redrawSteps(); + }); + + const msgEl = el('p', { class: 'form-msg err-text' }); + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel'); + closeBtn.addEventListener('click', () => { + if (dialog.open) dialog.close(); + }); + + const form = el( + 'form', + { class: 'stack' }, + el('div', { class: 'grid-2' }, + el('div', {}, el('label', {}, 'Workflow ID'), idInput), + el('div', {}, el('label', {}, 'Name'), nameInput), + ), + el('div', {}, el('label', {}, 'Description'), descInput), + el('div', { class: 'grid-3' }, + el('div', {}, el('label', {}, 'Trigger'), trigSel), + el('div', {}, el('label', {}, 'Overlap Policy'), overlapSel), + el('div', {}, el('label', {}, 'Display Mode'), displaySel), + ), + trigDetailBox, + el('div', { class: 'row' }, + el('label', { class: 'chk-row' }, enabledChk, 'Enabled'), + el('label', { class: 'chk-row' }, stopOnErrChk, 'Stop on Error'), + el('label', { class: 'chk-row' }, pinChk, 'Pin to Dashboard'), + ), + el('div', { class: 'row-between' }, el('h2', {}, 'DAG Steps'), addStepBtn), + stepsHost, + msgEl, + el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Save Workflow')), + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + msgEl.textContent = ''; + + const trigger = + trigSel.value === 'cron' + ? { type: 'cron', expression: cronExprInput.value.trim(), timezone: cronTzInput.value.trim() || 'UTC' } + : trigSel.value === 'event' + ? { type: 'event', event: eventSel.value } + : { type: 'manual' }; + + const payload = { + id: idInput.value.trim(), + name: nameInput.value.trim(), + description: descInput.value.trim() || undefined, + enabled: enabledChk.checked, + trigger, + overlapPolicy: overlapSel.value, + stopOnError: stopOnErrChk.checked, + display: { + mode: displaySel.value, + pinToDashboard: pinChk.checked, + }, + pinToDashboard: pinChk.checked, + inputs: existing?.inputs ?? [], + steps: draftSteps, + }; + + try { + await apiFetch( + existing ? `/api/workflows/${encodeURIComponent(existing.id)}` : '/api/workflows', + { method: existing ? 'PUT' : 'POST', body: payload }, + ); + if (dialog.open) dialog.close(); + await onSaved(); + } catch (err) { + msgEl.textContent = extractErrorMessage(err); + } + }); + + dialog.append(el('h1', { id: 'wf-edit-title' }, existing ? `Edit Workflow: ${existing.id}` : 'Create Workflow'), form); + dialog.addEventListener('close', () => dialog.remove()); + document.body.append(dialog); + dialog.showModal(); +} + +export async function renderWorkflowsView( + root: HTMLElement, + state: ClientState, + wsClient: MultiplexWsClient, +): Promise { + if (unsubWfWs) { + unsubWfWs(); + unsubWfWs = null; + } + wsClient.subscribe(['workflows']); + root.replaceChildren(); + + const tabBar = el( + 'div', + { class: 'row' }, + ...([ + ['workflows', 'Workflows & Runs'], + ['broadcast', 'Ad-Hoc Fleet Broadcast'], + ['snippets', 'Command Snippets'], + ] as const).map(([id, label]) => { + const btn = el( + 'button', + { type: 'button', class: `btn btn-sm${activeSubTab === id ? ' btn-primary' : ''}` }, + label, + ); + btn.addEventListener('click', () => { + activeSubTab = id; + void renderWorkflowsView(root, state, wsClient); + }); + return btn; + }), + ); + + root.append( + el( + 'section', + { class: 'panel row-between' }, + el('div', {}, el('h1', {}, 'Automation, Broadcast & Snippets'), el('p', { class: 'muted' }, 'DAG workflows, croner triggers, hub-relayed transfers, and saved snippets.')), + tabBar, + ), + ); + + const [serversRes, snippetsRes] = await Promise.all([ + apiFetch<{ servers: ServerEntry[] }>('/api/servers'), + apiFetch<{ snippets: SnippetItem[] }>('/api/snippets'), + ]); + const servers = serversRes.servers; + const snippets = snippetsRes.snippets; + + if (activeSubTab === 'workflows') { + const [wfRes, runsRes, sysRes] = await Promise.all([ + apiFetch<{ workflows: WorkflowSummaryEntry[] }>('/api/workflows'), + apiFetch<{ runs: WorkflowRunItem[] }>('/api/workflows/runs?limit=25'), + apiFetch<{ systems: Array<{ system: { id: string; name: string; actions: Array<{ id: string; label: string }> } }> }>('/api/systems'), + ]); + + const previewBox = el('section', { class: 'panel', hidden: true }); + const streamPanel = el('section', { class: 'panel', hidden: true }); + const detailPanel = el('section', { class: 'panel', hidden: true }); + + const newBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, '+ New Workflow'); + newBtn.addEventListener('click', () => { + openWorkflowEditorDialog(null, servers, sysRes.systems, () => renderWorkflowsView(root, state, wsClient)); + }); + const refBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh'); + refBtn.addEventListener('click', () => { + void renderWorkflowsView(root, state, wsClient); + }); + + const wfSection = el('section', { class: 'panel panel-region' }); + wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, refBtn))); + + const watchRunStream = (runId: string, wfId: string) => { + streamPanel.hidden = false; + const logPre = el('pre', { class: 'stream-log mono' }, `Subscribed to live run ${runId} (${wfId})...\n`); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel Run'); + cancelBtn.addEventListener('click', async () => { + cancelBtn.disabled = true; + await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }); + }); + streamPanel.replaceChildren( + el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn), + logPre, + ); + + if (unsubWfWs) unsubWfWs(); + unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { + if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { + if (frame.stream !== 'meta') { + logPre.textContent += frame.data; + logPre.scrollTop = logPre.scrollHeight; + } else { + try { + const m = JSON.parse(frame.data) as { event?: string; status?: string }; + if (m.event === 'done') { + cancelBtn.disabled = true; + selectedRunDetailId = runId; + void loadRunDetail(runId); + } + } catch { + // Ignore meta parse error + } + } + } + }); + wsClient.subscribe([`stream:wf:${runId}`]); + }; + + const loadRunDetail = async (runId: string) => { + const res = await apiFetch<{ + run: WorkflowRunItem; + stepLogs: WorkflowStepLogItem[]; + workflow: WorkflowConfigItem | null; + }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); + detailPanel.hidden = false; + renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); + }; + + if (wfRes.workflows.length === 0) { + wfSection.append(el('p', { class: 'muted' }, 'No workflows configured yet. Click "+ New Workflow" to create one.')); + } else { + for (const item of wfRes.workflows) { + const wf = item.workflow; + const trigText = + wf.trigger.type === 'cron' + ? `CRON "${wf.trigger.expression}" (${wf.trigger.timezone}) | Next: ${fmtTime(item.nextRunAt)}` + : wf.trigger.type === 'event' + ? `EVENT: ${wf.trigger.event}` + : 'MANUAL'; + + const dryBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Dry-Run'); + dryBtn.addEventListener('click', async () => { + const inp = await promptWorkflowInputs(wf.name, wf.inputs, servers); + if (!inp) return; + const dry = await apiFetch<{ + plan: { + workflowId: string; + inputs: Record; + steps: Array<{ + stepId: string; + type: string; + wave: number; + targets: Array<{ serverId: string }>; + renderedCommand?: string; + renderedPath?: string; + transferPreview?: { mode: string; sourceServerId: string; sourcePath: string; destinationServerId: string; destinationPath: string }; + }>; + }; + }>(`/api/workflows/${encodeURIComponent(wf.id)}/dry-run`, { + method: 'POST', + body: { inputs: inp }, + }); + const closePreviewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close'); + closePreviewBtn.addEventListener('click', () => { previewBox.hidden = true; }); + previewBox.hidden = false; + previewBox.replaceChildren( + el('div', { class: 'row-between' }, el('strong', {}, `Dry-Run Preview: ${wf.name}`), closePreviewBtn), + el('pre', { class: 'diff-body mono', style: 'margin-top:8px' }, JSON.stringify(dry.plan, null, 2)), + ); + }); + + const runBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Run Now'); + runBtn.addEventListener('click', async () => { + const inp = await promptWorkflowInputs(wf.name, wf.inputs, servers); + if (!inp) return; + const triggered = await apiFetch<{ runId: string; status: string }>( + `/api/workflows/${encodeURIComponent(wf.id)}/run`, + { method: 'POST', body: { inputs: inp } }, + ); + if (triggered.status !== 'skipped') { + watchRunStream(triggered.runId, wf.id); + } else { + previewBox.hidden = false; + previewBox.replaceChildren(el('p', { class: 'warn-text' }, `Run ${triggered.runId} skipped due to overlapPolicy="skip".`)); + } + }); + + const editBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Edit'); + editBtn.addEventListener('click', () => { + openWorkflowEditorDialog(wf, servers, sysRes.systems, () => renderWorkflowsView(root, state, wsClient)); + }); + + const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); + delBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Delete workflow "${wf.id}"?`); + if (!ok) return; + await apiFetch(`/api/workflows/${encodeURIComponent(wf.id)}`, { method: 'DELETE' }); + await renderWorkflowsView(root, state, wsClient); + }); + + wfSection.append( + el( + 'div', + { class: 'panel' }, + el( + 'div', + { class: 'row-between' }, + el( + 'div', + {}, + el('strong', {}, `${wf.name} `), + el('span', { class: 'mono muted' }, `(${wf.id})`), + wf.display.pinToDashboard || wf.pinToDashboard + ? el('span', { class: 'badge badge-ok' }, '[PINNED]') + : '', + item.latestRun + ? el('span', { class: statusBadgeClass(item.latestRun.status) }, `[LAST: ${item.latestRun.status.toUpperCase()}]`) + : '', + ), + el('div', { class: 'row' }, dryBtn, runBtn, editBtn, delBtn), + ), + el('div', { class: 'mono muted', style: 'margin-top:4px' }, `${trigText} | Overlap: ${wf.overlapPolicy} | Mode: ${wf.display.mode} | Steps: ${wf.steps.length}${item.queuedCount > 0 ? ` | Queued: ${item.queuedCount}` : ''}`), + ), + ); + } + } + + const runsSection = el('section', { class: 'panel panel-region' }); + runsSection.append(el('h2', {}, `Recent Runs (${runsRes.runs.length})`)); + const rTbl = el('table'); + rTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Run ID'), el('th', {}, 'Workflow'), el('th', {}, 'Trigger'), el('th', {}, 'Status'), el('th', {}, 'Started'), el('th', {}, 'Actions')))); + const rBody = el('tbody'); + if (runsRes.runs.length === 0) { + rBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No workflow runs yet.'))); + } else { + for (const r of runsRes.runs) { + const inspectBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Output'); + inspectBtn.addEventListener('click', () => { + selectedRunDetailId = r.runId; + void loadRunDetail(r.runId); + }); + const actRow = el('div', { class: 'row' }, inspectBtn); + if (r.status === 'running' || r.status === 'queued') { + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Cancel'); + cancelBtn.addEventListener('click', async () => { + await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' }); + await renderWorkflowsView(root, state, wsClient); + }); + actRow.append(cancelBtn); + } + rBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, r.runId), + el('td', { class: 'mono' }, r.workflowId), + el('td', { class: 'mono' }, r.triggerSource), + el('td', {}, el('span', { class: statusBadgeClass(r.status) }, `[${r.status.toUpperCase()}]`)), + el('td', { class: 'mono' }, fmtTime(r.startedAt)), + el('td', {}, actRow), + ), + ); + } + } + rTbl.append(rBody); + runsSection.append(el('div', { class: 'table-wrap' }, rTbl)); + + root.append(wfSection, previewBox, streamPanel, detailPanel, runsSection); + if (selectedRunDetailId) { + void loadRunDetail(selectedRunDetailId).catch(() => undefined); + } + return; + } + + if (activeSubTab === 'broadcast') { + const panel = el('section', { class: 'panel' }); + const modeSel = el( + 'select', + {}, + el('option', { value: 'adhoc' }, 'Ad-Hoc Shell Command'), + el('option', { value: 'snippet', selected: Boolean(broadcastPresetSnippetId) }, 'Saved Command Snippet'), + ); + const snipSel = el( + 'select', + {}, + ...snippets.map((s) => + el('option', { value: s.id, selected: broadcastPresetSnippetId === s.id }, `${s.name} (${s.id})`), + ), + ); + const cmdArea = el('textarea', { rows: 3, placeholder: 'uptime && free -m' }); + const sudoChk = el('input', { type: 'checkbox' }); + const concInput = el('input', { type: 'number', min: 1, max: 32, value: '4' }); + const tgtModeSel = el( + 'select', + {}, + el('option', { value: 'all' }, 'All Enabled Servers'), + el('option', { value: 'tags' }, 'Filter by Tags'), + el('option', { value: 'selected' }, 'Select Specific Servers'), + ); + const tagsInput = el('input', { placeholder: 'prod, web' }); + const srvChecks = new Map(); + const srvChecksBox = el('div', { class: 'chip-list' }); + for (const s of servers.filter((x) => x.config.enabled)) { + const c = el('input', { type: 'checkbox', checked: true }); + srvChecks.set(s.config.id, c); + srvChecksBox.append(el('label', { class: 'chk-row mono' }, c, s.config.id)); + } + + const modeBox = el('div', { class: 'stack' }); + const tgtBox = el('div', { class: 'stack' }); + const redrawBroadcastForm = () => { + modeBox.replaceChildren(); + if (modeSel.value === 'snippet' && snippets.length > 0) { + const chosen = snippets.find((s) => s.id === snipSel.value); + modeBox.append( + el('label', {}, 'Snippet'), + snipSel, + el('div', { class: 'mono muted' }, chosen?.command ?? ''), + ); + } else { + modeBox.append(el('label', {}, 'Ad-Hoc Command'), cmdArea); + } + tgtBox.replaceChildren(); + if (tgtModeSel.value === 'tags') tgtBox.append(el('label', {}, 'Tags (comma-separated)'), tagsInput); + else if (tgtModeSel.value === 'selected') tgtBox.append(srvChecksBox); + }; + modeSel.addEventListener('change', redrawBroadcastForm); + snipSel.addEventListener('change', redrawBroadcastForm); + tgtModeSel.addEventListener('change', redrawBroadcastForm); + redrawBroadcastForm(); + + const msgEl = el('p', { class: 'form-msg' }); + const cardsGrid = el('div', { class: 'grid-2' }); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action', hidden: true }, 'Cancel Broadcast'); + let activeJobId: string | null = null; + cancelBtn.addEventListener('click', async () => { + if (!activeJobId) return; + cancelBtn.disabled = true; + await apiFetch(`/api/workflows/broadcast/${encodeURIComponent(activeJobId)}/cancel`, { method: 'POST' }); + }); + + const form = el( + 'form', + { class: 'stack' }, + el('div', { class: 'grid-3' }, + el('div', {}, el('label', {}, 'Source'), modeSel), + el('div', {}, el('label', {}, 'Target Scope'), tgtModeSel), + el('div', {}, el('label', {}, 'Concurrency'), concInput), + ), + modeBox, + tgtBox, + el('div', { class: 'row-between' }, el('label', { class: 'chk-row' }, sudoChk, 'Run with sudo'), el('div', { class: 'row' }, cancelBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Run Fleet Broadcast'))), + msgEl, + ); + + form.addEventListener('submit', async (ev) => { + ev.preventDefault(); + msgEl.textContent = ''; + cardsGrid.replaceChildren(); + + const target: { all?: boolean; tags?: string[]; serverIds?: string[] } = + tgtModeSel.value === 'tags' + ? { tags: tagsInput.value.split(',').map((t) => t.trim()).filter(Boolean) } + : tgtModeSel.value === 'selected' + ? { serverIds: [...srvChecks.entries()].filter(([, chk]) => chk.checked).map(([id]) => id) } + : { all: true }; + + try { + const res = await apiFetch<{ + job: { + jobId: string; + targets: Array<{ serverId: string; serverName: string; status: string }>; + }; + }>('/api/workflows/broadcast', { + method: 'POST', + body: { + snippetId: modeSel.value === 'snippet' ? snipSel.value : undefined, + command: modeSel.value === 'adhoc' ? cmdArea.value : undefined, + sudo: sudoChk.checked, + concurrency: Number(concInput.value || 4), + target, + }, + }); + + activeJobId = res.job.jobId; + cancelBtn.hidden = false; + cancelBtn.disabled = false; + const cardMap = new Map(); + + for (const t of res.job.targets) { + const badge = el('span', { class: 'badge badge-warn' }, '[PENDING]'); + const pre = el('pre', { class: 'stream-log mono', style: 'max-height:180px' }); + cardMap.set(t.serverId, { badge, pre }); + cardsGrid.append( + el('article', { class: 'panel' }, el('div', { class: 'row-between' }, el('strong', {}, `${t.serverName} (${t.serverId})`), badge), pre), + ); + } + + if (unsubWfWs) unsubWfWs(); + unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { + if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return; + try { + const m = JSON.parse(frame.data) as { + event?: string; + serverId?: string; + data?: string; + status?: string; + exitCode?: number | null; + okCount?: number; + total?: number; + }; + if (m.event === 'server-start' && m.serverId) { + const card = cardMap.get(m.serverId); + if (card) { + card.badge.className = 'badge badge-warn'; + card.badge.textContent = '[RUNNING]'; + } + } else if (m.event === 'server-output' && m.serverId && m.data) { + const card = cardMap.get(m.serverId); + if (card) { + card.pre.textContent += m.data; + card.pre.scrollTop = card.pre.scrollHeight; + } + } else if (m.event === 'server-exit' && m.serverId) { + const card = cardMap.get(m.serverId); + if (card) { + card.badge.className = statusBadgeClass(m.status ?? 'error'); + card.badge.textContent = `[${String(m.status).toUpperCase()} exit=${String(m.exitCode)}]`; + } + } else if (m.event === 'done') { + cancelBtn.hidden = true; + msgEl.className = 'form-msg ok-text'; + msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`; + } + } catch { + // Ignore meta parse error + } + }); + wsClient.subscribe([`stream:${activeJobId}`]); + } catch (err) { + msgEl.className = 'form-msg err-text'; + msgEl.textContent = extractErrorMessage(err); + } + }); + + panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form); + root.append(panel, cardsGrid); + return; + } + + // Command Snippets tab + const listPanel = el('section', { class: 'panel panel-region' }); + listPanel.append(el('h2', {}, `Saved Command Snippets (${snippets.length})`)); + const sTbl = el('table'); + sTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Name'), el('th', {}, 'Command'), el('th', {}, 'Flags'), el('th', {}, 'Actions')))); + const sBody = el('tbody'); + for (const s of snippets) { + const bcastBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Broadcast →'); + bcastBtn.addEventListener('click', () => { + broadcastPresetSnippetId = s.id; + activeSubTab = 'broadcast'; + void renderWorkflowsView(root, state, wsClient); + }); + const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); + delBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Delete snippet "${s.id}"?`); + if (!ok) return; + await apiFetch(`/api/snippets/${encodeURIComponent(s.id)}`, { method: 'DELETE' }); + await renderWorkflowsView(root, state, wsClient); + }); + sBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, s.id), + el('td', {}, s.name), + el('td', { class: 'mono' }, s.command), + el('td', { class: 'mono' }, `${s.sudo ? 'sudo ' : ''}${s.confirm ? 'confirm ' : ''}${s.tags.join(',')}`), + el('td', {}, el('div', { class: 'row' }, bcastBtn, delBtn)), + ), + ); + } + sTbl.append(sBody); + listPanel.append(el('div', { class: 'table-wrap' }, sTbl)); + + const addPanel = el('section', { class: 'panel' }); + const snId = el('input', { placeholder: 'check-nginx', required: true }); + const snName = el('input', { placeholder: 'Check Nginx Config', required: true }); + const snCmd = el('textarea', { rows: 2, placeholder: 'nginx -t', required: true }); + const snTags = el('input', { placeholder: 'web, diagnostics' }); + const snSudo = el('input', { type: 'checkbox' }); + const snMsg = el('p', { class: 'form-msg' }); + const snForm = el( + 'form', + { class: 'stack' }, + el('div', { class: 'grid-2' }, el('div', {}, el('label', {}, 'Snippet ID'), snId), el('div', {}, el('label', {}, 'Name'), snName)), + el('label', {}, 'Command'), + snCmd, + el('div', { class: 'row-between' }, el('div', { class: 'row' }, el('label', {}, 'Tags'), snTags, el('label', { class: 'chk-row' }, snSudo, 'sudo')), el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Save Snippet')), + snMsg, + ); + snForm.addEventListener('submit', async (ev) => { + ev.preventDefault(); + snMsg.textContent = ''; + try { + await apiFetch('/api/snippets', { + method: 'POST', + body: { + id: snId.value.trim(), + name: snName.value.trim(), + command: snCmd.value.trim(), + tags: snTags.value.split(',').map((t) => t.trim()).filter(Boolean), + sudo: snSudo.checked, + inputs: [], + }, + }); + await renderWorkflowsView(root, state, wsClient); + } catch (err) { + snMsg.className = 'form-msg err-text'; + snMsg.textContent = extractErrorMessage(err); + } + }); + addPanel.append(el('h2', {}, 'Add Command Snippet'), snForm); + root.append(listPanel, addPanel); +} diff --git a/src/client/ts/ws-client.ts b/src/client/ts/ws-client.ts index cd84612..507dcbb 100644 --- a/src/client/ts/ws-client.ts +++ b/src/client/ts/ws-client.ts @@ -8,7 +8,7 @@ export class MultiplexWsClient { private reconnectTimer: number | null = null; private pingTimer: number | null = null; private shouldRun = false; - private channels = new Set(['config', 'alerts', 'metrics']); + private channels = new Set(['config', 'alerts', 'metrics', 'workflows']); private readonly frameListeners = new Set<(frame: ServerWsFrame) => void>(); private readonly statusListeners = new Set<(status: WsConnectionStatus) => void>(); From 3791f83bf689c1b8d4b45b0fc5a713f15a83aa30 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:35:53 +0000 Subject: [PATCH 04/10] fix(automation,vault): drain direct rsync stdout, guard ssh2 ed25519 keygen, and match succeeded badge --- src/client/ts/views/dashboard-view.ts | 4 +- src/client/ts/views/systems-view.ts | 11 ++++-- src/server/automation/transfer-engine.ts | 3 ++ src/server/security/vault.ts | 50 +++++++++++++++++------- 4 files changed, 48 insertions(+), 20 deletions(-) diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts index 2e4c106..1cf86c0 100644 --- a/src/client/ts/views/dashboard-view.ts +++ b/src/client/ts/views/dashboard-view.ts @@ -371,9 +371,9 @@ export async function renderDashboardView( const wf = entry.workflow; const runStatus = entry.latestRun?.status ?? 'idle'; const badgeClass = - runStatus === 'success' + runStatus === 'succeeded' ? 'badge badge-ok' - : runStatus === 'failed' || runStatus === 'timed-out' + : runStatus === 'failed' || runStatus === 'cancelled' ? 'badge badge-err' : runStatus === 'running' || runStatus === 'queued' ? 'badge badge-warn' diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index 7491f6f..33ca44c 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -577,17 +577,20 @@ export async function renderSystemsView( 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: - entry.latestRun?.status === 'success' + runStatus === 'succeeded' ? 'badge badge-ok' - : entry.latestRun?.status === 'failed' + : runStatus === 'failed' || runStatus === 'cancelled' ? 'badge badge-err' - : 'badge', + : runStatus === 'running' || runStatus === 'queued' + ? 'badge badge-warn' + : 'badge', }, - entry.latestRun?.status ?? 'idle', + runStatus, ); const runTaskBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Run Task'); runTaskBtn.addEventListener('click', async () => { diff --git a/src/server/automation/transfer-engine.ts b/src/server/automation/transfer-engine.ts index e913f3e..88acdeb 100644 --- a/src/server/automation/transfer-engine.ts +++ b/src/server/automation/transfer-engine.ts @@ -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); diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 1a26b91..82794d5 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -91,6 +91,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 extends unknown ? Omit : never; export type VaultCredentialInput = DistributiveOmit< @@ -483,25 +514,16 @@ export class VaultService { this.assertWriteUnlocked(); this.autoInitializedEmpty = false; - const keyPair = options.passphrase - ? ssh2.utils.generateKeyPairSync('ed25519', { - 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); + const { privateKey, publicKey, fingerprint } = generateValidEd25519KeyPair({ + comment: options.comment ?? options.id, + passphrase: options.passphrase, + }); return this.upsertCredential({ id: options.id, name: options.name, type: 'ssh-key', - privateKey: keyPair.private, + privateKey, publicKey, passphrase: options.passphrase || undefined, fingerprint, From 413053182b99db1cc312c70ea7313ad1a6bab642 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 06:35:53 +0000 Subject: [PATCH 05/10] test(phase-4): add E2E suites for DAG workflows, SFTP transfers, broadcast, and AlertEngine --- tests/alerts-engine.test.ts | 664 ++++++++++++++++++++++ tests/helpers/mock-ssh-server.ts | 17 +- tests/workflows-and-transfer.test.ts | 790 +++++++++++++++++++++++++++ 3 files changed, 1464 insertions(+), 7 deletions(-) create mode 100644 tests/alerts-engine.test.ts create mode 100644 tests/workflows-and-transfer.test.ts diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts new file mode 100644 index 0000000..59d0fd8 --- /dev/null +++ b/tests/alerts-engine.test.ts @@ -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> = []; + +class CookieJar { + private cookies = new Map(); + 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) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + 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( + fn: () => T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 30, +): Promise { + 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((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((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 = {}; + 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; + 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 * * * 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); + }, + ); +}); diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 4507984..67a03df 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -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 { 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; } diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts new file mode 100644 index 0000000..41ee12e --- /dev/null +++ b/tests/workflows-and-transfer.test.ts @@ -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> = []; + +class CookieJar { + private cookies = new Map(); + 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) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + 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( + fn: () => Promise | T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 30, +): Promise { + 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 = {}; + 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; + 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: 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' }); + }, + ); +}); From fbc1eb94e08b2c8ffc4a1aef5f669ff4faf1bbea Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:23:22 +0000 Subject: [PATCH 06/10] feat(backup,cli): add AES-256-GCM .gcoord.enc backup, verify, restore CLI and API --- src/cli/gcoord.ts | 240 ++++++++++- src/server/api/routes/backup.routes.ts | 216 ++++++++++ src/server/app.ts | 34 ++ src/server/config/config-manager.ts | 52 +++ src/server/security/backup.ts | 534 +++++++++++++++++++++++++ src/server/security/vault.ts | 69 +++- src/server/ssh/known-hosts.ts | 29 ++ 7 files changed, 1155 insertions(+), 19 deletions(-) create mode 100644 src/server/api/routes/backup.routes.ts create mode 100644 src/server/security/backup.ts diff --git a/src/cli/gcoord.ts b/src/cli/gcoord.ts index ad4a3f8..ef67f22 100644 --- a/src/cli/gcoord.ts +++ b/src/cli/gcoord.ts @@ -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'; @@ -9,17 +14,47 @@ function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: - rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key + rotate-key Re-encrypt vault.enc atomically with a new 32-byte master key --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) --current-key-file Path to file containing current 32-byte key --new-key-out 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 Output bundle path (required) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --key-file Path to 32-byte Vault master key (default mode) + --passphrase-file Path to passphrase file (overrides key-file using scrypt) + + verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data + Backup bundle path (or --bundle ) + --key-file Path to 32-byte master key + --passphrase-file Path to backup passphrase file + --vault-key-file 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 + Backup bundle path (or --bundle ) + --data-dir Target data directory (default: GCOORD_DATA_DIR or ./data) + --key-file Path to 32-byte master key + --passphrase-file Path to backup passphrase file + --vault-key-file Optional Vault master key if backup used a passphrase `); } -async function readCurrentKey(keyFile?: string): Promise { +async function promptHiddenOrLine(promptText: string): Promise { + 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 { if (keyFile) { return fs.readFileSync(keyFile, 'utf8').trim(); } @@ -29,16 +64,42 @@ async function readCurrentKey(keyFile?: string): Promise { 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 { @@ -89,6 +150,147 @@ async function runRotateKey(args: string[]): Promise { return 0; } +async function runBackup(args: string[]): Promise { + 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 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 { + 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 { + 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 { const [command, ...rest] = process.argv.slice(2); if (!command || command === '-h' || command === '--help') { @@ -99,10 +301,14 @@ async function main(): Promise { 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}`); diff --git a/src/server/api/routes/backup.routes.ts b/src/server/api/routes/backup.routes.ts new file mode 100644 index 0000000..70aff8a --- /dev/null +++ b/src/server/api/routes/backup.routes.ts @@ -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; +} + +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; +} diff --git a/src/server/app.ts b/src/server/app.ts index 54358a6..4aba4d8 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -31,6 +31,7 @@ import { CustomSystemsEngine } from './systems/systems-engine.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'; @@ -384,6 +385,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', diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index e8a1463..14bed4c 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -133,6 +133,58 @@ export class ConfigManager { } } + get configDirPath(): string { + return this.configDir; + } + + async pauseWatcher(): Promise { + 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 { + 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 () => { diff --git a/src/server/security/backup.ts b/src/server/security/backup.ts new file mode 100644 index 0000000..f6daf45 --- /dev/null +++ b/src/server/security/backup.ts @@ -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; + +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; + +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 { + const out: Record = {}; + 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> = []; + let alertSilences: Array> = []; + 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>; + + 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>; + } + } 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): 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; +} diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 82794d5..26811a3 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -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; +export type VaultEnvelope = z.infer; 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) { @@ -375,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(); diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index a3148f3..0fc21ee 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -243,6 +243,35 @@ export class KnownHostsService { .all() as KnownHostRecord[]; } + replaceAllKnownHosts( + records: Array< + Pick & + Partial> + >, + ): 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 = ?') From 076df61f4d0fb78180e4ae1344cd653263b639b0 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:25:17 +0000 Subject: [PATCH 07/10] feat(ai): implement opt-in OpenAI-compatible AiService, secret redactor, surface guides, and WS streaming --- src/server/ai/ai-service.ts | 624 +++++++++++++++++++++++++++++ src/server/ai/guides.ts | 159 ++++++++ src/server/ai/redactor.ts | 129 ++++++ src/server/api/routes/ai.routes.ts | 127 ++++++ src/server/api/ws-hub.ts | 11 +- src/server/app.ts | 24 ++ 6 files changed, 1073 insertions(+), 1 deletion(-) create mode 100644 src/server/ai/ai-service.ts create mode 100644 src/server/ai/guides.ts create mode 100644 src/server/ai/redactor.ts create mode 100644 src/server/api/routes/ai.routes.ts diff --git a/src/server/ai/ai-service.ts b/src/server/ai/ai-service.ts new file mode 100644 index 0000000..fd9c629 --- /dev/null +++ b/src/server/ai/ai-service.ts @@ -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(); + 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 { + try { + const headers: Record = { + '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 = { '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), id: (obj as Record).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) } + : 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) } + : 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', +]); diff --git a/src/server/ai/guides.ts b/src/server/ai/guides.ts new file mode 100644 index 0000000..5d3b16f --- /dev/null +++ b/src/server/ai/guides.ts @@ -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; + +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/.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/.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_. 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/.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'), + }; + } +} diff --git a/src/server/ai/redactor.ts b/src/server/ai/redactor.ts new file mode 100644 index 0000000..43a4fe8 --- /dev/null +++ b/src/server/ai/redactor.ts @@ -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(); + 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 }; +} diff --git a/src/server/api/routes/ai.routes.ts b/src/server/api/routes/ai.routes.ts new file mode 100644 index 0000000..6f45cec --- /dev/null +++ b/src/server/api/routes/ai.routes.ts @@ -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; +} diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index 7f1208c..abfa4ff 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -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(); @@ -44,6 +48,7 @@ export class WsHub { private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; private readonly subscribeListeners = new Set(); 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; } } diff --git a/src/server/app.ts b/src/server/app.ts index 4aba4d8..3a0ba6e 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -3,6 +3,7 @@ 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'; @@ -28,6 +29,7 @@ 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'; @@ -76,6 +78,7 @@ export interface GCoordinatorInstance { workflowEngine: WorkflowEngine; broadcastService: BroadcastService; alertEngine: AlertEngine; + aiService: AiService; wsHub: WsHub; port: number; close(): Promise; @@ -186,6 +189,13 @@ export async function createGCoordinatorServer( wsHub, auditService, ); + const aiService = new AiService( + configManager, + vaultService, + sshPool, + wsHub, + auditService, + ); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); @@ -198,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); @@ -228,6 +243,11 @@ export async function createGCoordinatorServer( 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') { ctx.send({ type: 'servers:state', states: sshPool.getStates() }); } @@ -290,6 +310,7 @@ export async function createGCoordinatorServer( alertEngine.start(); vaultService.onPanicLock(() => { + aiService.cancelAll(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -445,6 +466,7 @@ export async function createGCoordinatorServer( '/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 }), @@ -520,9 +542,11 @@ export async function createGCoordinatorServer( workflowEngine, broadcastService, alertEngine, + aiService, wsHub, port: actualPort, async close() { + aiService.close(); alertEngine.close(); workflowEngine.close(); broadcastService.cancelAll(); From 01aae919820f0b3382fe263e931c4f189dd7354e Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:26:39 +0000 Subject: [PATCH 08/10] feat(ui,perf): add 3 terminal themes, mobile touch/scroll polish, and bounded stream/sparkline memory --- src/client/build.ts | 6 ++++ src/client/css/base.css | 39 +++++++++++++++++--- src/client/css/themes.css | 51 +++++++++++++++++++++++++++ src/client/index.html | 3 ++ src/client/ts/state.ts | 46 ++++++++++++++++++++++++ src/client/ts/views/dashboard-view.ts | 14 ++++++-- src/client/ts/views/settings-view.ts | 6 ++-- src/client/ts/views/systems-view.ts | 6 ++-- src/client/ts/views/workflows-view.ts | 5 +-- src/shared/schemas/settings.schema.ts | 5 +++ 10 files changed, 167 insertions(+), 14 deletions(-) diff --git a/src/client/build.ts b/src/client/build.ts index d4caf5b..e17addc 100644 --- a/src/client/build.ts +++ b/src/client/build.ts @@ -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 { 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)`, + ); + } } } diff --git a/src/client/css/base.css b/src/client/css/base.css index 8c2fb2e..1077214 100644 --- a/src/client/css/base.css +++ b/src/client/css/base.css @@ -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; } diff --git a/src/client/css/themes.css b/src/client/css/themes.css index 9c34d62..5cb4045 100644 --- a/src/client/css/themes.css +++ b/src/client/css/themes.css @@ -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); +} diff --git a/src/client/index.html b/src/client/index.html index f58ec26..2484694 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -29,6 +29,9 @@ + + + diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index cd0f705..c0f690c 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -117,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 = { + '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; @@ -127,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( diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts index 1cf86c0..c67870b 100644 --- a/src/client/ts/views/dashboard-view.ts +++ b/src/client/ts/views/dashboard-view.ts @@ -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; } @@ -462,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; diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index c6edea3..9176402 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -1,6 +1,7 @@ import { apiFetch } from '../api.js'; import { confirmDialog, promptStepUp } from '../dialogs.js'; import { + CLIENT_THEME_IDS, el, extractErrorMessage, fmtTime, @@ -71,9 +72,8 @@ export async function renderSettingsView( const themeSelect = el( 'select', {}, - ...['phosphor-green', 'amber-term', 'nord-dark', 'gruvbox-dark', 'paper-light'].map( - (t) => - el('option', { value: t, selected: state.theme === t ? true : undefined }, t), + ...CLIENT_THEME_IDS.map((t) => + el('option', { value: t, selected: state.theme === t ? true : undefined }, t), ), ); themeSelect.addEventListener('change', () => onThemeChange(themeSelect.value)); diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index 33ca44c..a6d813d 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -1,7 +1,7 @@ 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, type ClientState, type ServerEntry } from '../state.js'; import type { MultiplexWsClient } from '../ws-client.js'; interface SystemActionDef { @@ -238,7 +238,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 +246,7 @@ async function runSystemAction(opts: { // Ignore meta parse errors } } else { - logPre.textContent += frame.data; + appendBoundedStreamText(logPre, frame.data); } logPre.scrollTop = logPre.scrollHeight; }); diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 52030d8..45d6435 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -2,6 +2,7 @@ import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; import { + appendBoundedStreamText, el, extractErrorMessage, fmtTime, @@ -757,7 +758,7 @@ export async function renderWorkflowsView( unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { if (frame.stream !== 'meta') { - logPre.textContent += frame.data; + appendBoundedStreamText(logPre, frame.data); logPre.scrollTop = logPre.scrollHeight; } else { try { @@ -1078,7 +1079,7 @@ export async function renderWorkflowsView( } else if (m.event === 'server-output' && m.serverId && m.data) { const card = cardMap.get(m.serverId); if (card) { - card.pre.textContent += m.data; + appendBoundedStreamText(card.pre, m.data); card.pre.scrollTop = card.pre.scrollHeight; } } else if (m.event === 'server-exit' && m.serverId) { diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts index fb868a0..efd2ca8 100644 --- a/src/shared/schemas/settings.schema.ts +++ b/src/shared/schemas/settings.schema.ts @@ -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', From 6dcfa8192534cab286b2eb6cf9ec57aedeabdbd5 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:31:43 +0000 Subject: [PATCH 09/10] feat(client): add lazy-loaded AI Assistant drawer across 5 surfaces and Settings AI/Backup panels --- src/client/ts/main.ts | 4 +- src/client/ts/views/ai-drawer.ts | 352 ++++++++++++++++++++++++++ src/client/ts/views/alerts-view.ts | 58 ++++- src/client/ts/views/config-view.ts | 50 +++- src/client/ts/views/settings-view.ts | 233 ++++++++++++++++- src/client/ts/views/systems-view.ts | 83 +++++- src/client/ts/views/terminal-view.ts | 37 ++- src/client/ts/views/workflows-view.ts | 64 ++++- 8 files changed, 859 insertions(+), 22 deletions(-) create mode 100644 src/client/ts/views/ai-drawer.ts diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index 8f1f14d..d41b44c 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -200,7 +200,7 @@ async function renderCurrentView(): Promise { return; } if (route === 'config') { - await renderConfigView(root, state.overview!, async () => { + await renderConfigView(root, state.overview!, state, wsClient, async () => { await refreshOverview(); await renderCurrentView(); }); @@ -253,7 +253,7 @@ async function renderCurrentView(): Promise { } if (route === 'alerts') { const { renderAlertsView } = await import('./views/alerts-view.js'); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); } } diff --git a/src/client/ts/views/ai-drawer.ts b/src/client/ts/views/ai-drawer.ts new file mode 100644 index 0000000..d3620f7 --- /dev/null +++ b/src/client/ts/views/ai-drawer.ts @@ -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; +} + +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 { + 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('/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)}`; + } +} diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts index 90cbec1..9014748 100644 --- a/src/client/ts/views/alerts-view.ts +++ b/src/client/ts/views/alerts-view.ts @@ -1,6 +1,13 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + isAiEnabled, + type ClientState, +} from '../state.js'; +import type { MultiplexWsClient } from '../ws-client.js'; interface AlertChannelItem { id: string; @@ -87,6 +94,7 @@ interface AlertsPayload { export async function renderAlertsView( root: HTMLElement, state: ClientState, + wsClient: MultiplexWsClient, ): Promise { root.replaceChildren(); const [data, credsRes] = await Promise.all([ @@ -101,15 +109,33 @@ export async function renderAlertsView( const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh'); refreshBtn.addEventListener('click', () => { - void renderAlertsView(root, state); + 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.`)), - refreshBtn, + el('div', { class: 'row' }, ...(aiHelpBtn ? [aiHelpBtn] : []), refreshBtn), ), ); @@ -133,15 +159,31 @@ export async function renderAlertsView( method: 'POST', body: { scopeType, targetId, durationMinutes, reason: `Quick snooze from ${evt.id}` }, }); - await renderAlertsView(root, state); + 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)), + 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'}`), ), @@ -184,7 +226,7 @@ export async function renderAlertsView( reason: silReason.value.trim() || undefined, }, }); - await renderAlertsView(root, state); + await renderAlertsView(root, state, wsClient); }); silPanel.append(silForm); @@ -192,7 +234,7 @@ export async function renderAlertsView( 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); + 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), @@ -203,7 +245,7 @@ export async function renderAlertsView( 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); + await renderAlertsView(root, state, wsClient); }; for (const w of cfg.maintenanceWindows) { diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts index 6df092d..6bc070f 100644 --- a/src/client/ts/views/config-view.ts +++ b/src/client/ts/views/config-view.ts @@ -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, ): Promise { 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', diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 9176402..4830224 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -55,10 +55,13 @@ export async function renderSettingsView( ): Promise { 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('/api/auth/factors'), + apiFetch<{ credentials: Array<{ id: string; name: string; type: string }> }>( + '/api/vault/credentials', + ).catch(() => ({ credentials: [] })), ]); const sec = factorsRes.security; @@ -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 => { + 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 }>('/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' }); diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index a6d813d..a24300b 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -1,7 +1,15 @@ import type { ServerWsFrame } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { appendBoundedStreamText, 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, ), ); @@ -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, @@ -743,6 +814,7 @@ export async function renderSystemsView( ); btn.addEventListener('click', () => { void runSystemAction({ + state, systemId, serverId: snap.serverId, action: act, @@ -796,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, diff --git a/src/client/ts/views/terminal-view.ts b/src/client/ts/views/terminal-view.ts index 0c747f4..3bf01db 100644 --- a/src/client/ts/views/terminal-view.ts +++ b/src/client/ts/views/terminal-view.ts @@ -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), ), diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 45d6435..83a4b30 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -6,6 +6,7 @@ import { el, extractErrorMessage, fmtTime, + isAiEnabled, type ClientState, type ServerEntry, } from '../state.js'; @@ -737,9 +738,25 @@ export async function renderWorkflowsView( refBtn.addEventListener('click', () => { void renderWorkflowsView(root, state, wsClient); }); + const aiWfBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Draft Workflow]') + : null; + if (aiWfBtn) { + aiWfBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'workflows', + title: 'AI Workflow DAG Drafter', + defaultDraftKind: 'workflow', + onApplied: () => renderWorkflowsView(root, state, wsClient), + }); + }); + } const wfSection = el('section', { class: 'panel panel-region' }); - wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, refBtn))); + wfSection.append(el('div', { class: 'row-between' }, el('h2', {}, `Configured Workflows (${wfRes.workflows.length})`), el('div', { class: 'row' }, newBtn, ...(aiWfBtn ? [aiWfBtn] : []), refBtn))); const watchRunStream = (runId: string, wfId: string) => { streamPanel.hidden = false; @@ -785,6 +802,31 @@ export async function renderWorkflowsView( }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); detailPanel.hidden = false; renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); + if (isAiEnabled(state)) { + const diagBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm', style: 'margin-top:8px' }, + '[AI Diagnose Run]', + ); + diagBtn.addEventListener('click', async () => { + const logText = res.stepLogs + .map( + (l) => + `[${l.stepId}@${l.serverId} exit=${String(l.exitCode)} ${l.durationMs}ms]\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`, + ) + .join('\n\n'); + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'logs', + title: `AI Log Debugger (${runId})`, + contextText: `Workflow: ${res.run.workflowId} (${res.run.status})\n\n${logText}`, + serverId: res.stepLogs[0]?.serverId.split(':')[0], + }); + }); + detailPanel.append(diagBtn); + } }; if (wfRes.workflows.length === 0) { @@ -1111,7 +1153,25 @@ export async function renderWorkflowsView( // Command Snippets tab const listPanel = el('section', { class: 'panel panel-region' }); - listPanel.append(el('h2', {}, `Saved Command Snippets (${snippets.length})`)); + const aiSnipBtn = isAiEnabled(state) + ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Draft Snippet]') + : null; + if (aiSnipBtn) { + aiSnipBtn.addEventListener('click', async () => { + const { openAiAssistantDrawer } = await import('./ai-drawer.js'); + await openAiAssistantDrawer({ + state, + wsClient, + surface: 'snippets', + title: 'AI Snippet Generator', + defaultDraftKind: 'snippet', + onApplied: () => renderWorkflowsView(root, state, wsClient), + }); + }); + } + listPanel.append( + el('div', { class: 'row-between' }, el('h2', {}, `Saved Command Snippets (${snippets.length})`), ...(aiSnipBtn ? [aiSnipBtn] : [])), + ); const sTbl = el('table'); sTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Name'), el('th', {}, 'Command'), el('th', {}, 'Flags'), el('th', {}, 'Actions')))); const sBody = el('tbody'); From b12df1e2d79917347f5a868e90b6d1f959c54e17 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 14:32:31 +0000 Subject: [PATCH 10/10] test(phase-5): add E2E suites for .gcoord.enc backup/CLI, AI assistant/redactor, and mobile bundle/themes --- tests/ai-assistant.test.ts | 414 ++++++++++++++++++++++++++++++++ tests/backup-and-cli.test.ts | 320 ++++++++++++++++++++++++ tests/mobile-and-themes.test.ts | 78 ++++++ 3 files changed, 812 insertions(+) create mode 100644 tests/ai-assistant.test.ts create mode 100644 tests/backup-and-cli.test.ts create mode 100644 tests/mobile-and-themes.test.ts diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts new file mode 100644 index 0000000..8dedbae --- /dev/null +++ b/tests/ai-assistant.test.ts @@ -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> = []; + +class CookieJar { + private cookies = new Map(); + 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) { + return new Promise<{ ws: WebSocket; frames: Array> }>((resolve, reject) => { + const frames: Array> = []; + 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( + fn: () => T | undefined | null | false, + timeoutMs = 5000, + intervalMs = 25, +): Promise { + 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(); + + 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((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((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 = {}; + 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; + 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: 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, + ); + }); +}); diff --git a/tests/backup-and-cli.test.ts b/tests/backup-and-cli.test.ts new file mode 100644 index 0000000..e6e58e9 --- /dev/null +++ b/tests/backup-and-cli.test.ts @@ -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> = []; + +class CookieJar { + private cookies = new Map(); + 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 = {}; + 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; + 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 }> }; + 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']); + }); +}); diff --git a/tests/mobile-and-themes.test.ts b/tests/mobile-and-themes.test.ts new file mode 100644 index 0000000..9195ab7 --- /dev/null +++ b/tests/mobile-and-themes.test.ts @@ -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:'); + }); +});