diff --git a/src/server/db/database.ts b/src/server/db/database.ts new file mode 100644 index 0000000..d2e8a2c --- /dev/null +++ b/src/server/db/database.ts @@ -0,0 +1,46 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import Database from 'better-sqlite3'; +import { migration001Initial, type Migration } from './migrations/001_initial.js'; + +const MIGRATIONS: Migration[] = [migration001Initial]; + +export function openDatabase(dbPath: string): Database.Database { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + const db = new Database(dbPath); + + db.pragma('journal_mode = WAL'); + db.pragma('synchronous = NORMAL'); + db.pragma('foreign_keys = ON'); + db.pragma('busy_timeout = 5000'); + + runMigrations(db); + return db; +} + +export function runMigrations(db: Database.Database): void { + db.exec(` + CREATE TABLE IF NOT EXISTS schema_migrations ( + id TEXT PRIMARY KEY, + applied_at INTEGER NOT NULL + ); + `); + + const appliedStmt = db.prepare('SELECT id FROM schema_migrations'); + const applied = new Set( + (appliedStmt.all() as Array<{ id: string }>).map((row) => row.id), + ); + + const insertStmt = db.prepare( + 'INSERT INTO schema_migrations (id, applied_at) VALUES (?, ?)', + ); + + for (const migration of MIGRATIONS) { + if (applied.has(migration.id)) continue; + const applyTx = db.transaction(() => { + migration.up(db); + insertStmt.run(migration.id, Date.now()); + }); + applyTx(); + } +} diff --git a/src/server/db/migrations/001_initial.ts b/src/server/db/migrations/001_initial.ts new file mode 100644 index 0000000..2479439 --- /dev/null +++ b/src/server/db/migrations/001_initial.ts @@ -0,0 +1,179 @@ +import type Database from 'better-sqlite3'; + +export interface Migration { + id: string; + up(db: Database.Database): void; +} + +export const migration001Initial: Migration = { + id: '001_initial', + up(db) { + db.exec(` + CREATE TABLE IF NOT EXISTS admin_users ( + id INTEGER PRIMARY KEY CHECK (id = 1), + username TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + totp_secret TEXT NOT NULL, + last_login_totp_step INTEGER, + last_stepup_totp_step INTEGER, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS recovery_codes ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + code_hash TEXT NOT NULL UNIQUE, + used_at INTEGER + ); + + CREATE TABLE IF NOT EXISTS sessions ( + id_hash TEXT PRIMARY KEY, + csrf_token_hash TEXT NOT NULL, + safe_mode INTEGER NOT NULL DEFAULT 0, + elevated_until INTEGER, + ip TEXT NOT NULL, + user_agent TEXT NOT NULL, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at); + + CREATE TABLE IF NOT EXISTS webauthn_credentials ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + public_key BLOB NOT NULL, + counter INTEGER NOT NULL DEFAULT 0, + transports TEXT, + created_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS known_hosts ( + host_port TEXT PRIMARY KEY, + algorithm TEXT NOT NULL, + fingerprint TEXT NOT NULL, + trusted_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts INTEGER NOT NULL, + action TEXT NOT NULL, + actor_ip TEXT NOT NULL, + session_id_hash TEXT, + target TEXT, + status TEXT NOT NULL, + details TEXT + ); + CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(ts DESC); + CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log(action); + + CREATE TABLE IF NOT EXISTS config_revisions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + file_path TEXT NOT NULL, + sha256 TEXT NOT NULL, + source TEXT NOT NULL, + summary TEXT, + content TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_config_rev_file_ts ON config_revisions(file_path, id DESC); + + CREATE TABLE IF NOT EXISTS metrics_raw ( + ts INTEGER NOT NULL, + server_id TEXT NOT NULL, + cpu_pct REAL NOT NULL, + mem_used_mb REAL NOT NULL, + mem_total_mb REAL NOT NULL, + net_rx_bps REAL NOT NULL, + net_tx_bps REAL NOT NULL, + load_1m REAL NOT NULL, + uptime_sec INTEGER NOT NULL, + PRIMARY KEY (server_id, ts) + ); + + CREATE TABLE IF NOT EXISTS metrics_disks ( + ts INTEGER NOT NULL, + server_id TEXT NOT NULL, + mount_point TEXT NOT NULL, + fs_type TEXT NOT NULL, + used_mb REAL NOT NULL, + total_mb REAL NOT NULL, + used_pct REAL NOT NULL, + PRIMARY KEY (server_id, mount_point, ts) + ); + + CREATE TABLE IF NOT EXISTS metrics_rollup ( + bucket_ts INTEGER NOT NULL, + granularity TEXT NOT NULL, + server_id TEXT NOT NULL, + cpu_min REAL NOT NULL, + cpu_avg REAL NOT NULL, + cpu_max REAL NOT NULL, + mem_avg_pct REAL NOT NULL, + load_max REAL NOT NULL, + PRIMARY KEY (server_id, granularity, bucket_ts) + ); + + CREATE TABLE IF NOT EXISTS probe_results ( + ts INTEGER NOT NULL, + server_id TEXT NOT NULL, + probe_id TEXT NOT NULL, + ok INTEGER NOT NULL, + status_code INTEGER, + latency_ms REAL NOT NULL, + error TEXT, + PRIMARY KEY (server_id, probe_id, ts) + ); + + CREATE TABLE IF NOT EXISTS workflow_runs ( + run_id TEXT PRIMARY KEY, + workflow_id TEXT NOT NULL, + trigger_source TEXT NOT NULL, + status TEXT NOT NULL, + started_at INTEGER NOT NULL, + finished_at INTEGER, + cancelled_by TEXT + ); + CREATE INDEX IF NOT EXISTS idx_wf_runs_wf_ts ON workflow_runs(workflow_id, started_at DESC); + + CREATE TABLE IF NOT EXISTS workflow_step_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + run_id TEXT NOT NULL, + step_id TEXT NOT NULL, + server_id TEXT NOT NULL, + exit_code INTEGER, + duration_ms INTEGER NOT NULL, + stdout TEXT NOT NULL, + stderr TEXT NOT NULL, + created_at INTEGER NOT NULL, + FOREIGN KEY (run_id) REFERENCES workflow_runs(run_id) ON DELETE CASCADE + ); + CREATE INDEX IF NOT EXISTS idx_wf_step_logs_run ON workflow_step_logs(run_id); + + CREATE TABLE IF NOT EXISTS alert_events ( + id TEXT PRIMARY KEY, + rule_id TEXT NOT NULL, + server_id TEXT, + state TEXT NOT NULL, + severity TEXT NOT NULL, + message TEXT NOT NULL, + webhook_status TEXT, + triggered_at INTEGER NOT NULL, + resolved_at INTEGER + ); + CREATE INDEX IF NOT EXISTS idx_alert_events_ts ON alert_events(triggered_at DESC); + + CREATE TABLE IF NOT EXISTS alert_silences ( + id TEXT PRIMARY KEY, + scope_type TEXT NOT NULL, + target_id TEXT NOT NULL, + reason TEXT, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_alert_silences_exp ON alert_silences(expires_at); + `); + }, +}; diff --git a/src/shared/schemas/alerts.schema.ts b/src/shared/schemas/alerts.schema.ts new file mode 100644 index 0000000..2f7ba6d --- /dev/null +++ b/src/shared/schemas/alerts.schema.ts @@ -0,0 +1,85 @@ +import { z } from 'zod'; +import { CronExpressionSchema, EntityIdSchema } from './common.js'; + +export const AlertChannelSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), + url: z.string().url().optional(), + secretRef: EntityIdSchema, + chatId: z.string().optional(), + topic: z.string().optional(), + enabled: z.boolean().default(true), +}); + +export const AlertRuleTargetSchema = z.object({ + serverId: EntityIdSchema.optional(), + tags: z.array(z.string().min(1)).optional(), + all: z.boolean().optional(), +}); + +const AlertRuleBase = { + id: EntityIdSchema, + name: z.string().min(1).max(120), + severity: z.enum(['warn', 'critical']).default('warn'), + target: AlertRuleTargetSchema.default({ all: true }), + forConsecutivePolls: z.number().int().min(1).max(100).default(3), + cooldownSec: z.number().int().min(0).max(86400).default(300), + channelIds: z.array(EntityIdSchema).default([]), + remediationWorkflowId: EntityIdSchema.optional(), + enabled: z.boolean().default(true), +}; + +export const AlertRuleSchema = z.discriminatedUnion('kind', [ + z.object({ + ...AlertRuleBase, + kind: z.literal('metric'), + metric: z.enum(['cpuPct', 'memPct', 'load1m']), + operator: z.enum(['gt', 'gte', 'lt', 'lte']).default('gt'), + threshold: z.number(), + }), + z.object({ + ...AlertRuleBase, + kind: z.literal('disk'), + mountPoint: z.string().optional(), + thresholdPct: z.number().min(1).max(100), + }), + z.object({ + ...AlertRuleBase, + kind: z.literal('offline'), + offlineSec: z.number().int().min(5).max(86400).default(60), + }), + z.object({ + ...AlertRuleBase, + kind: z.literal('probe'), + probeId: EntityIdSchema.optional(), + }), + z.object({ + ...AlertRuleBase, + kind: z.literal('system'), + systemId: EntityIdSchema, + item: z.string().optional(), + }), +]); + +export const MaintenanceWindowSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + cron: CronExpressionSchema, + timezone: z.string().min(1).default('UTC'), + durationMinutes: z.number().int().min(1).max(1440), + target: AlertRuleTargetSchema.default({ all: true }), + enabled: z.boolean().default(true), +}); + +export const AlertsFileSchema = z.object({ + version: z.literal(1).default(1), + channels: z.array(AlertChannelSchema).default([]), + rules: z.array(AlertRuleSchema).default([]), + maintenanceWindows: z.array(MaintenanceWindowSchema).default([]), +}); + +export type AlertChannel = z.infer; +export type AlertRule = z.infer; +export type MaintenanceWindow = z.infer; +export type AlertsFile = z.infer; diff --git a/src/shared/schemas/common.ts b/src/shared/schemas/common.ts new file mode 100644 index 0000000..081c377 --- /dev/null +++ b/src/shared/schemas/common.ts @@ -0,0 +1,36 @@ +import { CronPattern } from 'croner'; +import { z } from 'zod'; + +export const EntityIdSchema = z + .string() + .min(1, 'ID must not be empty') + .max(64, 'ID must be at most 64 characters') + .regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/, 'ID must start with alphanumeric and contain only [a-zA-Z0-9._-]'); + +export const PortSchema = z.number().int().min(1).max(65535); + +export const CronExpressionSchema = z + .string() + .min(1) + .superRefine((expr, ctx) => { + try { + new CronPattern(expr); + } catch (err) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `Invalid cron expression "${expr}": ${err instanceof Error ? err.message : String(err)}`, + }); + } + }); + +export const InputDefSchema = z.object({ + name: EntityIdSchema, + type: z.enum(['string', 'number', 'boolean', 'server', 'select']).default('string'), + label: z.string().min(1).optional(), + description: z.string().optional(), + required: z.boolean().default(false), + default: z.union([z.string(), z.number(), z.boolean()]).optional(), + options: z.array(z.string()).optional(), +}); + +export type InputDef = z.infer; diff --git a/src/shared/schemas/index.ts b/src/shared/schemas/index.ts new file mode 100644 index 0000000..673b5d4 --- /dev/null +++ b/src/shared/schemas/index.ts @@ -0,0 +1,8 @@ +export * from './common.js'; +export * from './server.schema.js'; +export * from './system.schema.js'; +export * from './workflow.schema.js'; +export * from './snippets.schema.js'; +export * from './alerts.schema.js'; +export * from './settings.schema.js'; +export * from './vault.schema.js'; diff --git a/src/shared/schemas/server.schema.ts b/src/shared/schemas/server.schema.ts new file mode 100644 index 0000000..c3426e1 --- /dev/null +++ b/src/shared/schemas/server.schema.ts @@ -0,0 +1,77 @@ +import { z } from 'zod'; +import { EntityIdSchema, PortSchema } from './common.js'; + +export const HttpProbeSchema = z.object({ + id: EntityIdSchema, + type: z.literal('http'), + url: z.string().url(), + from: z.enum(['hub', 'target']).default('target'), + intervalSec: z.number().int().min(5).max(86400).default(30), + timeoutMs: z.number().int().min(200).max(60000).default(5000), + expectedStatus: z.number().int().min(100).max(599).default(200), + bodyIncludes: z.string().optional(), + enabled: z.boolean().default(true), +}); + +export const TcpProbeSchema = z.object({ + id: EntityIdSchema, + type: z.literal('tcp'), + host: z.string().min(1).default('127.0.0.1'), + port: PortSchema, + from: z.enum(['hub', 'target']).default('target'), + intervalSec: z.number().int().min(5).max(86400).default(30), + timeoutMs: z.number().int().min(200).max(60000).default(5000), + enabled: z.boolean().default(true), +}); + +export const ServerProbeSchema = z.discriminatedUnion('type', [HttpProbeSchema, TcpProbeSchema]); + +export const ServerSystemAttachmentSchema = z.object({ + systemId: EntityIdSchema, + params: z.record(z.unknown()).default({}), + itemOverrides: z + .record( + z + .object({ + activeFiles: z.array(z.string().min(1)).optional(), + }) + .passthrough(), + ) + .default({}), +}); + +export const ServerTunnelSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp']), + bindHost: z.string().min(1).optional(), + bindPort: PortSchema.optional(), + targetHost: z.string().min(1).default('127.0.0.1'), + targetPort: PortSchema, + autoStart: z.boolean().default(false), +}); + +export const ServerConfigSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + host: z.string().min(1), + port: PortSchema.default(22), + username: z.string().min(1).max(64), + credentialId: EntityIdSchema, + jumpHostId: EntityIdSchema.optional(), + sudoCredentialId: EntityIdSchema.optional(), + hostKeyFingerprint: z.string().min(1).optional(), + tags: z.array(z.string().min(1)).default([]), + osHint: z.enum(['auto', 'linux', 'bsd', 'macos']).default('auto'), + pollIntervalSec: z.number().int().min(2).max(3600).default(10), + diskMountFilter: z.array(z.string().min(1)).optional(), + probes: z.array(ServerProbeSchema).default([]), + systems: z.array(ServerSystemAttachmentSchema).default([]), + tunnels: z.array(ServerTunnelSchema).default([]), + enabled: z.boolean().default(true), +}); + +export type ServerProbe = z.infer; +export type ServerSystemAttachment = z.infer; +export type ServerTunnel = z.infer; +export type ServerConfig = z.infer; diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts new file mode 100644 index 0000000..b091b73 --- /dev/null +++ b/src/shared/schemas/settings.schema.ts @@ -0,0 +1,40 @@ +import { z } from 'zod'; +import { EntityIdSchema } from './common.js'; + +export const ThemeIdSchema = z.enum([ + 'phosphor-green', + 'amber-term', + 'nord-dark', + 'gruvbox-dark', + 'paper-light', +]); + +export const SettingsSchema = z.object({ + version: z.literal(1).default(1), + theme: ThemeIdSchema.default('phosphor-green'), + defaultMobileSafeMode: z.boolean().default(true), + rawRetentionHours: z.number().int().min(1).max(720).default(48), + rollupRetentionDays: z.number().int().min(1).max(3650).default(30), + configRevisionLimit: z.number().int().min(5).max(500).default(50), + ptyScrollbackBytes: z.number().int().min(16384).max(4194304).default(524288), + ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200), + sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000), + sshReadyTimeoutMs: z.number().int().min(3000).max(120000).default(15000), + ai: z + .object({ + enabled: z.boolean().default(false), + baseUrl: z.string().url().default('http://127.0.0.1:11434'), + model: z.string().min(1).default('qwen2.5-coder:7b'), + secretRef: EntityIdSchema.optional(), + maxContextChars: z.number().int().min(1000).max(128000).default(16000), + }) + .default({ + enabled: false, + baseUrl: 'http://127.0.0.1:11434', + model: 'qwen2.5-coder:7b', + maxContextChars: 16000, + }), +}); + +export type ThemeId = z.infer; +export type SettingsConfig = z.infer; diff --git a/src/shared/schemas/snippets.schema.ts b/src/shared/schemas/snippets.schema.ts new file mode 100644 index 0000000..905a5f9 --- /dev/null +++ b/src/shared/schemas/snippets.schema.ts @@ -0,0 +1,35 @@ +import { z } from 'zod'; +import { EntityIdSchema, InputDefSchema } from './common.js'; + +export const SnippetSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + description: z.string().optional(), + command: z.string().min(1), + tags: z.array(z.string().min(1)).default([]), + inputs: z.array(InputDefSchema).default([]), + sudo: z.boolean().default(false), + confirm: z.boolean().default(false), +}); + +export const SnippetsFileSchema = z + .object({ + version: z.literal(1).default(1), + snippets: z.array(SnippetSchema).default([]), + }) + .superRefine((doc, ctx) => { + const seen = new Set(); + doc.snippets.forEach((snip, idx) => { + if (seen.has(snip.id)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['snippets', idx, 'id'], + message: `Duplicate snippet id "${snip.id}"`, + }); + } + seen.add(snip.id); + }); + }); + +export type Snippet = z.infer; +export type SnippetsFile = z.infer; diff --git a/src/shared/schemas/system.schema.ts b/src/shared/schemas/system.schema.ts new file mode 100644 index 0000000..dc54458 --- /dev/null +++ b/src/shared/schemas/system.schema.ts @@ -0,0 +1,72 @@ +import { z } from 'zod'; +import { EntityIdSchema } from './common.js'; + +export const SystemParamDefSchema = z.object({ + name: EntityIdSchema, + type: z.enum(['string', 'number', 'boolean', 'string[]']), + default: z.unknown().optional(), + required: z.boolean().default(false), + description: z.string().optional(), +}); + +export const FolderScanDiscoverySchema = z.object({ + type: z.literal('folder-scan'), + rootsParam: EntityIdSchema, + maxDepth: z.number().int().min(1).max(5).default(1), + matchFiles: z.array(z.string().min(1)).min(1), + selectableFiles: z.array(z.string().min(1)).optional(), +}); + +export const CommandDiscoverySchema = z.object({ + type: z.literal('command'), + command: z.string().min(1), + parser: z.enum(['lines', 'json', 'json-lines']).default('lines'), +}); + +export const SystemDiscoverySchema = z.discriminatedUnion('type', [ + FolderScanDiscoverySchema, + CommandDiscoverySchema, +]); + +export const SystemHealthRuleSchema = z.object({ + field: z.string().min(1).optional(), + healthyValues: z.array(z.string()).optional(), + degradedValues: z.array(z.string()).optional(), + healthyExitCodes: z.array(z.number().int()).optional(), +}); + +export const SystemStatusSchema = z.object({ + command: z.string().min(1), + parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']), + subItemField: z.string().min(1).optional(), + regexPattern: z.string().min(1).optional(), + health: SystemHealthRuleSchema.optional(), +}); + +export const SystemActionSchema = z.object({ + id: EntityIdSchema, + label: z.string().min(1).max(80), + scope: z.enum(['system', 'item', 'subitem']), + mode: z.enum(['oneshot', 'stream', 'interactive']), + command: z.string().min(1), + sudo: z.boolean().default(false), + confirm: z.boolean().default(false), +}); + +export const SystemConfigSchema = z.object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + description: z.string().optional(), + cacheTtlSec: z.number().int().min(0).max(86400).default(45), + backgroundCheckSec: z.number().int().min(10).max(86400).optional(), + params: z.array(SystemParamDefSchema).default([]), + discovery: SystemDiscoverySchema, + status: SystemStatusSchema, + actions: z.array(SystemActionSchema).default([]), + editableFiles: z.array(z.string().min(1)).default([]), +}); + +export type SystemParamDef = z.infer; +export type SystemHealthRule = z.infer; +export type SystemAction = z.infer; +export type SystemConfig = z.infer; diff --git a/src/shared/schemas/vault.schema.ts b/src/shared/schemas/vault.schema.ts new file mode 100644 index 0000000..1a461c0 --- /dev/null +++ b/src/shared/schemas/vault.schema.ts @@ -0,0 +1,59 @@ +import { z } from 'zod'; +import { EntityIdSchema } from './common.js'; + +const VaultMetaFields = { + id: EntityIdSchema, + name: z.string().min(1).max(120), + createdAt: z.string(), + updatedAt: z.string(), +}; + +export const VaultCredentialSchema = z.discriminatedUnion('type', [ + z.object({ + ...VaultMetaFields, + type: z.literal('ssh-key'), + privateKey: z.string().min(1), + publicKey: z.string().min(1).optional(), + passphrase: z.string().optional(), + fingerprint: z.string().optional(), + }), + z.object({ + ...VaultMetaFields, + type: z.literal('ssh-password'), + password: z.string().min(1), + }), + z.object({ + ...VaultMetaFields, + type: z.literal('sudo-password'), + password: z.string().min(1), + }), + z.object({ + ...VaultMetaFields, + type: z.literal('webhook-secret'), + secret: z.string().min(1), + }), + z.object({ + ...VaultMetaFields, + type: z.literal('api-token'), + token: z.string().min(1), + }), +]); + +export const VaultPayloadSchema = z.object({ + version: z.literal(1).default(1), + credentials: z.record(VaultCredentialSchema).default({}), +}); + +export interface VaultCredentialMeta { + id: string; + name: string; + type: VaultCredential['type']; + fingerprint?: string; + publicKey?: string; + hasPassphrase?: boolean; + createdAt: string; + updatedAt: string; +} + +export type VaultCredential = z.infer; +export type VaultPayload = z.infer; diff --git a/src/shared/schemas/workflow.schema.ts b/src/shared/schemas/workflow.schema.ts new file mode 100644 index 0000000..7e1cf6c --- /dev/null +++ b/src/shared/schemas/workflow.schema.ts @@ -0,0 +1,231 @@ +import { z } from 'zod'; +import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js'; + +export const WorkflowTargetSchema = z + .object({ + serverId: z.string().min(1).optional(), + tags: z.array(z.string().min(1)).optional(), + all: z.boolean().optional(), + }) + .refine( + (t) => Boolean(t.serverId || (t.tags && t.tags.length > 0) || t.all), + 'Target must specify serverId, non-empty tags, or all: true', + ); + +export const StepDependencySchema = z.union([ + EntityIdSchema, + z.object({ + stepId: EntityIdSchema, + on: z.enum(['success', 'failure', 'always']).default('success'), + }), +]); + +export const StepFailureActionSchema = z.union([ + z.literal('abort'), + z.literal('continue'), + z.string().min(1), + z.object({ + action: z.enum(['abort', 'continue', 'notify', 'run-workflow']), + channelId: z.string().min(1).optional(), + workflowId: EntityIdSchema.optional(), + }), +]); + +const StepBaseFields = { + id: EntityIdSchema, + name: z.string().min(1).max(120).optional(), + dependsOn: z.array(StepDependencySchema).default([]), + timeoutSec: z.number().int().min(1).max(86400).optional(), + sudo: z.boolean().default(false), + captureAs: z.string().min(1).max(64).optional(), + onFailure: StepFailureActionSchema.optional(), +}; + +export const ExecStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('exec'), + target: WorkflowTargetSchema, + command: z.string().min(1), + concurrency: z.number().int().min(1).max(64).optional(), +}); + +export const ReadFileStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('read-file'), + target: WorkflowTargetSchema, + path: z.string().min(1), + tailLines: z.union([z.number().int().positive(), z.string().min(1)]).optional(), +}); + +export const SystemActionStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('system-action'), + target: WorkflowTargetSchema, + systemId: EntityIdSchema, + action: EntityIdSchema, + item: z.string().min(1).default('*'), + subItem: z.string().min(1).optional(), + concurrency: z.number().int().min(1).max(64).optional(), +}); + +export const TransferStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('transfer'), + mode: z.enum(['hub-relayed', 'direct']).default('hub-relayed'), + source: z.object({ + serverId: z.string().min(1), + path: z.string().min(1), + }), + destination: z.object({ + serverId: z.string().min(1), + path: z.string().min(1), + }), +}); + +export const WorkflowStepSchema = z.discriminatedUnion('type', [ + ExecStepSchema, + ReadFileStepSchema, + SystemActionStepSchema, + TransferStepSchema, +]); + +export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ + z.object({ type: z.literal('manual') }), + z.object({ + type: z.literal('cron'), + expression: CronExpressionSchema, + timezone: z.string().min(1).default('UTC'), + }), + z.object({ + type: z.literal('event'), + event: z.enum([ + 'server.offline', + 'server.online', + 'probe.failed', + 'system.unhealthy', + 'alert.fired', + ]), + filter: z + .object({ + serverId: EntityIdSchema.optional(), + tags: z.array(z.string().min(1)).optional(), + systemId: EntityIdSchema.optional(), + }) + .optional(), + }), +]); + +export const WorkflowConfigSchema = z + .object({ + id: EntityIdSchema, + name: z.string().min(1).max(160), + description: z.string().optional(), + trigger: WorkflowTriggerSchema, + scope: z + .object({ + serverId: EntityIdSchema.optional(), + systemId: EntityIdSchema.optional(), + item: z.string().min(1).optional(), + }) + .optional(), + inputs: z.array(InputDefSchema).default([]), + concurrency: z.number().int().min(1).max(64).default(4), + overlapPolicy: z.enum(['skip', 'queue', 'cancel-previous']).default('skip'), + stopOnError: z.boolean().default(true), + display: z + .object({ + mode: z.enum(['log', 'file-view', 'json', 'table', 'summary']).default('log'), + syntax: z.string().min(1).optional(), + pinToDashboard: z.boolean().default(false), + }) + .default({ mode: 'log', pinToDashboard: false }), + pinToDashboard: z.boolean().optional(), + steps: z.array(WorkflowStepSchema).min(1), + enabled: z.boolean().default(true), + }) + .superRefine((workflow, ctx) => { + const stepIndexById = new Map(); + workflow.steps.forEach((step, idx) => { + if (stepIndexById.has(step.id)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['steps', idx, 'id'], + message: `Duplicate workflow step id "${step.id}"`, + }); + } else { + stepIndexById.set(step.id, idx); + } + }); + + // Build adjacency list & in-degrees for Kahn's topological cycle detection + const inDegree = new Map(); + const dependents = new Map(); + for (const step of workflow.steps) { + inDegree.set(step.id, 0); + dependents.set(step.id, []); + } + + let hasInvalidRef = false; + workflow.steps.forEach((step, idx) => { + const seenDeps = new Set(); + step.dependsOn.forEach((dep, depIdx) => { + const depId = typeof dep === 'string' ? dep : dep.stepId; + if (depId === step.id) { + hasInvalidRef = true; + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['steps', idx, 'dependsOn', depIdx], + message: `Step "${step.id}" cannot depend on itself`, + }); + return; + } + if (!stepIndexById.has(depId)) { + hasInvalidRef = true; + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['steps', idx, 'dependsOn', depIdx], + message: `Step "${step.id}" depends on unknown step "${depId}"`, + }); + return; + } + if (!seenDeps.has(depId)) { + seenDeps.add(depId); + dependents.get(depId)!.push(step.id); + inDegree.set(step.id, (inDegree.get(step.id) ?? 0) + 1); + } + }); + }); + + if (hasInvalidRef) return; + + const queue: string[] = []; + for (const [stepId, deg] of inDegree.entries()) { + if (deg === 0) queue.push(stepId); + } + + let visited = 0; + while (queue.length > 0) { + const current = queue.shift()!; + visited += 1; + for (const nextId of dependents.get(current) ?? []) { + const nextDeg = (inDegree.get(nextId) ?? 0) - 1; + inDegree.set(nextId, nextDeg); + if (nextDeg === 0) queue.push(nextId); + } + } + + if (visited < stepIndexById.size) { + const cycleNodes = [...inDegree.entries()] + .filter(([, deg]) => deg > 0) + .map(([id]) => id); + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['steps'], + message: `Workflow DAG contains a dependency cycle involving steps: ${cycleNodes.join(', ')}`, + }); + } + }); + +export type WorkflowStep = z.infer; +export type WorkflowTrigger = z.infer; +export type WorkflowConfig = z.infer; diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts new file mode 100644 index 0000000..bae4d68 --- /dev/null +++ b/src/shared/ws-protocol.ts @@ -0,0 +1,139 @@ +import { z } from 'zod'; + +export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; + +export interface ConfigWarning { + filePath: string; + code: string; + message: string; +} + +export interface ConfigError { + filePath: string; + message: string; + issues?: Array<{ path: string; message: string }>; +} + +export interface MetricSample { + ts: number; + cpuPct: number; + memUsedMb: number; + memTotalMb: number; + netRxBps: number; + netTxBps: number; + load1m: number; + uptimeSec: number; +} + +export interface DiskSample { + mountPoint: string; + fsType: string; + usedMb: number; + totalMb: number; + usedPct: number; +} + +export interface ProbeSample { + probeId: string; + ok: boolean; + statusCode?: number; + latencyMs: number; + error?: string; +} + +export interface AlertEventSummary { + id: string; + ruleId: string; + serverId?: string; + severity: 'warn' | 'critical' | 'resolved'; + message: string; + ts: number; +} + +export interface HostKeyAlert { + serverId: string; + host: string; + port: number; + expectedFingerprint: string; + actualFingerprint: string; +} + +export const ClientWsFrameSchema = z.discriminatedUnion('type', [ + z.object({ + type: z.literal('ping'), + ts: z.number().finite(), + }), + z.object({ + type: z.literal('sub'), + channels: z.array(z.string().min(1).max(128)).max(64), + }), + z.object({ + type: z.literal('unsub'), + channels: z.array(z.string().min(1).max(128)).max(64), + }), + z.object({ + type: z.literal('safe-mode'), + enabled: z.boolean(), + }), + z.object({ + type: z.literal('pty:input'), + sessionId: z.string().min(1).max(64), + data: z.string().max(65536), + }), + z.object({ + type: z.literal('pty:resize'), + sessionId: z.string().min(1).max(64), + cols: z.number().int().min(10).max(500), + rows: z.number().int().min(4).max(200), + }), + z.object({ + type: z.literal('ai:cancel'), + chatId: z.string().min(1).max(64), + }), +]); + +export type ClientWsFrame = z.infer; + +export type ServerWsFrame = + | { type: 'pong'; ts: number; serverTs: number } + | { + type: 'hello'; + vaultState: VaultState; + safeMode: boolean; + elevatedUntil: number | null; + } + | { + type: 'config:updated'; + entityType: 'server' | 'system' | 'workflow' | 'snippets' | 'alerts' | 'settings' | 'all'; + id?: string; + warnings: ConfigWarning[]; + errors: ConfigError[]; + } + | { type: 'security:panic-lock' } + | { type: 'error'; code: string; message: string } + | { + type: 'metrics:tick'; + serverId: string; + sample: MetricSample; + disks: DiskSample[]; + probes?: ProbeSample[]; + } + | { type: 'pty:output'; sessionId: string; data: string; replay?: boolean } + | { type: 'pty:exit'; sessionId: string; exitCode: number | null } + | { type: 'stream:chunk'; jobId: string; stream: 'stdout' | 'stderr' | 'meta'; data: string } + | { + type: 'alerts:update'; + activeCount: number; + event?: AlertEventSummary; + hostKeyMismatch?: HostKeyAlert; + } + | { type: 'ai:delta'; chatId: string; chunk: string; done?: boolean; error?: string }; + +export const WS_CHANNELS = { + METRICS: 'metrics', + ALERTS: 'alerts', + CONFIG: 'config', + pty: (sessionId: string) => `pty:${sessionId}`, + stream: (jobId: string) => `stream:${jobId}`, + ai: (chatId: string) => `ai:${chatId}`, +} as const;