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();