From afc2d6358adca6aeec46c0d412a6985206afe3a9 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:15:50 +0000 Subject: [PATCH 01/19] feat(db,schemas): add migration 004, runtime throttle profile, and v1.1 Zod schemas --- src/client/ts/state.ts | 2 +- src/server/alerts/alert-engine.ts | 4 +- src/server/automation/workflow-engine.ts | 28 +++++ src/server/config/config-manager.ts | 2 +- src/server/config/runtime-limits.ts | 132 +++++++++++++++++++++ src/server/db/database.ts | 38 +++++- src/server/db/migrations/004_v1_1.ts | 65 ++++++++++ src/server/security/auth.ts | 2 + src/server/ssh/known-hosts.ts | 3 +- src/shared/schemas/alerts.schema.ts | 91 +++++++++++--- src/shared/schemas/common.ts | 34 +++++- src/shared/schemas/server.schema.ts | 119 ++++++++++++++----- src/shared/schemas/settings.schema.ts | 58 ++++++++- src/shared/schemas/snippets.schema.ts | 1 + src/shared/schemas/system.schema.ts | 79 +++++++++--- src/shared/schemas/workflow.schema.ts | 50 ++++++-- src/shared/ws-protocol.ts | 3 + tests/ai-assistant.test.ts | 8 +- tests/alerts-engine.test.ts | 8 +- tests/api-ws-smoke.test.ts | 35 ++++-- tests/auth-and-guards.test.ts | 13 +- tests/backup-and-cli.test.ts | 8 +- tests/custom-systems.test.ts | 8 +- tests/multi-auth-and-recovery.test.ts | 44 ++++++- tests/passkeys.test.ts | 8 +- tests/pty-and-sftp.test.ts | 8 +- tests/servers-api-e2e.test.ts | 5 +- tests/tunnels-and-proxy.test.ts | 8 +- tests/vault-runtime-and-collectors.test.ts | 15 ++- tests/workflows-and-transfer.test.ts | 31 ++++- 30 files changed, 792 insertions(+), 118 deletions(-) create mode 100644 src/server/config/runtime-limits.ts create mode 100644 src/server/db/migrations/004_v1_1.ts diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index c0f690c..f44aac5 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -74,7 +74,7 @@ export interface ClientSecuritySettings { requireTotpOnLogin: boolean; passwordMode: 'any' | 'all'; totpMode: 'any' | 'all'; - stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session'; + stepUpPolicy: 'off' | 'every-action' | '5m' | '15m' | '1h' | '24h' | 'session'; stepUpMethod: 'totp' | 'password' | 'both' | 'passkey'; elevateOnLogin: boolean; keepElevationOnSafeMode: boolean; diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index 7dfc025..93bd169 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -771,9 +771,9 @@ export class AlertEngine { ts: number; }, ): Promise<{ ok: boolean; statusCode?: number; error?: string }> { - const secret = this.readChannelSecret(channel.secretRef); + const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; if (!secret && !channel.url) { - return { ok: false, error: `Missing vault secret "${channel.secretRef}"` }; + return { ok: false, error: `Missing vault secret "${channel.secretRef ?? ''}"` }; } try { diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts index 8d3a181..d1de18a 100644 --- a/src/server/automation/workflow-engine.ts +++ b/src/server/automation/workflow-engine.ts @@ -245,6 +245,13 @@ export class WorkflowEngine { return next ? next.getTime() : null; } + async triggerScheduledCron(workflowId: string): Promise { + const job = this.cronJobs.get(workflowId); + if (!job) return false; + await job.trigger(); + return true; + } + listWorkflowsWithSummary(): Array<{ workflow: WorkflowConfig; nextRunAt: number | null; @@ -632,6 +639,18 @@ export class WorkflowEngine { continue; } + if (step.type === 'http' || step.type === 'notify') { + steps.push({ + stepId: step.id, + type: step.type, + wave, + dependsOn: deps, + targets: [], + envKeys, + }); + continue; + } + const matched = resolveTargetServers(step.target, allServers, baseCtx); const plan: DryRunStepPlan = { stepId: step.id, @@ -1034,6 +1053,15 @@ export class WorkflowEngine { } } + if (step.type === 'http' || step.type === 'notify') { + const msg = `Step type "${step.type}" handler not yet wired`; + control.emitter.push('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'hub', 1, 0, '', 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}"`; diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index 14bed4c..f86cc2a 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -351,7 +351,7 @@ export class ConfigManager { const channelIds = new Set(this.alerts.channels.map((c) => c.id)); if (this.vault && this.vault.isRuntimeReady) { for (const ch of this.alerts.channels) { - if (!this.vault.hasCredential(ch.secretRef)) { + if (ch.secretRef && !this.vault.hasCredential(ch.secretRef)) { next.push({ filePath: 'alerts.json', code: 'MISSING_CHANNEL_SECRET', diff --git a/src/server/config/runtime-limits.ts b/src/server/config/runtime-limits.ts new file mode 100644 index 0000000..5c30c30 --- /dev/null +++ b/src/server/config/runtime-limits.ts @@ -0,0 +1,132 @@ +import type { ThrottleMode } from '../../shared/schemas/settings.schema.js'; + +export interface RuntimeLimits { + mode: ThrottleMode; + argon2MemoryCost: number; + argon2Concurrency: number; + argon2MaxQueue: number; + scryptConcurrency: number; + backupMaxGunzipBytes: number; + backupMaxBodyBytes: number; + sqliteCacheKb: number; + sqliteMmapBytes: number; + sqliteTempStore: 'FILE' | 'MEMORY'; + maxActivePtys: number; + maxRetainedExitedPtys: number; + defaultPtyScrollbackBytes: number; + maxConcurrentMetricPolls: number; + staggerPolls: boolean; + maxParallelSystemInspect: number; + maxSystemCacheEntries: number; + maxConcurrentWorkflows: number; + maxWorkflowStepTargets: number; + maxWorkflowQueue: number; + maxStepLogBytes: number; + streamReplayBytes: number; + maxRamBroadcastJobs: number; + maxConcurrentAiStreams: number; + maxTunnelSocketsPerTunnel: number; + maxGlobalTunnelSockets: number; +} + +const PRESETS: Record = { + 'low-resource': { + mode: 'low-resource', + argon2MemoryCost: 32768, + argon2Concurrency: 1, + argon2MaxQueue: 8, + scryptConcurrency: 1, + backupMaxGunzipBytes: 16 * 1024 * 1024, + backupMaxBodyBytes: 8 * 1024 * 1024, + sqliteCacheKb: 8000, + sqliteMmapBytes: 0, + sqliteTempStore: 'FILE', + maxActivePtys: 12, + maxRetainedExitedPtys: 5, + defaultPtyScrollbackBytes: 262144, + maxConcurrentMetricPolls: 4, + staggerPolls: true, + maxParallelSystemInspect: 2, + maxSystemCacheEntries: 64, + maxConcurrentWorkflows: 2, + maxWorkflowStepTargets: 4, + maxWorkflowQueue: 10, + maxStepLogBytes: 131072, + streamReplayBytes: 65536, + maxRamBroadcastJobs: 5, + maxConcurrentAiStreams: 2, + maxTunnelSocketsPerTunnel: 64, + maxGlobalTunnelSockets: 256, + }, + balanced: { + mode: 'balanced', + argon2MemoryCost: 65536, + argon2Concurrency: 2, + argon2MaxQueue: 16, + scryptConcurrency: 2, + backupMaxGunzipBytes: 32 * 1024 * 1024, + backupMaxBodyBytes: 16 * 1024 * 1024, + sqliteCacheKb: 32000, + sqliteMmapBytes: 0, + sqliteTempStore: 'FILE', + maxActivePtys: 32, + maxRetainedExitedPtys: 12, + defaultPtyScrollbackBytes: 524288, + maxConcurrentMetricPolls: 12, + staggerPolls: true, + maxParallelSystemInspect: 4, + maxSystemCacheEntries: 128, + maxConcurrentWorkflows: 6, + maxWorkflowStepTargets: 12, + maxWorkflowQueue: 25, + maxStepLogBytes: 262144, + streamReplayBytes: 131072, + maxRamBroadcastJobs: 15, + maxConcurrentAiStreams: 6, + maxTunnelSocketsPerTunnel: 128, + maxGlobalTunnelSockets: 512, + }, + unthrottled: { + mode: 'unthrottled', + argon2MemoryCost: 65536, + argon2Concurrency: 4, + argon2MaxQueue: 32, + scryptConcurrency: 4, + backupMaxGunzipBytes: 64 * 1024 * 1024, + backupMaxBodyBytes: 32 * 1024 * 1024, + sqliteCacheKb: 64000, + sqliteMmapBytes: 134217728, + sqliteTempStore: 'MEMORY', + maxActivePtys: 128, + maxRetainedExitedPtys: 30, + defaultPtyScrollbackBytes: 524288, + maxConcurrentMetricPolls: 0, + staggerPolls: false, + maxParallelSystemInspect: 16, + maxSystemCacheEntries: 512, + maxConcurrentWorkflows: 32, + maxWorkflowStepTargets: 0, + maxWorkflowQueue: 100, + maxStepLogBytes: 524288, + streamReplayBytes: 262144, + maxRamBroadcastJobs: 25, + maxConcurrentAiStreams: 16, + maxTunnelSocketsPerTunnel: 512, + maxGlobalTunnelSockets: 2048, + }, +}; + +export function normalizeThrottleMode(raw: string | undefined): ThrottleMode | undefined { + if (raw === 'low-resource' || raw === 'balanced' || raw === 'unthrottled') { + return raw; + } + return undefined; +} + +export function resolveRuntimeLimits( + mode: ThrottleMode = 'low-resource', + envOverride?: string, +): RuntimeLimits { + const effective = normalizeThrottleMode(envOverride) ?? mode; + return PRESETS[effective] ?? PRESETS['low-resource']; +} diff --git a/src/server/db/database.ts b/src/server/db/database.ts index 0e1fedc..b9f2fd5 100644 --- a/src/server/db/database.ts +++ b/src/server/db/database.ts @@ -1,26 +1,62 @@ import fs from 'node:fs'; import path from 'node:path'; import Database from 'better-sqlite3'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import { migration001Initial, type Migration } from './migrations/001_initial.js'; import { migration002MultiAuth } from './migrations/002_multi_auth.js'; import { migration003Phase4Meta } from './migrations/003_phase4_meta.js'; +import { migration004V11 } from './migrations/004_v1_1.js'; const MIGRATIONS: Migration[] = [ migration001Initial, migration002MultiAuth, migration003Phase4Meta, + migration004V11, ]; +function chmodBestEffort(targetPath: string, mode: number): void { + try { + if (fs.existsSync(targetPath)) { + fs.chmodSync(targetPath, mode); + } + } catch { + // Best effort on filesystems without POSIX permissions + } +} + +export function applyDatabaseThrottlePragmas( + db: Database.Database, + limits: Pick, +): void { + const cacheKb = Math.max(2000, Math.floor(limits.sqliteCacheKb)); + const mmapBytes = Math.max(0, Math.floor(limits.sqliteMmapBytes)); + const tempStore = limits.sqliteTempStore === 'MEMORY' ? 'MEMORY' : 'FILE'; + db.pragma(`cache_size = -${cacheKb}`); + db.pragma(`mmap_size = ${mmapBytes}`); + db.pragma(`temp_store = ${tempStore}`); +} + export function openDatabase(dbPath: string): Database.Database { - fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + const parentDir = path.dirname(dbPath); + fs.mkdirSync(parentDir, { recursive: true, mode: 0o700 }); + chmodBestEffort(parentDir, 0o700); const db = new Database(dbPath); db.pragma('journal_mode = WAL'); db.pragma('synchronous = NORMAL'); db.pragma('foreign_keys = ON'); db.pragma('busy_timeout = 5000'); + db.pragma('secure_delete = ON'); + db.pragma('cache_size = -8000'); + db.pragma('mmap_size = 0'); + db.pragma('temp_store = FILE'); + db.pragma('wal_autocheckpoint = 1000'); + db.pragma('journal_size_limit = 16777216'); runMigrations(db); + chmodBestEffort(dbPath, 0o600); + chmodBestEffort(`${dbPath}-wal`, 0o600); + chmodBestEffort(`${dbPath}-shm`, 0o600); return db; } diff --git a/src/server/db/migrations/004_v1_1.ts b/src/server/db/migrations/004_v1_1.ts new file mode 100644 index 0000000..fde7645 --- /dev/null +++ b/src/server/db/migrations/004_v1_1.ts @@ -0,0 +1,65 @@ +import type Database from 'better-sqlite3'; +import type { Migration } from './001_initial.js'; + +export const migration004V11: Migration = { + id: '004_v1_1', + up(db: Database.Database) { + db.exec(` + ALTER TABLE admin_totps ADD COLUMN last_used_step INTEGER; + ALTER TABLE admin_totps ADD COLUMN secret_enc TEXT; + + UPDATE admin_totps + SET last_used_step = CASE + WHEN last_login_step IS NOT NULL AND last_stepup_step IS NOT NULL THEN MAX(last_login_step, last_stepup_step) + WHEN last_login_step IS NOT NULL THEN last_login_step + ELSE last_stepup_step + END; + + UPDATE admin_users + SET password_hash = '', totp_secret = '' + WHERE EXISTS (SELECT 1 FROM admin_passwords); + + CREATE TABLE IF NOT EXISTS rate_limits ( + scope_key TEXT PRIMARY KEY, + failures INTEGER NOT NULL, + locked_until INTEGER NOT NULL, + updated_at INTEGER NOT NULL + ); + + CREATE TABLE IF NOT EXISTS known_hosts_v2 ( + host_port TEXT NOT NULL, + algorithm TEXT NOT NULL, + fingerprint TEXT NOT NULL, + trusted_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY (host_port, algorithm) + ); + + INSERT OR IGNORE INTO known_hosts_v2 (host_port, algorithm, fingerprint, trusted_at, updated_at) + SELECT host_port, algorithm, fingerprint, trusted_at, updated_at FROM known_hosts; + + DROP TABLE known_hosts; + ALTER TABLE known_hosts_v2 RENAME TO known_hosts; + + ALTER TABLE metrics_rollup ADD COLUMN net_rx_avg_bps REAL NOT NULL DEFAULT 0; + ALTER TABLE metrics_rollup ADD COLUMN net_tx_avg_bps REAL NOT NULL DEFAULT 0; + ALTER TABLE metrics_rollup ADD COLUMN disk_max_pct REAL NOT NULL DEFAULT 0; + + CREATE TABLE IF NOT EXISTS broadcast_jobs ( + job_id TEXT PRIMARY KEY, + command TEXT NOT NULL, + snippet_id TEXT, + targets_json TEXT NOT NULL, + status TEXT NOT NULL, + started_at INTEGER NOT NULL, + finished_at INTEGER, + results_json TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_broadcast_jobs_ts ON broadcast_jobs(started_at DESC); + + CREATE INDEX IF NOT EXISTS idx_audit_status ON audit_log(status); + CREATE INDEX IF NOT EXISTS idx_audit_ip ON audit_log(actor_ip); + CREATE INDEX IF NOT EXISTS idx_audit_target ON audit_log(target); + `); + }, +}; diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 30bdb06..6d9480e 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -179,6 +179,8 @@ function computeElevatedUntil( return fromLogin ? null : nowMs + 60_000; case '5m': return nowMs + 5 * 60 * 1000; + case '15m': + return nowMs + 15 * 60 * 1000; case '1h': return nowMs + 60 * 60 * 1000; case '24h': diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index 0fc21ee..68b66a7 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -296,8 +296,7 @@ export class KnownHostsService { .prepare( `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) VALUES (?, ?, ?, ?, ?) - ON CONFLICT(host_port) DO UPDATE SET - algorithm = excluded.algorithm, + ON CONFLICT(host_port, algorithm) DO UPDATE SET fingerprint = excluded.fingerprint, updated_at = excluded.updated_at`, ) diff --git a/src/shared/schemas/alerts.schema.ts b/src/shared/schemas/alerts.schema.ts index 2f7ba6d..1c0959f 100644 --- a/src/shared/schemas/alerts.schema.ts +++ b/src/shared/schemas/alerts.schema.ts @@ -1,16 +1,38 @@ import { z } from 'zod'; -import { CronExpressionSchema, EntityIdSchema } from './common.js'; +import { + CronExpressionSchema, + EntityIdSchema, + HttpUrlSchema, + IanaTimezoneSchema, +} 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 AlertChannelSchema = z + .object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), + url: HttpUrlSchema.optional(), + secretRef: EntityIdSchema.optional(), + chatId: z.string().optional(), + topic: z.string().optional(), + enabled: z.boolean().default(true), + }) + .superRefine((ch, ctx) => { + if (!ch.url && !ch.secretRef) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['secretRef'], + message: 'Alert channel must specify either url or secretRef', + }); + } + if ((ch.type === 'discord' || ch.type === 'telegram') && !ch.secretRef && !ch.url) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['secretRef'], + message: `${ch.type} channel requires secretRef or url`, + }); + } + }); export const AlertRuleTargetSchema = z.object({ serverId: EntityIdSchema.optional(), @@ -30,6 +52,14 @@ const AlertRuleBase = { enabled: z.boolean().default(true), }; +export const SecurityEventKindSchema = z.enum([ + 'login_burst', + 'new_ip_login', + 'panic_lock', + 'key_rotation', + 'backup_restore', +]); + export const AlertRuleSchema = z.discriminatedUnion('kind', [ z.object({ ...AlertRuleBase, @@ -60,26 +90,51 @@ export const AlertRuleSchema = z.discriminatedUnion('kind', [ systemId: EntityIdSchema, item: z.string().optional(), }), + z.object({ + ...AlertRuleBase, + kind: z.literal('security-event'), + events: z.array(SecurityEventKindSchema).min(1), + }), ]); export const MaintenanceWindowSchema = z.object({ id: EntityIdSchema, name: z.string().min(1).max(120), cron: CronExpressionSchema, - timezone: z.string().min(1).default('UTC'), + timezone: IanaTimezoneSchema.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 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([]), + }) + .superRefine((doc, ctx) => { + const checkDupes = (items: Array<{ id: string }>, arrPath: string) => { + const seen = new Set(); + items.forEach((item, idx) => { + if (seen.has(item.id)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: [arrPath, idx, 'id'], + message: `Duplicate ${arrPath} id "${item.id}"`, + }); + } + seen.add(item.id); + }); + }; + checkDupes(doc.channels, 'channels'); + checkDupes(doc.rules, 'rules'); + checkDupes(doc.maintenanceWindows, 'maintenanceWindows'); + }); export type AlertChannel = z.infer; export type AlertRule = z.infer; +export type SecurityEventKind = 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 index 081c377..3493d45 100644 --- a/src/shared/schemas/common.ts +++ b/src/shared/schemas/common.ts @@ -5,16 +5,44 @@ 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._-]'); + .regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/, 'ID must start with alphanumeric and contain only [a-zA-Z0-9._-]') + .refine((v) => !v.includes('..'), 'ID cannot contain ".."'); export const PortSchema = z.number().int().min(1).max(65535); +export const HttpUrlSchema = z + .string() + .url() + .refine((u) => /^https?:\/\//i.test(u), 'URL must use http:// or https://'); + +export const IanaTimezoneSchema = z + .string() + .min(1) + .max(64) + .refine((tz) => { + try { + Intl.DateTimeFormat(undefined, { timeZone: tz }); + return true; + } catch { + return false; + } + }, 'Invalid IANA timezone'); + export const CronExpressionSchema = z .string() .min(1) .superRefine((expr, ctx) => { + const trimmed = expr.trim(); + const fields = trimmed.split(/\s+/); + if (fields.length !== 5) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'Cron expression must have exactly 5 fields (minute hour day month weekday)', + }); + return; + } try { - new CronPattern(expr); + new CronPattern(trimmed); } catch (err) { ctx.addIssue({ code: z.ZodIssueCode.custom, @@ -25,7 +53,7 @@ export const CronExpressionSchema = z export const InputDefSchema = z.object({ name: EntityIdSchema, - type: z.enum(['string', 'number', 'boolean', 'server', 'select']).default('string'), + type: z.enum(['string', 'number', 'boolean', 'server', 'select', 'secret']).default('string'), label: z.string().min(1).optional(), description: z.string().optional(), required: z.boolean().default(false), diff --git a/src/shared/schemas/server.schema.ts b/src/shared/schemas/server.schema.ts index c3426e1..95f7d4d 100644 --- a/src/shared/schemas/server.schema.ts +++ b/src/shared/schemas/server.schema.ts @@ -1,22 +1,42 @@ import { z } from 'zod'; -import { EntityIdSchema, PortSchema } from './common.js'; +import { EntityIdSchema, HttpUrlSchema, PortSchema } from './common.js'; + +export const SafeHostSchema = z + .string() + .min(1) + .max(255) + .regex( + /^[A-Za-z0-9\[][A-Za-z0-9._:\[\]-]*$/, + 'Host cannot start with "-" or contain whitespace, "@", or control characters', + ); + +export const SafeUsernameSchema = z + .string() + .min(1) + .max(64) + .regex( + /^[A-Za-z0-9_][A-Za-z0-9._-]*$/, + 'Username cannot start with "-" or contain whitespace, "@", or ":"', + ); export const HttpProbeSchema = z.object({ id: EntityIdSchema, type: z.literal('http'), - url: z.string().url(), + url: HttpUrlSchema, 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(), + tlsRejectUnauthorized: z.boolean().default(true), + tlsCheckExpiryDays: z.number().int().min(1).max(365).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'), + host: SafeHostSchema.default('127.0.0.1'), port: PortSchema, from: z.enum(['hub', 'target']).default('target'), intervalSec: z.number().int().min(5).max(86400).default(30), @@ -40,36 +60,71 @@ export const ServerSystemAttachmentSchema = z.object({ .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 ServerTunnelSchema = z + .object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp', 'socks5']), + bindHost: SafeHostSchema.optional(), + bindPort: PortSchema.optional(), + targetHost: SafeHostSchema.default('127.0.0.1'), + targetPort: z.number().int().min(0).max(65535).default(0), + targetProtocol: z.enum(['http', 'https']).default('http'), + tlsRejectUnauthorized: z.boolean().default(true), + tlsServerName: z.string().max(255).optional(), + ttlSec: z.number().int().min(60).max(86400).optional(), + autoStart: z.boolean().default(false), + }) + .superRefine((tunnel, ctx) => { + if (tunnel.mode !== 'socks5' && tunnel.targetPort < 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['targetPort'], + message: 'targetPort must be between 1 and 65535', + }); + } + }); -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 const ServerConfigSchema = z + .object({ + id: EntityIdSchema, + name: z.string().min(1).max(120), + host: SafeHostSchema, + port: PortSchema.default(22), + username: SafeUsernameSchema, + 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), + }) + .superRefine((srv, ctx) => { + const checkDupes = (items: Array<{ id?: string; systemId?: string }>, key: 'id' | 'systemId', arrPath: string) => { + const seen = new Set(); + items.forEach((item, idx) => { + const val = item[key]; + if (!val) return; + if (seen.has(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: [arrPath, idx, key], + message: `Duplicate ${arrPath} identifier "${val}"`, + }); + } + seen.add(val); + }); + }; + checkDupes(srv.probes, 'id', 'probes'); + checkDupes(srv.systems, 'systemId', 'systems'); + checkDupes(srv.tunnels, 'id', 'tunnels'); + }); export type ServerProbe = z.infer; export type ServerSystemAttachment = z.infer; diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts index efd2ca8..811b3e9 100644 --- a/src/shared/schemas/settings.schema.ts +++ b/src/shared/schemas/settings.schema.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { EntityIdSchema } from './common.js'; +import { EntityIdSchema, HttpUrlSchema, IanaTimezoneSchema } from './common.js'; export const ThemeIdSchema = z.enum([ 'phosphor-green', @@ -14,10 +14,13 @@ export const ThemeIdSchema = z.enum([ export const THEME_IDS = ThemeIdSchema.options; +export const ThrottleModeSchema = z.enum(['low-resource', 'balanced', 'unthrottled']); + export const StepUpPolicySchema = z.enum([ 'off', 'every-action', '5m', + '15m', '1h', '24h', 'session', @@ -29,11 +32,15 @@ export const SecuritySettingsSchema = z.object({ requireTotpOnLogin: z.boolean().default(true), passwordMode: z.enum(['any', 'all']).default('any'), totpMode: z.enum(['any', 'all']).default('any'), - stepUpPolicy: StepUpPolicySchema.default('1h'), + stepUpPolicy: StepUpPolicySchema.default('15m'), stepUpMethod: StepUpMethodSchema.default('totp'), - elevateOnLogin: z.boolean().default(true), + elevateOnLogin: z.boolean().default(false), keepElevationOnSafeMode: z.boolean().default(true), - enableEmergencySecretsBackup: z.boolean().default(true), + enableEmergencySecretsBackup: z.boolean().default(false), + allowSameOriginProxy: z.boolean().default(false), + egressAllowedCidrs: z.array(z.string().min(1).max(64)).max(64).default([]), + sessionTtlHours: z.number().int().min(1).max(720).default(168), + sessionIdleTimeoutMin: z.number().int().min(0).max(10080).default(60), }); export const SettingsSchema = z.object({ @@ -42,29 +49,68 @@ export const SettingsSchema = z.object({ 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), + auditRetentionDays: z.number().int().min(1).max(3650).default(90), + workflowRunRetentionDays: z.number().int().min(1).max(3650).default(30), + alertEventRetentionDays: 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), + ptyScrollbackBytes: z.number().int().min(16384).max(2097152).default(262144), 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), + runtime: z + .object({ + throttleMode: ThrottleModeSchema.default('low-resource'), + }) + .default({ throttleMode: 'low-resource' }), + scheduledBackup: z + .object({ + enabled: z.boolean().default(false), + cron: z.string().min(1).default('0 3 * * *'), + timezone: IanaTimezoneSchema.default('UTC'), + destination: z.enum(['local', 'sftp']).default('local'), + localDir: z.string().min(1).max(128).default('backups'), + remoteServerId: EntityIdSchema.optional(), + remotePath: z.string().min(1).max(256).optional(), + retentionCount: z.number().int().min(1).max(100).default(7), + passphraseSecretRef: EntityIdSchema.optional(), + }) + .default({ + enabled: false, + cron: '0 3 * * *', + timezone: 'UTC', + destination: 'local', + localDir: 'backups', + retentionCount: 7, + }), + metrics: z + .object({ + prometheusEnabled: z.boolean().default(false), + prometheusSecretRef: EntityIdSchema.optional(), + }) + .default({ prometheusEnabled: false }), security: SecuritySettingsSchema.default({}), ai: z .object({ enabled: z.boolean().default(false), - baseUrl: z.string().url().default('http://127.0.0.1:11434'), + baseUrl: HttpUrlSchema.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), + timeoutSec: z.number().int().min(5).max(300).default(90), + maxTokens: z.number().int().min(64).max(32768).default(2048), }) .default({ enabled: false, baseUrl: 'http://127.0.0.1:11434', model: 'qwen2.5-coder:7b', maxContextChars: 16000, + timeoutSec: 90, + maxTokens: 2048, }), }); export type ThemeId = z.infer; +export type ThrottleMode = z.infer; export type StepUpPolicy = z.infer; export type StepUpMethod = z.infer; export type SecuritySettings = z.infer; diff --git a/src/shared/schemas/snippets.schema.ts b/src/shared/schemas/snippets.schema.ts index 905a5f9..c85a888 100644 --- a/src/shared/schemas/snippets.schema.ts +++ b/src/shared/schemas/snippets.schema.ts @@ -7,6 +7,7 @@ export const SnippetSchema = z.object({ description: z.string().optional(), command: z.string().min(1), tags: z.array(z.string().min(1)).default([]), + osFilter: z.array(z.enum(['linux', 'bsd', 'macos'])).optional(), inputs: z.array(InputDefSchema).default([]), sudo: z.boolean().default(false), confirm: z.boolean().default(false), diff --git a/src/shared/schemas/system.schema.ts b/src/shared/schemas/system.schema.ts index dc54458..1d2a59e 100644 --- a/src/shared/schemas/system.schema.ts +++ b/src/shared/schemas/system.schema.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { EntityIdSchema } from './common.js'; +import { EntityIdSchema, InputDefSchema } from './common.js'; export const SystemParamDefSchema = z.object({ name: EntityIdSchema, @@ -39,7 +39,19 @@ 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(), + regexPattern: z + .string() + .min(1) + .max(512) + .refine((pat) => { + try { + new RegExp(pat); + return true; + } catch { + return false; + } + }, 'Invalid regular expression pattern') + .optional(), health: SystemHealthRuleSchema.optional(), }); @@ -49,22 +61,61 @@ export const SystemActionSchema = z.object({ scope: z.enum(['system', 'item', 'subitem']), mode: z.enum(['oneshot', 'stream', 'interactive']), command: z.string().min(1), + inputs: z.array(InputDefSchema).default([]), + timeoutSec: z.number().int().min(5).max(3600).optional(), 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 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([]), + }) + .superRefine((sys, ctx) => { + const paramNames = new Set(); + sys.params.forEach((p, idx) => { + if (paramNames.has(p.name)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['params', idx, 'name'], + message: `Duplicate system param "${p.name}"`, + }); + } + paramNames.add(p.name); + }); + + if ( + sys.discovery.type === 'folder-scan' && + !paramNames.has(sys.discovery.rootsParam) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['discovery', 'rootsParam'], + message: `rootsParam "${sys.discovery.rootsParam}" is not defined in params`, + }); + } + + const actionIds = new Set(); + sys.actions.forEach((a, idx) => { + if (actionIds.has(a.id)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['actions', idx, 'id'], + message: `Duplicate action id "${a.id}"`, + }); + } + actionIds.add(a.id); + }); + }); export type SystemParamDef = z.infer; export type SystemHealthRule = z.infer; diff --git a/src/shared/schemas/workflow.schema.ts b/src/shared/schemas/workflow.schema.ts index 7e1cf6c..646a10f 100644 --- a/src/shared/schemas/workflow.schema.ts +++ b/src/shared/schemas/workflow.schema.ts @@ -1,5 +1,11 @@ import { z } from 'zod'; -import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js'; +import { + CronExpressionSchema, + EntityIdSchema, + HttpUrlSchema, + IanaTimezoneSchema, + InputDefSchema, +} from './common.js'; export const WorkflowTargetSchema = z .object({ @@ -23,12 +29,13 @@ export const StepDependencySchema = z.union([ 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(), - }), + EntityIdSchema, + z.discriminatedUnion('action', [ + z.object({ action: z.literal('abort') }), + z.object({ action: z.literal('continue') }), + z.object({ action: z.literal('notify'), channelId: EntityIdSchema }), + z.object({ action: z.literal('run-workflow'), workflowId: EntityIdSchema }), + ]), ]); const StepBaseFields = { @@ -36,6 +43,9 @@ const StepBaseFields = { name: z.string().min(1).max(120).optional(), dependsOn: z.array(StepDependencySchema).default([]), timeoutSec: z.number().int().min(1).max(86400).optional(), + retries: z.number().int().min(0).max(5).default(0), + retryBackoffSec: z.number().int().min(1).max(300).default(5), + when: z.string().min(1).max(256).optional(), sudo: z.boolean().default(false), captureAs: z.string().min(1).max(64).optional(), onFailure: StepFailureActionSchema.optional(), @@ -80,6 +90,28 @@ export const TransferStepSchema = z.object({ serverId: z.string().min(1), path: z.string().min(1), }), + delete: z.boolean().optional(), + exclude: z.array(z.string().min(1)).max(32).optional(), +}); + +export const HttpStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('http'), + url: HttpUrlSchema, + method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']).default('POST'), + headers: z.record(z.string()).optional(), + body: z.string().optional(), + secretRef: EntityIdSchema.optional(), + expectedStatus: z.number().int().min(100).max(599).optional(), +}); + +export const NotifyStepSchema = z.object({ + ...StepBaseFields, + type: z.literal('notify'), + channelIds: z.array(EntityIdSchema).min(1), + title: z.string().min(1).max(160), + message: z.string().min(1).max(4000), + severity: z.enum(['warn', 'critical']).default('warn'), }); export const WorkflowStepSchema = z.discriminatedUnion('type', [ @@ -87,6 +119,8 @@ export const WorkflowStepSchema = z.discriminatedUnion('type', [ ReadFileStepSchema, SystemActionStepSchema, TransferStepSchema, + HttpStepSchema, + NotifyStepSchema, ]); export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ @@ -94,7 +128,7 @@ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ z.object({ type: z.literal('cron'), expression: CronExpressionSchema, - timezone: z.string().min(1).default('UTC'), + timezone: IanaTimezoneSchema.default('UTC'), }), z.object({ type: z.literal('event'), diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index 66a596e..0dc686c 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -1,6 +1,7 @@ import { z } from 'zod'; export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; +export type VaultSealState = 'uninitialized' | 'sealed' | 'write-locked' | 'unlocked'; export type ServerConnectionStatus = | 'disconnected' @@ -133,6 +134,7 @@ export type ServerWsFrame = type: 'hello'; vaultState: VaultState; vaultRuntimeReady?: boolean; + vaultSealState?: VaultSealState; safeMode: boolean; elevatedUntil: number | null; } @@ -140,6 +142,7 @@ export type ServerWsFrame = type: 'vault:state'; vaultState: VaultState; vaultRuntimeReady: boolean; + vaultSealState?: VaultSealState; isPanicLocked: boolean; } | { diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts index 8dedbae..48d5181 100644 --- a/tests/ai-assistant.test.ts +++ b/tests/ai-assistant.test.ts @@ -3,7 +3,7 @@ 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 { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; @@ -205,6 +205,8 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide return { status: res.status, data }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -225,7 +227,11 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); await api('/api/vault/credentials', { diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts index 59d0fd8..59f6380 100644 --- a/tests/alerts-engine.test.ts +++ b/tests/alerts-engine.test.ts @@ -3,7 +3,7 @@ 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 { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -132,6 +132,8 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => return { status: res.status, data }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -152,7 +154,11 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/api-ws-smoke.test.ts b/tests/api-ws-smoke.test.ts index 863fa15..d697842 100644 --- a/tests/api-ws-smoke.test.ts +++ b/tests/api-ws-smoke.test.ts @@ -3,7 +3,7 @@ import os from 'node:os'; import path from 'node:path'; import zlib from 'node:zlib'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; @@ -115,7 +115,9 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { expect(health.status).toBe(200); await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401'); - // 2. Bootstrap Admin + TOTP + // 2. Bootstrap Admin + TOTP (offset 65s back so step-up tests below have fresh TOTP steps) + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 65_000); const bootInfo = await api('/api/auth/bootstrap'); expect(bootInfo.status).toBe(200); const secretBase32 = String(bootInfo.data.secretBase32); @@ -138,6 +140,7 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { initialSafeMode: false, }, }); + vi.setSystemTime(Date.now() + 31_000); expect(bootDone.status).toBe(201); csrfToken = String(bootDone.data.csrfToken); const recoveryCodes = bootDone.data.recoveryCodes as string[]; @@ -198,17 +201,14 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status, ).toBe(200); - // 6. Vault Init + Drop Elevation -> Step-Up guard + Generate Ed25519 key + // 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); expect(vInit.status).toBe(201); const generatedMasterKey = String(vInit.data.generatedKeyHex); - // Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement - const statusBeforeDrop = await api('/api/auth/status'); - expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); - const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); - expect(dropped.status).toBe(200); - expect(dropped.data.elevatedUntil).toBeNull(); + // v1.1 defaults elevateOnLogin=false; step up first, then verify drop-elevation clears it + const statusInitial = await api('/api/auth/status'); + expect(statusInitial.data.elevatedUntil).toBeNull(); const noStepUp = await api('/api/vault/generate-ed25519', { method: 'POST', @@ -223,6 +223,23 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { }); expect(stepUpRes.status).toBe(200); + const statusBeforeDrop = await api('/api/auth/status'); + expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); + const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); + expect(dropped.status).toBe(200); + expect(dropped.data.elevatedUntil).toBeNull(); + + const afterDropDenied = await api('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'prod-key', name: 'Prod Key' }, + }); + expect(afterDropDenied.status).toBe(403); + + vi.useRealTimers(); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totpGen.generate() } })).status, + ).toBe(200); + const genRes = await api('/api/vault/generate-ed25519', { method: 'POST', body: { id: 'prod-key', name: 'Prod Key' }, diff --git a/tests/auth-and-guards.test.ts b/tests/auth-and-guards.test.ts index 7d6b6bf..2fb7ca6 100644 --- a/tests/auth-and-guards.test.ts +++ b/tests/auth-and-guards.test.ts @@ -164,7 +164,7 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { db.close(); }); - it('grants default 1h elevation on bootstrap/login and preserves elevation across Safe Mode toggle', async () => { + it('keeps elevateOnLogin disabled by default (15m step-up policy) and preserves elevation across Safe Mode toggle', async () => { vi.useFakeTimers({ toFake: ['Date'] }); const t0 = 1_700_000_010_000; vi.setSystemTime(t0); @@ -180,11 +180,18 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { userAgent: 'vitest', }); - expect(boot.session.elevatedUntil).toBe(t0 + 60 * 60 * 1000); + expect(boot.session.elevatedUntil).toBeNull(); + + vi.setSystemTime(t0 + 31_000); + const step = await auth.stepUp(boot.session.idHash, generateTotp(enroll.secretBase32, t0 + 31_000)); + expect(step).toEqual({ + ok: true, + elevatedUntil: t0 + 31_000 + 15 * 60 * 1000, + }); const safeSession = auth.setSafeMode(boot.session.idHash, true); expect(safeSession?.safeMode).toBe(true); - expect(safeSession?.elevatedUntil).toBe(t0 + 60 * 60 * 1000); + expect(safeSession?.elevatedUntil).toBe(t0 + 31_000 + 15 * 60 * 1000); db.close(); }); diff --git a/tests/backup-and-cli.test.ts b/tests/backup-and-cli.test.ts index e6e58e9..63fdc36 100644 --- a/tests/backup-and-cli.test.ts +++ b/tests/backup-and-cli.test.ts @@ -4,7 +4,7 @@ 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 { afterEach, describe, expect, it, vi } 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'; @@ -84,6 +84,8 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C return { status: res.status, data }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -104,7 +106,11 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/custom-systems.test.ts b/tests/custom-systems.test.ts index f587d67..e5e12a4 100644 --- a/tests/custom-systems.test.ts +++ b/tests/custom-systems.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -103,6 +103,8 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & return { status: res.status, data: data as Record }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -123,7 +125,11 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions & initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index f2431b2..7e61fe3 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -192,7 +192,13 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(201); - // Initialize vault & generate key while default 1h login elevation is active + // Explicitly step up before vault mutations (v1.1 default elevateOnLogin=false) + vi.setSystemTime(t0 + 31_000); + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status, + ).toBe(200); + + // Initialize vault & generate key while elevated expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect( ( @@ -231,7 +237,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200); api.clearCsrf(); - vi.setSystemTime(t0 + 31_000); + vi.setSystemTime(t0 + 62_000); const anyLogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -275,7 +281,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret // Logout and test 'all' enforcement expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200); api.clearCsrf(); - vi.setSystemTime(t0 + 62_000); + vi.setSystemTime(t0 + 93_000); const partialPw = await api.call('/api/auth/login', { method: 'POST', @@ -288,7 +294,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }); expect(partialPw.status).toBe(401); - vi.setSystemTime(t0 + 93_000); + vi.setSystemTime(t0 + 124_000); const partialTotp = await api.call('/api/auth/login', { method: 'POST', body: { @@ -300,7 +306,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret }); expect(partialTotp.status).toBe(401); - vi.setSystemTime(t0 + 124_000); + vi.setSystemTime(t0 + 155_000); const fullAllLogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -364,6 +370,24 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret } }); + const curSettings = server.configManager.getSettings(); + server.configManager.saveConfigText( + 'settings.json', + JSON.stringify( + { + ...curSettings, + security: { + ...curSettings.security, + enableEmergencySecretsBackup: true, + }, + }, + null, + 2, + ), + 'ui', + 'Enable emergency recovery for test', + ); + let api = createApiClient(server); const bootInfo = await api.call('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); @@ -382,6 +406,11 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect(boot.status).toBe(201); const recoveryCodes = boot.data.recoveryCodes as string[]; + vi.setSystemTime(t0 + 31_000); + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + const vInit = await api.call('/api/vault/init', { method: 'POST', body: {} }); expect(vInit.status).toBe(201); const masterKeyHex = String(vInit.data.generatedKeyHex); @@ -478,6 +507,11 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(200); + vi.setSystemTime(t0 + 62_000); + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + const wipeRes = await api.call('/api/auth/recovery-backup?disable=1', { method: 'DELETE', }); diff --git a/tests/passkeys.test.ts b/tests/passkeys.test.ts index 7489aee..9f5c444 100644 --- a/tests/passkeys.test.ts +++ b/tests/passkeys.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { createGCoordinatorServer } from '../src/server/app.js'; const cleanups: Array<() => Promise | void> = []; @@ -202,6 +202,8 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { return { status: res.status, data }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -226,6 +228,10 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { }) ).status, ).toBe(201); + vi.useRealTimers(); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); await api('/api/vault/generate-ed25519', { diff --git a/tests/pty-and-sftp.test.ts b/tests/pty-and-sftp.test.ts index a65c8c6..40cb5ba 100644 --- a/tests/pty-and-sftp.test.ts +++ b/tests/pty-and-sftp.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +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'; @@ -82,6 +82,8 @@ async function setupServerWithSsh() { return { status: res.status, data: data as Record }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -102,7 +104,11 @@ async function setupServerWithSsh() { initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/servers-api-e2e.test.ts b/tests/servers-api-e2e.test.ts index 6b34ce5..583252b 100644 --- a/tests/servers-api-e2e.test.ts +++ b/tests/servers-api-e2e.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -88,6 +88,8 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic }; // Bootstrap + Auth + Vault + Ed25519 Key + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -108,6 +110,7 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic secretBase32, }, }); + vi.useRealTimers(); expect(bootRes.status).toBe(201); csrfToken = String(bootRes.data.csrfToken); diff --git a/tests/tunnels-and-proxy.test.ts b/tests/tunnels-and-proxy.test.ts index 0d1e9e0..9ae5a40 100644 --- a/tests/tunnels-and-proxy.test.ts +++ b/tests/tunnels-and-proxy.test.ts @@ -4,7 +4,7 @@ import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import WebSocket, { WebSocketServer } from 'ws'; import { createGCoordinatorServer } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -127,6 +127,8 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC return { status: res.status, data: data as Record }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -147,7 +149,11 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { diff --git a/tests/vault-runtime-and-collectors.test.ts b/tests/vault-runtime-and-collectors.test.ts index 373a588..6c1374e 100644 --- a/tests/vault-runtime-and-collectors.test.ts +++ b/tests/vault-runtime-and-collectors.test.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import * as OTPAuth from 'otpauth'; -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; import { MockSshServer } from './helpers/mock-ssh-server.js'; @@ -104,6 +104,8 @@ describe('Always-on background collectors & write-only Vault lock', () => { } }); + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 65_000); let api = createApiClient(activeServer); const bootInfo = await api.call('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); @@ -130,6 +132,12 @@ describe('Always-on background collectors & write-only Vault lock', () => { const recoveryCodes = bootRes.data.recoveryCodes as string[]; expect(recoveryCodes.length).toBeGreaterThan(0); + vi.setSystemTime(Date.now() + 31_000); + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + vi.useRealTimers(); + // Explicitly initialize & add SSH key, register server, then lock Vault expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); const keyRes = await api.call('/api/vault/generate-ed25519', { @@ -230,6 +238,11 @@ describe('Always-on background collectors & write-only Vault lock', () => { expect((await api.call('/api/servers/srv-1/inspect')).status).toBe(200); expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).status).toBe(200); + // Step up so the Vault write-lock guard (423 VAULT_LOCKED) is reached + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + // Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked const addBlocked = await api.call('/api/vault/credentials', { method: 'POST', diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts index 41ee12e..ec1e5f2 100644 --- a/tests/workflows-and-transfer.test.ts +++ b/tests/workflows-and-transfer.test.ts @@ -141,6 +141,8 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers return { status: res.status, data }; }; + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() - 35_000); const bootInfo = await api('/api/auth/bootstrap'); const secretBase32 = String(bootInfo.data.secretBase32); const totp = new OTPAuth.TOTP({ @@ -161,7 +163,11 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers initialSafeMode: false, }, }); + vi.useRealTimers(); csrfToken = String(boot.data.csrfToken); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); await api('/api/vault/init', { method: 'POST', body: {} }); const keyRes = await api('/api/vault/generate-ed25519', { @@ -751,20 +757,36 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(dCancelled.run.status).toBe('cancelled'); expect(dCancelled.run.cancelledBy).toBe('admin'); - // --- 5. Cron Workflow Scheduling --- - await api('/api/workflows', { + // --- 5. Cron Workflow Scheduling (5-field enforced; 6-field rejected) --- + const badCronRes = await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-cron-bad', + name: '6-Field Spam 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 NOPE' }], + }, + }); + expect(badCronRes.status).toBe(400); + + const okCronRes = await api('/api/workflows', { method: 'POST', body: { id: 'wf-cron-sec', - name: 'Every Second Cron', + name: 'Every Minute Cron', enabled: true, - trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, + 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' }], }, }); + expect(okCronRes.status).toBe(201); const listSummary = await api('/api/workflows'); const cronSummary = ( @@ -776,6 +798,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers expect(typeof cronSummary?.nextRunAt).toBe('number'); expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000); + expect(await server.workflowEngine.triggerScheduledCron('wf-cron-sec')).toBe(true); const cronRun = await waitFor( () => { const runs = server.workflowEngine.listRuns('wf-cron-sec'); From 005c82e6bf39bc1f545368cdf3a98f19871ee4b4 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:18:02 +0000 Subject: [PATCH 02/19] security(egress,guards,docker): add Zero-Trust egress guard, SQLite rate limiter, proxy CIDR trust & Docker hardening --- .dockerignore | 12 ++ docker/Dockerfile | 14 +- docker/docker-compose.lan.yml | 1 + docker/docker-compose.yml | 18 +- src/server/app.ts | 79 ++++++-- src/server/index.ts | 21 +++ src/server/security/egress-guard.ts | 244 +++++++++++++++++++++++++ src/server/security/guards.ts | 269 +++++++++++++++++++++++++--- 8 files changed, 616 insertions(+), 42 deletions(-) create mode 100644 .dockerignore create mode 100644 src/server/security/egress-guard.ts diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..98b322b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,12 @@ +node_modules/ +dist/ +data/ +docker/secrets/ +.git/ +.env +.env.* +*.gcoord.enc +*.tsbuildinfo +coverage/ +tests/ +.DS_Store diff --git a/docker/Dockerfile b/docker/Dockerfile index c473dcc..f2993fc 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -18,19 +18,21 @@ FROM node:22-bookworm-slim AS runtime WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends \ - ca-certificates openssh-client rsync zstd tar \ + ca-certificates \ && rm -rf /var/lib/apt/lists/* \ - && mkdir -p /data && chown -R 1000:1000 /app /data + && mkdir -p /data && chown 1000:1000 /data && chmod 0700 /data -COPY --from=builder --chown=1000:1000 /app/package.json ./ -COPY --from=builder --chown=1000:1000 /app/node_modules ./node_modules -COPY --from=builder --chown=1000:1000 /app/dist ./dist +COPY --from=builder /app/package.json ./ +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/dist ./dist USER 1000:1000 ENV NODE_ENV=production \ PORT=3000 \ - GCOORD_DATA_DIR=/data + HOST=0.0.0.0 \ + GCOORD_DATA_DIR=/data \ + NODE_OPTIONS="--max-old-space-size=384" EXPOSE 3000 diff --git a/docker/docker-compose.lan.yml b/docker/docker-compose.lan.yml index 1b38964..2ccd7dc 100644 --- a/docker/docker-compose.lan.yml +++ b/docker/docker-compose.lan.yml @@ -2,6 +2,7 @@ services: gcoordinator: environment: - TRUST_CLOUDFLARE=false + - GCOORD_ALLOW_LAN_TUNNELS=${GCOORD_ALLOW_LAN_TUNNELS:-false} ports: - "${GCOORD_LAN_BIND:-127.0.0.1}:3000:3000" - "${GCOORD_LAN_BIND:-127.0.0.1}:20000-20020:20000-20020" diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 5451cf0..15a1e1f 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -7,13 +7,22 @@ services: restart: unless-stopped user: "1000:1000" read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: ${GCOORD_MEM_LIMIT:-512m} + pids_limit: 128 tmpfs: - - /tmp + - /tmp:rw,noexec,nosuid,nodev,size=64m environment: - NODE_ENV=production - PORT=3000 + - HOST=0.0.0.0 - GCOORD_DATA_DIR=/data - TRUST_CLOUDFLARE=true + - GCOORD_THROTTLE_MODE=${GCOORD_THROTTLE_MODE:-low-resource} + - NODE_OPTIONS=--max-old-space-size=${GCOORD_NODE_MAX_OLD_SPACE:-384} secrets: - gcoord_master_key volumes: @@ -26,6 +35,13 @@ services: image: cloudflare/cloudflared:latest container_name: gcoordinator-tunnel restart: unless-stopped + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 128m + pids_limit: 64 command: tunnel --no-autoupdate run environment: - TUNNEL_TOKEN=${CLOUDFLARED_TUNNEL_TOKEN} diff --git a/src/server/app.ts b/src/server/app.ts index 3a0ba6e..a4f433b 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -2,23 +2,27 @@ import fs from 'node:fs'; import http from 'node:http'; import path from 'node:path'; import type Database from 'better-sqlite3'; -import express, { type Express } from 'express'; +import express, { type Express, type NextFunction, type Request, type Response } from 'express'; +import type { ThrottleMode } from '../shared/schemas/settings.schema.js'; import { AiService } from './ai/ai-service.js'; import { AlertEngine } from './alerts/alert-engine.js'; import { BroadcastService } from './automation/broadcast-service.js'; import { TransferEngine } from './automation/transfer-engine.js'; import { WorkflowEngine } from './automation/workflow-engine.js'; import { ConfigManager } from './config/config-manager.js'; -import { openDatabase } from './db/database.js'; +import { resolveRuntimeLimits } from './config/runtime-limits.js'; +import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js'; import { ServerInspector } from './monitoring/inspector.js'; import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; import { + DEFAULT_TRUSTED_PROXY_CIDRS, RateLimiter, attachClientIp, createStepUpGuard, + isTrustedProxyPeer, } from './security/guards.js'; import { EmergencyRecoveryService } from './security/recovery-store.js'; import { VaultService } from './security/vault.js'; @@ -53,6 +57,15 @@ export interface ServerOptions { secretFilePath?: string; envMasterKey?: string; trustCloudflare?: boolean; + trustedProxyCidrs?: string[]; + allowLanTunnels?: boolean; + proxyBaseDomain?: string; + proxyPort?: number; + webauthnRpId?: string; + webauthnOrigins?: string[]; + metricsToken?: string; + throttleModeOverride?: ThrottleMode; + autoKeyFile?: boolean; watchConfig?: boolean; } @@ -92,8 +105,14 @@ export async function createGCoordinatorServer( const dbPath = path.join(dataDir, 'gcoord.db'); const vaultPath = path.join(dataDir, 'vault.enc'); const trustCloudflare = Boolean(options.trustCloudflare); + const trustedProxyCidrs = options.trustedProxyCidrs ?? DEFAULT_TRUSTED_PROXY_CIDRS; - fs.mkdirSync(dataDir, { recursive: true }); + fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 }); + try { + fs.chmodSync(dataDir, 0o700); + } catch { + // Best-effort on filesystems without POSIX permissions + } const db = openDatabase(dbPath); const auditService = new AuditService(db); @@ -101,11 +120,18 @@ export async function createGCoordinatorServer( keyFilePath: path.join(dataDir, 'vault.key'), }); const recoveryStore = new EmergencyRecoveryService(dataDir); - const rateLimiter = new RateLimiter(); + const rateLimiter = new RateLimiter({ db }); const configManager = new ConfigManager(configDir, db, vaultService); await configManager.init({ watch: options.watchConfig ?? true }); + const getRuntimeLimits = () => + resolveRuntimeLimits( + configManager.getSettings().runtime?.throttleMode ?? 'low-resource', + options.throttleModeOverride, + ); + applyDatabaseThrottlePragmas(db, getRuntimeLimits()); + const authService = new AuthService(db, { getSecuritySettings: () => configManager.getSettings().security, recoveryStore, @@ -129,9 +155,10 @@ export async function createGCoordinatorServer( } const app = express(); + app.locals.auditService = auditService; app.disable('x-powered-by'); if (trustCloudflare) { - app.set('trust proxy', 1); + app.set('trust proxy', (ip: string) => isTrustedProxyPeer(ip, trustedProxyCidrs)); } const httpServer = http.createServer(app); @@ -256,17 +283,30 @@ export async function createGCoordinatorServer( app.use((req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); + res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); + if (req.secure || trustCloudflare) { + res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); + } + if (req.path.startsWith('/api/')) { + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Pragma', 'no-cache'); + } if (!req.path.startsWith('/proxy/')) { + const rawHost = typeof req.headers.host === 'string' ? req.headers.host.trim() : ''; + const safeHost = /^[A-Za-z0-9.\-:\[\]]+$/.test(rawHost) ? rawHost : ''; + const connectSrc = safeHost + ? `'self' ws://${safeHost} wss://${safeHost}` + : `'self'`; res.setHeader('X-Frame-Options', 'DENY'); res.setHeader( 'Content-Security-Policy', - "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self' ws: wss:; frame-ancestors 'none'; base-uri 'self'", + `default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src ${connectSrc}; object-src 'none'; form-action 'self'; frame-ancestors 'none'; base-uri 'self'`, ); } next(); }); - app.use(attachClientIp(trustCloudflare)); + app.use(attachClientIp(trustCloudflare, trustedProxyCidrs)); // Mount /proxy before express.json so proxied POST/PUT payloads stream untouched upstream app.use('/proxy', createProxyRouter({ authService, tunnelManager })); @@ -350,6 +390,7 @@ export async function createGCoordinatorServer( customSystemsEngine.invalidateCache(); } if (event.entityType === 'settings') { + applyDatabaseThrottlePragmas(db, getRuntimeLimits()); authService.syncRecovery(); } monitoringService.syncServers(); @@ -365,11 +406,7 @@ export async function createGCoordinatorServer( ); app.get('/api/healthz', (_req, res) => { - res.json({ - ok: true, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); + res.json({ ok: true }); }); app.use( @@ -508,6 +545,24 @@ export async function createGCoordinatorServer( }); } + app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => { + const statusErr = err as { status?: number; type?: string; message?: string }; + const status = + typeof statusErr?.status === 'number' && statusErr.status >= 400 && statusErr.status < 600 + ? statusErr.status + : 500; + if (!res.headersSent) { + res.status(status).json({ + error: status === 413 || statusErr?.type === 'entity.too.large' + ? 'PAYLOAD_TOO_LARGE' + : status < 500 + ? 'BAD_REQUEST' + : 'INTERNAL_SERVER_ERROR', + message: status < 500 && statusErr?.message ? statusErr.message : 'Internal server error', + }); + } + }); + await new Promise((resolve, reject) => { httpServer.once('error', reject); httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { diff --git a/src/server/index.ts b/src/server/index.ts index fbe1059..67672d9 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -1,14 +1,26 @@ import path from 'node:path'; import { createGCoordinatorServer } from './app.js'; +import { normalizeThrottleMode } from './config/runtime-limits.js'; + +function parseCsvList(raw: string | undefined): string[] | undefined { + if (!raw || !raw.trim()) return undefined; + const list = raw + .split(',') + .map((s) => s.trim()) + .filter(Boolean); + return list.length > 0 ? list : undefined; +} async function main(): Promise { const dataDir = path.resolve(process.env.GCOORD_DATA_DIR ?? './data'); const port = Number(process.env.PORT ?? 3000); const host = process.env.HOST ?? '0.0.0.0'; const trustCloudflare = process.env.TRUST_CLOUDFLARE === 'true'; + const trustedProxyCidrs = parseCsvList(process.env.TRUSTED_PROXY_CIDRS); const secretFilePath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; const envMasterKey = process.env.GCOORD_MASTER_KEY; + const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined; const instance = await createGCoordinatorServer({ dataDir, @@ -17,6 +29,15 @@ async function main(): Promise { secretFilePath, envMasterKey, trustCloudflare, + trustedProxyCidrs, + allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', + proxyBaseDomain: process.env.GCOORD_PROXY_BASE_DOMAIN?.trim() || undefined, + proxyPort: proxyPortRaw && Number.isFinite(proxyPortRaw) ? proxyPortRaw : undefined, + webauthnRpId: process.env.GCOORD_WEBAUTHN_RP_ID?.trim() || undefined, + webauthnOrigins: parseCsvList(process.env.GCOORD_WEBAUTHN_ORIGINS), + metricsToken: process.env.GCOORD_METRICS_TOKEN?.trim() || undefined, + throttleModeOverride: normalizeThrottleMode(process.env.GCOORD_THROTTLE_MODE), + autoKeyFile: process.env.GCOORD_AUTO_KEYFILE === 'true', }); console.log( diff --git a/src/server/security/egress-guard.ts b/src/server/security/egress-guard.ts new file mode 100644 index 0000000..aae5c4b --- /dev/null +++ b/src/server/security/egress-guard.ts @@ -0,0 +1,244 @@ +import dns from 'node:dns'; +import net from 'node:net'; + +export class EgressBlockedError extends Error { + readonly code = 'EGRESS_BLOCKED'; + + constructor(message: string) { + super(message); + this.name = 'EgressBlockedError'; + } +} + +interface ParsedCidr { + family: 4 | 6; + network: bigint; + mask: bigint; +} + +const DEFAULT_BLOCKED_CIDR_STRINGS = [ + '0.0.0.0/8', + '10.0.0.0/8', + '100.64.0.0/10', + '127.0.0.0/8', + '169.254.0.0/16', + '172.16.0.0/12', + '192.0.0.0/24', + '192.168.0.0/16', + '198.18.0.0/15', + '224.0.0.0/4', + '240.0.0.0/4', + '::/128', + '::1/128', + 'fc00::/7', + 'fe80::/10', + 'ff00::/8', + 'fd00:ec2::254/128', +]; + +function stripZoneAndBrackets(raw: string): { ip: string; hasZone: boolean } { + let s = raw.trim(); + if (s.startsWith('[') && s.endsWith(']')) { + s = s.slice(1, -1); + } + const pct = s.indexOf('%'); + if (pct >= 0) { + return { ip: s.slice(0, pct), hasZone: true }; + } + return { ip: s, hasZone: false }; +} + +function parseIpv4ToBigInt(ip: string): bigint | null { + const parts = ip.split('.'); + if (parts.length !== 4) return null; + let val = 0n; + for (const part of parts) { + if (!/^\d{1,3}$/.test(part)) return null; + const n = Number(part); + if (n < 0 || n > 255) return null; + val = (val << 8n) | BigInt(n); + } + return val; +} + +function parseIpv6ToBigInt(ip: string): bigint | null { + let s = ip.toLowerCase(); + const lastColon = s.lastIndexOf(':'); + if (lastColon >= 0 && s.includes('.')) { + const v4Part = s.slice(lastColon + 1); + const v4 = parseIpv4ToBigInt(v4Part); + if (v4 === null) return null; + const hi = Number((v4 >> 16n) & 0xffffn).toString(16); + const lo = Number(v4 & 0xffffn).toString(16); + s = `${s.slice(0, lastColon)}:${hi}:${lo}`; + } + + const dblIdx = s.indexOf('::'); + let groups: string[]; + if (dblIdx >= 0) { + if (s.indexOf('::', dblIdx + 2) >= 0) return null; + const left = dblIdx === 0 ? [] : s.slice(0, dblIdx).split(':'); + const right = dblIdx + 2 >= s.length ? [] : s.slice(dblIdx + 2).split(':'); + const missing = 8 - (left.length + right.length); + if (missing < 1) return null; + groups = [...left, ...Array(missing).fill('0'), ...right]; + } else { + groups = s.split(':'); + if (groups.length !== 8) return null; + } + + let out = 0n; + for (const g of groups) { + if (!/^[0-9a-f]{1,4}$/.test(g)) return null; + out = (out << 16n) | BigInt(parseInt(g, 16)); + } + return out; +} + +function parseIpNormalized(rawIp: string): { family: 4 | 6; value: bigint; hasZone: boolean } | null { + const { ip, hasZone } = stripZoneAndBrackets(rawIp); + const kind = net.isIP(ip); + if (kind === 4) { + const value = parseIpv4ToBigInt(ip); + return value === null ? null : { family: 4, value, hasZone }; + } + if (kind === 6) { + const v6 = parseIpv6ToBigInt(ip); + if (v6 === null) return null; + // Unwrap IPv4-mapped IPv6 addresses (::ffff:0:0/96) + if ((v6 >> 32n) === 0xffffn) { + return { family: 4, value: v6 & 0xffffffffn, hasZone }; + } + return { family: 6, value: v6, hasZone }; + } + return null; +} + +export function parseCidr(raw: string): ParsedCidr | null { + const trimmed = raw.trim(); + if (!trimmed) return null; + const slash = trimmed.indexOf('/'); + const ipStr = slash >= 0 ? trimmed.slice(0, slash) : trimmed; + const parsed = parseIpNormalized(ipStr); + if (!parsed) return null; + + const totalBits = parsed.family === 4 ? 32 : 128; + const prefixLen = + slash >= 0 ? Number(trimmed.slice(slash + 1)) : totalBits; + if (!Number.isInteger(prefixLen) || prefixLen < 0 || prefixLen > totalBits) { + return null; + } + + const shift = BigInt(totalBits - prefixLen); + const fullMask = parsed.family === 4 ? 0xffffffffn : (1n << 128n) - 1n; + const mask = prefixLen === 0 ? 0n : (fullMask << shift) & fullMask; + return { + family: parsed.family, + network: parsed.value & mask, + mask, + }; +} + +const DEFAULT_BLOCKED_CIDRS: ParsedCidr[] = DEFAULT_BLOCKED_CIDR_STRINGS + .map((c) => parseCidr(c)!) + .filter(Boolean); + +export function isIpInCidrs(rawIp: string, cidrs: string[]): boolean { + const parsed = parseIpNormalized(rawIp); + if (!parsed) return false; + for (const rawCidr of cidrs) { + const cidr = parseCidr(rawCidr); + if (!cidr || cidr.family !== parsed.family) continue; + if ((parsed.value & cidr.mask) === cidr.network) { + return true; + } + } + return false; +} + +export function isBlockedByDefaultIp(rawIp: string): boolean { + const parsed = parseIpNormalized(rawIp); + if (!parsed || parsed.hasZone) return true; + for (const cidr of DEFAULT_BLOCKED_CIDRS) { + if (cidr.family === parsed.family && (parsed.value & cidr.mask) === cidr.network) { + return true; + } + } + return false; +} + +export async function assertEgressHostAllowed( + rawHost: string, + allowedCidrs: string[] = [], +): Promise { + const { ip: cleanHost } = stripZoneAndBrackets(rawHost); + if (!cleanHost) { + throw new EgressBlockedError('Empty egress destination host'); + } + + if (net.isIP(cleanHost) !== 0) { + if (isBlockedByDefaultIp(rawHost) && !isIpInCidrs(rawHost, allowedCidrs)) { + throw new EgressBlockedError( + `Egress to non-public IP "${cleanHost}" is blocked by Zero-Trust egress policy`, + ); + } + return; + } + + let records: dns.LookupAddress[]; + try { + records = await dns.promises.lookup(cleanHost, { all: true, verbatim: true }); + } catch (err) { + throw new EgressBlockedError( + `Failed to resolve egress host "${cleanHost}": ${err instanceof Error ? err.message : String(err)}`, + ); + } + + if (records.length === 0) { + throw new EgressBlockedError(`Egress host "${cleanHost}" resolved to no addresses`); + } + + for (const rec of records) { + if (isBlockedByDefaultIp(rec.address) && !isIpInCidrs(rec.address, allowedCidrs)) { + throw new EgressBlockedError( + `Egress host "${cleanHost}" resolved to blocked address ${rec.address}`, + ); + } + } +} + +export async function assertEgressUrlAllowed( + rawUrl: string, + allowedCidrs: string[] = [], +): Promise { + let url: URL; + try { + url = new URL(rawUrl); + } catch { + throw new EgressBlockedError(`Invalid URL "${rawUrl}"`); + } + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new EgressBlockedError(`Unsupported egress URL scheme "${url.protocol}"`); + } + await assertEgressHostAllowed(url.hostname, allowedCidrs); + return url; +} + +export async function fetchWithEgressGuard( + rawUrl: string, + init: RequestInit = {}, + opts: { allowedCidrs?: string[]; timeoutMs?: number } = {}, +): Promise { + const url = await assertEgressUrlAllowed(rawUrl, opts.allowedCidrs ?? []); + const timeoutMs = Math.max(500, Math.min(300_000, opts.timeoutMs ?? 15_000)); + const timeoutSignal = AbortSignal.timeout(timeoutMs); + const signal = init.signal + ? AbortSignal.any([init.signal, timeoutSignal]) + : timeoutSignal; + + return fetch(url.toString(), { + ...init, + redirect: 'error', + signal, + }); +} diff --git a/src/server/security/guards.ts b/src/server/security/guards.ts index 470383d..cf445b5 100644 --- a/src/server/security/guards.ts +++ b/src/server/security/guards.ts @@ -1,12 +1,16 @@ import crypto from 'node:crypto'; -import type { NextFunction, Request, Response } from 'express'; +import net from 'node:net'; +import type Database from 'better-sqlite3'; +import type { NextFunction, Request, RequestHandler, Response } from 'express'; import type { StepUpPolicy } from '../../shared/schemas/settings.schema.js'; +import type { AuditService } from './audit.js'; import { SESSION_COOKIE_NAME, sha256Hex, type AuthService, type AuthSession, } from './auth.js'; +import { isIpInCidrs } from './egress-guard.js'; declare global { namespace Express { @@ -17,54 +21,207 @@ declare global { } } +export const DEFAULT_TRUSTED_PROXY_CIDRS = [ + '127.0.0.0/8', + '::1/128', + '10.0.0.0/8', + '172.16.0.0/12', + '192.168.0.0/16', + 'fc00::/7', +]; + interface RateBucketState { failures: number; lockedUntil: number; + updatedAt: number; } +const DECAY_WINDOW_MS = 60 * 60 * 1000; +const MAX_INMEM_BUCKETS = 2000; +const GLOBAL_LOGIN_THRESHOLD = 20; + export class RateLimiter { private readonly buckets = new Map(); + private readonly inFlightCounts = new Map(); + private readonly db?: Database.Database; + private lastPruneAt = 0; + + constructor(options: { db?: Database.Database } = {}) { + this.db = options.db; + } check(scope: string, ip: string): { allowed: boolean; retryAfterSec: number } { const key = `${scope}:${ip}`; - const state = this.buckets.get(key); - if (!state) return { allowed: true, retryAfterSec: 0 }; - + const state = this.readBucket(key); const now = Date.now(); - if (state.lockedUntil > now) { + if (state && state.lockedUntil > now) { return { allowed: false, retryAfterSec: Math.max(1, Math.ceil((state.lockedUntil - now) / 1000)), }; } + + if (scope === 'login') { + const globalState = this.readBucket('login:__global__'); + if (globalState && globalState.lockedUntil > now) { + return { + allowed: false, + retryAfterSec: Math.max(1, Math.ceil((globalState.lockedUntil - now) / 1000)), + }; + } + } + return { allowed: true, retryAfterSec: 0 }; } - recordFailure(scope: string, ip: string): number { + acquireInFlight(scope: string, ip: string, maxConcurrent = 2): boolean { const key = `${scope}:${ip}`; - const prev = this.buckets.get(key) ?? { failures: 0, lockedUntil: 0 }; - const failures = prev.failures + 1; + const cur = this.inFlightCounts.get(key) ?? 0; + if (cur >= maxConcurrent) return false; + this.inFlightCounts.set(key, cur + 1); + return true; + } + + releaseInFlight(scope: string, ip: string): void { + const key = `${scope}:${ip}`; + const cur = this.inFlightCounts.get(key) ?? 0; + if (cur <= 1) { + this.inFlightCounts.delete(key); + } else { + this.inFlightCounts.set(key, cur - 1); + } + } + + recordFailure(scope: string, ip: string): { lockedUntil: number; failures: number; globalTriggered: boolean } { + const now = Date.now(); + const key = `${scope}:${ip}`; + const prev = this.readBucket(key); + const baseFailures = + prev && (now - prev.updatedAt <= DECAY_WINDOW_MS || prev.lockedUntil > now) + ? prev.failures + : 0; + const failures = baseFailures + 1; let lockedUntil = 0; if (failures >= 5) { const delayMs = Math.min(300_000, 2000 * 2 ** (failures - 5)); - lockedUntil = Date.now() + delayMs; + lockedUntil = now + delayMs; } - this.buckets.set(key, { failures, lockedUntil }); - return lockedUntil; + this.writeBucket(key, { failures, lockedUntil, updatedAt: now }); + + let globalTriggered = false; + if (scope === 'login') { + const gPrev = this.readBucket('login:__global__'); + const gBase = + gPrev && (now - gPrev.updatedAt <= 15 * 60 * 1000 || gPrev.lockedUntil > now) + ? gPrev.failures + : 0; + const gFailures = gBase + 1; + let gLockedUntil = gPrev?.lockedUntil ?? 0; + if (gFailures >= GLOBAL_LOGIN_THRESHOLD) { + const gDelay = Math.min(300_000, 60_000 * 2 ** Math.min(3, Math.floor((gFailures - GLOBAL_LOGIN_THRESHOLD) / 5))); + gLockedUntil = now + gDelay; + globalTriggered = true; + } + this.writeBucket('login:__global__', { + failures: gFailures, + lockedUntil: gLockedUntil, + updatedAt: now, + }); + } + + return { lockedUntil, failures, globalTriggered }; } recordSuccess(scope: string, ip: string): void { - this.buckets.delete(`${scope}:${ip}`); + this.deleteBucket(`${scope}:${ip}`); + if (scope === 'login') { + this.deleteBucket('login:__global__'); + } + } + + private readBucket(key: string): RateBucketState | undefined { + if (this.db) { + try { + const row = this.db + .prepare( + 'SELECT failures, locked_until AS lockedUntil, updated_at AS updatedAt FROM rate_limits WHERE scope_key = ?', + ) + .get(key) as RateBucketState | undefined; + if (!row) return undefined; + const now = Date.now(); + if (row.lockedUntil <= now && now - row.updatedAt > DECAY_WINDOW_MS) { + this.deleteBucket(key); + return undefined; + } + return row; + } catch { + // Fallback to in-memory map if DB unavailable + } + } + + const mem = this.buckets.get(key); + if (!mem) return undefined; + const now = Date.now(); + if (mem.lockedUntil <= now && now - mem.updatedAt > DECAY_WINDOW_MS) { + this.buckets.delete(key); + return undefined; + } + return mem; + } + + private writeBucket(key: string, state: RateBucketState): void { + if (this.db) { + try { + this.db + .prepare( + `INSERT INTO rate_limits (scope_key, failures, locked_until, updated_at) + VALUES (?, ?, ?, ?) + ON CONFLICT(scope_key) DO UPDATE SET + failures = excluded.failures, + locked_until = excluded.locked_until, + updated_at = excluded.updated_at`, + ) + .run(key, state.failures, state.lockedUntil, state.updatedAt); + + if (state.updatedAt - this.lastPruneAt > 10 * 60 * 1000) { + this.lastPruneAt = state.updatedAt; + this.db + .prepare('DELETE FROM rate_limits WHERE locked_until <= ? AND updated_at < ?') + .run(state.updatedAt, state.updatedAt - DECAY_WINDOW_MS); + } + return; + } catch { + // Fallback below + } + } + + if (this.buckets.size >= MAX_INMEM_BUCKETS && !this.buckets.has(key)) { + const oldestKey = this.buckets.keys().next().value; + if (oldestKey) this.buckets.delete(oldestKey); + } + this.buckets.set(key, state); + } + + private deleteBucket(key: string): void { + if (this.db) { + try { + this.db.prepare('DELETE FROM rate_limits WHERE scope_key = ?').run(key); + } catch { + // Ignore DB error + } + } + this.buckets.delete(key); } } export function extractCookies(cookieHeader: string | undefined): Record { - const result: Record = {}; + const result = Object.create(null) as Record; if (!cookieHeader) return result; for (const part of cookieHeader.split(';')) { const eq = part.indexOf('='); if (eq <= 0) continue; const key = part.slice(0, eq).trim(); + if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue; const rawVal = part.slice(eq + 1).trim(); try { result[key] = decodeURIComponent(rawVal); @@ -75,23 +232,54 @@ export function extractCookies(cookieHeader: string | undefined): Record 0) { - return cf.split(',')[0]!.trim(); - } - } - return req.ip || req.socket.remoteAddress || 'unknown'; +export function isTrustedProxyPeer( + remoteAddr: string | undefined, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +): boolean { + if (!remoteAddr) return false; + return isIpInCidrs(remoteAddr, trustedProxyCidrs); } -export function attachClientIp(trustCloudflare: boolean) { +export function resolveClientIp( + req: Request, + trustCloudflare: boolean, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +): string { + const peerIp = req.socket?.remoteAddress; + if (trustCloudflare && isTrustedProxyPeer(peerIp, trustedProxyCidrs)) { + const cf = req.headers['cf-connecting-ip']; + if (typeof cf === 'string' && cf.trim().length > 0) { + const candidate = cf.split(',')[0]!.trim(); + if (net.isIP(candidate) !== 0) { + return candidate; + } + } + } + return req.ip || peerIp || 'unknown'; +} + +export function attachClientIp( + trustCloudflare: boolean, + trustedProxyCidrs: string[] = DEFAULT_TRUSTED_PROXY_CIDRS, +) { return (req: Request, _res: Response, next: NextFunction): void => { - req.clientIp = resolveClientIp(req, trustCloudflare); + req.clientIp = resolveClientIp(req, trustCloudflare, trustedProxyCidrs); next(); }; } +export function asyncHandler( + fn: (req: Request, res: Response, next: NextFunction) => Promise | void, +): RequestHandler { + return (req, res, next) => { + Promise.resolve(fn(req, res, next)).catch(next); + }; +} + +function getAudit(req: Request): AuditService | undefined { + return req.app?.locals?.auditService as AuditService | undefined; +} + export function requireAuth(authService: AuthService) { return (req: Request, res: Response, next: NextFunction): void => { const cookies = extractCookies(req.headers.cookie); @@ -118,6 +306,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo } const headerToken = req.headers['x-csrf-token']; if (typeof headerToken !== 'string' || headerToken.length < 16) { + getAudit(req)?.log({ + action: 'security.csrf_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -127,6 +322,13 @@ export function requireCsrf(req: Request, res: Response, next: NextFunction): vo providedHash.length !== expectedHash.length || !crypto.timingSafeEqual(providedHash, expectedHash) ) { + getAudit(req)?.log({ + action: 'security.csrf_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'CSRF_INVALID' }); return; } @@ -140,6 +342,13 @@ export function enforceSafeMode(req: Request, res: Response, next: NextFunction) } const clientSafeHeader = req.headers['x-gcoord-safe-mode'] === '1'; if (req.authSession?.safeMode || clientSafeHeader) { + getAudit(req)?.log({ + action: 'security.safe_mode_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession?.idHash ?? null, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(423).json({ error: 'SAFE_MODE_ACTIVE', message: 'Disable Safe / Read-Only Mode before performing mutating actions.', @@ -167,6 +376,13 @@ export function createStepUpGuard( } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { + getAudit(req)?.log({ + action: 'security.stepup_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.', @@ -189,6 +405,13 @@ export function requireStepUp(req: Request, res: Response, next: NextFunction): return; } if (!session.elevatedUntil || session.elevatedUntil <= Date.now()) { + getAudit(req)?.log({ + action: 'security.stepup_denied', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: session.idHash, + target: `${req.method} ${req.path}`, + status: 'denied', + }); res.status(403).json({ error: 'STEP_UP_REQUIRED', message: 'Re-authentication verification is required for this sensitive operation.', From e3f716d24fbb01626be3454e2438d3680d8213ae Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:22:59 +0000 Subject: [PATCH 03/19] security(vault,recovery,config): harden Vault keyfile/seal, strip recovery passwords, guard config & symlinks --- src/server/api/routes/config.routes.ts | 167 ++++++++++++------- src/server/api/routes/vault.routes.ts | 215 ++++++++++++++++++------- src/server/app.ts | 22 ++- src/server/config/config-manager.ts | 50 +++++- src/server/config/presets.ts | 5 +- src/server/security/auth.ts | 18 --- src/server/security/recovery-store.ts | 81 ++++++---- src/server/security/vault.ts | 120 +++++++++++--- src/server/ssh/ssh-pool.ts | 7 +- tests/api-ws-smoke.test.ts | 19 +-- tests/multi-auth-and-recovery.test.ts | 5 +- tests/servers-api-e2e.test.ts | 2 +- 12 files changed, 504 insertions(+), 207 deletions(-) diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts index 7bcde14..ef1b955 100644 --- a/src/server/api/routes/config.routes.ts +++ b/src/server/api/routes/config.routes.ts @@ -1,4 +1,4 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { ZodError, z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; @@ -7,17 +7,29 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface ConfigRouterDeps { authService: AuthService; configManager: ConfigManager; auditService: AuditService; + stepUpGuard?: RequestHandler; +} + +function isStepUpSensitiveConfigPath(rawPath: string): boolean { + const norm = rawPath.replace(/\\/g, '/').replace(/^\/+/, ''); + return norm === 'settings.json' || norm === 'alerts.json' || norm.startsWith('servers/'); } export function createConfigRouter(deps: ConfigRouterDeps): Router { const router = Router(); - const { authService, configManager, auditService } = deps; + const { + authService, + configManager, + auditService, + stepUpGuard = requireStepUp, + } = deps; router.get('/overview', requireAuth(authService), (_req, res) => { res.json({ @@ -63,38 +75,46 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { return; } - try { - const saved = configManager.saveConfigText( - parsed.data.path, - parsed.data.content, - 'ui', - parsed.data.summary, - ); - auditService.log({ - action: 'config.save', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: saved.filePath, - status: 'ok', - }); - res.json(saved); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'CONFIG_SCHEMA_ERROR', - message: 'Schema validation failed', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), + const executeSave = () => { + try { + const saved = configManager.saveConfigText( + parsed.data.path, + parsed.data.content, + 'ui', + parsed.data.summary, + ); + auditService.log({ + action: 'config.save', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: saved.filePath, + status: 'ok', + }); + res.json(saved); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'CONFIG_SCHEMA_ERROR', + message: 'Schema validation failed', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'CONFIG_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save config file', }); - return; } - res.status(400).json({ - error: 'CONFIG_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save config file', - }); + }; + + if (isStepUpSensitiveConfigPath(parsed.data.path)) { + stepUpGuard(req, res, executeSave); + return; } + executeSave(); }); router.delete( @@ -108,26 +128,34 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'MISSING_PATH' }); return; } - try { - const deleted = configManager.deleteEntityFile(filePath); - if (!deleted) { - res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); - return; + const executeDelete = () => { + try { + const deleted = configManager.deleteEntityFile(filePath); + if (!deleted) { + res.status(404).json({ error: 'CONFIG_NOT_FOUND' }); + return; + } + auditService.log({ + action: 'config.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: filePath, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'CONFIG_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete config file', + }); } - auditService.log({ - action: 'config.delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: filePath, - status: 'ok', - }); - res.json({ deleted: true }); - } catch (err) { - res.status(400).json({ - error: 'CONFIG_DELETE_ERROR', - message: err instanceof Error ? err.message : 'Unable to delete config file', - }); + }; + + if (isStepUpSensitiveConfigPath(filePath)) { + stepUpGuard(req, res, executeDelete); + return; } + executeDelete(); }, ); @@ -174,23 +202,38 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { res.status(400).json({ error: 'INVALID_REVISION_ID' }); return; } - try { - const result = configManager.rollbackRevision(id); - auditService.log({ - action: 'config.rollback', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: result.filePath, - status: 'ok', - details: { revisionId: id }, - }); - res.json(result); - } catch (err) { + const rev = configManager.getRevision(id); + if (!rev) { res.status(400).json({ error: 'ROLLBACK_FAILED', - message: err instanceof Error ? err.message : 'Rollback failed', + message: `Revision #${id} not found`, }); + return; } + const executeRollback = () => { + try { + const result = configManager.rollbackRevision(id); + auditService.log({ + action: 'config.rollback', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: result.filePath, + status: 'ok', + details: { revisionId: id }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'ROLLBACK_FAILED', + message: err instanceof Error ? err.message : 'Rollback failed', + }); + } + }; + if (isStepUpSensitiveConfigPath(rev.filePath)) { + stepUpGuard(req, res, executeRollback); + return; + } + executeRollback(); }, ); diff --git a/src/server/api/routes/vault.routes.ts b/src/server/api/routes/vault.routes.ts index 504f861..8cf4836 100644 --- a/src/server/api/routes/vault.routes.ts +++ b/src/server/api/routes/vault.routes.ts @@ -15,6 +15,7 @@ import { import { computeOpenSshFingerprint, generateMasterKeyBuffer, + validatePrivateKey, type VaultCredentialInput, type VaultService, } from '../../security/vault.js'; @@ -114,6 +115,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { type: 'vault:state', vaultState: vaultService.state, vaultRuntimeReady: vaultService.isRuntimeReady, + vaultSealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }; @@ -122,43 +124,52 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); - vaultRouter.post('/init', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - const ip = req.clientIp ?? 'unknown'; - const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); - if (!parsed.success) { - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - try { - const result = vaultService.initializeNewVault(parsed.data.masterKey); - notifyConfigReeval(); - onVaultUnlocked?.(); - onVaultChanged?.('vault-init'); - broadcastVaultState(); - auditService.log({ - action: 'vault.init', - actorIp: ip, - sessionIdHash: req.authSession!.idHash, - status: 'ok', - }); - res.status(201).json({ - state: vaultService.state, - runtimeReady: vaultService.isRuntimeReady, - generatedKeyHex: result.generatedKeyHex, - }); - } catch (err) { - res.status(400).json({ - error: 'VAULT_INIT_FAILED', - message: err instanceof Error ? err.message : 'Vault initialization failed', - }); - } - }); + vaultRouter.post( + '/init', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const ip = req.clientIp ?? 'unknown'; + const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const result = vaultService.initializeNewVault(parsed.data.masterKey); + notifyConfigReeval(); + onVaultUnlocked?.(); + onVaultChanged?.('vault-init'); + broadcastVaultState(); + auditService.log({ + action: 'vault.init', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.status(201).json({ + state: vaultService.state, + runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, + generatedKeyHex: result.generatedKeyHex, + }); + } catch (err) { + res.status(400).json({ + error: 'VAULT_INIT_FAILED', + message: err instanceof Error ? err.message : 'Vault initialization failed', + }); + } + }, + ); - vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, (req, res) => { + vaultRouter.post('/unlock', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { const ip = req.clientIp ?? 'unknown'; const parsed = z.object({ masterKey: z.string().optional() }).safeParse(req.body ?? {}); if (!parsed.success) { @@ -191,6 +202,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -231,6 +243,7 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); } catch (err) { @@ -254,10 +267,35 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.json({ state: vaultService.state, runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, isPanicLocked: vaultService.isPanicLocked, }); }); + vaultRouter.post( + '/seal', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + vaultService.seal(); + broadcastVaultState(); + auditService.log({ + action: 'vault.seal', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ + state: vaultService.state, + runtimeReady: vaultService.isRuntimeReady, + sealState: vaultService.sealState, + isPanicLocked: vaultService.isPanicLocked, + }); + }, + ); + // Panic Lock is ALWAYS reachable when authenticated + CSRF verified (even under Safe Mode!) panicLockHandler.post('/panic-lock', requireAuth(authService), requireCsrf, (req, res) => { const session = req.authSession!; @@ -299,6 +337,13 @@ export function createVaultRouter(deps: VaultRouterDeps): { requireAuth(authService), stepUpGuard, (req, res) => { + if (req.authSession?.safeMode || req.headers['x-gcoord-safe-mode'] === '1') { + res.status(423).json({ + error: 'SAFE_MODE_ACTIVE', + message: 'Disable Safe / Read-Only Mode before revealing secrets.', + }); + return; + } if (vaultService.state !== 'unlocked') { res.status(423).json({ error: 'VAULT_LOCKED' }); return; @@ -337,15 +382,27 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if ( - credInput.type === 'ssh-key' && - credInput.publicKey && - !credInput.fingerprint - ) { + if (credInput.type === 'ssh-key') { try { - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch { - // Leave fingerprint omitted if user imported an unusual public key format + validatePrivateKey(credInput.privateKey, credInput.passphrase); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH private key', + }); + return; + } + if (credInput.publicKey) { + try { + credInput.publicKey = credInput.publicKey.trim(); + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_PUBLIC_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH public key', + }); + return; + } } } const meta = vaultService.upsertCredential(credInput); @@ -381,15 +438,27 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } const credInput: VaultCredentialInput = { ...parsed.data }; - if ( - credInput.type === 'ssh-key' && - credInput.publicKey && - !credInput.fingerprint - ) { + if (credInput.type === 'ssh-key') { try { - credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); - } catch { - // Ignore non-standard public key strings + validatePrivateKey(credInput.privateKey, credInput.passphrase); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH private key', + }); + return; + } + if (credInput.publicKey) { + try { + credInput.publicKey = credInput.publicKey.trim(); + credInput.fingerprint = computeOpenSshFingerprint(credInput.publicKey); + } catch (err) { + res.status(400).json({ + error: 'INVALID_SSH_PUBLIC_KEY', + message: err instanceof Error ? err.message : 'Invalid SSH public key', + }); + return; + } } } const meta = vaultService.upsertCredential(credInput); @@ -495,6 +564,12 @@ export function createVaultRouter(deps: VaultRouterDeps): { sessionIdHash: req.authSession!.idHash, expiresAt, }; + auditService.log({ + action: 'vault.rotate_key.prepare', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); res.json({ candidateKeyHex, confirmToken, expiresAt }); }, ); @@ -510,10 +585,17 @@ export function createVaultRouter(deps: VaultRouterDeps): { res.status(423).json({ error: 'VAULT_LOCKED' }); return; } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('vault-rotate-commit', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } const parsed = z .object({ confirmToken: z.string().min(1), - confirmedKeyHex: z.string().min(1).optional(), + confirmedKeyHex: z.string().min(64).max(64), }) .safeParse(req.body); if (!parsed.success) { @@ -521,32 +603,57 @@ export function createVaultRouter(deps: VaultRouterDeps): { return; } + const timingEq = (a: string, b: string) => { + const ba = Buffer.from(a, 'utf8'); + const bb = Buffer.from(b, 'utf8'); + return ba.length === bb.length && crypto.timingSafeEqual(ba, bb); + }; + if ( !pendingRotation || pendingRotation.expiresAt <= Date.now() || pendingRotation.sessionIdHash !== req.authSession!.idHash || - pendingRotation.confirmToken !== parsed.data.confirmToken + !timingEq(pendingRotation.confirmToken, parsed.data.confirmToken) ) { + pendingRotation = null; + rateLimiter.recordFailure('vault-rotate-commit', ip); + auditService.log({ + action: 'vault.rotate_key.commit', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + }); res.status(400).json({ error: 'ROTATION_TOKEN_INVALID_OR_EXPIRED' }); return; } if ( - parsed.data.confirmedKeyHex && - parsed.data.confirmedKeyHex.trim().toLowerCase() !== - pendingRotation.candidateKeyHex.toLowerCase() + !timingEq( + parsed.data.confirmedKeyHex.trim().toLowerCase(), + pendingRotation.candidateKeyHex.toLowerCase(), + ) ) { + pendingRotation = null; + rateLimiter.recordFailure('vault-rotate-commit', ip); + auditService.log({ + action: 'vault.rotate_key.commit', + actorIp: ip, + sessionIdHash: req.authSession!.idHash, + status: 'denied', + details: { reason: 'key_confirmation_mismatch' }, + }); res.status(400).json({ error: 'KEY_CONFIRMATION_MISMATCH' }); return; } + rateLimiter.recordSuccess('vault-rotate-commit', ip); const nextHex = pendingRotation.candidateKeyHex; pendingRotation = null; vaultService.rotateMasterKey(nextHex); onVaultChanged?.('master-key-rotation'); auditService.log({ action: 'vault.rotate_key', - actorIp: req.clientIp ?? 'unknown', + actorIp: ip, sessionIdHash: req.authSession!.idHash, status: 'ok', }); diff --git a/src/server/app.ts b/src/server/app.ts index a4f433b..c0cdded 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -118,6 +118,7 @@ export async function createGCoordinatorServer( const auditService = new AuditService(db); const vaultService = new VaultService(vaultPath, { keyFilePath: path.join(dataDir, 'vault.key'), + allowLocalKeyFile: options.autoKeyFile ?? true, }); const recoveryStore = new EmergencyRecoveryService(dataDir); const rateLimiter = new RateLimiter({ db }); @@ -349,6 +350,19 @@ export async function createGCoordinatorServer( workflowEngine.start(); alertEngine.start(); + vaultService.onSeal(() => { + aiService.cancelAll(); + alertEngine.handlePanicLock(); + workflowEngine.handlePanicLock(); + broadcastService.cancelAll(); + monitoringService.stopAll(); + customSystemsEngine.stopBackgroundChecks(); + customSystemsEngine.cancelAllStreams(); + tunnelManager.stopAll(); + ptyManager.closeAll(true); + sshPool.closeAll('vault_sealed'); + }); + vaultService.onPanicLock(() => { aiService.cancelAll(); alertEngine.handlePanicLock(); @@ -391,7 +405,11 @@ export async function createGCoordinatorServer( } if (event.entityType === 'settings') { applyDatabaseThrottlePragmas(db, getRuntimeLimits()); - authService.syncRecovery(); + if (!configManager.getSettings().security.enableEmergencySecretsBackup) { + recoveryStore.wipeAll(); + } else { + authService.syncRecovery(); + } } monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); @@ -528,7 +546,7 @@ export async function createGCoordinatorServer( ); app.use( '/api/config', - createConfigRouter({ authService, configManager, auditService }), + createConfigRouter({ authService, configManager, auditService, stepUpGuard }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); diff --git a/src/server/config/config-manager.ts b/src/server/config/config-manager.ts index f86cc2a..c23a4ba 100644 --- a/src/server/config/config-manager.ts +++ b/src/server/config/config-manager.ts @@ -368,6 +368,21 @@ export class ConfigManager { } } + for (const ch of this.alerts.channels) { + if ( + ch.url && + /(discord\.com\/api\/webhooks\/|api\.telegram\.org\/bot|[?&](token|key|secret|password)=)/i.test( + ch.url, + ) + ) { + next.push({ + filePath: 'alerts.json', + code: 'ALERT_INLINE_SECRET', + message: `Alert channel "${ch.id}" URL appears to contain an inline token/secret; store secrets in Vault via secretRef instead.`, + }); + } + } + for (const rule of this.alerts.rules) { for (const cid of rule.channelIds) { if (!channelIds.has(cid)) { @@ -604,6 +619,7 @@ export class ConfigManager { ignoreInitial: true, persistent: true, depth: 2, + followSymlinks: false, }); const scheduleReload = (absPath: string, kind: 'upsert' | 'unlink') => { @@ -813,11 +829,39 @@ export class ConfigManager { } private resolveSafeAbsPath(relPath: string): string { - const resolved = path.resolve(this.configDir, relPath); const root = path.resolve(this.configDir); + const resolved = path.resolve(root, relPath); if (!resolved.startsWith(`${root}${path.sep}`)) { throw new Error(`Path escapes config directory: ${relPath}`); } + + // Verify no symlinked directory/file components inside configDir + let cur = root; + const parts = path.relative(root, resolved).split(path.sep).filter(Boolean); + for (const part of parts) { + cur = path.join(cur, part); + if (fs.existsSync(cur)) { + const lstat = fs.lstatSync(cur); + if (lstat.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed inside config directory: ${relPath}`); + } + } + } + + if (fs.existsSync(root)) { + const realRoot = fs.realpathSync(root); + let checkPath = resolved; + while (!fs.existsSync(checkPath) && checkPath !== root) { + checkPath = path.dirname(checkPath); + } + if (fs.existsSync(checkPath)) { + const realTarget = fs.realpathSync(checkPath); + if (realTarget !== realRoot && !realTarget.startsWith(`${realRoot}${path.sep}`)) { + throw new Error(`Realpath escapes config directory: ${relPath}`); + } + } + } + return resolved; } @@ -898,8 +942,8 @@ export class ConfigManager { } private writeAtomicFile(absPath: string, content: string): void { - fs.mkdirSync(path.dirname(absPath), { recursive: true }); - const tmpPath = `${absPath}.tmp.${process.pid}.${Date.now()}`; + fs.mkdirSync(path.dirname(absPath), { recursive: true, mode: 0o700 }); + const tmpPath = `${absPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); diff --git a/src/server/config/presets.ts b/src/server/config/presets.ts index da391d8..b603c41 100644 --- a/src/server/config/presets.ts +++ b/src/server/config/presets.ts @@ -322,7 +322,10 @@ export function seedDefaultConfigs(configDir: string): string[] { for (const [relPath, obj] of defaults) { const absPath = path.join(configDir, relPath); if (!fs.existsSync(absPath)) { - fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, 'utf8'); + fs.writeFileSync(absPath, `${JSON.stringify(obj, null, 2)}\n`, { + encoding: 'utf8', + mode: 0o600, + }); created.push(relPath); } } diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 6d9480e..fb1500d 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -374,12 +374,6 @@ export class AuthService { this.pendingBootstrap = null; this.syncRecovery({ - passwordPlaintextUpdate: { - id: 'pw-primary', - label: 'Primary Password', - password: params.password, - createdAt: nowMs, - }, newRecoveryCodes: recoveryCodes, snapshotReason: 'bootstrap', }); @@ -942,12 +936,6 @@ export class AuthService { .run(id, cleanLabel, hash, createdAt); this.syncRecovery({ - passwordPlaintextUpdate: { - id, - label: cleanLabel, - password, - createdAt, - }, snapshotReason: 'password-added', }); @@ -1090,12 +1078,6 @@ export class AuthService { syncRecovery( overrides: { - passwordPlaintextUpdate?: { - id: string; - label: string; - password: string; - createdAt?: number; - }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; diff --git a/src/server/security/recovery-store.ts b/src/server/security/recovery-store.ts index d77c752..e0c5312 100644 --- a/src/server/security/recovery-store.ts +++ b/src/server/security/recovery-store.ts @@ -1,3 +1,4 @@ +import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import type { VaultCredential } from '../../shared/schemas/vault.schema.js'; @@ -6,7 +7,6 @@ import type { VaultService } from './vault.js'; export interface SavedPasswordEntry { id: string; label: string; - plaintextPassword?: string; createdAt: string; } @@ -48,7 +48,6 @@ export interface SyncRecoveryOptions { username?: string | null; totps?: SavedTotpEntry[]; passwordMetaList?: Array<{ id: string; label: string; createdAt: number }>; - passwordPlaintextUpdate?: { id: string; label: string; password: string; createdAt?: number }; removedPasswordId?: string; newRecoveryCodes?: string[]; snapshotReason?: string; @@ -74,6 +73,8 @@ export class EmergencyRecoveryService { readBundle(): EmergencySecretsBundle | null { if (!fs.existsSync(this.bundlePath)) return null; try { + const stat = fs.lstatSync(this.bundlePath); + if (!stat.isFile() || stat.isSymbolicLink()) return null; const raw = JSON.parse(fs.readFileSync(this.bundlePath, 'utf8')); if (!raw || typeof raw !== 'object' || raw.version !== 1) return null; return raw as EmergencySecretsBundle; @@ -105,43 +106,30 @@ export class EmergencyRecoveryService { ? opts.vault.exportAllCredentials() : existing?.vaultCredentials ?? {}; - // Merge saved plaintext passwords safely across updates const prevPwById = new Map(); for (const p of existing?.admin.passwords ?? []) { - prevPwById.set(p.id, p); + prevPwById.set(p.id, { + id: p.id, + label: p.label, + createdAt: p.createdAt, + }); } if (opts.removedPasswordId) { prevPwById.delete(opts.removedPasswordId); } - if (opts.passwordPlaintextUpdate) { - const u = opts.passwordPlaintextUpdate; - prevPwById.set(u.id, { - id: u.id, - label: u.label, - plaintextPassword: u.password, - createdAt: new Date(u.createdAt ?? Date.now()).toISOString(), - }); - } - let finalPasswords: SavedPasswordEntry[]; - if (opts.passwordMetaList) { - finalPasswords = opts.passwordMetaList.map((meta) => { - const prev = prevPwById.get(meta.id); - return { + const finalPasswords: SavedPasswordEntry[] = opts.passwordMetaList + ? opts.passwordMetaList.map((meta) => ({ id: meta.id, label: meta.label, - plaintextPassword: prev?.plaintextPassword, createdAt: new Date(meta.createdAt).toISOString(), - }; - }); - } else { - finalPasswords = [...prevPwById.values()]; - } + })) + : [...prevPwById.values()]; const bundle: EmergencySecretsBundle = { version: 1, updatedAt: nowIso, - note: 'Local emergency plaintext backup managed by GCoordinator. Keep this file private (chmod 0600).', + note: 'Local emergency recovery bundle managed by GCoordinator (passwords excluded). Keep this file private (chmod 0600).', vaultMasterKeyHex: masterKeyHex, admin: { username: opts.username !== undefined ? opts.username : existing?.admin.username ?? null, @@ -185,10 +173,22 @@ export class EmergencyRecoveryService { wipeAll(): void { const shred = (filePath: string) => { - if (!fs.existsSync(filePath)) return; + let stat: fs.Stats; try { - const stat = fs.statSync(filePath); - if (stat.isFile() && stat.size > 0) { + stat = fs.lstatSync(filePath); + } catch { + return; + } + if (stat.isSymbolicLink()) { + fs.unlinkSync(filePath); + return; + } + if (stat.isDirectory()) { + fs.rmSync(filePath, { recursive: true, force: true }); + return; + } + if (stat.isFile() && stat.size > 0) { + try { const fd = fs.openSync(filePath, 'r+'); try { fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); @@ -196,9 +196,9 @@ export class EmergencyRecoveryService { } finally { fs.closeSync(fd); } + } catch { + // Best-effort overwrite before unlink } - } catch { - // Best-effort overwrite before unlink } fs.unlinkSync(filePath); }; @@ -208,7 +208,11 @@ export class EmergencyRecoveryService { for (const f of fs.readdirSync(this.snapshotsDir)) { shred(path.join(this.snapshotsDir, f)); } - fs.rmdirSync(this.snapshotsDir); + try { + fs.rmdirSync(this.snapshotsDir); + } catch { + // Ignore unexpected remaining files + } } if (fs.existsSync(this.recoveryDir)) { try { @@ -227,7 +231,7 @@ export class EmergencyRecoveryService { } private writeAtomicSecure(targetPath: string, content: string): void { - const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -247,8 +251,19 @@ export class EmergencyRecoveryService { .sort(); while (files.length > MAX_SNAPSHOTS) { const oldest = files.shift()!; + const p = path.join(this.snapshotsDir, oldest); try { - fs.unlinkSync(path.join(this.snapshotsDir, oldest)); + const stat = fs.lstatSync(p); + if (stat.isFile() && !stat.isSymbolicLink() && stat.size > 0) { + const fd = fs.openSync(p, 'r+'); + try { + fs.writeSync(fd, Buffer.alloc(stat.size, 0), 0, stat.size, 0); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + } + fs.unlinkSync(p); } catch { // Ignore cleanup failure } diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 26811a3..5207c67 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -10,11 +10,14 @@ import { type VaultCredentialMeta, type VaultPayload, } from '../../shared/schemas/vault.schema.js'; -import type { VaultState } from '../../shared/ws-protocol.js'; +import type { VaultSealState, VaultState } from '../../shared/ws-protocol.js'; + +const VAULT_AAD = Buffer.from('gcoord-vault-v1', 'utf8'); export const VaultEnvelopeSchema = z.object({ version: z.literal(1), alg: z.literal('aes-256-gcm'), + aad: z.boolean().optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -42,6 +45,7 @@ export function generateMasterKeyBuffer(): Buffer { function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); + cipher.setAAD(VAULT_AAD); const plaintext = Buffer.from(JSON.stringify(payload), 'utf8'); const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]); const tag = cipher.getAuthTag(); @@ -50,6 +54,7 @@ function encryptPayload(payload: VaultPayload, key: Buffer): VaultEnvelope { return { version: 1, alg: 'aes-256-gcm', + aad: true, iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), @@ -67,6 +72,9 @@ function decryptEnvelope(envelope: VaultEnvelope, key: Buffer): VaultPayload { } const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + if (envelope.aad) { + decipher.setAAD(VAULT_AAD); + } decipher.setAuthTag(tag); const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]); try { @@ -109,7 +117,11 @@ export function verifyVaultEnvelopeText( } export function computeOpenSshFingerprint(publicKeyLine: string): string { - const parsed = ssh2.utils.parseKey(publicKeyLine.trim()); + const trimmed = publicKeyLine.trim(); + if (/[\r\n\0]/.test(trimmed)) { + throw new Error('Public key must be a single line'); + } + const parsed = ssh2.utils.parseKey(trimmed); if (parsed instanceof Error) { throw parsed; } @@ -122,6 +134,13 @@ export function computeOpenSshFingerprint(publicKeyLine: string): string { return `SHA256:${hash}`; } +export function validatePrivateKey(privateKey: string, passphrase?: string): void { + const parsed = ssh2.utils.parseKey(privateKey, passphrase); + if (parsed instanceof Error) { + throw new Error(`Invalid SSH private key or passphrase: ${parsed.message}`); + } +} + /** * Generates an OpenSSH Ed25519 keypair, retrying around ssh2's BitString * leading-zero stripping bug when a generated public key starts with 0x00. @@ -165,22 +184,29 @@ export type VaultCredentialInput = DistributiveOmit< export interface VaultServiceOptions { keyFilePath?: string; + allowLocalKeyFile?: boolean; } +type KeySource = 'secret-file' | 'env' | 'key-file' | 'backup' | 'generated' | 'manual'; + export class VaultService { private masterKey: Buffer | null = null; private credentials = new Map(); private writeUnlocked = false; private autoInitializedEmpty = false; private wasPanicLocked = false; + private keySource: KeySource | null = null; private readonly keyFilePath: string | null; + private readonly allowLocalKeyFile: boolean; private readonly panicListeners = new Set<() => void>(); + private readonly sealListeners = new Set<() => void>(); constructor( private readonly vaultFilePath: string, options: VaultServiceOptions = {}, ) { this.keyFilePath = options.keyFilePath ? path.resolve(options.keyFilePath) : null; + this.allowLocalKeyFile = options.allowLocalKeyFile ?? true; this.wasPanicLocked = fs.existsSync(this.panicLockMarkerPath()); } @@ -212,6 +238,12 @@ export class VaultService { return fs.existsSync(this.vaultFilePath) ? 'locked' : 'uninitialized'; } + get sealState(): VaultSealState { + if (!fs.existsSync(this.vaultFilePath)) return 'uninitialized'; + if (this.masterKey === null) return 'sealed'; + return this.writeUnlocked ? 'unlocked' : 'write-locked'; + } + get isPanicLocked(): boolean { return this.wasPanicLocked || fs.existsSync(this.panicLockMarkerPath()); } @@ -223,6 +255,13 @@ export class VaultService { }; } + onSeal(listener: () => void): () => void { + this.sealListeners.add(listener); + return () => { + this.sealListeners.delete(listener); + }; + } + initRuntime(options: { secretFilePath?: string; envKey?: string; @@ -234,20 +273,20 @@ export class VaultService { return { runtimeReady: false, reason: 'panic_locked' }; } - const candidates: string[] = []; + const candidates: Array<{ value: string; source: KeySource }> = []; if (options.secretFilePath && fs.existsSync(options.secretFilePath)) { const val = fs.readFileSync(options.secretFilePath, 'utf8').trim(); - if (val) candidates.push(val); + if (val) candidates.push({ value: val, source: 'secret-file' }); } if (options.envKey && options.envKey.trim().length > 0) { - candidates.push(options.envKey.trim()); + candidates.push({ value: options.envKey.trim(), source: 'env' }); } if (this.keyFilePath && fs.existsSync(this.keyFilePath)) { const val = fs.readFileSync(this.keyFilePath, 'utf8').trim(); - if (val) candidates.push(val); + if (val) candidates.push({ value: val, source: 'key-file' }); } if (options.backupKey && options.backupKey.trim().length > 0) { - candidates.push(options.backupKey.trim()); + candidates.push({ value: options.backupKey.trim(), source: 'backup' }); } if (fs.existsSync(this.vaultFilePath)) { @@ -268,15 +307,19 @@ export class VaultService { for (const candidate of candidates) { let keyBuf: Buffer | null = null; try { - keyBuf = parseMasterKey(candidate); + keyBuf = parseMasterKey(candidate.value); const payload = decryptEnvelope(envelope, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = candidate.source; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = false; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + // Security invariant: NEVER mirror Docker Secret or env master keys to disk vault.key + if (candidate.source === 'key-file') { + this.persistKeyFileIfConfigured(keyBuf); + } return { runtimeReady: true }; } catch { keyBuf?.fill(0); @@ -291,17 +334,28 @@ export class VaultService { let keyBuf: Buffer | null = null; try { - keyBuf = candidates[0] ? parseMasterKey(candidates[0]) : generateMasterKeyBuffer(); + const chosen = candidates[0]; + const source: KeySource = chosen ? chosen.source : 'generated'; + keyBuf = chosen ? parseMasterKey(chosen.value) : generateMasterKeyBuffer(); const emptyPayload: VaultPayload = { version: 1, credentials: {} }; this.writeVerifiedVaultAtomic(emptyPayload, keyBuf); this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = source; this.credentials.clear(); this.writeUnlocked = false; this.autoInitializedEmpty = true; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + // Only write local keyfile when generated locally (or already using key-file) and allowed + if ( + this.allowLocalKeyFile && + source !== 'secret-file' && + source !== 'env' && + source !== 'backup' + ) { + this.persistKeyFileIfConfigured(keyBuf); + } return { runtimeReady: true, initialized: true }; } catch (err) { keyBuf?.fill(0); @@ -362,11 +416,14 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = 'manual'; this.credentials.clear(); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { + this.persistKeyFileIfConfigured(keyBuf); + } return masterKeyInput ? {} : { generatedKeyHex: keyBuf.toString('hex') }; } @@ -384,17 +441,36 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = keyBuf; + this.keySource = 'manual'; this.credentials = new Map(Object.entries(payload.credentials)); this.writeUnlocked = true; this.autoInitializedEmpty = false; this.setPanicLockMarker(false); - this.persistKeyFileIfConfigured(keyBuf); + if (this.allowLocalKeyFile && this.keyFilePath && fs.existsSync(this.keyFilePath)) { + this.persistKeyFileIfConfigured(keyBuf); + } } catch (err) { keyBuf.fill(0); throw err; } } + seal(): void { + this.zeroizeMasterKey(); + this.keySource = null; + this.credentials.clear(); + this.writeUnlocked = false; + this.autoInitializedEmpty = false; + + for (const listener of this.sealListeners) { + try { + listener(); + } catch { + // Seal cleanup must continue across all listeners + } + } + } + unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault'); @@ -472,7 +548,15 @@ export class VaultService { this.zeroizeMasterKey(); this.masterKey = nextKey; this.writeUnlocked = true; - this.persistKeyFileIfConfigured(nextKey); + if ( + this.allowLocalKeyFile && + this.keySource !== 'secret-file' && + this.keySource !== 'env' && + this.keyFilePath && + fs.existsSync(this.keyFilePath) + ) { + this.persistKeyFileIfConfigured(nextKey); + } return newMasterKeyInput ? {} : { generatedKeyHex: nextKey.toString('hex') }; } catch (err) { nextKey.fill(0); @@ -613,8 +697,8 @@ export class VaultService { this.keyFilePath ?? (fs.existsSync(siblingKeyFile) ? siblingKeyFile : null); if (!targetPath) return; - fs.mkdirSync(path.dirname(targetPath), { recursive: true }); - const tmpPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; + fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 }); + const tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, `${key.toString('hex')}\n`, 'utf8'); @@ -635,11 +719,11 @@ export class VaultService { private writeVerifiedVaultAtomic(payload: VaultPayload, key: Buffer): void { const dir = path.dirname(this.vaultFilePath); - fs.mkdirSync(dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const envelope = encryptPayload(payload, key); const serialized = JSON.stringify(envelope, null, 2); - const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${Date.now()}`; + const tmpPath = `${this.vaultFilePath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts index e27920f..58e4969 100644 --- a/src/server/ssh/ssh-pool.ts +++ b/src/server/ssh/ssh-pool.ts @@ -574,7 +574,7 @@ export class SSHPool { } } - closeAll(reason: 'panic_lock' | 'shutdown'): void { + closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void { if (reason === 'shutdown') { this.closed = true; } @@ -588,12 +588,13 @@ export class SSHPool { this.closeServer(id); } - if (reason === 'panic_lock') { + if (reason === 'panic_lock' || reason === 'vault_sealed') { + const msg = reason === 'panic_lock' ? 'Panic Lock engaged' : 'Vault sealed'; for (const server of this.configManager.listServers()) { this.states.set(server.id, { serverId: server.id, status: server.enabled ? 'vault_locked' : 'disabled', - lastError: server.enabled ? 'Panic Lock engaged' : undefined, + lastError: server.enabled ? msg : undefined, }); } this.emitStates(); diff --git a/tests/api-ws-smoke.test.ts b/tests/api-ws-smoke.test.ts index d697842..1e603de 100644 --- a/tests/api-ws-smoke.test.ts +++ b/tests/api-ws-smoke.test.ts @@ -202,20 +202,13 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { ).toBe(200); // 6. Vault Init + Step-Up guard + Drop Elevation + Generate Ed25519 key - const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); - expect(vInit.status).toBe(201); - const generatedMasterKey = String(vInit.data.generatedKeyHex); - - // v1.1 defaults elevateOnLogin=false; step up first, then verify drop-elevation clears it + // v1.1 defaults elevateOnLogin=false; verify non-elevated session cannot init vault const statusInitial = await api('/api/auth/status'); expect(statusInitial.data.elevatedUntil).toBeNull(); - const noStepUp = await api('/api/vault/generate-ed25519', { - method: 'POST', - body: { id: 'prod-key', name: 'Prod Key' }, - }); - expect(noStepUp.status).toBe(403); - expect(noStepUp.data.error).toBe('STEP_UP_REQUIRED'); + const vInitDenied = await api('/api/vault/init', { method: 'POST', body: {} }); + expect(vInitDenied.status).toBe(403); + expect(vInitDenied.data.error).toBe('STEP_UP_REQUIRED'); const stepUpRes = await api('/api/auth/step-up', { method: 'POST', @@ -223,6 +216,10 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => { }); expect(stepUpRes.status).toBe(200); + const vInit = await api('/api/vault/init', { method: 'POST', body: {} }); + expect(vInit.status).toBe(201); + const generatedMasterKey = String(vInit.data.generatedKeyHex); + const statusBeforeDrop = await api('/api/auth/status'); expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); const dropped = await api('/api/auth/drop-elevation', { method: 'POST' }); diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 7e61fe3..921ce26 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -250,6 +250,9 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret expect(anyLogin.status).toBe(200); // Switch settings.json to strict multi-factor 'all' + 'every-action' + password step-up + expect( + (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp1.generate() } })).status, + ).toBe(200); const rawSettings = await api.call('/api/config/file?path=settings.json'); expect(rawSettings.status).toBe(200); const parsedSettings = JSON.parse(String(rawSettings.data.rawContent)) as Record< @@ -431,7 +434,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret const bundle = JSON.parse(fs.readFileSync(bundlePath, 'utf8')) as EmergencySecretsBundle; expect(bundle.vaultMasterKeyHex).toBe(masterKeyHex); expect(bundle.admin.username).toBe('admin'); - expect(bundle.admin.passwords.some((p) => p.plaintextPassword === password)).toBe(true); + expect(bundle.admin.passwords.some((p) => p.label === 'Primary Password' && !('plaintextPassword' in p))).toBe(true); expect(bundle.admin.totps.some((t) => t.secretBase32 === secretBase32)).toBe(true); expect(bundle.admin.recoveryCodes).toEqual(recoveryCodes); expect(bundle.vaultCredentials['backup-key']).toBeDefined(); diff --git a/tests/servers-api-e2e.test.ts b/tests/servers-api-e2e.test.ts index 583252b..26e9060 100644 --- a/tests/servers-api-e2e.test.ts +++ b/tests/servers-api-e2e.test.ts @@ -121,10 +121,10 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic }); ws.send(JSON.stringify({ type: 'sub', channels: ['metrics', 'alerts', 'config'] })); - expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect( (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); + expect((await api('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); const keyRes = await api('/api/vault/generate-ed25519', { method: 'POST', From 1b2e425a006e4f6892394bf587990b3ebccb317e Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:31:37 +0000 Subject: [PATCH 04/19] security(auth,ws): fix Auth/TOTP/WebAuthn/bootstrap vulnerabilities, session idle TTL & real-time WS revocation --- src/client/ts/main.ts | 6 +- src/client/ts/state.ts | 8 +- src/client/ts/views/auth-view.ts | 9 +- src/client/ts/views/settings-view.ts | 5 +- src/server/api/routes/auth.routes.ts | 715 +++++++++++++-------- src/server/api/ws-hub.ts | 245 +++++-- src/server/app.ts | 14 +- src/server/index.ts | 2 + src/server/security/auth.ts | 576 ++++++++++++++--- tests/auth-and-guards.test.ts | 25 +- tests/multi-auth-and-recovery.test.ts | 4 +- tests/passkeys.test.ts | 110 +++- tests/vault-runtime-and-collectors.test.ts | 6 +- 13 files changed, 1248 insertions(+), 477 deletions(-) diff --git a/src/client/ts/main.ts b/src/client/ts/main.ts index d41b44c..e15f94c 100644 --- a/src/client/ts/main.ts +++ b/src/client/ts/main.ts @@ -284,7 +284,7 @@ async function syncStatusAndRender(): Promise { authenticated: boolean; safeMode?: boolean; elevatedUntil?: number | null; - vaultState: ClientState['vaultState']; + vaultState?: ClientState['vaultState']; vaultRuntimeReady?: boolean; isPanicLocked?: boolean; defaultMobileSafeMode: boolean; @@ -295,8 +295,8 @@ async function syncStatusAndRender(): Promise { state.bootstrapped = status.bootstrapped; state.authenticated = status.authenticated; - state.vaultState = status.vaultState; - state.vaultRuntimeReady = status.vaultRuntimeReady ?? status.vaultState === 'unlocked'; + state.vaultState = status.vaultState ?? 'locked'; + state.vaultRuntimeReady = status.vaultRuntimeReady ?? false; state.isPanicLocked = Boolean(status.isPanicLocked); state.defaultMobileSafeMode = status.defaultMobileSafeMode; state.elevatedUntil = status.elevatedUntil ?? null; diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index f44aac5..9224ff1 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -85,13 +85,13 @@ export interface ClientAuthRequirements { requireTotpOnLogin: boolean; passwordMode: 'any' | 'all'; passwordCount: number; - passwordLabels: Array<{ id: string; label: string }>; + passwordLabels?: Array<{ id: string; label: string }>; totpMode: 'any' | 'all'; totpCount: number; - totpLabels: Array<{ id: string; label: string }>; + totpLabels?: Array<{ id: string; label: string }>; passkeyCount: number; - stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; - stepUpMethod: ClientSecuritySettings['stepUpMethod']; + stepUpPolicy?: ClientSecuritySettings['stepUpPolicy']; + stepUpMethod?: ClientSecuritySettings['stepUpMethod']; } export interface ClientState { diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index d183e36..6dab298 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -7,9 +7,11 @@ import { import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; interface BootstrapData { + bootstrapToken?: string; secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri?: string; } export async function renderAuthView( @@ -87,9 +89,11 @@ export async function renderAuthView( }); let secretBase32 = ''; + let bootstrapToken = ''; try { const data = await apiFetch('/api/auth/bootstrap'); secretBase32 = data.secretBase32; + bootstrapToken = data.bootstrapToken ?? ''; const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); if (doc.documentElement.nodeName === 'svg') { qrContainer.append(document.importNode(doc.documentElement, true)); @@ -134,6 +138,7 @@ export async function renderAuthView( password: passInput.value, totpCode: codeInput.value.trim(), secretBase32, + ...(bootstrapToken ? { bootstrapToken } : {}), initialSafeMode, securityPreset: presetSelect.value, }, @@ -283,7 +288,7 @@ export async function renderAuthView( form.append(el('label', { for: 'login-username' }, 'Username'), userInput); const passwordInputs: HTMLInputElement[] = []; - const pwCount = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; + const pwCount = Math.max(1, reqs?.passwordCount ?? pwLabels.length); for (let i = 0; i < pwCount; i++) { const labelText = pwMode === 'all' ? `Password — ${pwLabels[i]?.label ?? `#${i + 1}`}` : 'Password'; @@ -310,7 +315,7 @@ export async function renderAuthView( const codeInputs: HTMLInputElement[] = []; if (requireTotp) { - const totpCount = totpMode === 'all' ? Math.max(1, totpLabels.length) : 1; + const totpCount = Math.max(1, reqs?.totpCount ?? totpLabels.length); for (let i = 0; i < totpCount; i++) { const labelText = totpMode === 'all' diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 4830224..2524ecc 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -837,7 +837,10 @@ export async function renderSettingsView( dlBackupBtn.addEventListener('click', async () => { bMsg.textContent = ''; try { - const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export'); + const res = await apiFetch<{ bundle: unknown }>('/api/auth/recovery-backup/export', { + method: 'POST', + body: {}, + }); const blob = new Blob([`${JSON.stringify(res.bundle, null, 2)}\n`], { type: 'application/json', }); diff --git a/src/server/api/routes/auth.routes.ts b/src/server/api/routes/auth.routes.ts index 4f9fe52..44dc5bf 100644 --- a/src/server/api/routes/auth.routes.ts +++ b/src/server/api/routes/auth.routes.ts @@ -1,13 +1,19 @@ -import { Router, type Request, type Response } from 'express'; +import { Router, type NextFunction, type Request, type Response } from 'express'; import { z } from 'zod'; import type { AuthenticationResponseJSON, RegistrationResponseJSON, } from '@simplewebauthn/server'; +import { SecuritySettingsSchema } from '../../../shared/schemas/settings.schema.js'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../../security/auth.js'; import { + AuthOverloadError, + SESSION_COOKIE_NAME, + type AuthService, +} from '../../security/auth.js'; +import { + asyncHandler, createStepUpGuard, enforceSafeMode, extractCookies, @@ -28,6 +34,8 @@ export interface AuthRouterDeps { recoveryStore: EmergencyRecoveryService; rateLimiter: RateLimiter; trustCloudflare: boolean; + webauthnRpId?: string; + webauthnOrigins?: string[]; } function isSecureCookie(req: Request, trustCloudflare: boolean): boolean { @@ -44,9 +52,10 @@ function setAuthCookies( sessionToken: string, csrfToken: string, trustCloudflare: boolean, + sessionTtlHours = 168, ): void { const secure = isSecureCookie(req, trustCloudflare); - const maxAge = 7 * 24 * 60 * 60 * 1000; + const maxAge = Math.max(1, sessionTtlHours) * 60 * 60 * 1000; res.cookie(SESSION_COOKIE_NAME, sessionToken, { httpOnly: true, sameSite: 'strict', @@ -76,6 +85,8 @@ class WebAuthnRpError extends Error { function resolveWebAuthnRp( req: Request, trustCloudflare: boolean, + configuredRpId?: string, + configuredOrigins?: string[], ): { rpID: string; expectedOrigin: string } { const originHeader = typeof req.headers.origin === 'string' && req.headers.origin.trim() @@ -92,10 +103,35 @@ function resolveWebAuthnRp( throw new WebAuthnRpError('Invalid Origin header for WebAuthn request'); } - const rpID = parsed.hostname; - if (/^\d+\.\d+\.\d+\.\d+$/.test(rpID) || rpID.includes(':')) { + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + throw new WebAuthnRpError('WebAuthn Origin must use http or https'); + } + + if (configuredOrigins && configuredOrigins.length > 0) { + if (!configuredOrigins.includes(parsed.origin)) { + throw new WebAuthnRpError( + `Origin "${parsed.origin}" is not listed in GCOORD_WEBAUTHN_ORIGINS`, + ); + } + } else if (originHeader && parsed.host !== hostHeader) { + throw new WebAuthnRpError('WebAuthn Origin host does not match Request Host'); + } + + const hostname = parsed.hostname; + if (/^\d+\.\d+\.\d+\.\d+$/.test(hostname) || hostname.includes(':')) { throw new WebAuthnRpError( - `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${rpID}" is rejected by browsers).`, + `WebAuthn Passkeys require "localhost" or an HTTPS domain name (IP address "${hostname}" is rejected by browsers).`, + ); + } + + const rpID = configuredRpId || hostname; + if ( + configuredRpId && + hostname !== configuredRpId && + !hostname.endsWith(`.${configuredRpId}`) + ) { + throw new WebAuthnRpError( + `Hostname "${hostname}" does not match GCOORD_WEBAUTHN_RP_ID "${configuredRpId}"`, ); } @@ -115,6 +151,8 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { recoveryStore, rateLimiter, trustCloudflare, + webauthnRpId, + webauthnOrigins, } = deps; const stepUpGuard = createStepUpGuard( @@ -133,11 +171,16 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { res.json({ bootstrapped, authenticated: false, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, - authRequirements, + authRequirements: { + requireTotpOnLogin: authRequirements.requireTotpOnLogin, + passwordMode: authRequirements.passwordMode, + passwordCount: authRequirements.passwordCount, + totpMode: authRequirements.totpMode, + totpCount: authRequirements.totpCount, + passkeyCount: authRequirements.passkeyCount, + }, }); return; } @@ -148,196 +191,231 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { safeMode: session.safeMode, elevatedUntil: session.elevatedUntil, vaultState: vaultService.state, + sealState: vaultService.sealState, vaultRuntimeReady: vaultService.isRuntimeReady, isPanicLocked: vaultService.isPanicLocked, defaultMobileSafeMode: settings.defaultMobileSafeMode, theme: settings.theme, security: settings.security, + runtime: settings.runtime, authRequirements, }); }); - router.get('/bootstrap', async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const username = - typeof req.query.username === 'string' && req.query.username.trim() - ? req.query.username.trim() - : 'admin'; - const data = await authService.beginBootstrap(username); - res.json(data); - }); + router.get( + '/bootstrap', + asyncHandler(async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const rawUser = + typeof req.query.username === 'string' && req.query.username.trim() + ? req.query.username.trim().slice(0, 64) + : 'admin'; + const data = await authService.beginBootstrap(rawUser); + res.json(data); + }), + ); - router.post('/bootstrap', async (req, res) => { - if (authService.isBootstrapped()) { - res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('bootstrap', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const bodySchema = z.object({ - username: z.string().min(2).max(64).default('admin'), - password: z.string().min(10).max(256), - totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), - secretBase32: z.string().optional(), - initialSafeMode: z.boolean().optional(), - securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), - }); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('bootstrap', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - try { - if (parsed.data.securityPreset) { - const cur = configManager.getSettings(); - const presetSecurity = - parsed.data.securityPreset === 'relaxed' - ? { - ...cur.security, - requireTotpOnLogin: false, - stepUpPolicy: 'off' as const, - stepUpMethod: 'password' as const, - elevateOnLogin: true, - keepElevationOnSafeMode: true, - } - : parsed.data.securityPreset === 'strict' - ? { - ...cur.security, - requireTotpOnLogin: true, - stepUpPolicy: '5m' as const, - stepUpMethod: 'totp' as const, - elevateOnLogin: false, - keepElevationOnSafeMode: false, - } - : cur.security; - - configManager.saveConfigText( - 'settings.json', - JSON.stringify({ ...cur, security: presetSecurity }, null, 2), - 'ui', - `Bootstrap preset: ${parsed.data.securityPreset}`, - ); + router.post( + '/bootstrap', + asyncHandler(async (req, res) => { + if (authService.isBootstrapped()) { + res.status(409).json({ error: 'ALREADY_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('bootstrap', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; } - const result = await authService.completeBootstrap({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); - rateLimiter.recordSuccess('bootstrap', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username, - status: 'ok', - }); - res.status(201).json({ - authenticated: true, - csrfToken: result.csrfToken, - recoveryCodes: result.recoveryCodes, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - } catch (err) { - rateLimiter.recordFailure('bootstrap', ip); - auditService.log({ - action: 'auth.bootstrap', - actorIp: ip, - status: 'error', - details: err instanceof Error ? err.message : 'Bootstrap failed', - }); - res.status(400).json({ - error: 'BOOTSTRAP_FAILED', - message: err instanceof Error ? err.message : 'Bootstrap failed', - }); - } - }); - - router.post('/login', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const bodySchema = z - .object({ - username: z.string().min(1).optional(), - password: z.string().min(1).optional(), - passwords: z.array(z.string().min(1)).optional(), - code: z.string().max(32).optional(), - codes: z.array(z.string().max(32)).optional(), + const bodySchema = z.object({ + username: z.string().trim().min(2).max(64).default('admin'), + password: z.string().min(10).max(256), + totpCode: z.string().regex(/^\d{6}$/, 'TOTP code must be 6 digits'), + secretBase32: z.string().max(128).optional(), + bootstrapToken: z.string().min(16).max(128).optional(), initialSafeMode: z.boolean().optional(), - }) - .refine( - (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), - 'Password is required', - ); - const parsed = bodySchema.safeParse(req.body); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const result = await authService.login({ - ...parsed.data, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - }); - - if (!result) { - rateLimiter.recordFailure('login', ip); - auditService.log({ - action: 'auth.login', - actorIp: ip, - target: parsed.data.username ?? 'admin', - status: 'denied', + securityPreset: z.enum(['relaxed', 'balanced', 'strict']).optional(), }); - res.status(401).json({ error: 'INVALID_CREDENTIALS' }); - return; - } + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('bootstrap', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.login', - actorIp: ip, - sessionIdHash: result.session.idHash, - target: parsed.data.username ?? 'admin', - status: 'ok', - }); + try { + const result = await authService.completeBootstrap({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - }); + if (parsed.data.securityPreset) { + const cur = configManager.getSettings(); + const presetSecurity = + parsed.data.securityPreset === 'relaxed' + ? { + ...cur.security, + requireTotpOnLogin: false, + stepUpPolicy: 'off' as const, + stepUpMethod: 'password' as const, + elevateOnLogin: true, + keepElevationOnSafeMode: true, + } + : parsed.data.securityPreset === 'strict' + ? { + ...cur.security, + requireTotpOnLogin: true, + stepUpPolicy: '5m' as const, + stepUpMethod: 'totp' as const, + elevateOnLogin: false, + keepElevationOnSafeMode: false, + } + : cur.security; + + configManager.saveConfigText( + 'settings.json', + JSON.stringify({ ...cur, security: presetSecurity }, null, 2), + 'ui', + `Bootstrap preset: ${parsed.data.securityPreset}`, + ); + authService.syncRecovery({ + newRecoveryCodes: result.recoveryCodes, + snapshotReason: 'bootstrap-preset', + }); + } + + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('bootstrap', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + res.status(201).json({ + authenticated: true, + csrfToken: result.csrfToken, + recoveryCodes: result.recoveryCodes, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + } catch (err) { + if (err instanceof AuthOverloadError) throw err; + rateLimiter.recordFailure('bootstrap', ip); + auditService.log({ + action: 'auth.bootstrap', + actorIp: ip, + status: 'error', + details: err instanceof Error ? err.message : 'Bootstrap failed', + }); + res.status(400).json({ + error: 'BOOTSTRAP_FAILED', + message: err instanceof Error ? err.message : 'Bootstrap failed', + }); + } + }), + ); + + router.post( + '/login', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + if (!rateLimiter.acquireInFlight('login', ip, 2)) { + res.setHeader('Retry-After', '2'); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: 2 }); + return; + } + + try { + const bodySchema = z + .object({ + username: z.string().trim().min(1).max(64), + password: z.string().min(1).max(256).optional(), + passwords: z.array(z.string().min(1).max(256)).max(16).optional(), + code: z.string().max(64).optional(), + codes: z.array(z.string().max(64)).max(16).optional(), + initialSafeMode: z.boolean().optional(), + }) + .refine( + (b) => Boolean(b.password || (b.passwords && b.passwords.length > 0)), + 'Password is required', + ); + const parsed = bodySchema.safeParse(req.body); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.login({ + ...parsed.data, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + }); + + if (!result) { + const failState = rateLimiter.recordFailure('login', ip); + if (failState.lockedUntil > 0 || failState.globalTriggered) { + authService.emitSecurityEvent('auth.lockout', ip, { + failures: failState.failures, + globalTriggered: failState.globalTriggered, + }); + } + auditService.log({ + action: 'auth.login', + actorIp: ip, + target: parsed.data.username, + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_CREDENTIALS' }); + return; + } + + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); + auditService.log({ + action: 'auth.login', + actorIp: ip, + sessionIdHash: result.session.idHash, + target: parsed.data.username, + status: 'ok', + }); + + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + } finally { + rateLimiter.releaseInFlight('login', ip); + } + }), + ); // Exempt from enforceSafeMode router.post('/logout', requireAuth(authService), requireCsrf, (req, res) => { @@ -383,7 +461,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -394,10 +472,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const parsed = z .object({ - code: z.string().optional(), - codes: z.array(z.string()).optional(), - password: z.string().optional(), - passwords: z.array(z.string()).optional(), + code: z.string().max(64).optional(), + codes: z.array(z.string().max(64)).max(16).optional(), + password: z.string().max(256).optional(), + passwords: z.array(z.string().max(256)).max(16).optional(), }) .safeParse(req.body ?? {}); if (!parsed.success) { @@ -407,7 +485,12 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { const outcome = await authService.stepUp(req.authSession!.idHash, parsed.data); if (!outcome.ok) { - rateLimiter.recordFailure('step-up', ip); + const failState = rateLimiter.recordFailure('step-up', ip); + if (failState.lockedUntil > 0) { + authService.emitSecurityEvent('auth.step_up_lockout', ip, { + failures: failState.failures, + }); + } auditService.log({ action: 'auth.step_up', actorIp: ip, @@ -430,7 +513,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); - }, + }), ); router.post('/drop-elevation', requireAuth(authService), requireCsrf, (req, res) => { @@ -627,7 +710,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(async (req, res) => { const parsed = z .object({ label: z.string().min(1).max(64).default('Passkey') }) .safeParse(req.body ?? {}); @@ -636,7 +719,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare); + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const data = await authService.beginPasskeyRegistration({ label: parsed.data.label, ...rp, @@ -648,7 +731,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey registration', }); } - }, + }), ); router.post( @@ -657,10 +740,10 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(async (req, res) => { const parsed = z .object({ - challengeId: z.string().min(1), + challengeId: z.string().min(1).max(128), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -687,7 +770,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to verify passkey registration', }); } - }, + }), ); router.delete( @@ -721,102 +804,115 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.post('/passkeys/login/options', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - try { - const rp = resolveWebAuthnRp(req, trustCloudflare); - const data = await authService.beginPasskeyAuthentication({ - purpose: 'login', - ...rp, + router.post( + '/passkeys/login/options', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + try { + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); + const data = await authService.beginPasskeyAuthentication({ + purpose: 'login', + ...rp, + }); + res.json(data); + } catch (err) { + res.status(400).json({ + error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', + message: err instanceof Error ? err.message : 'No passkeys available', + }); + } + }), + ); + + router.post( + '/passkeys/login/verify', + asyncHandler(async (req, res) => { + if (!authService.isBootstrapped()) { + res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); + return; + } + const ip = req.clientIp ?? 'unknown'; + const rate = rateLimiter.check('login', ip); + if (!rate.allowed) { + res.setHeader('Retry-After', String(rate.retryAfterSec)); + res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); + return; + } + + const parsed = z + .object({ + challengeId: z.string().min(1).max(128), + response: z.record(z.unknown()), + initialSafeMode: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + rateLimiter.recordFailure('login', ip); + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const result = await authService.loginWithPasskey({ + challengeId: parsed.data.challengeId, + response: parsed.data.response as unknown as AuthenticationResponseJSON, + ip, + userAgent: String(req.headers['user-agent'] ?? 'unknown'), + initialSafeMode: parsed.data.initialSafeMode, }); - res.json(data); - } catch (err) { - res.status(400).json({ - error: err instanceof WebAuthnRpError ? err.code : 'PASSKEY_LOGIN_OPTIONS_FAILED', - message: err instanceof Error ? err.message : 'No passkeys available', - }); - } - }); + if (!result) { + const failState = rateLimiter.recordFailure('login', ip); + if (failState.lockedUntil > 0 || failState.globalTriggered) { + authService.emitSecurityEvent('auth.lockout', ip, { + failures: failState.failures, + globalTriggered: failState.globalTriggered, + }); + } + auditService.log({ + action: 'auth.passkey_login', + actorIp: ip, + status: 'denied', + }); + res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); + return; + } - router.post('/passkeys/login/verify', async (req, res) => { - if (!authService.isBootstrapped()) { - res.status(409).json({ error: 'NOT_BOOTSTRAPPED' }); - return; - } - const ip = req.clientIp ?? 'unknown'; - const rate = rateLimiter.check('login', ip); - if (!rate.allowed) { - res.setHeader('Retry-After', String(rate.retryAfterSec)); - res.status(429).json({ error: 'RATE_LIMITED', retryAfterSec: rate.retryAfterSec }); - return; - } - - const parsed = z - .object({ - challengeId: z.string().min(1), - response: z.record(z.unknown()), - initialSafeMode: z.boolean().optional(), - }) - .safeParse(req.body ?? {}); - if (!parsed.success) { - rateLimiter.recordFailure('login', ip); - res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); - return; - } - - const result = await authService.loginWithPasskey({ - challengeId: parsed.data.challengeId, - response: parsed.data.response as unknown as AuthenticationResponseJSON, - ip, - userAgent: String(req.headers['user-agent'] ?? 'unknown'), - initialSafeMode: parsed.data.initialSafeMode, - }); - if (!result) { - rateLimiter.recordFailure('login', ip); + const ttlHours = configManager.getSettings().security.sessionTtlHours; + rateLimiter.recordSuccess('login', ip); + setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare, ttlHours); auditService.log({ action: 'auth.passkey_login', actorIp: ip, - status: 'denied', + sessionIdHash: result.session.idHash, + status: 'ok', }); - res.status(401).json({ error: 'INVALID_PASSKEY_ASSERTION' }); - return; - } - rateLimiter.recordSuccess('login', ip); - setAuthCookies(res, req, result.sessionToken, result.csrfToken, trustCloudflare); - auditService.log({ - action: 'auth.passkey_login', - actorIp: ip, - sessionIdHash: result.session.idHash, - status: 'ok', - }); - - res.json({ - authenticated: true, - csrfToken: result.csrfToken, - safeMode: result.session.safeMode, - elevatedUntil: result.session.elevatedUntil, - vaultState: vaultService.state, - vaultRuntimeReady: vaultService.isRuntimeReady, - }); - }); + res.json({ + authenticated: true, + csrfToken: result.csrfToken, + safeMode: result.session.safeMode, + elevatedUntil: result.session.elevatedUntil, + vaultState: vaultService.state, + vaultRuntimeReady: vaultService.isRuntimeReady, + }); + }), + ); router.post( '/passkeys/step-up/options', requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -825,7 +921,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { return; } try { - const rp = resolveWebAuthnRp(req, trustCloudflare); + const rp = resolveWebAuthnRp(req, trustCloudflare, webauthnRpId, webauthnOrigins); const data = await authService.beginPasskeyAuthentication({ purpose: 'stepup', sessionIdHash: req.authSession!.idHash, @@ -838,7 +934,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { message: err instanceof Error ? err.message : 'Unable to start passkey verification', }); } - }, + }), ); router.post( @@ -846,7 +942,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + asyncHandler(async (req, res) => { const ip = req.clientIp ?? 'unknown'; const rate = rateLimiter.check('step-up', ip); if (!rate.allowed) { @@ -856,7 +952,7 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { } const parsed = z .object({ - challengeId: z.string().min(1), + challengeId: z.string().min(1).max(128), response: z.record(z.unknown()), }) .safeParse(req.body ?? {}); @@ -894,6 +990,46 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { status: 'ok', }); res.json({ elevatedUntil: outcome.elevatedUntil }); + }), + ); + + router.put( + '/security-policy', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const cur = configManager.getSettings(); + const bodyObj = + typeof req.body === 'object' && req.body !== null && !Array.isArray(req.body) + ? (req.body as Record) + : null; + if (!bodyObj) { + res.status(400).json({ error: 'VALIDATION_ERROR', message: 'Expected JSON object' }); + return; + } + const parsed = SecuritySettingsSchema.safeParse({ + ...cur.security, + ...bodyObj, + }); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + configManager.saveConfigText( + 'settings.json', + JSON.stringify({ ...cur, security: parsed.data }, null, 2), + 'ui', + 'Updated security policy via /api/auth/security-policy', + ); + auditService.log({ + action: 'auth.security_policy_update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'ok', + }); + res.json({ security: parsed.data }); }, ); @@ -922,9 +1058,11 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); - router.get( + router.post( '/recovery-backup/export', requireAuth(authService), + requireCsrf, + enforceSafeMode, stepUpGuard, (req, res) => { const settings = configManager.getSettings(); @@ -1032,5 +1170,14 @@ export function createAuthRouter(deps: AuthRouterDeps): Router { }, ); + router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { + if (err instanceof AuthOverloadError) { + res.setHeader('Retry-After', '2'); + res.status(503).json({ error: err.code, message: err.message }); + return; + } + next(err); + }); + return router; } diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index abfa4ff..42f80e7 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -5,10 +5,18 @@ import { ClientWsFrameSchema, type ServerWsFrame, } from '../../shared/ws-protocol.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import { + SESSION_COOKIE_NAME, + type AuthService, + type AuthSession, +} from '../security/auth.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; +const WS_MAX_PAYLOAD_BYTES = 128 * 1024; +const WS_SOFT_BACKPRESSURE_BYTES = 1024 * 1024; +const WS_HARD_BACKPRESSURE_BYTES = 4 * 1024 * 1024; + interface WsClientMeta { ws: WebSocket; sessionToken: string; @@ -42,25 +50,41 @@ export interface WsAiHandlers { } export class WsHub { - private readonly wss = new WebSocketServer({ noServer: true }); + private readonly wss = new WebSocketServer({ + noServer: true, + maxPayload: WS_MAX_PAYLOAD_BYTES, + }); private readonly clients = new Set(); private readonly pingTimer: NodeJS.Timeout; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; private readonly subscribeListeners = new Set(); private ptyHandlers: WsPtyHandlers | null = null; private aiHandlers: WsAiHandlers | null = null; + private readonly trustCloudflare: boolean; constructor( httpServer: HttpServer, private readonly authService: AuthService, private readonly vaultService: VaultService, + options: { trustCloudflare?: boolean } = {}, ) { + this.trustCloudflare = Boolean(options.trustCloudflare); httpServer.on('upgrade', (req, socket, head) => { this.handleUpgrade(req, socket, head); }); this.pingTimer = setInterval(() => { for (const client of this.clients) { + const session = this.authService.getSessionByToken(client.sessionToken); + if (!session) { + try { + client.ws.close(4001, 'Session expired'); + } catch { + client.ws.terminate(); + } + this.clients.delete(client); + continue; + } if (!client.alive) { client.ws.terminate(); this.clients.delete(client); @@ -73,6 +97,24 @@ export class WsHub { this.pingTimer.unref(); } + disconnectSessions(idHashes: string[]): void { + if (idHashes.length === 0) return; + const targetSet = new Set(idHashes); + for (const client of this.clients) { + if (!targetSet.has(client.sessionIdHash)) continue; + try { + if (client.ws.readyState === WebSocket.OPEN) { + client.ws.close(4001, 'Session revoked'); + } else { + client.ws.terminate(); + } + } catch { + // Ignore close errors + } + this.clients.delete(client); + } + } + registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void { this.upgradeHandlers.push({ prefix, handler }); } @@ -118,21 +160,18 @@ export class WsHub { broadcastAll(frame: ServerWsFrame): void { const text = JSON.stringify(frame); + const critical = frame.type === 'security:panic-lock' || frame.type === 'vault:state'; for (const client of this.clients) { - if (client.ws.readyState === WebSocket.OPEN) { - client.ws.send(text); - } + this.safeSendRaw(client, text, critical); } } broadcastChannel(channel: string, frame: ServerWsFrame): void { const text = JSON.stringify(frame); + const critical = frame.type === 'pty:exit' || frame.type === 'error'; for (const client of this.clients) { - if ( - client.ws.readyState === WebSocket.OPEN && - (client.channels.has(channel) || client.channels.has('*')) - ) { - client.ws.send(text); + if (client.channels.has(channel)) { + this.safeSendRaw(client, text, critical); } } } @@ -155,13 +194,29 @@ export class WsHub { return; } - // Validate Origin when provided by browsers to block cross-site WS hijacking + const cookies = extractCookies(req.headers.cookie); + const token = cookies[SESSION_COOKIE_NAME]; + const session = this.authService.getSessionByToken(token); + if (!session || !token) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + // Validate Origin strictly when present (browsers always send Origin) to block CSWSH const origin = req.headers.origin; const host = req.headers.host; - if (origin && host) { + if (origin) { try { const originUrl = new URL(origin); - if (originUrl.host !== host) { + const validScheme = + originUrl.protocol === 'http:' || originUrl.protocol === 'https:'; + const isHttpsReq = Boolean( + (req.socket as { encrypted?: boolean }).encrypted || + (this.trustCloudflare && req.headers['x-forwarded-proto'] === 'https'), + ); + const expectedScheme = isHttpsReq ? 'https:' : 'http:'; + if (!validScheme || !host || originUrl.host !== host || originUrl.protocol !== expectedScheme) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -173,15 +228,6 @@ export class WsHub { } } - const cookies = extractCookies(req.headers.cookie); - const token = cookies[SESSION_COOKIE_NAME]; - const session = this.authService.getSessionByToken(token); - if (!session || !token) { - socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); - socket.destroy(); - return; - } - this.wss.handleUpgrade(req, socket, head, (ws) => { const meta: WsClientMeta = { ws, @@ -193,13 +239,17 @@ export class WsHub { }; this.clients.add(meta); - this.sendFrame(ws, { - type: 'hello', - vaultState: this.vaultService.state, - vaultRuntimeReady: this.vaultService.isRuntimeReady, - safeMode: session.safeMode, - elevatedUntil: session.elevatedUntil, - }); + this.sendFrame( + ws, + { + type: 'hello', + vaultState: this.vaultService.state, + vaultRuntimeReady: this.vaultService.isRuntimeReady, + safeMode: session.safeMode, + elevatedUntil: session.elevatedUntil, + }, + true, + ); ws.on('pong', () => { meta.alive = true; @@ -219,40 +269,69 @@ export class WsHub { }); } + private ensureActiveSession(meta: WsClientMeta): AuthSession | null { + const latestSession = this.authService.getSessionByToken(meta.sessionToken); + if (!latestSession) { + try { + meta.ws.close(4001, 'Session expired'); + } catch { + meta.ws.terminate(); + } + this.clients.delete(meta); + return null; + } + return latestSession; + } + private onMessage(meta: WsClientMeta, raw: unknown): void { let parsedJson: unknown; try { const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8'); parsedJson = JSON.parse(text); } catch { - this.sendFrame(meta.ws, { - type: 'error', - code: 'BAD_JSON', - message: 'Invalid WebSocket JSON frame', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'BAD_JSON', + message: 'Invalid WebSocket JSON frame', + }, + true, + ); return; } const result = ClientWsFrameSchema.safeParse(parsedJson); if (!result.success) { - this.sendFrame(meta.ws, { - type: 'error', - code: 'INVALID_FRAME', - message: 'Unrecognized or malformed WebSocket frame', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'INVALID_FRAME', + message: 'Unrecognized or malformed WebSocket frame', + }, + true, + ); return; } const frame = result.data; switch (frame.type) { - case 'ping': - this.sendFrame(meta.ws, { - type: 'pong', - ts: frame.ts, - serverTs: Date.now(), - }); + case 'ping': { + if (!this.ensureActiveSession(meta)) return; + this.sendFrame( + meta.ws, + { + type: 'pong', + ts: frame.ts, + serverTs: Date.now(), + }, + true, + ); break; + } case 'sub': { + if (!this.ensureActiveSession(meta)) return; const ctx = { send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame), sessionIdHash: meta.sessionIdHash, @@ -274,44 +353,78 @@ export class WsHub { meta.channels.delete(ch); } break; - case 'safe-mode': - meta.clientSafeMode = frame.enabled; + case 'safe-mode': { + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; + meta.clientSafeMode = latestSession.safeMode || frame.enabled; break; + } case 'pty:input': { - const latestSession = this.authService.getSessionByToken(meta.sessionToken); - if (!latestSession) { - meta.ws.close(4001, 'Session expired'); - return; - } + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; if (latestSession.safeMode || meta.clientSafeMode) { - this.sendFrame(meta.ws, { - type: 'error', - code: 'SAFE_MODE_ACTIVE', - message: 'Safe / Read-Only Mode blocks terminal input.', - }); + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks terminal input.', + }, + true, + ); return; } this.ptyHandlers?.onInput(frame.sessionId, frame.data); break; } case 'pty:resize': { - const latestSession = this.authService.getSessionByToken(meta.sessionToken); - if (!latestSession) { - meta.ws.close(4001, 'Session expired'); - return; - } + if (!this.ensureActiveSession(meta)) return; this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows); break; } - case 'ai:cancel': + case 'ai:cancel': { + const latestSession = this.ensureActiveSession(meta); + if (!latestSession) return; + if (latestSession.safeMode || meta.clientSafeMode) { + this.sendFrame( + meta.ws, + { + type: 'error', + code: 'SAFE_MODE_ACTIVE', + message: 'Safe / Read-Only Mode blocks mutating AI actions.', + }, + true, + ); + return; + } this.aiHandlers?.onCancel(frame.chatId); break; + } } } - private sendFrame(ws: WebSocket, frame: ServerWsFrame): void { - if (ws.readyState === WebSocket.OPEN) { - ws.send(JSON.stringify(frame)); + private safeSendRaw(client: WsClientMeta, payload: string, critical = false): void { + if (client.ws.readyState !== WebSocket.OPEN) return; + if (client.ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { + client.ws.terminate(); + this.clients.delete(client); + return; } + if (!critical && client.ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { + return; + } + client.ws.send(payload); + } + + private sendFrame(ws: WebSocket, frame: ServerWsFrame, critical = false): void { + if (ws.readyState !== WebSocket.OPEN) return; + if (ws.bufferedAmount > WS_HARD_BACKPRESSURE_BYTES) { + ws.terminate(); + return; + } + if (!critical && ws.bufferedAmount > WS_SOFT_BACKPRESSURE_BYTES) { + return; + } + ws.send(JSON.stringify(frame)); } } diff --git a/src/server/app.ts b/src/server/app.ts index c0cdded..2b889a8 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -56,6 +56,7 @@ export interface ServerOptions { publicDir?: string; secretFilePath?: string; envMasterKey?: string; + envDbKey?: string; trustCloudflare?: boolean; trustedProxyCidrs?: string[]; allowLanTunnels?: boolean; @@ -135,8 +136,11 @@ export async function createGCoordinatorServer( const authService = new AuthService(db, { getSecuritySettings: () => configManager.getSettings().security, + getRuntimeLimits, recoveryStore, vaultService, + dataDir, + envDbKey: options.envDbKey, }); const backupKey = configManager.getSettings().security.enableEmergencySecretsBackup @@ -163,7 +167,10 @@ export async function createGCoordinatorServer( } const httpServer = http.createServer(app); - const wsHub = new WsHub(httpServer, authService, vaultService); + const wsHub = new WsHub(httpServer, authService, vaultService, { trustCloudflare }); + authService.onSessionsRevoked((idHashes) => { + wsHub.disconnectSessions(idHashes); + }); const knownHosts = new KnownHostsService(db, auditService); const sshPool = new SSHPool(configManager, vaultService, knownHosts); @@ -374,8 +381,8 @@ export async function createGCoordinatorServer( tunnelManager.stopAll(); ptyManager.closeAll(true); sshPool.closeAll('panic_lock'); - authService.revokeAllSessions(); wsHub.handlePanicLock(); + authService.revokeAllSessions(); }); configManager.onChange((event) => { @@ -437,6 +444,8 @@ export async function createGCoordinatorServer( recoveryStore, rateLimiter, trustCloudflare, + webauthnRpId: options.webauthnRpId, + webauthnOrigins: options.webauthnOrigins, }), ); @@ -628,6 +637,7 @@ export async function createGCoordinatorServer( tunnelManager.stopAll(); ptyManager.close(); sshPool.closeAll('shutdown'); + authService.close(); wsHub.close(); await configManager.close(); await new Promise((resolve) => { diff --git a/src/server/index.ts b/src/server/index.ts index 67672d9..8e1a56b 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -20,6 +20,7 @@ async function main(): Promise { const secretFilePath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; const envMasterKey = process.env.GCOORD_MASTER_KEY; + const envDbKey = process.env.GCOORD_DB_KEY; const proxyPortRaw = process.env.GCOORD_PROXY_PORT ? Number(process.env.GCOORD_PROXY_PORT) : undefined; const instance = await createGCoordinatorServer({ @@ -28,6 +29,7 @@ async function main(): Promise { host, secretFilePath, envMasterKey, + envDbKey, trustCloudflare, trustedProxyCidrs, allowLanTunnels: process.env.GCOORD_ALLOW_LAN_TUNNELS === 'true', diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index fb1500d..0c33dd8 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -1,4 +1,6 @@ import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; import { generateAuthenticationOptions, generateRegistrationOptions, @@ -17,18 +19,120 @@ import { type SecuritySettings, type StepUpPolicy, } from '../../shared/schemas/settings.schema.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { EmergencyRecoveryService, SavedTotpEntry } from './recovery-store.js'; import type { VaultService } from './vault.js'; const RECOVERY_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; -const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; const BOOTSTRAP_TTL_MS = 15 * 60 * 1000; const WEBAUTHN_TTL_MS = 5 * 60 * 1000; +const SESSION_REAPER_MS = 5 * 60 * 1000; const TOTP_PERIOD_SEC = 30; const DEFAULT_SECURITY = SecuritySettingsSchema.parse({}); export const SESSION_COOKIE_NAME = 'gcoord_sid'; +export class AuthOverloadError extends Error { + readonly code = 'AUTH_OVERLOADED'; + constructor(message = 'Authentication queue is busy; try again shortly') { + super(message); + this.name = 'AuthOverloadError'; + } +} + +export function loadOrCreateDbKey(options: { dataDir?: string; envDbKey?: string }): Buffer { + if (options.envDbKey && options.envDbKey.trim().length > 0) { + const clean = options.envDbKey.trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error('GCOORD_DB_KEY must be exactly 64 hex characters (32 bytes)'); + } + return Buffer.from(clean, 'hex'); + } + + if (!options.dataDir) { + return crypto.randomBytes(32); + } + + const keyPath = path.join(options.dataDir, 'db.key'); + try { + const stat = fs.lstatSync(keyPath); + if (stat.isSymbolicLink() || !stat.isFile()) { + throw new Error(`Refusing symlink or non-file db key at ${keyPath}`); + } + const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error(`Invalid db.key format at ${keyPath}`); + } + try { + fs.chmodSync(keyPath, 0o600); + } catch { + // Best-effort POSIX permission tightening + } + return Buffer.from(clean, 'hex'); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') { + throw err; + } + } + + const key = crypto.randomBytes(32); + const hex = `${key.toString('hex')}\n`; + try { + fs.mkdirSync(path.dirname(keyPath), { recursive: true, mode: 0o700 }); + const fd = fs.openSync( + keyPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + try { + fs.writeSync(fd, hex, 0, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + return key; + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code === 'EEXIST') { + const clean = fs.readFileSync(keyPath, 'utf8').trim().toLowerCase(); + if (!/^[0-9a-f]{64}$/.test(clean)) { + throw new Error(`Invalid db.key format at ${keyPath}`); + } + return Buffer.from(clean, 'hex'); + } + throw err; + } +} + +export function encryptTotpSecret(dbKey: Buffer, totpId: string, secretBase32: string): string { + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv('aes-256-gcm', dbKey, iv); + cipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); + const ct = Buffer.concat([cipher.update(secretBase32, 'utf8'), cipher.final()]); + const tag = cipher.getAuthTag(); + return `v1:${iv.toString('hex')}:${tag.toString('hex')}:${ct.toString('hex')}`; +} + +export function decryptTotpSecret(dbKey: Buffer, totpId: string, encoded: string): string { + const parts = encoded.split(':'); + if (parts.length !== 4 || parts[0] !== 'v1') { + throw new Error(`Invalid encrypted TOTP envelope for ${totpId}`); + } + const iv = Buffer.from(parts[1]!, 'hex'); + const tag = Buffer.from(parts[2]!, 'hex'); + const ct = Buffer.from(parts[3]!, 'hex'); + const decipher = crypto.createDecipheriv('aes-256-gcm', dbKey, iv); + decipher.setAAD(Buffer.from(`gcoord-totp-v1:${totpId}`, 'utf8')); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); +} + +function timingSafeStringEqual(a: string, b: string): boolean { + const bufA = Buffer.from(a, 'utf8'); + const bufB = Buffer.from(b, 'utf8'); + if (bufA.length !== bufB.length) return false; + return crypto.timingSafeEqual(bufA, bufB); +} + export interface AuthSession { idHash: string; csrfTokenHash: string; @@ -96,8 +200,16 @@ export type StepUpInput = export interface AuthServiceOptions { getSecuritySettings?: () => SecuritySettings; + getRuntimeLimits?: () => RuntimeLimits; recoveryStore?: EmergencyRecoveryService; vaultService?: VaultService; + dataDir?: string; + envDbKey?: string; + onSecurityEvent?: (event: { + type: string; + ip?: string; + details?: Record; + }) => void; } interface AdminRow { @@ -120,8 +232,10 @@ interface TotpRow { id: string; label: string; secret_base32: string; + secret_enc: string | null; last_login_step: number | null; last_stepup_step: number | null; + last_used_step: number | null; created_at: number; } @@ -191,13 +305,21 @@ function computeElevatedUntil( } export class AuthService { - private pendingBootstrap: { secretBase32: string; createdAt: number } | null = null; + private pendingBootstrap: { secretBase32: string; token: string; createdAt: number } | null = null; private readonly pendingEnrollments = new Map< string, { label: string; secretBase32: string; createdAt: number } >(); private readonly pendingWebAuthn = new Map(); + private readonly sessionRevokedListeners = new Set<(idHashes: string[]) => void>(); private readonly getSecurity: () => SecuritySettings; + private readonly getRuntimeLimits?: () => RuntimeLimits; + private onSecurityEvent?: AuthServiceOptions['onSecurityEvent']; + private readonly dbKey: Buffer; + private readonly sessionReaperTimer: NodeJS.Timeout; + private argon2Active = 0; + private readonly argon2Queue: Array<{ resolve: () => void; reject: (err: Error) => void }> = []; + private dummyArgon2Hash: string | null = null; private recoveryStore?: EmergencyRecoveryService; private vaultService?: VaultService; @@ -206,8 +328,169 @@ export class AuthService { options: AuthServiceOptions = {}, ) { this.getSecurity = options.getSecuritySettings ?? (() => DEFAULT_SECURITY); + this.getRuntimeLimits = options.getRuntimeLimits; + this.onSecurityEvent = options.onSecurityEvent; this.recoveryStore = options.recoveryStore; this.vaultService = options.vaultService; + + const inferredDir = + options.dataDir ?? + (db.name && db.name !== ':memory:' ? path.dirname(db.name) : undefined); + this.dbKey = loadOrCreateDbKey({ dataDir: inferredDir, envDbKey: options.envDbKey }); + this.migratePlaintextTotpsIfNeeded(); + + this.sessionReaperTimer = setInterval(() => { + this.reapExpiredSessions(); + }, SESSION_REAPER_MS); + this.sessionReaperTimer.unref(); + } + + close(): void { + clearInterval(this.sessionReaperTimer); + while (this.argon2Queue.length > 0) { + const waiter = this.argon2Queue.shift()!; + waiter.reject(new Error('AuthService shutting down')); + } + } + + setSecurityEventListener(listener: AuthServiceOptions['onSecurityEvent']): void { + this.onSecurityEvent = listener; + } + + emitSecurityEvent(type: string, ip?: string, details?: Record): void { + try { + this.onSecurityEvent?.({ type, ip, details }); + } catch { + // Never let security event hook break authentication flow + } + } + + onSessionsRevoked(listener: (idHashes: string[]) => void): () => void { + this.sessionRevokedListeners.add(listener); + return () => { + this.sessionRevokedListeners.delete(listener); + }; + } + + private notifySessionsRevoked(idHashes: string[]): void { + if (idHashes.length === 0) return; + for (const listener of this.sessionRevokedListeners) { + try { + listener(idHashes); + } catch { + // Ignore subscriber errors + } + } + } + + private async runArgon2(task: (memoryCost: number) => Promise): Promise { + const limits = this.getRuntimeLimits?.(); + const concurrency = Math.max(1, limits?.argon2Concurrency ?? 2); + const maxQueue = Math.max(1, limits?.argon2MaxQueue ?? 16); + const memoryCost = limits?.argon2MemoryCost ?? 32768; + + if (this.argon2Active >= concurrency) { + if (this.argon2Queue.length >= maxQueue) { + throw new AuthOverloadError(); + } + await new Promise((resolve, reject) => { + this.argon2Queue.push({ resolve, reject }); + }); + } + + this.argon2Active += 1; + try { + return await task(memoryCost); + } finally { + this.argon2Active -= 1; + const next = this.argon2Queue.shift(); + if (next) next.resolve(); + } + } + + private hashPassword(password: string): Promise { + return this.runArgon2((memoryCost) => + argon2.hash(password, { + type: argon2.argon2id, + memoryCost, + timeCost: 3, + parallelism: 1, + }), + ); + } + + private verifyPasswordHash(hash: string, candidate: string): Promise { + return this.runArgon2(() => argon2.verify(hash, candidate).catch(() => false)); + } + + private async verifyDummyPassword(candidate: string): Promise { + if (!this.dummyArgon2Hash) { + this.dummyArgon2Hash = await this.hashPassword('gcoord-dummy-timing-guard-v1'); + } + await this.verifyPasswordHash(this.dummyArgon2Hash, candidate); + } + + private getTotpSecret(row: TotpRow): string { + if (row.secret_enc && row.secret_enc.startsWith('v1:')) { + return decryptTotpSecret(this.dbKey, row.id, row.secret_enc); + } + if (row.secret_base32 && row.secret_base32.length > 0) { + const enc = encryptTotpSecret(this.dbKey, row.id, row.secret_base32); + try { + this.db + .prepare("UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?") + .run(enc, row.id); + } catch { + // Ignore read-only DB edge case + } + return row.secret_base32; + } + throw new Error(`Missing TOTP secret for ${row.id}`); + } + + private migratePlaintextTotpsIfNeeded(): void { + try { + const rows = this.db + .prepare("SELECT id, secret_base32 FROM admin_totps WHERE (secret_enc IS NULL OR secret_enc = '') AND secret_base32 != ''") + .all() as Array<{ id: string; secret_base32: string }>; + if (rows.length === 0) return; + const tx = this.db.transaction(() => { + const stmt = this.db.prepare( + "UPDATE admin_totps SET secret_enc = ?, secret_base32 = '' WHERE id = ?", + ); + for (const r of rows) { + stmt.run(encryptTotpSecret(this.dbKey, r.id, r.secret_base32), r.id); + } + }); + tx(); + } catch { + // Safe before migrations finish if constructed manually + } + } + + reapExpiredSessions(): number { + const now = Date.now(); + const sec = this.getSecurity(); + const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; + const rows = + idleMs > 0 + ? (this.db + .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') + .all(now, now - idleMs) as Array<{ id_hash: string }>) + : (this.db + .prepare('SELECT id_hash FROM sessions WHERE expires_at <= ?') + .all(now) as Array<{ id_hash: string }>); + if (rows.length === 0) return 0; + const hashes = rows.map((r) => r.id_hash); + if (idleMs > 0) { + this.db + .prepare('DELETE FROM sessions WHERE expires_at <= ? OR last_seen_at <= ?') + .run(now, now - idleMs); + } else { + this.db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now); + } + this.notifySessionsRevoked(hashes); + return hashes.length; } attachRecoveryDependencies( @@ -259,9 +542,11 @@ export class AuthService { } async beginBootstrap(username = 'admin'): Promise<{ + bootstrapToken: string; secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri: string; }> { if (this.isBootstrapped()) { throw new Error('Admin account is already configured'); @@ -274,17 +559,24 @@ export class AuthService { const secret = new OTPAuth.Secret({ size: 20 }); this.pendingBootstrap = { secretBase32: secret.base32, + token: crypto.randomBytes(24).toString('base64url'), createdAt: Date.now(), }; } - const totp = buildTotp(this.pendingBootstrap.secretBase32, username); + const cleanUser = username.trim().slice(0, 64) || 'admin'; + const totp = buildTotp(this.pendingBootstrap.secretBase32, cleanUser); const otpauthUri = totp.toString(); - const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); + const [qrSvg, qrDataUri] = await Promise.all([ + QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), + QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), + ]); return { + bootstrapToken: this.pendingBootstrap.token, secretBase32: this.pendingBootstrap.secretBase32, otpauthUri, qrSvg, + qrDataUri, }; } @@ -293,6 +585,7 @@ export class AuthService { password: string; totpCode: string; secretBase32?: string; + bootstrapToken?: string; ip: string; userAgent: string; initialSafeMode?: boolean; @@ -313,11 +606,30 @@ export class AuthService { throw new Error('Password must be at least 10 characters'); } - const secretBase32 = params.secretBase32 ?? this.pendingBootstrap?.secretBase32; - if (!secretBase32) { + if ( + !this.pendingBootstrap || + Date.now() - this.pendingBootstrap.createdAt > BOOTSTRAP_TTL_MS + ) { + this.pendingBootstrap = null; throw new Error('Bootstrap enrollment session expired; reload setup'); } + if ( + params.bootstrapToken !== undefined && + !timingSafeStringEqual(params.bootstrapToken, this.pendingBootstrap.token) + ) { + throw new Error('Invalid bootstrap session token; reload setup'); + } + + if ( + params.secretBase32 !== undefined && + !timingSafeStringEqual(params.secretBase32.trim(), this.pendingBootstrap.secretBase32) + ) { + throw new Error('Bootstrap secret mismatch; reload setup'); + } + + const secretBase32 = this.pendingBootstrap.secretBase32; + const nowMs = Date.now(); const totp = buildTotp(secretBase32, username); const delta = totp.validate({ @@ -330,12 +642,8 @@ export class AuthService { } const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; - const passwordHash = await argon2.hash(params.password, { - type: argon2.argon2id, - memoryCost: 65536, - timeCost: 3, - parallelism: 1, - }); + const passwordHash = await this.hashPassword(params.password); + const secretEnc = encryptTotpSecret(this.dbKey, 'totp-primary', secretBase32); const recoveryCodes: string[] = []; for (let i = 0; i < 8; i++) { @@ -346,9 +654,9 @@ export class AuthService { this.db .prepare( `INSERT INTO admin_users (id, username, password_hash, totp_secret, last_login_totp_step, last_stepup_totp_step, created_at, updated_at) - VALUES (1, ?, ?, ?, ?, NULL, ?, ?)`, + VALUES (1, ?, '', '', ?, ?, ?, ?)`, ) - .run(username, passwordHash, secretBase32, matchedStep, nowMs, nowMs); + .run(username, matchedStep, matchedStep, nowMs, nowMs); this.db .prepare( @@ -358,10 +666,10 @@ export class AuthService { this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) - VALUES (?, ?, ?, ?, NULL, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, ?, '', ?, ?, ?, ?, ?)`, ) - .run('totp-primary', 'Primary Authenticator', secretBase32, matchedStep, nowMs); + .run('totp-primary', 'Primary Authenticator', secretEnc, matchedStep, matchedStep, matchedStep, nowMs); const insertRec = this.db.prepare( 'INSERT INTO recovery_codes (code_hash, used_at) VALUES (?, NULL)', @@ -399,28 +707,35 @@ export class AuthService { const admin = this.db .prepare('SELECT * FROM admin_users WHERE id = 1') .get() as AdminRow | undefined; - if (!admin) return null; + const suppliedPasswords = ( + params.passwords ?? (params.password !== undefined ? [params.password] : []) + ) + .filter((p) => p.length > 0) + .slice(0, 16); + const cleanUser = params.username?.trim() ?? ''; - if (params.username && params.username.trim() !== admin.username) { + if ( + !admin || + !cleanUser || + cleanUser.length > 64 || + suppliedPasswords.length === 0 || + !timingSafeStringEqual(cleanUser, admin.username) + ) { + await this.verifyDummyPassword(suppliedPasswords[0] ?? 'dummy'); return null; } const sec = this.getSecurity(); - const suppliedPasswords = ( - params.passwords ?? (params.password !== undefined ? [params.password] : []) - ).filter((p) => p.length > 0); - if (suppliedPasswords.length === 0) return null; - const pwOk = await this.verifyPasswords(suppliedPasswords, sec.passwordMode); if (!pwOk) return null; - const totpRows = this.listTotpRows(); - if (sec.requireTotpOnLogin && totpRows.length > 0) { + if (sec.requireTotpOnLogin) { const suppliedCodes = ( params.codes ?? (params.code !== undefined ? [params.code] : []) ) .map((c) => c.trim()) - .filter((c) => c.length > 0); + .filter((c) => c.length > 0) + .slice(0, 16); if (suppliedCodes.length === 0) return null; @@ -429,6 +744,7 @@ export class AuthService { sec.totpMode, 'login', admin.username, + params.ip, ); if (!mfaOk) return null; } @@ -451,10 +767,24 @@ export class AuthService { const now = Date.now(); if (row.expires_at <= now) { this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + this.notifySessionsRevoked([idHash]); return null; } - if (now - row.last_seen_at > 60_000) { + const sec = this.getSecurity(); + const idleMs = (sec.sessionIdleTimeoutMin ?? 60) * 60 * 1000; + if (idleMs > 0 && now - row.last_seen_at > idleMs) { + this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + this.notifySessionsRevoked([idHash]); + this.emitSecurityEvent('auth.session_idle_expired', row.ip, { + idPrefix: idHash.slice(0, 12), + }); + return null; + } + + const touchIntervalMs = + idleMs > 0 ? Math.min(60_000, Math.max(1000, Math.floor(idleMs / 4))) : 60_000; + if (now - row.last_seen_at > touchIntervalMs) { this.db .prepare('UPDATE sessions SET last_seen_at = ? WHERE id_hash = ?') .run(now, idHash); @@ -522,20 +852,17 @@ export class AuthService { } if (sec.stepUpMethod === 'totp' || sec.stepUpMethod === 'both') { - const totpRows = this.listTotpRows(); - if (totpRows.length > 0) { - if (suppliedCodes.length === 0) { - return { ok: false, reason: 'invalid_totp' }; - } - const totpResult = this.verifyTotpRows( - suppliedCodes, - sec.totpMode, - 'stepup', - admin.username, - ); - if (!totpResult.ok) { - return { ok: false, reason: totpResult.reason }; - } + if (suppliedCodes.length === 0) { + return { ok: false, reason: 'invalid_totp' }; + } + const totpResult = this.verifyTotpRows( + suppliedCodes, + sec.totpMode, + 'stepup', + admin.username, + ); + if (!totpResult.ok) { + return { ok: false, reason: totpResult.reason }; } } @@ -680,7 +1007,7 @@ export class AuthService { })), authenticatorSelection: { residentKey: 'preferred', - userVerification: 'preferred', + userVerification: 'required', }, }); @@ -711,7 +1038,7 @@ export class AuthService { expectedChallenge: pending.challenge, expectedOrigin: pending.expectedOrigin, expectedRPID: pending.rpID, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified || !verification.registrationInfo) { @@ -776,7 +1103,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, })), - userVerification: 'preferred', + userVerification: 'required', }); const challengeId = crypto.randomBytes(16).toString('hex'); @@ -802,6 +1129,14 @@ export class AuthService { if (!this.isBootstrapped()) return null; const pending = this.consumeWebAuthnChallenge(params.challengeId, 'login'); if (!pending) return null; + if ( + !params.response || + typeof params.response.id !== 'string' || + params.response.id.length === 0 || + params.response.id.length > 512 + ) { + return null; + } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -822,7 +1157,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified) return null; @@ -857,11 +1192,22 @@ export class AuthService { if (session.safe_mode === 1) { return { ok: false, reason: 'safe_mode_active' }; } + if (sec.stepUpMethod !== 'passkey') { + return { ok: false, reason: 'passkey_stepup_not_enabled' }; + } const pending = this.consumeWebAuthnChallenge(params.challengeId, 'stepup'); if (!pending || pending.sessionIdHash !== params.idHash) { return { ok: false, reason: 'invalid_challenge' }; } + if ( + !params.response || + typeof params.response.id !== 'string' || + params.response.id.length === 0 || + params.response.id.length > 512 + ) { + return { ok: false, reason: 'invalid_assertion' }; + } const row = this.db .prepare('SELECT * FROM webauthn_credentials WHERE id = ?') @@ -882,7 +1228,7 @@ export class AuthService { ? (JSON.parse(row.transports) as AuthenticatorTransportFuture[]) : undefined, }, - requireUserVerification: false, + requireUserVerification: true, }); if (!verification.verified) { return { ok: false, reason: 'invalid_assertion' }; @@ -922,12 +1268,7 @@ export class AuthService { const id = `pw-${crypto.randomBytes(4).toString('hex')}`; const createdAt = Date.now(); - const hash = await argon2.hash(password, { - type: argon2.argon2id, - memoryCost: 65536, - timeCost: 3, - parallelism: 1, - }); + const hash = await this.hashPassword(password); this.db .prepare( @@ -962,6 +1303,7 @@ export class AuthService { secretBase32: string; otpauthUri: string; qrSvg: string; + qrDataUri: string; }> { const cleanLabel = label.trim(); if (cleanLabel.length < 1 || cleanLabel.length > 64) { @@ -985,13 +1327,17 @@ export class AuthService { const username = this.getAdminUsername() ?? 'admin'; const totp = buildTotp(secret.base32, `${username} (${cleanLabel})`); const otpauthUri = totp.toString(); - const qrSvg = await QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }); + const [qrSvg, qrDataUri] = await Promise.all([ + QRCode.toString(otpauthUri, { type: 'svg', margin: 1 }), + QRCode.toDataURL(otpauthUri, { margin: 1, width: 220 }), + ]); return { enrollmentId, label: cleanLabel, secretBase32: secret.base32, otpauthUri, qrSvg, + qrDataUri, }; } @@ -1019,12 +1365,13 @@ export class AuthService { const matchedStep = Math.floor(nowMs / 1000 / TOTP_PERIOD_SEC) + delta; const id = `totp-${crypto.randomBytes(4).toString('hex')}`; + const secretEnc = encryptTotpSecret(this.dbKey, id, pending.secretBase32); this.db .prepare( - `INSERT INTO admin_totps (id, label, secret_base32, last_login_step, last_stepup_step, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, ?, '', ?, ?, ?, ?, ?)`, ) - .run(id, pending.label, pending.secretBase32, matchedStep, matchedStep, nowMs); + .run(id, pending.label, secretEnc, matchedStep, matchedStep, matchedStep, nowMs); this.pendingEnrollments.delete(enrollmentId); this.syncRecovery({ snapshotReason: 'totp-added' }); @@ -1092,16 +1439,19 @@ export class AuthService { .prepare('SELECT id, label, created_at AS createdAt FROM admin_passwords ORDER BY created_at ASC') .all() as Array<{ id: string; label: string; createdAt: number }>; const totpRows = this.listTotpRows(); - const totps: SavedTotpEntry[] = totpRows.map((t) => ({ - id: t.id, - label: t.label, - secretBase32: t.secret_base32, - otpauthUri: buildTotp( - t.secret_base32, - username ? `${username} (${t.label})` : t.label, - ).toString(), - createdAt: new Date(t.created_at).toISOString(), - })); + const totps: SavedTotpEntry[] = totpRows.map((t) => { + const secretBase32 = this.getTotpSecret(t); + return { + id: t.id, + label: t.label, + secretBase32, + otpauthUri: buildTotp( + secretBase32, + username ? `${username} (${t.label})` : t.label, + ).toString(), + createdAt: new Date(t.created_at).toISOString(), + }; + }); this.recoveryStore.syncState({ enabled: sec.enableEmergencySecretsBackup, @@ -1134,24 +1484,43 @@ export class AuthService { } revokeSessionByHash(idHash: string): void { - this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + const res = this.db.prepare('DELETE FROM sessions WHERE id_hash = ?').run(idHash); + if (res.changes > 0) { + this.notifySessionsRevoked([idHash]); + } } revokeSessionByPrefix(prefix: string): number { if (!/^[0-9a-f]{8,64}$/i.test(prefix)) return 0; + const rows = this.db + .prepare('SELECT id_hash FROM sessions WHERE id_hash LIKE ?') + .all(`${prefix}%`) as Array<{ id_hash: string }>; + if (rows.length === 0) return 0; const result = this.db .prepare('DELETE FROM sessions WHERE id_hash LIKE ?') .run(`${prefix}%`); + if (result.changes > 0) { + this.notifySessionsRevoked(rows.map((r) => r.id_hash)); + } return result.changes; } revokeAllSessions(exceptIdHash?: string): number { - if (exceptIdHash) { - return this.db - .prepare('DELETE FROM sessions WHERE id_hash != ?') - .run(exceptIdHash).changes; + const rows = ( + exceptIdHash + ? this.db + .prepare('SELECT id_hash FROM sessions WHERE id_hash != ?') + .all(exceptIdHash) + : this.db.prepare('SELECT id_hash FROM sessions').all() + ) as Array<{ id_hash: string }>; + if (rows.length === 0) return 0; + const changes = exceptIdHash + ? this.db.prepare('DELETE FROM sessions WHERE id_hash != ?').run(exceptIdHash).changes + : this.db.prepare('DELETE FROM sessions').run().changes; + if (changes > 0) { + this.notifySessionsRevoked(rows.map((r) => r.id_hash)); } - return this.db.prepare('DELETE FROM sessions').run().changes; + return changes; } private listTotpRows(): TotpRow[] { @@ -1172,7 +1541,7 @@ export class AuthService { if (mode === 'any') { for (const row of rows) { for (const candidate of suppliedPasswords) { - if (await argon2.verify(row.password_hash, candidate)) { + if (await this.verifyPasswordHash(row.password_hash, candidate)) { return true; } } @@ -1184,7 +1553,7 @@ export class AuthService { for (const row of rows) { let rowMatched = false; for (const candidate of suppliedPasswords) { - if (await argon2.verify(row.password_hash, candidate)) { + if (await this.verifyPasswordHash(row.password_hash, candidate)) { rowMatched = true; break; } @@ -1199,8 +1568,9 @@ export class AuthService { mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, + ip?: string, ): boolean { - const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username); + const totpRes = this.verifyTotpRows(suppliedCodes, mode, purpose, username, ip); if (totpRes.ok) return true; // In 'any' mode, a single-use recovery code may replace TOTP @@ -1214,33 +1584,48 @@ export class AuthService { 'UPDATE recovery_codes SET used_at = ? WHERE code_hash = ? AND used_at IS NULL', ) .run(Date.now(), sha256Hex(normalized)); - if (updated.changes === 1) return true; + if (updated.changes === 1) { + this.emitSecurityEvent('auth.recovery_code_used', ip, { username }); + return true; + } } } return false; } + private getRowLastUsedStep(row: TotpRow): number | null { + if (row.last_used_step !== null && row.last_used_step !== undefined) { + return row.last_used_step; + } + const candidates = [row.last_login_step, row.last_stepup_step].filter( + (n): n is number => typeof n === 'number', + ); + return candidates.length > 0 ? Math.max(...candidates) : null; + } + private verifyTotpRows( suppliedCodes: string[], mode: 'any' | 'all', purpose: 'login' | 'stepup', username: string, + ip?: string, ): { ok: true } | { ok: false; reason: string } { const rows = this.listTotpRows(); - if (rows.length === 0) return { ok: true }; + if (rows.length === 0) { + return { ok: false, reason: 'totp_not_configured' }; + } const numericCodes = suppliedCodes.filter((c) => /^\d{6}$/.test(c)); if (numericCodes.length === 0) return { ok: false, reason: 'invalid_totp' }; const nowMs = Date.now(); - const stepCol = purpose === 'login' ? 'last_login_step' : 'last_stepup_step'; if (mode === 'any') { let sawReplay = false; for (const row of rows) { - const totp = buildTotp(row.secret_base32, username); - const lastStep = - purpose === 'login' ? row.last_login_step : row.last_stepup_step; + const secret = this.getTotpSecret(row); + const totp = buildTotp(secret, username); + const lastStep = this.getRowLastUsedStep(row); for (const code of numericCodes) { const delta = totp.validate({ token: code, window: 1, timestamp: nowMs }); if (delta === null) continue; @@ -1250,20 +1635,25 @@ export class AuthService { continue; } this.db - .prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`) - .run(matchedStep, row.id); + .prepare( + 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', + ) + .run(matchedStep, matchedStep, matchedStep, row.id); return { ok: true }; } } + if (sawReplay) { + this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); + } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } // 'all': every configured TOTP authenticator must match a supplied valid non-replayed code const matchedUpdates: Array<{ id: string; step: number }> = []; for (const row of rows) { - const totp = buildTotp(row.secret_base32, username); - const lastStep = - purpose === 'login' ? row.last_login_step : row.last_stepup_step; + const secret = this.getTotpSecret(row); + const totp = buildTotp(secret, username); + const lastStep = this.getRowLastUsedStep(row); let rowStep: number | null = null; let sawReplay = false; @@ -1280,15 +1670,20 @@ export class AuthService { } if (rowStep === null) { + if (sawReplay) { + this.emitSecurityEvent('auth.totp_replay', ip, { purpose }); + } return { ok: false, reason: sawReplay ? 'totp_replayed' : 'invalid_totp' }; } matchedUpdates.push({ id: row.id, step: rowStep }); } const tx = this.db.transaction(() => { - const stmt = this.db.prepare(`UPDATE admin_totps SET ${stepCol} = ? WHERE id = ?`); + const stmt = this.db.prepare( + 'UPDATE admin_totps SET last_used_step = ?, last_login_step = ?, last_stepup_step = ? WHERE id = ?', + ); for (const upd of matchedUpdates) { - stmt.run(upd.step, upd.id); + stmt.run(upd.step, upd.step, upd.step, upd.id); } }); tx(); @@ -1305,8 +1700,9 @@ export class AuthService { const idHash = sha256Hex(sessionToken); const csrfTokenHash = sha256Hex(csrfToken); const now = Date.now(); - const expiresAt = now + SESSION_TTL_MS; const sec = this.getSecurity(); + const ttlMs = (sec.sessionTtlHours ?? 168) * 60 * 60 * 1000; + const expiresAt = now + ttlMs; const shouldElevate = sec.elevateOnLogin && (!safeMode || sec.keepElevationOnSafeMode); diff --git a/tests/auth-and-guards.test.ts b/tests/auth-and-guards.test.ts index 2fb7ca6..1683dbe 100644 --- a/tests/auth-and-guards.test.ts +++ b/tests/auth-and-guards.test.ts @@ -129,15 +129,21 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { }); expect(boot.session.elevatedUntil).toBeNull(); - // Step-up tracks replay independently from login step - const stepUp1 = await auth.stepUp(boot.session.idHash, code0); + // Unified monotonic TOTP step blocks replaying bootstrap code for step-up + const replayBootCode = await auth.stepUp(boot.session.idHash, code0); + expect(replayBootCode).toEqual({ ok: false, reason: 'totp_replayed' }); + + const t1 = t0 + 31_000; + vi.setSystemTime(t1); + const code1 = generateTotp(enroll.secretBase32, t1); + const stepUp1 = await auth.stepUp(boot.session.idHash, code1); expect(stepUp1).toEqual({ ok: true, - elevatedUntil: t0 + 5 * 60 * 1000, + elevatedUntil: t1 + 5 * 60 * 1000, }); // Replaying exact same step-up code is denied - const stepUpReplay = await auth.stepUp(boot.session.idHash, code0); + const stepUpReplay = await auth.stepUp(boot.session.idHash, code1); expect(stepUpReplay).toEqual({ ok: false, reason: 'totp_replayed' }); // Enabling Safe Mode clears elevatedUntil immediately @@ -146,18 +152,19 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => { expect(safeSession?.elevatedUntil).toBeNull(); // Step-up is blocked while Safe Mode is ON - vi.setSystemTime(t0 + 31_000); - const code1 = generateTotp(enroll.secretBase32, t0 + 31_000); - const whileSafe = await auth.stepUp(boot.session.idHash, code1); + const t2 = t1 + 31_000; + vi.setSystemTime(t2); + const code2 = generateTotp(enroll.secretBase32, t2); + const whileSafe = await auth.stepUp(boot.session.idHash, code2); expect(whileSafe).toEqual({ ok: false, reason: 'safe_mode_active' }); // Turning Safe Mode OFF allows step-up again auth.setSafeMode(boot.session.idHash, false); - const stepUp2 = await auth.stepUp(boot.session.idHash, code1); + const stepUp2 = await auth.stepUp(boot.session.idHash, code2); expect(stepUp2.ok).toBe(true); // Elevation expires automatically after 5 minutes - vi.setSystemTime(t0 + 31_000 + 5 * 60 * 1000 + 1000); + vi.setSystemTime(t2 + 5 * 60 * 1000 + 1000); const expiredSession = auth.getSessionByToken(boot.sessionToken); expect(expiredSession?.elevatedUntil).toBeNull(); diff --git a/tests/multi-auth-and-recovery.test.ts b/tests/multi-auth-and-recovery.test.ts index 921ce26..60b4710 100644 --- a/tests/multi-auth-and-recovery.test.ts +++ b/tests/multi-auth-and-recovery.test.ts @@ -453,7 +453,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret activeServer = server; api = createApiClient(server); - vi.setSystemTime(t0 + 31_000); + vi.setSystemTime(t0 + 62_000); const relogin = await api.call('/api/auth/login', { method: 'POST', body: { @@ -510,7 +510,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret ).status, ).toBe(200); - vi.setSystemTime(t0 + 62_000); + vi.setSystemTime(t0 + 93_000); expect( (await api.call('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, ).toBe(200); diff --git a/tests/passkeys.test.ts b/tests/passkeys.test.ts index 9f5c444..0a9137b 100644 --- a/tests/passkeys.test.ts +++ b/tests/passkeys.test.ts @@ -1,5 +1,6 @@ import crypto from 'node:crypto'; 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'; @@ -152,6 +153,7 @@ function buildSyntheticAuthenticator(rpID: string, expectedOrigin: string) { } afterEach(async () => { + vi.useRealTimers(); while (cleanups.length > 0) { await cleanups.pop()!(); } @@ -172,7 +174,6 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { fs.rmSync(dataDir, { recursive: true, force: true }); }); - const baseUrl = `http://127.0.0.1:${server.port}`; const origin = `http://localhost:${server.port}`; const jar = new CookieJar(); let csrfToken = ''; @@ -186,16 +187,57 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { Host: `localhost:${server.port}`, }; if (jar.header()) headers.Cookie = jar.header(); - if (opts.body !== undefined) headers['Content-Type'] = 'application/json'; + const payload = opts.body !== undefined ? JSON.stringify(opts.body) : undefined; + if (payload !== undefined) { + headers['Content-Type'] = 'application/json'; + headers['Content-Length'] = String(Buffer.byteLength(payload)); + } 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; + const res = await new Promise<{ status: number; setCookies: string[]; text: string }>( + (resolve, reject) => { + const req = http.request( + { + host: '127.0.0.1', + port: server.port, + path: pathname, + method: opts.method ?? 'GET', + headers, + }, + (incoming) => { + const chunks: Buffer[] = []; + incoming.on('data', (c) => chunks.push(Buffer.from(c))); + incoming.on('end', () => { + const rawSetCookie = incoming.headers['set-cookie']; + resolve({ + status: incoming.statusCode ?? 0, + setCookies: Array.isArray(rawSetCookie) ? rawSetCookie : [], + text: Buffer.concat(chunks).toString('utf8'), + }); + }); + }, + ); + req.on('error', reject); + if (payload !== undefined) req.write(payload); + req.end(); + }, + ); + for (const line of res.setCookies) { + 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 === '') jar['cookies'].delete(name); + else jar['cookies'].set(name, val); + } + } + let data: Record = {}; + try { + data = JSON.parse(res.text) as Record; + } catch { + data = {}; + } if (typeof data.csrfToken === 'string' && data.csrfToken) { csrfToken = data.csrfToken; } @@ -316,7 +358,38 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { }); expect(loginVerify2.status).toBe(200); - // 3. Step-Up Verification via Passkey + // 3. Step-Up Verification via Passkey requires stepUpMethod === 'passkey' + await api('/api/auth/drop-elevation', { method: 'POST' }); + expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); + + const deniedOpts = await api('/api/auth/passkeys/step-up/options', { method: 'POST', body: {} }); + expect(deniedOpts.status).toBe(200); + const deniedVerify = await api('/api/auth/passkeys/step-up/verify', { + method: 'POST', + body: { + challengeId: String(deniedOpts.data.challengeId), + response: authn.createAuthenticationResponse( + String((deniedOpts.data.options as { challenge: string }).challenge), + ), + }, + }); + expect(deniedVerify.status).toBe(403); + expect(deniedVerify.data.reason).toBe('passkey_stepup_not_enabled'); + + // Step up with TOTP in next step, enable stepUpMethod = 'passkey', then drop & verify passkey step-up + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + 35_000); + expect( + (await api('/api/auth/step-up', { method: 'POST', body: { code: totp.generate() } })).status, + ).toBe(200); + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { stepUpMethod: 'passkey' }, + }) + ).status, + ).toBe(200); await api('/api/auth/drop-elevation', { method: 'POST' }); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(403); @@ -335,7 +408,22 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => { expect(typeof stepVerify.data.elevatedUntil).toBe('number'); expect((await api('/api/vault/credentials/pk-test-key/reveal')).status).toBe(200); - // 4. Delete passkey factor + // 4. Cannot delete the last passkey while stepUpMethod === 'passkey' + const blockedDel = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { + method: 'DELETE', + }); + expect(blockedDel.status).toBe(400); + + // Switch stepUpMethod back to 'totp', then delete passkey cleanly + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { stepUpMethod: 'totp' }, + }) + ).status, + ).toBe(200); + const delRes = await api(`/api/auth/factors/passkeys/${encodeURIComponent(authn.credId)}`, { method: 'DELETE', }); diff --git a/tests/vault-runtime-and-collectors.test.ts b/tests/vault-runtime-and-collectors.test.ts index 6c1374e..77ee897 100644 --- a/tests/vault-runtime-and-collectors.test.ts +++ b/tests/vault-runtime-and-collectors.test.ts @@ -188,12 +188,12 @@ describe('Always-on background collectors & write-only Vault lock', () => { }); api = createApiClient(activeServer); - // Before ANY user logs in, status is unauthenticated + write-locked, yet runtime collectors run immediately + // Before ANY user logs in, status is unauthenticated and omits internal vault state, yet runtime collectors run immediately const preLoginStatus = await api.call('/api/auth/status'); expect(preLoginStatus.status).toBe(200); expect(preLoginStatus.data.authenticated).toBe(false); - expect(preLoginStatus.data.vaultState).toBe('locked'); - expect(preLoginStatus.data.vaultRuntimeReady).toBe(true); + expect(preLoginStatus.data.vaultState).toBeUndefined(); + expect(preLoginStatus.data.vaultRuntimeReady).toBeUndefined(); const latestBeforeLogin = await waitFor( () => activeServer!.monitoringService.getLatest('srv-1')?.sample, From 9a27525defe4f7707ae3c1d7dbccca32b977c00f Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:37:20 +0000 Subject: [PATCH 05/19] feat(audit,backup,cli): upgrade Audit Log, harden async Backup + scheduled backups & CLI tools --- src/cli/gcoord.ts | 655 +++++++++++++++++++++--- src/server/api/routes/audit.routes.ts | 68 ++- src/server/api/routes/backup.routes.ts | 158 ++++-- src/server/app.ts | 37 +- src/server/security/audit.ts | 166 +++++- src/server/security/backup-scheduler.ts | 275 ++++++++++ src/server/security/backup.ts | 441 +++++++++++++--- src/server/security/vault.ts | 12 + 8 files changed, 1590 insertions(+), 222 deletions(-) create mode 100644 src/server/security/backup-scheduler.ts diff --git a/src/cli/gcoord.ts b/src/cli/gcoord.ts index ef67f22..c38df01 100644 --- a/src/cli/gcoord.ts +++ b/src/cli/gcoord.ts @@ -1,7 +1,16 @@ +import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline/promises'; import { parseArgs } from 'node:util'; +import argon2 from 'argon2'; +import Database from 'better-sqlite3'; +import * as OTPAuth from 'otpauth'; +import { openDatabase } from '../server/db/database.js'; +import { + encryptTotpSecret, + loadOrCreateDbKey, +} from '../server/security/auth.js'; import { createBackupBundle, restoreBackupBundle, @@ -9,24 +18,42 @@ import { } from '../server/security/backup.js'; import { EmergencyRecoveryService } from '../server/security/recovery-store.js'; import { VaultService } from '../server/security/vault.js'; +import { SettingsSchema } from '../shared/schemas/settings.schema.js'; function printUsage(): void { console.log(`GCoordinator CLI (gcoord) Commands: + status Inspect GCoordinator data directory state (read-only) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --json Print status summary as JSON + + panic-lock Engage Panic Lock offline: mark vault locked and revoke all sessions + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + + reset-2fa Reset TOTP authenticators offline (re-enroll new TOTP or disable 2FA) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --disable Disable requireTotpOnLogin and switch stepUpMethod to password + --json Print new secret & otpauth URI as JSON + + reset-password Reset the admin password offline (revokes all sessions & clears lockouts) + --data-dir Data directory (default: GCOORD_DATA_DIR or ./data) + --password-file Read new password (>= 10 chars) from file instead of prompt + 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 + --new-key-out Exclusive output file (0600, O_EXCL) for generated key 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) + --passphrase-file Path to passphrase file (>= 12 chars, uses scrypt) verify-backup Verify GCM tag, JSON schemas, and Vault envelope without modifying data Backup bundle path (or --bundle ) + --data-dir Data directory fallback for vault.key lookup --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 @@ -41,7 +68,153 @@ Commands: `); } +function readRegularFileStrict(filePath: string): string { + const abs = path.resolve(filePath); + const stat = fs.lstatSync(abs); + if (stat.isSymbolicLink() || !stat.isFile()) { + throw new Error(`Refusing symlink or non-file path: ${abs}`); + } + return fs.readFileSync(abs, 'utf8').trim(); +} + +function writeAtomicSecureFile(targetPath: string, content: string): void { + const abs = path.resolve(targetPath); + try { + const stat = fs.lstatSync(abs); + if (stat.isSymbolicLink()) { + throw new Error(`Refusing to overwrite symlink at ${abs}`); + } + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'ENOENT') throw err; + } + + fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); + const tmpPath = `${abs}.tmp.${process.pid}.${crypto.randomBytes(6).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, abs); + fs.chmodSync(abs, 0o600); + } catch (err) { + try { + fs.unlinkSync(tmpPath); + } catch { + // Ignore cleanup error + } + throw err; + } +} + +function writeExclusiveSecureFile(targetPath: string, content: string): void { + const abs = path.resolve(targetPath); + fs.mkdirSync(path.dirname(abs), { recursive: true, mode: 0o700 }); + const fd = fs.openSync( + abs, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + try { + fs.writeFileSync(fd, content, 'utf8'); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } +} + +function isPidAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + +async function withDataDirLock(dataDir: string, fn: () => Promise): Promise { + const absDir = path.resolve(dataDir); + fs.mkdirSync(absDir, { recursive: true, mode: 0o700 }); + const lockPath = path.join(absDir, 'gcoord.lock'); + + const tryAcquire = (): number => + fs.openSync( + lockPath, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, + 0o600, + ); + + let fd: number; + try { + fd = tryAcquire(); + } catch (err) { + if ((err as NodeJS.ErrnoException)?.code !== 'EEXIST') throw err; + const raw = fs.readFileSync(lockPath, 'utf8'); + const existingPid = Number.parseInt(raw.split(/\r?\n/)[0] ?? '', 10); + if (isPidAlive(existingPid)) { + throw new Error(`Another gcoord CLI command (PID ${existingPid}) holds ${lockPath}`); + } + fs.rmSync(lockPath, { force: true }); + fd = tryAcquire(); + } + + try { + fs.writeFileSync(fd, `${process.pid}\n${Date.now()}\n`, 'utf8'); + fs.closeSync(fd); + return await fn(); + } finally { + fs.rmSync(lockPath, { force: true }); + } +} + async function promptHiddenOrLine(promptText: string): Promise { + if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') { + process.stderr.write(promptText); + const wasRaw = Boolean(process.stdin.isRaw); + process.stdin.setRawMode(true); + process.stdin.resume(); + + return new Promise((resolve, reject) => { + let buf = ''; + const cleanup = () => { + process.stdin.off('data', onData); + try { + process.stdin.setRawMode(wasRaw); + } catch { + // Ignore restore error + } + process.stdin.pause(); + }; + const onData = (chunk: Buffer) => { + const text = chunk.toString('utf8'); + for (const ch of text) { + if (ch === '\u0003') { + cleanup(); + process.stderr.write('\n'); + reject(new Error('Aborted by user')); + return; + } + if (ch === '\r' || ch === '\n') { + cleanup(); + process.stderr.write('\n'); + resolve(buf.trim()); + return; + } + if (ch === '\u007f' || ch === '\b') { + if (buf.length > 0) buf = buf.slice(0, -1); + continue; + } + buf += ch; + } + }; + process.stdin.on('data', onData); + }); + } + const rl = readline.createInterface({ input: process.stdin, output: process.stderr, @@ -56,18 +229,19 @@ async function promptHiddenOrLine(promptText: string): Promise { async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { if (keyFile) { - return fs.readFileSync(keyFile, 'utf8').trim(); + return readRegularFileStrict(keyFile); } 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(); + const secretPath = process.env.GCOORD_MASTER_KEY_FILE ?? '/run/secrets/gcoord_master_key'; + if (fs.existsSync(secretPath)) { + return readRegularFileStrict(secretPath); } if (dataDir) { const localKeyFile = path.join(path.resolve(dataDir), 'vault.key'); if (fs.existsSync(localKeyFile)) { - return fs.readFileSync(localKeyFile, 'utf8').trim(); + return readRegularFileStrict(localKeyFile); } } return promptHiddenOrLine('Enter current 32-byte vault master key (hex or base64): '); @@ -75,18 +249,19 @@ async function readCurrentKey(keyFile?: string, dataDir?: string): Promise { + const settingsPath = path.join(dataDir, 'config', 'settings.json'); + if (!fs.existsSync(settingsPath)) return SettingsSchema.parse({}); + return SettingsSchema.parse(JSON.parse(readRegularFileStrict(settingsPath))); +} + +async function runStatus(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + json: { type: 'boolean', default: false }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + const vaultPath = path.join(dataDir, 'vault.enc'); + const vaultKeyPath = path.join(dataDir, 'vault.key'); + const dbKeyPath = path.join(dataDir, 'db.key'); + const panicMarkerPath = `${vaultPath}.panic-locked`; + + const status: Record = { + dataDir, + dataDirExists: fs.existsSync(dataDir), + vaultInitialized: fs.existsSync(vaultPath), + panicLocked: fs.existsSync(panicMarkerPath), + localVaultKeyFile: fs.existsSync(vaultKeyPath), + localDbKeyFile: fs.existsSync(dbKeyPath), + dbInitialized: fs.existsSync(dbPath), + }; + + if (fs.existsSync(dbPath)) { + const roDb = new Database(dbPath, { readonly: true }); + try { + const admin = roDb + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + const now = Date.now(); + const pwCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_passwords').get() as { cnt: number }).cnt; + const totpCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM admin_totps').get() as { cnt: number }).cnt; + const passkeyCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM webauthn_credentials').get() as { cnt: number }).cnt; + const activeSessions = ( + roDb.prepare('SELECT COUNT(*) AS cnt FROM sessions WHERE expires_at > ?').get(now) as { cnt: number } + ).cnt; + const auditCount = (roDb.prepare('SELECT COUNT(*) AS cnt FROM audit_log').get() as { cnt: number }).cnt; + let activeLockouts = 0; + try { + activeLockouts = ( + roDb.prepare('SELECT COUNT(*) AS cnt FROM rate_limits WHERE locked_until > ?').get(now) as { cnt: number } + ).cnt; + } catch { + activeLockouts = 0; + } + + Object.assign(status, { + bootstrapped: Boolean(admin), + username: admin?.username ?? null, + passwordCount: pwCount, + totpCount, + passkeyCount, + activeSessions, + activeLockouts, + auditLogRows: auditCount, + }); + } finally { + roDb.close(); + } + } + + if (parsed.values.json) { + console.log(JSON.stringify(status, null, 2)); + } else { + console.log( + `GCoordinator status (${dataDir}): vault=${status.vaultInitialized ? (status.panicLocked ? 'panic-locked' : 'present') : 'uninitialized'}, db=${status.dbInitialized ? 'present' : 'missing'}, bootstrapped=${Boolean(status.bootstrapped)}, sessions=${String(status.activeSessions ?? 0)}, auditRows=${String(status.auditLogRows ?? 0)}`, + ); + } + return 0; +} + +async function runPanicLock(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + if (!fs.existsSync(dataDir)) { + console.error(`Error: Data directory not found at ${dataDir}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const markerPath = path.join(dataDir, 'vault.enc.panic-locked'); + writeAtomicSecureFile(markerPath, `${Date.now()}\n`); + + const dbPath = path.join(dataDir, 'gcoord.db'); + let revoked = 0; + if (fs.existsSync(dbPath)) { + const db = openDatabase(dbPath); + try { + revoked = db.prepare('DELETE FROM sessions').run().changes; + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', + ).run(Date.now(), 'security.cli_panic_lock', 'cli', 'vault', 'ok', JSON.stringify({ revoked })); + } finally { + db.close(); + } + } + + console.log(`Panic Lock engaged cleanly (marker=${markerPath}, revokedSessions=${revoked}).`); + return 0; + }); +} + +async function runReset2fa(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + disable: { type: 'boolean', default: false }, + json: { type: 'boolean', default: false }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + if (!fs.existsSync(dbPath)) { + console.error(`Error: Database not found at ${dbPath}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const db = openDatabase(dbPath); + try { + const admin = db + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + if (!admin) { + console.error('Error: Admin account is not bootstrapped yet'); + return 1; + } + + if (parsed.values.disable) { + const settingsPath = path.join(dataDir, 'config', 'settings.json'); + const settings = loadSettingsObject(dataDir) as { + security?: Record; + [k: string]: unknown; + }; + const updated = SettingsSchema.parse({ + ...settings, + security: { + ...(settings.security ?? {}), + requireTotpOnLogin: false, + stepUpMethod: 'password', + }, + }); + writeAtomicSecureFile(settingsPath, `${JSON.stringify(updated, null, 2)}\n`); + + db.transaction(() => { + db.prepare('DELETE FROM admin_totps').run(); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', + ).run(Date.now(), 'auth.cli_reset_2fa_disable', 'cli', admin.username, 'ok'); + })(); + + console.log('TOTP 2FA disabled offline. Sessions revoked and rate limits cleared.'); + return 0; + } + + const dbKey = loadOrCreateDbKey({ dataDir, envDbKey: process.env.GCOORD_DB_KEY }); + const secret = new OTPAuth.Secret({ size: 20 }); + const id = `totp-${crypto.randomBytes(4).toString('hex')}`; + const enc = encryptTotpSecret(dbKey, id, secret.base32); + const now = Date.now(); + const otpauthUri = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: `${admin.username} (CLI Reset)`, + algorithm: 'SHA1', + digits: 6, + period: 30, + secret, + }).toString(); + + db.transaction(() => { + db.prepare('DELETE FROM admin_totps').run(); + db.prepare( + `INSERT INTO admin_totps (id, label, secret_base32, secret_enc, last_login_step, last_stepup_step, last_used_step, created_at) + VALUES (?, 'CLI Reset Authenticator', '', ?, NULL, NULL, NULL, ?)`, + ).run(id, enc, now); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, ?)', + ).run(now, 'auth.cli_reset_2fa', 'cli', admin.username, 'ok', JSON.stringify({ totpId: id })); + })(); + + if (parsed.values.json) { + console.log( + JSON.stringify({ + reset: true, + username: admin.username, + totpId: id, + secretBase32: secret.base32, + otpauthUri, + }), + ); + } else { + console.log(`TOTP reset cleanly for "${admin.username}". Enroll this new authenticator secret:`); + console.log(`Secret (Base32): ${secret.base32}`); + console.log(`otpauth URI: ${otpauthUri}`); + } + return 0; + } finally { + db.close(); + } + }); +} + +async function runResetPassword(args: string[]): Promise { + const parsed = parseArgs({ + args, + options: { + 'data-dir': { type: 'string' }, + 'password-file': { type: 'string' }, + }, + allowPositionals: false, + }); + + const dataDir = path.resolve( + parsed.values['data-dir'] ?? process.env.GCOORD_DATA_DIR ?? './data', + ); + const dbPath = path.join(dataDir, 'gcoord.db'); + if (!fs.existsSync(dbPath)) { + console.error(`Error: Database not found at ${dbPath}`); + return 1; + } + + return withDataDirLock(dataDir, async () => { + const newPassword = parsed.values['password-file'] + ? readRegularFileStrict(parsed.values['password-file']) + : await promptHiddenOrLine('Enter new admin password (>= 10 characters): '); + + if (newPassword.length < 10 || newPassword.length > 256) { + console.error('Error: Password must be between 10 and 256 characters'); + return 1; + } + + const db = openDatabase(dbPath); + try { + const admin = db + .prepare('SELECT username FROM admin_users WHERE id = 1') + .get() as { username: string } | undefined; + if (!admin) { + console.error('Error: Admin account is not bootstrapped yet'); + return 1; + } + + const hash = await argon2.hash(newPassword, { + type: argon2.argon2id, + memoryCost: 32768, + timeCost: 3, + parallelism: 1, + }); + const now = Date.now(); + + db.transaction(() => { + db.prepare('DELETE FROM admin_passwords').run(); + db.prepare( + 'INSERT INTO admin_passwords (id, label, password_hash, created_at) VALUES (?, ?, ?, ?)', + ).run('pw-primary', 'Primary Password', hash, now); + db.prepare("UPDATE admin_users SET password_hash = '', updated_at = ? WHERE id = 1").run( + now, + ); + db.prepare('DELETE FROM sessions').run(); + db.prepare('DELETE FROM rate_limits').run(); + db.prepare( + 'INSERT INTO audit_log (ts, action, actor_ip, session_id_hash, target, status, details) VALUES (?, ?, ?, NULL, ?, ?, NULL)', + ).run(now, 'auth.cli_reset_password', 'cli', admin.username, 'ok'); + })(); + + console.log( + `Admin password reset cleanly for "${admin.username}". All active sessions revoked.`, + ); + return 0; + } finally { + db.close(); + } + }); +} + async function runRotateKey(args: string[]): Promise { const parsed = parseArgs({ args, @@ -122,32 +601,40 @@ async function runRotateKey(args: string[]): Promise { return 1; } - const currentKey = await readCurrentKey(parsed.values['current-key-file']); - const vault = new VaultService(vaultPath); - vault.unlock(currentKey); - const { generatedKeyHex } = vault.rotateMasterKey(); + return withDataDirLock(dataDir, async () => { + const currentKey = await readCurrentKey(parsed.values['current-key-file'], dataDir); + const vault = new VaultService(vaultPath, { + keyFilePath: path.join(dataDir, 'vault.key'), + }); + vault.unlock(currentKey); + const { generatedKeyHex } = vault.rotateMasterKey(); - if (!generatedKeyHex) { - console.error('Error: Unexpected empty rotated key'); - return 1; - } + if (!generatedKeyHex) { + console.error('Error: Unexpected empty rotated key'); + return 1; + } - const recovery = new EmergencyRecoveryService(dataDir); - if (recovery.readBundle() !== null) { - recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' }); - } + const recovery = new EmergencyRecoveryService(dataDir); + const settings = loadSettingsObject(dataDir) as { + security?: { enableEmergencySecretsBackup?: boolean }; + }; + if ( + settings.security?.enableEmergencySecretsBackup && + recovery.readBundle() !== null + ) { + recovery.syncState({ enabled: true, vault, snapshotReason: 'cli-rotate-key' }); + } - if (parsed.values['new-key-out']) { - const outPath = path.resolve(parsed.values['new-key-out']); - fs.mkdirSync(path.dirname(outPath), { recursive: true }); - fs.writeFileSync(outPath, `${generatedKeyHex}\n`, { mode: 0o600 }); - fs.chmodSync(outPath, 0o600); - console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); - } else { - console.log('Vault master key rotated cleanly. Store this new key securely:'); - console.log(generatedKeyHex); - } - return 0; + if (parsed.values['new-key-out']) { + const outPath = path.resolve(parsed.values['new-key-out']); + writeExclusiveSecureFile(outPath, `${generatedKeyHex}\n`); + console.log(`Vault master key rotated cleanly. New key written to ${outPath} (mode 0600).`); + } else { + console.log('Vault master key rotated cleanly. Store this new key securely:'); + console.log(generatedKeyHex); + } + return 0; + }); } async function runBackup(args: string[]): Promise { @@ -183,17 +670,7 @@ async function runBackup(args: string[]): Promise { }); 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); + writeAtomicSecureFile(outPath, result.serialized); console.log( `Backup created at ${outPath} (kdf=${result.summary.kdf}, configs=${result.summary.configFileCount}, knownHosts=${result.summary.knownHostsCount}, vaultVerified=${result.summary.vaultVerified})`, @@ -206,6 +683,7 @@ async function runVerifyBackup(args: string[]): Promise { args, options: { bundle: { type: 'string' }, + 'data-dir': { type: 'string' }, 'key-file': { type: 'string' }, 'passphrase-file': { type: 'string' }, 'vault-key-file': { type: 'string' }, @@ -220,17 +698,26 @@ async function runVerifyBackup(args: string[]): Promise { return 1; } - const rawBuf = fs.readFileSync(path.resolve(bundleArg)); + const dataDir = parsed.values['data-dir'] + ? path.resolve(parsed.values['data-dir']) + : process.env.GCOORD_DATA_DIR + ? path.resolve(process.env.GCOORD_DATA_DIR) + : undefined; + + const bundlePath = path.resolve(bundleArg); + const rawBuf = Buffer.from(readRegularFileStrict(bundlePath), 'utf8'); const passphrase = readOptionalPassphrase(parsed.values['passphrase-file']); - let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file']); + let masterKey = readOptionalKeyNonInteractive(parsed.values['key-file'], dataDir); 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)'); + throw new Error( + 'Passphrase required for scrypt-encrypted backup (--passphrase-file or GCOORD_BACKUP_PASSPHRASE)', + ); } - masterKey = await readCurrentKey(undefined); + masterKey = await readCurrentKey(undefined, dataDir); } - const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file']); + const vaultMasterKey = readOptionalKeyNonInteractive(parsed.values['vault-key-file'], dataDir); const summary = verifyBackupSummaryOnly(rawBuf, { masterKey, @@ -270,25 +757,28 @@ async function runRestore(args: string[]): Promise { 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, + return withDataDirLock(dataDir, async () => { + const rawBuf = Buffer.from(readRegularFileStrict(bundleArg), 'utf8'); + 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; }); - - console.log( - `Restored GCoordinator state to ${dataDir} (configs=${summary.configFileCount}, knownHosts=${summary.knownHostsCount}, silences=${summary.alertSilenceCount})`, - ); - return 0; } async function main(): Promise { @@ -298,22 +788,25 @@ async function main(): Promise { process.exit(0); } - if (command === 'rotate-key') { - process.exit(await runRotateKey(rest)); - } - 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)); + const handlers: Record Promise> = { + status: runStatus, + 'panic-lock': runPanicLock, + 'reset-2fa': runReset2fa, + 'reset-password': runResetPassword, + 'rotate-key': runRotateKey, + backup: runBackup, + 'verify-backup': runVerifyBackup, + restore: runRestore, + }; + + const handler = handlers[command]; + if (!handler) { + console.error(`Unknown command: ${command}`); + printUsage(); + process.exit(1); } - console.error(`Unknown command: ${command}`); - printUsage(); - process.exit(1); + process.exit(await handler(rest)); } main().catch((err) => { diff --git a/src/server/api/routes/audit.routes.ts b/src/server/api/routes/audit.routes.ts index 48b66a5..1194bcc 100644 --- a/src/server/api/routes/audit.routes.ts +++ b/src/server/api/routes/audit.routes.ts @@ -1,8 +1,33 @@ import { Router } from 'express'; -import type { AuditService } from '../../security/audit.js'; +import { z } from 'zod'; +import type { AuditListOptions, AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { requireAuth } from '../../security/guards.js'; +const AuditQuerySchema = z.object({ + limit: z.coerce.number().int().min(1).max(200).optional(), + offset: z.coerce.number().int().min(0).optional(), + action: z.string().trim().min(1).max(128).optional(), + actionPrefix: z.string().trim().min(1).max(64).optional(), + status: z.enum(['ok', 'denied', 'error']).optional(), + ip: z.string().trim().min(1).max(64).optional(), + target: z.string().trim().min(1).max(128).optional(), + q: z.string().trim().min(1).max(128).optional(), + from: z.coerce.number().int().min(0).optional(), + to: z.coerce.number().int().min(0).optional(), + format: z.enum(['csv', 'ndjson']).optional(), +}); + +function pickFilterOptions(raw: Record): AuditListOptions & { format?: 'csv' | 'ndjson' } { + const cleaned: Record = {}; + for (const [k, v] of Object.entries(raw)) { + if (typeof v === 'string' && v.trim() === '') continue; + cleaned[k] = v; + } + const parsed = AuditQuerySchema.safeParse(cleaned); + return parsed.success ? parsed.data : {}; +} + export function createAuditRouter( authService: AuthService, auditService: AuditService, @@ -10,20 +35,37 @@ export function createAuditRouter( const router = Router(); router.get('/', requireAuth(authService), (req, res) => { - const limit = req.query.limit ? Number(req.query.limit) : 50; - const offset = req.query.offset ? Number(req.query.offset) : 0; - const action = - typeof req.query.action === 'string' && req.query.action.trim() - ? req.query.action.trim() - : undefined; + const opts = pickFilterOptions(req.query as Record); + const result = auditService.list(opts); + res.json({ + ...result, + actions: auditService.listActions(), + }); + }); - res.json( - auditService.list({ - limit: Number.isFinite(limit) ? limit : 50, - offset: Number.isFinite(offset) ? offset : 0, - action, - }), + router.get('/export', requireAuth(authService), (req, res) => { + const opts = pickFilterOptions(req.query as Record); + const format = opts.format ?? 'ndjson'; + const content = auditService.exportRecords(opts, format); + + auditService.log({ + action: 'audit.export', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: format, + status: 'ok', + }); + + res.setHeader('Cache-Control', 'no-store'); + res.setHeader( + 'Content-Type', + format === 'csv' ? 'text/csv; charset=utf-8' : 'application/x-ndjson; charset=utf-8', ); + res.setHeader( + 'Content-Disposition', + `attachment; filename="gcoordinator-audit-export.${format === 'csv' ? 'csv' : 'ndjson'}"`, + ); + res.send(content); }); return router; diff --git a/src/server/api/routes/backup.routes.ts b/src/server/api/routes/backup.routes.ts index 70aff8a..a4ba2b1 100644 --- a/src/server/api/routes/backup.routes.ts +++ b/src/server/api/routes/backup.routes.ts @@ -1,17 +1,21 @@ import type Database from 'better-sqlite3'; -import { Router, type RequestHandler } from 'express'; +import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express'; import { z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; +import type { RuntimeLimits } from '../../config/runtime-limits.js'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; import { - createBackupBundle, - restoreBackupBundle, - verifyBackupSummaryOnly, + BackupBusyError, + createBackupBundleAsync, + restoreBackupBundleAsync, + verifyBackupSummaryOnlyAsync, type BackupInnerPayload, type BackupVerificationSummary, } from '../../security/backup.js'; +import type { BackupScheduler } from '../../security/backup-scheduler.js'; import { + asyncHandler, enforceSafeMode, requireAuth, requireCsrf, @@ -26,6 +30,8 @@ export interface BackupRouterDeps { configManager: ConfigManager; auditService: AuditService; stepUpGuard: RequestHandler; + getRuntimeLimits?: () => RuntimeLimits; + backupScheduler?: BackupScheduler; onRestored: (info: { summary: BackupVerificationSummary; inner: BackupInnerPayload; @@ -54,6 +60,8 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { configManager, auditService, stepUpGuard, + getRuntimeLimits, + backupScheduler, onRestored, } = deps; @@ -63,7 +71,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - (req, res) => { + asyncHandler(async (req, res) => { const parsed = ExportBackupBodySchema.safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); @@ -81,11 +89,13 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { } try { - const result = createBackupBundle({ + const limits = getRuntimeLimits?.(); + const result = await createBackupBundleAsync({ dataDir, db, masterKey, passphrase, + scryptConcurrency: limits?.scryptConcurrency, }); const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); const filename = `gcoordinator-backup-${stamp}.gcoord.enc`; @@ -109,38 +119,73 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { summary: result.summary, }); } catch (err) { + if (err instanceof BackupBusyError) throw 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; - } + // Read-only verification: exempt from enforceSafeMode, still requires step-up and writes audit entry + router.post( + '/verify', + requireAuth(authService), + requireCsrf, + stepUpGuard, + asyncHandler(async (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 limits = getRuntimeLimits?.(); + const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; 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', - }); - } - }); + if (rawBuf.length > maxBodyBytes) { + res.status(413).json({ + error: 'PAYLOAD_TOO_LARGE', + message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, + }); + return; + } + + try { + const summary = await verifyBackupSummaryOnlyAsync(rawBuf, { + masterKey: + parsed.data.masterKey?.trim() || vaultService.exportMasterKeyHex() || undefined, + passphrase: parsed.data.passphrase?.trim() || undefined, + vaultMasterKey: parsed.data.vaultMasterKey?.trim() || undefined, + scryptConcurrency: limits?.scryptConcurrency, + maxGunzipBytes: limits?.backupMaxGunzipBytes, + }); + auditService.log({ + action: 'backup.verify', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: summary.kdf, + status: 'ok', + details: { configFileCount: summary.configFileCount, vaultVerified: summary.vaultVerified }, + }); + res.json({ summary }); + } catch (err) { + if (err instanceof BackupBusyError) throw err; + auditService.log({ + action: 'backup.verify', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + status: 'error', + details: { message: err instanceof Error ? err.message : 'Verification failed' }, + }); + res.status(400).json({ + error: 'BACKUP_INVALID', + message: err instanceof Error ? err.message : 'Backup verification failed', + }); + } + }), + ); router.post( '/restore', @@ -148,14 +193,24 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { requireCsrf, enforceSafeMode, stepUpGuard, - async (req, res) => { + asyncHandler(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 limits = getRuntimeLimits?.(); + const maxBodyBytes = limits?.backupMaxBodyBytes ?? 16 * 1024 * 1024; const rawBuf = Buffer.from(parsed.data.bundleBase64, 'base64'); + if (rawBuf.length > maxBodyBytes) { + res.status(413).json({ + error: 'PAYLOAD_TOO_LARGE', + message: `Backup bundle exceeds limit (${maxBodyBytes} bytes)`, + }); + return; + } + const passphrase = parsed.data.passphrase?.trim() || undefined; const runtimeKey = vaultService.exportMasterKeyHex() ?? undefined; const masterKey = parsed.data.masterKey?.trim() || runtimeKey; @@ -163,12 +218,14 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { const wasWatching = await configManager.pauseWatcher(); try { - const restored = restoreBackupBundle(rawBuf, { + const restored = await restoreBackupBundleAsync(rawBuf, { dataDir, db, masterKey, passphrase, vaultMasterKey, + scryptConcurrency: limits?.scryptConcurrency, + maxGunzipBytes: limits?.backupMaxGunzipBytes, }); await onRestored({ @@ -192,6 +249,7 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { res.json({ restored: true, summary: restored.summary }); } catch (err) { + if (err instanceof BackupBusyError) throw err; auditService.log({ action: 'backup.restore', actorIp: req.clientIp ?? 'unknown', @@ -209,8 +267,44 @@ export function createBackupRouter(deps: BackupRouterDeps): Router { await configManager.resumeWatcher(); } } - }, + }), ); + router.get('/schedule', requireAuth(authService), (_req, res) => { + if (!backupScheduler) { + res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); + return; + } + res.json({ schedule: backupScheduler.getStatus() }); + }); + + router.post( + '/schedule/run', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + asyncHandler(async (_req, res) => { + if (!backupScheduler) { + res.status(404).json({ error: 'SCHEDULER_UNAVAILABLE' }); + return; + } + const outcome = await backupScheduler.runNow('manual'); + res.status(outcome.ok ? 200 : 400).json({ + ...outcome, + schedule: backupScheduler.getStatus(), + }); + }), + ); + + router.use((err: unknown, _req: Request, res: Response, next: NextFunction) => { + if (err instanceof BackupBusyError) { + res.setHeader('Retry-After', '2'); + res.status(503).json({ error: err.code, message: err.message }); + return; + } + next(err); + }); + return router; } diff --git a/src/server/app.ts b/src/server/app.ts index 2b889a8..2b2c901 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -17,6 +17,7 @@ import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; +import { BackupScheduler } from './security/backup-scheduler.js'; import { DEFAULT_TRUSTED_PROXY_CIDRS, RateLimiter, @@ -88,6 +89,7 @@ export interface GCoordinatorInstance { customSystemsEngine: CustomSystemsEngine; serverInspector: ServerInspector; monitoringService: MonitoringService; + backupScheduler: BackupScheduler; transferEngine: TransferEngine; workflowEngine: WorkflowEngine; broadcastService: BroadcastService; @@ -231,6 +233,15 @@ export async function createGCoordinatorServer( wsHub, auditService, ); + const backupScheduler = new BackupScheduler( + dataDir, + db, + configManager, + vaultService, + sftpService, + auditService, + getRuntimeLimits, + ); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); @@ -319,11 +330,16 @@ export async function createGCoordinatorServer( app.use('/proxy', createProxyRouter({ authService, tunnelManager })); const jsonParser = express.json({ limit: '2mb' }); + const backupJsonParser = express.json({ limit: '16mb' }); app.use((req, res, next) => { if (req.path.endsWith('/sftp/upload')) { next(); return; } + if (req.path.startsWith('/api/backup/')) { + backupJsonParser(req, res, next); + return; + } jsonParser(req, res, next); }); @@ -356,9 +372,12 @@ export async function createGCoordinatorServer( customSystemsEngine.syncBackgroundChecks(); workflowEngine.start(); alertEngine.start(); + backupScheduler.start(); + auditService.pruneOlderThan(configManager.getSettings().auditRetentionDays); vaultService.onSeal(() => { aiService.cancelAll(); + backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -372,6 +391,7 @@ export async function createGCoordinatorServer( vaultService.onPanicLock(() => { aiService.cancelAll(); + backupScheduler.stop(); alertEngine.handlePanicLock(); workflowEngine.handlePanicLock(); broadcastService.cancelAll(); @@ -421,6 +441,7 @@ export async function createGCoordinatorServer( monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); + backupScheduler.sync(); void tunnelManager.syncAutoStart(); } }); @@ -461,6 +482,7 @@ export async function createGCoordinatorServer( monitoringService.syncServers(); customSystemsEngine.syncBackgroundChecks(); workflowEngine.syncCronJobs(); + backupScheduler.sync(); void tunnelManager.syncAutoStart(); }, onVaultChanged: (snapshotReason) => { @@ -480,18 +502,27 @@ export async function createGCoordinatorServer( configManager, auditService, stepUpGuard, + getRuntimeLimits, + backupScheduler, 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 + // Avoid keeping an old runtime master key unlocked against a newly restored foreign vault + vaultService.seal(); + vaultService.dropLocalKeyFile(); } } knownHosts.replaceAllKnownHosts(inner.knownHosts); configManager.reloadAllFromDisk(); sshPool.syncWithConfig(); - if (authService.isBootstrapped() && vaultService.isRuntimeReady) { + backupScheduler.sync(); + if ( + authService.isBootstrapped() && + vaultService.isRuntimeReady && + configManager.getSettings().security.enableEmergencySecretsBackup + ) { authService.syncRecovery({ snapshotReason: 'backup-restore' }); } wsHub.broadcastAll({ @@ -620,6 +651,7 @@ export async function createGCoordinatorServer( customSystemsEngine, serverInspector, monitoringService, + backupScheduler, transferEngine, workflowEngine, broadcastService, @@ -629,6 +661,7 @@ export async function createGCoordinatorServer( port: actualPort, async close() { aiService.close(); + backupScheduler.close(); alertEngine.close(); workflowEngine.close(); broadcastService.cancelAll(); diff --git a/src/server/security/audit.ts b/src/server/security/audit.ts index e63d78d..c7146e5 100644 --- a/src/server/security/audit.ts +++ b/src/server/security/audit.ts @@ -20,6 +20,28 @@ export interface AuditLogRecord { details: string | null; } +export interface AuditListOptions { + limit?: number; + offset?: number; + action?: string; + actionPrefix?: string; + status?: 'ok' | 'denied' | 'error'; + ip?: string; + target?: string; + q?: string; + from?: number; + to?: number; +} + +function escapeLike(input: string): string { + return input.replace(/[\\%_]/g, '\\$&'); +} + +function sanitizeCsvCell(value: string): string { + const safe = /^[ \t]*[=+\-@\t\r]/.test(value) ? `'${value}` : value; + return `"${safe.replace(/"/g, '""')}"`; +} + export class AuditService { private readonly insertStmt; @@ -49,33 +71,143 @@ export class AuditService { ); } - list(options: { limit?: number; offset?: number; action?: string } = {}): { + private buildWhereClause(options: AuditListOptions): { sql: string; params: Array } { + const clauses: string[] = []; + const params: Array = []; + + if (options.action) { + clauses.push('action = ?'); + params.push(options.action); + } else if (options.actionPrefix) { + clauses.push("action LIKE ? ESCAPE '\\'"); + params.push(`${escapeLike(options.actionPrefix)}%`); + } + + if (options.status) { + clauses.push('status = ?'); + params.push(options.status); + } + + if (options.ip) { + clauses.push('actor_ip = ?'); + params.push(options.ip); + } + + if (options.target) { + clauses.push("target LIKE ? ESCAPE '\\'"); + params.push(`%${escapeLike(options.target)}%`); + } + + if (typeof options.from === 'number' && Number.isFinite(options.from)) { + clauses.push('ts >= ?'); + params.push(options.from); + } + if (typeof options.to === 'number' && Number.isFinite(options.to)) { + clauses.push('ts <= ?'); + params.push(options.to); + } + + if (options.q) { + const needle = `%${escapeLike(options.q)}%`; + clauses.push( + "(action LIKE ? ESCAPE '\\' OR actor_ip LIKE ? ESCAPE '\\' OR COALESCE(target, '') LIKE ? ESCAPE '\\' OR COALESCE(details, '') LIKE ? ESCAPE '\\')", + ); + params.push(needle, needle, needle, needle); + } + + return { + sql: clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '', + params, + }; + } + + list(options: AuditListOptions = {}): { total: number; items: AuditLogRecord[]; } { const limit = Math.max(1, Math.min(200, options.limit ?? 50)); const offset = Math.max(0, options.offset ?? 0); - - if (options.action) { - const countRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM audit_log WHERE action = ?') - .get(options.action) as { cnt: number }; - const items = this.db - .prepare( - 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log WHERE action = ? ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', - ) - .all(options.action, limit, offset) as AuditLogRecord[]; - return { total: countRow.cnt, items }; - } + const where = this.buildWhereClause(options); const countRow = this.db - .prepare('SELECT COUNT(*) AS cnt FROM audit_log') - .get() as { cnt: number }; + .prepare(`SELECT COUNT(*) AS cnt FROM audit_log ${where.sql}`) + .get(...where.params) as { cnt: number }; + const items = this.db .prepare( - 'SELECT id, ts, action, actor_ip, session_id_hash, target, status, details FROM audit_log ORDER BY ts DESC, id DESC LIMIT ? OFFSET ?', + `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details + FROM audit_log ${where.sql} + ORDER BY ts DESC, id DESC + LIMIT ? OFFSET ?`, ) - .all(limit, offset) as AuditLogRecord[]; + .all(...where.params, limit, offset) as AuditLogRecord[]; + return { total: countRow.cnt, items }; } + + listActions(): string[] { + const rows = this.db + .prepare('SELECT DISTINCT action FROM audit_log ORDER BY action ASC LIMIT 200') + .all() as Array<{ action: string }>; + return rows.map((r) => r.action); + } + + exportRecords( + options: AuditListOptions, + format: 'csv' | 'ndjson', + maxRows = 10_000, + ): string { + const cap = Math.max(1, Math.min(50_000, maxRows)); + const where = this.buildWhereClause(options); + const rows = this.db + .prepare( + `SELECT id, ts, action, actor_ip, session_id_hash, target, status, details + FROM audit_log ${where.sql} + ORDER BY ts DESC, id DESC + LIMIT ?`, + ) + .all(...where.params, cap) as AuditLogRecord[]; + + if (format === 'ndjson') { + return `${rows + .map((r) => + JSON.stringify({ + id: r.id, + ts: r.ts, + isoTime: new Date(r.ts).toISOString(), + action: r.action, + status: r.status, + actorIp: r.actor_ip, + target: r.target, + sessionIdHash: r.session_id_hash, + details: r.details, + }), + ) + .join('\n')}\n`; + } + + const lines = [ + 'id,ts,isoTime,action,status,actorIp,target,sessionIdHash,details', + ...rows.map((r) => + [ + String(r.id), + String(r.ts), + sanitizeCsvCell(new Date(r.ts).toISOString()), + sanitizeCsvCell(r.action), + sanitizeCsvCell(r.status), + sanitizeCsvCell(r.actor_ip), + sanitizeCsvCell(r.target ?? ''), + sanitizeCsvCell(r.session_id_hash ?? ''), + sanitizeCsvCell(r.details ?? ''), + ].join(','), + ), + ]; + return `${lines.join('\n')}\n`; + } + + pruneOlderThan(retentionDays: number): number { + const days = Math.max(1, retentionDays); + const cutoff = Date.now() - days * 24 * 60 * 60 * 1000; + return this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(cutoff).changes; + } } diff --git a/src/server/security/backup-scheduler.ts b/src/server/security/backup-scheduler.ts new file mode 100644 index 0000000..abd4409 --- /dev/null +++ b/src/server/security/backup-scheduler.ts @@ -0,0 +1,275 @@ +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { Readable } from 'node:stream'; +import type Database from 'better-sqlite3'; +import { Cron } from 'croner'; +import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; +import type { SftpService } from '../ssh/sftp-service.js'; +import type { AuditService } from './audit.js'; +import { createBackupBundleAsync } from './backup.js'; +import type { VaultService } from './vault.js'; + +export interface ScheduledBackupStatus { + enabled: boolean; + cron: string; + timezone: string; + destination: 'local' | 'sftp'; + running: boolean; + lastRunAt: number | null; + lastStatus: 'never' | 'ok' | 'error' | 'skipped'; + lastFilename: string | null; + lastError: string | null; + nextRunAt: number | null; + localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; +} + +function resolveSafeLocalBackupDir(dataDir: string, rawLocalDir: string): string { + const baseDir = path.resolve(dataDir); + const rel = rawLocalDir.trim() || 'backups'; + if (path.isAbsolute(rel) || rel.includes('..') || rel.includes('\\')) { + throw new Error(`Unsafe local backup directory: ${rawLocalDir}`); + } + const targetDir = path.resolve(baseDir, rel); + if (targetDir === baseDir || !targetDir.startsWith(`${baseDir}${path.sep}`)) { + throw new Error(`Local backup directory must stay inside dataDir: ${rawLocalDir}`); + } + return targetDir; +} + +export class BackupScheduler { + private job: Cron | null = null; + private running = false; + private closed = false; + private lastRunAt: number | null = null; + private lastStatus: ScheduledBackupStatus['lastStatus'] = 'never'; + private lastFilename: string | null = null; + private lastError: string | null = null; + + constructor( + private readonly dataDir: string, + private readonly db: Database.Database, + private readonly configManager: ConfigManager, + private readonly vaultService: VaultService, + private readonly sftpService: SftpService, + private readonly auditService: AuditService, + private readonly getRuntimeLimits: () => RuntimeLimits, + ) {} + + start(): void { + this.sync(); + } + + stop(): void { + if (this.job) { + this.job.stop(); + this.job = null; + } + } + + close(): void { + this.closed = true; + this.stop(); + } + + sync(): void { + this.stop(); + if (this.closed || !this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { + return; + } + const cfg = this.configManager.getSettings().scheduledBackup; + if (!cfg?.enabled) { + return; + } + try { + this.job = new Cron( + cfg.cron, + { + timezone: cfg.timezone || 'UTC', + protect: true, + }, + () => { + void this.runNow('cron'); + }, + ); + } catch (err) { + this.lastStatus = 'error'; + this.lastError = err instanceof Error ? err.message : 'Invalid backup cron expression'; + } + } + + getStatus(): ScheduledBackupStatus { + const cfg = this.configManager.getSettings().scheduledBackup; + let localFiles: ScheduledBackupStatus['localFiles'] = []; + try { + const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); + if (fs.existsSync(dir) && !fs.lstatSync(dir).isSymbolicLink()) { + localFiles = fs + .readdirSync(dir) + .filter((name) => name.endsWith('.gcoord.enc')) + .map((name) => { + const p = path.join(dir, name); + const st = fs.lstatSync(p); + return !st.isSymbolicLink() && st.isFile() + ? { name, sizeBytes: st.size, mtimeMs: st.mtimeMs } + : null; + }) + .filter((v): v is NonNullable => v !== null) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + } + } catch { + localFiles = []; + } + + const nextDate = this.job?.nextRun() ?? null; + return { + enabled: Boolean(cfg.enabled), + cron: cfg.cron, + timezone: cfg.timezone, + destination: cfg.destination, + running: this.running, + lastRunAt: this.lastRunAt, + lastStatus: this.lastStatus, + lastFilename: this.lastFilename, + lastError: this.lastError, + nextRunAt: nextDate ? nextDate.getTime() : null, + localFiles, + }; + } + + async runNow(trigger: 'cron' | 'manual' = 'manual'): Promise<{ + ok: boolean; + filename?: string; + message?: string; + }> { + if (this.closed) { + return { ok: false, message: 'Scheduler stopped' }; + } + if (this.running) { + return { ok: false, message: 'Scheduled backup already in progress' }; + } + if (!this.vaultService.isRuntimeReady || this.vaultService.isPanicLocked) { + this.lastRunAt = Date.now(); + this.lastStatus = 'skipped'; + this.lastError = 'Vault is sealed'; + return { ok: false, message: 'Vault is sealed' }; + } + + const cfg = this.configManager.getSettings().scheduledBackup; + this.running = true; + try { + let passphrase: string | undefined; + if (cfg.passphraseSecretRef) { + const cred = this.vaultService.getSecret(cfg.passphraseSecretRef); + if (!cred) { + throw new Error(`Backup passphrase secret "${cfg.passphraseSecretRef}" not found in Vault`); + } + passphrase = + cred.type === 'api-token' + ? cred.token + : cred.type === 'webhook-secret' + ? cred.secret + : undefined; + if (!passphrase) { + throw new Error( + `Credential "${cfg.passphraseSecretRef}" must be an api-token or webhook-secret`, + ); + } + } + + const masterKey = this.vaultService.exportMasterKeyHex() ?? undefined; + const limits = this.getRuntimeLimits(); + const result = await createBackupBundleAsync({ + dataDir: this.dataDir, + db: this.db, + masterKey, + passphrase, + scryptConcurrency: limits.scryptConcurrency, + }); + + const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19); + const filename = `gcoord-sched-${stamp}.gcoord.enc`; + + if (cfg.destination === 'sftp') { + if (!cfg.remoteServerId || !cfg.remotePath) { + throw new Error('SFTP scheduled backup requires remoteServerId and remotePath'); + } + const remoteDir = path.posix.normalize(cfg.remotePath).replace(/\/+$/, '') || '/'; + const remoteFile = path.posix.join(remoteDir, filename); + const buf = Buffer.from(result.serialized, 'utf8'); + await this.sftpService.uploadStream(cfg.remoteServerId, remoteFile, Readable.from([buf])); + try { + const listing = await this.sftpService.listDirectory(cfg.remoteServerId, remoteDir); + const oldFiles = listing.entries + .filter( + (e) => + e.type === 'file' && + e.name.startsWith('gcoord-sched-') && + e.name.endsWith('.gcoord.enc'), + ) + .sort((a, b) => b.mtimeMs - a.mtimeMs); + for (const stale of oldFiles.slice(cfg.retentionCount)) { + await this.sftpService.deletePath(cfg.remoteServerId, stale.path, false); + } + } catch { + // Best-effort remote retention pruning + } + } else { + const dir = resolveSafeLocalBackupDir(this.dataDir, cfg.localDir); + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + const outPath = path.join(dir, filename); + const tmpPath = `${outPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; + 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); + + const existing = fs + .readdirSync(dir) + .filter((n) => n.startsWith('gcoord-sched-') && n.endsWith('.gcoord.enc')) + .map((n) => ({ + path: path.join(dir, n), + mtime: fs.lstatSync(path.join(dir, n)).mtimeMs, + })) + .sort((a, b) => b.mtime - a.mtime); + for (const stale of existing.slice(cfg.retentionCount)) { + fs.rmSync(stale.path, { force: true }); + } + } + + this.lastRunAt = Date.now(); + this.lastStatus = 'ok'; + this.lastFilename = filename; + this.lastError = null; + this.auditService.log({ + action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', + actorIp: 'system', + target: filename, + status: 'ok', + details: { destination: cfg.destination, kdf: result.summary.kdf }, + }); + return { ok: true, filename }; + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + this.lastRunAt = Date.now(); + this.lastStatus = 'error'; + this.lastError = message; + this.auditService.log({ + action: trigger === 'cron' ? 'backup.scheduled' : 'backup.scheduled_run', + actorIp: 'system', + target: cfg.destination, + status: 'error', + details: { message }, + }); + return { ok: false, message }; + } finally { + this.running = false; + } + } +} diff --git a/src/server/security/backup.ts b/src/server/security/backup.ts index f6daf45..1967ff3 100644 --- a/src/server/security/backup.ts +++ b/src/server/security/backup.ts @@ -21,6 +21,13 @@ export const BackupEnvelopeSchema = z.object({ alg: z.literal('aes-256-gcm'), kdf: z.enum(['raw-master-key', 'scrypt']), salt: z.string().optional(), + kdfParams: z + .object({ + N: z.number().int().min(16384).max(65536), + r: z.number().int().min(4).max(16), + p: z.number().int().min(1).max(4), + }) + .optional(), iv: z.string().min(1), tag: z.string().min(1), ciphertext: z.string().min(1), @@ -76,9 +83,62 @@ export interface BackupVerificationSummary { overlayCount: number; } +export class BackupBusyError extends Error { + readonly code = 'BACKUP_KDF_BUSY'; + constructor(message = 'Backup encryption worker queue is busy; try again shortly') { + super(message); + this.name = 'BackupBusyError'; + } +} + const SLUG_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/; -const MAX_GUNZIP_BYTES = 32 * 1024 * 1024; +const DEFAULT_MAX_GUNZIP_BYTES = 32 * 1024 * 1024; const SCRYPT_PARAMS = { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 } as const; +const BACKUP_AAD = Buffer.from('gcoord-backup-v1', 'utf8'); +const MIN_BACKUP_PASSPHRASE_LEN = 12; +const MAX_SCRYPT_QUEUE = 8; + +let scryptActive = 0; +const scryptWaiters: Array<() => void> = []; + +async function runScryptAsync( + password: string, + salt: Buffer, + params: { N: number; r: number; p: number; maxmem: number }, + concurrency = 1, +): Promise { + const limit = Math.max(1, concurrency); + if (scryptActive >= limit) { + if (scryptWaiters.length >= MAX_SCRYPT_QUEUE) { + throw new BackupBusyError(); + } + await new Promise((resolve) => { + scryptWaiters.push(resolve); + }); + } + scryptActive += 1; + try { + return await new Promise((resolve, reject) => { + crypto.scrypt(password, salt, 32, params, (err, derived) => { + if (err) reject(err); + else resolve(derived); + }); + }); + } finally { + scryptActive -= 1; + const next = scryptWaiters.shift(); + if (next) next(); + } +} + +function isRegularNonSymlink(filePath: string): boolean { + try { + const stat = fs.lstatSync(filePath); + return !stat.isSymbolicLink() && stat.isFile(); + } catch { + return false; + } +} function validateAndParseConfigEntry( relPath: string, @@ -147,18 +207,23 @@ function collectConfigFilesFromDisk(configDir: string): Record { for (const name of ['settings.json', 'alerts.json', 'snippets.json']) { const abs = path.join(configDir, name); - if (fs.existsSync(abs)) { + if (isRegularNonSymlink(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; + try { + const dirStat = fs.lstatSync(dir); + if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue; + } catch { + 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()) { + if (isRegularNonSymlink(abs)) { out[rel] = fs.readFileSync(abs, 'utf8'); } } @@ -166,6 +231,17 @@ function collectConfigFilesFromDisk(configDir: string): Record { return out; } +function validateEncryptPassphrase(passphrase?: string): string | undefined { + const pass = passphrase?.trim(); + if (!pass || pass.length === 0) return undefined; + if (pass.length < MIN_BACKUP_PASSPHRASE_LEN) { + throw new Error( + `Backup passphrase must be at least ${MIN_BACKUP_PASSPHRASE_LEN} characters`, + ); + } + return pass; +} + function deriveEnvelopeKeyForEncrypt(opts: { masterKey?: string; passphrase?: string; @@ -173,12 +249,18 @@ function deriveEnvelopeKeyForEncrypt(opts: { key: Buffer; kdf: 'raw-master-key' | 'scrypt'; saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; } { - const pass = opts.passphrase?.trim(); - if (pass && pass.length > 0) { + const pass = validateEncryptPassphrase(opts.passphrase); + if (pass) { const salt = crypto.randomBytes(16); const key = crypto.scryptSync(pass, salt, 32, SCRYPT_PARAMS); - return { key, kdf: 'scrypt', saltB64: salt.toString('base64') }; + return { + key, + kdf: 'scrypt', + saltB64: salt.toString('base64'), + kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, + }; } if (!opts.masterKey || !opts.masterKey.trim()) { throw new Error('Either Vault master key or backup passphrase is required'); @@ -186,40 +268,92 @@ function deriveEnvelopeKeyForEncrypt(opts: { return { key: parseMasterKey(opts.masterKey), kdf: 'raw-master-key' }; } +async function deriveEnvelopeKeyForEncryptAsync(opts: { + masterKey?: string; + passphrase?: string; + scryptConcurrency?: number; +}): Promise<{ + key: Buffer; + kdf: 'raw-master-key' | 'scrypt'; + saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; +}> { + const pass = validateEncryptPassphrase(opts.passphrase); + if (pass) { + const salt = crypto.randomBytes(16); + const key = await runScryptAsync(pass, salt, SCRYPT_PARAMS, opts.scryptConcurrency); + return { + key, + kdf: 'scrypt', + saltB64: salt.toString('base64'), + kdfParams: { N: SCRYPT_PARAMS.N, r: SCRYPT_PARAMS.r, p: SCRYPT_PARAMS.p }, + }; + } + 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 getDecryptScryptInputs( + envelope: BackupEnvelope, + opts: { masterKey?: string; passphrase?: string }, +): { pass: string; salt: Buffer; params: { N: number; r: number; p: number; maxmem: number } } { + 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'); + } + const p = envelope.kdfParams; + const params = p + ? { N: p.N, r: p.r, p: p.p, maxmem: 128 * 1024 * 1024 } + : SCRYPT_PARAMS; + return { pass, salt, params }; +} + 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); + const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); + return crypto.scryptSync(pass, salt, 32, 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: { +async function deriveEnvelopeKeyForDecryptAsync( + envelope: BackupEnvelope, + opts: { masterKey?: string; passphrase?: string; scryptConcurrency?: number }, +): Promise { + if (envelope.kdf === 'scrypt') { + const { pass, salt, params } = getDecryptScryptInputs(envelope, opts); + return runScryptAsync(pass, salt, params, opts.scryptConcurrency); + } + if (!opts.masterKey || !opts.masterKey.trim()) { + throw new Error('This backup requires the 32-byte Vault master key to decrypt'); + } + return parseMasterKey(opts.masterKey); +} + +function prepareBackupInner(opts: { dataDir: string; db?: Database.Database; masterKey?: string; - passphrase?: string; }): { - serialized: string; - envelope: BackupEnvelope; - summary: BackupVerificationSummary; + inner: BackupInnerPayload; + vaultVerified: boolean; + vaultCredentialCount?: number; + overlayCount: number; } { const dataDir = path.resolve(opts.dataDir); const configDir = path.join(dataDir, 'config'); @@ -232,7 +366,7 @@ export function createBackupBundle(opts: { overlayCount += validateAndParseConfigEntry(relPath, rawJson).overlayCount; } - const vaultEnvelopeRaw = fs.existsSync(vaultPath) + const vaultEnvelopeRaw = isRegularNonSymlink(vaultPath) ? fs.readFileSync(vaultPath, 'utf8') : null; let vaultVerified = false; @@ -249,7 +383,7 @@ export function createBackupBundle(opts: { let localDb: Database.Database | null = null; const db = opts.db ?? - (fs.existsSync(dbPath) ? (localDb = openDatabase(dbPath)) : null); + (isRegularNonSymlink(dbPath) ? (localDb = openDatabase(dbPath)) : null); let knownHosts: Array> = []; let alertSilences: Array> = []; @@ -257,7 +391,7 @@ export function createBackupBundle(opts: { 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', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC', ) .all() as Array>; @@ -286,17 +420,29 @@ export function createBackupBundle(opts: { knownHosts, dbMeta: { alertSilences }, }; + return { inner, vaultVerified, vaultCredentialCount, overlayCount }; +} - const { key, kdf, saltB64 } = deriveEnvelopeKeyForEncrypt({ - masterKey: opts.masterKey, - passphrase: opts.passphrase, - }); - +function finalizeBackupEnvelope( + prepared: ReturnType, + keyInfo: { + key: Buffer; + kdf: 'raw-master-key' | 'scrypt'; + saltB64?: string; + kdfParams?: { N: number; r: number; p: number }; + }, +): { + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +} { + const { inner, vaultVerified, vaultCredentialCount, overlayCount } = prepared; 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 cipher = crypto.createCipheriv('aes-256-gcm', keyInfo.key, iv); + cipher.setAAD(BACKUP_AAD); const ciphertext = Buffer.concat([cipher.update(compressed), cipher.final()]); const tag = cipher.getAuthTag(); @@ -304,63 +450,115 @@ export function createBackupBundle(opts: { magic: 'GCOORD_BACKUP_V1', version: 1, alg: 'aes-256-gcm', - kdf, - ...(saltB64 ? { salt: saltB64 } : {}), + kdf: keyInfo.kdf, + ...(keyInfo.saltB64 ? { salt: keyInfo.saltB64 } : {}), + ...(keyInfo.kdfParams ? { kdfParams: keyInfo.kdfParams } : {}), iv: iv.toString('base64'), tag: tag.toString('base64'), ciphertext: ciphertext.toString('base64'), - createdAt, + createdAt: inner.createdAt, }; - const fileList = Object.keys(configFiles).sort(); + const fileList = Object.keys(inner.configFiles).sort(); return { serialized: `${JSON.stringify(envelope, null, 2)}\n`, envelope, summary: { valid: true, - createdAt, - kdf, + createdAt: inner.createdAt, + kdf: keyInfo.kdf, configFileCount: fileList.length, configFiles: fileList, - hasVault: vaultEnvelopeRaw !== null, + hasVault: inner.vaultEnvelopeRaw !== null, vaultVerified, vaultCredentialCount, - knownHostsCount: knownHosts.length, - alertSilenceCount: alertSilences.length, + knownHostsCount: inner.knownHosts.length, + alertSilenceCount: inner.dbMeta.alertSilences.length, overlayCount, }, }; } finally { - key.fill(0); + keyInfo.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)); +export function createBackupBundle(opts: { + dataDir: string; + db?: Database.Database; + masterKey?: string; + passphrase?: string; +}): { + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +} { + const keyInfo = deriveEnvelopeKeyForEncrypt({ + masterKey: opts.masterKey, + passphrase: opts.passphrase, + }); + try { + const prepared = prepareBackupInner(opts); + return finalizeBackupEnvelope(prepared, keyInfo); + } catch (err) { + keyInfo.key.fill(0); + throw err; + } +} +export async function createBackupBundleAsync(opts: { + dataDir: string; + db?: Database.Database; + masterKey?: string; + passphrase?: string; + scryptConcurrency?: number; +}): Promise<{ + serialized: string; + envelope: BackupEnvelope; + summary: BackupVerificationSummary; +}> { + const keyInfo = await deriveEnvelopeKeyForEncryptAsync(opts); + try { + const prepared = prepareBackupInner(opts); + return finalizeBackupEnvelope(prepared, keyInfo); + } catch (err) { + keyInfo.key.fill(0); + throw err; + } +} + +function decryptVerifiedInner( + envelope: BackupEnvelope, + key: Buffer, + keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, + maxGunzipBytes = DEFAULT_MAX_GUNZIP_BYTES, +): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { 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 }); + const decryptOnce = (useAad: boolean): Buffer => { + const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); + if (useAad) decipher.setAAD(BACKUP_AAD); + decipher.setAuthTag(tag); + return Buffer.concat([decipher.update(ciphertext), decipher.final()]); + }; + + try { + compressed = decryptOnce(true); + } catch (aadErr) { + if (envelope.kdfParams) { + throw aadErr; + } + compressed = decryptOnce(false); + } + + plaintext = zlib.gunzipSync(compressed, { maxOutputLength: maxGunzipBytes }); inner = BackupInnerPayloadSchema.parse(JSON.parse(plaintext.toString('utf8'))); } finally { key.fill(0); @@ -404,16 +602,75 @@ export function verifyBackupBundle( }; } +function parseBackupEnvelopeForVerify(rawTextOrBuf: string | Buffer): BackupEnvelope { + 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'); + if (iv.length !== 12 || tag.length !== 16) { + throw new Error('Invalid AES-256-GCM parameters inside backup envelope'); + } + return envelope; +} + +export function verifyBackupBundle( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + maxGunzipBytes?: number; + }, +): { summary: BackupVerificationSummary; inner: BackupInnerPayload } { + const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); + const key = deriveEnvelopeKeyForDecrypt(envelope, keyOpts); + return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); +} + +export async function verifyBackupBundleAsync( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + scryptConcurrency?: number; + maxGunzipBytes?: number; + }, +): Promise<{ summary: BackupVerificationSummary; inner: BackupInnerPayload }> { + const envelope = parseBackupEnvelopeForVerify(rawTextOrBuf); + const key = await deriveEnvelopeKeyForDecryptAsync(envelope, keyOpts); + return decryptVerifiedInner(envelope, key, keyOpts, keyOpts.maxGunzipBytes); +} + export function verifyBackupSummaryOnly( rawTextOrBuf: string | Buffer, - keyOpts: { masterKey?: string; passphrase?: string; vaultMasterKey?: string }, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + maxGunzipBytes?: number; + }, ): BackupVerificationSummary { return verifyBackupBundle(rawTextOrBuf, keyOpts).summary; } +export async function verifyBackupSummaryOnlyAsync( + rawTextOrBuf: string | Buffer, + keyOpts: { + masterKey?: string; + passphrase?: string; + vaultMasterKey?: string; + scryptConcurrency?: number; + maxGunzipBytes?: number; + }, +): Promise { + const res = await verifyBackupBundleAsync(rawTextOrBuf, keyOpts); + return res.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 tmpPath = `${targetPath}.tmp.${process.pid}.${crypto.randomBytes(6).toString('hex')}`; const fd = fs.openSync(tmpPath, 'w', 0o600); try { fs.writeFileSync(fd, content, 'utf8'); @@ -436,7 +693,7 @@ function writeAtomicPrivateFile(targetPath: string, content: string): void { function swapConfigDirectoryAtomic(configDir: string, configFiles: Record): void { const parent = path.dirname(configDir); - const rand = crypto.randomBytes(5).toString('hex'); + const rand = crypto.randomBytes(6).toString('hex'); const stageDir = path.join(parent, `config.restore-${rand}`); const bakDir = path.join(parent, `config.bak-${rand}`); @@ -474,22 +731,10 @@ function swapConfigDirectoryAtomic(configDir: string, configFiles: Record { + const verified = await verifyBackupBundleAsync(rawTextOrBuf, { + masterKey: opts.masterKey, + passphrase: opts.passphrase, + vaultMasterKey: opts.vaultMasterKey, + scryptConcurrency: opts.scryptConcurrency, + maxGunzipBytes: opts.maxGunzipBytes, + }); + return applyVerifiedRestoreToDisk(verified, opts); +} diff --git a/src/server/security/vault.ts b/src/server/security/vault.ts index 5207c67..5bbc402 100644 --- a/src/server/security/vault.ts +++ b/src/server/security/vault.ts @@ -471,6 +471,18 @@ export class VaultService { } } + dropLocalKeyFile(): void { + if (!this.keyFilePath) return; + try { + const stat = fs.lstatSync(this.keyFilePath); + if (stat.isFile() || stat.isSymbolicLink()) { + fs.unlinkSync(this.keyFilePath); + } + } catch { + // Ignore missing or unreadable key file + } + } + unlockForModifications(): void { if (this.masterKey === null || this.isPanicLocked) { throw new Error('Master key is required to unseal vault'); From 716627afdd5a7db8c7d86a947c16ba7e15295b89 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:40:40 +0000 Subject: [PATCH 06/19] security(ssh,sudo,keys): fix Sudo stdin leak, SSHPool Panic Lock/ProxyJump races, multi-algo known_hosts & OpenSSH import --- src/server/api/routes/servers.routes.ts | 391 +++++++++++++++++------- src/server/ssh/key-manager.ts | 42 ++- src/server/ssh/known-hosts.ts | 72 +++-- src/server/ssh/ssh-config-import.ts | 149 +++++++++ src/server/ssh/ssh-pool.ts | 391 ++++++++++++++++++++++-- src/server/ssh/sudo.ts | 28 +- tests/helpers/mock-ssh-server.ts | 22 +- 7 files changed, 944 insertions(+), 151 deletions(-) create mode 100644 src/server/ssh/ssh-config-import.ts diff --git a/src/server/api/routes/servers.routes.ts b/src/server/api/routes/servers.routes.ts index f6e3d1d..d91ba04 100644 --- a/src/server/api/routes/servers.routes.ts +++ b/src/server/api/routes/servers.routes.ts @@ -19,6 +19,7 @@ import { import type { VaultService } from '../../security/vault.js'; import type { KeyManager } from '../../ssh/key-manager.js'; import type { KnownHostsService } from '../../ssh/known-hosts.js'; +import { parseOpenSshConfig } from '../../ssh/ssh-config-import.js'; import type { SSHPool } from '../../ssh/ssh-pool.js'; export interface ServersRouterDeps { @@ -78,22 +79,173 @@ export function createServersRouter(deps: ServersRouterDeps): Router { stepUpGuard, (req, res) => { const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : ''; + const algorithm = + typeof req.query.algorithm === 'string' && req.query.algorithm.trim() + ? req.query.algorithm.trim() + : undefined; if (!hostPort) { res.status(400).json({ error: 'MISSING_HOST_PORT' }); return; } - const deleted = knownHosts.deleteKnownHost(hostPort); + const deleted = knownHosts.deleteKnownHost(hostPort, algorithm); auditService.log({ action: 'ssh.known_host_delete', actorIp: req.clientIp ?? 'unknown', sessionIdHash: req.authSession!.idHash, - target: hostPort, + target: algorithm ? `${hostPort} (${algorithm})` : hostPort, status: deleted ? 'ok' : 'error', }); res.json({ deleted }); }, ); + const hasJumpCycle = ( + serverId: string, + jumpHostId: string | undefined, + extraMap?: Map, + ): boolean => { + const visited = new Set([serverId]); + let cur = jumpHostId; + while (cur) { + if (visited.has(cur)) return true; + visited.add(cur); + if (extraMap && extraMap.has(cur)) { + cur = extraMap.get(cur); + } else { + cur = configManager.getServer(cur)?.jumpHostId; + } + } + return false; + }; + + router.post( + '/test-connection', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + async (req, res) => { + const parsed = ServerConfigSchema.safeParse({ + ...(typeof req.body === 'object' && req.body !== null ? req.body : {}), + id: + typeof (req.body as { id?: unknown } | undefined)?.id === 'string' && + (req.body as { id: string }).id.trim() + ? (req.body as { id: string }).id.trim() + : 'test-probe-tmp', + name: + typeof (req.body as { name?: unknown } | undefined)?.name === 'string' && + (req.body as { name: string }).name.trim() + ? (req.body as { name: string }).name.trim() + : 'Test Connection', + }); + if (!parsed.success) { + res.status(400).json({ + error: 'VALIDATION_ERROR', + issues: parsed.error.issues, + }); + return; + } + if (hasJumpCycle(parsed.data.id, parsed.data.jumpHostId)) { + res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); + return; + } + const result = await sshPool.testConnection(parsed.data); + res.json(result); + }, + ); + + router.post( + '/import-ssh-config', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const parsed = z + .object({ + configText: z.string().min(1).max(256_000), + defaultCredentialId: EntityIdSchema.optional(), + apply: z.boolean().default(false), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + + const preview = parseOpenSshConfig(parsed.data.configText); + if (!parsed.data.apply) { + res.json({ ...preview, createdIds: [] }); + return; + } + + if (!parsed.data.defaultCredentialId) { + res.status(400).json({ + error: 'MISSING_CREDENTIAL_ID', + message: 'Select a default SSH credential before importing hosts', + }); + return; + } + + const aliasToId = new Map(); + const existingServers = configManager.listServers(); + const takenIds = new Set(existingServers.map((s) => s.id)); + for (const s of existingServers) { + aliasToId.set(s.name, s.id); + aliasToId.set(s.id, s.id); + } + + const resolvedIds = new Map(); + for (const entry of preview.entries) { + let finalId = entry.id; + if (takenIds.has(finalId)) { + let n = 2; + while (takenIds.has(`${finalId.slice(0, 58)}-${n}`)) n++; + finalId = `${finalId.slice(0, 58)}-${n}`; + } + takenIds.add(finalId); + resolvedIds.set(entry.alias, finalId); + aliasToId.set(entry.alias, finalId); + } + + const createdIds: string[] = []; + for (const entry of preview.entries) { + const finalId = resolvedIds.get(entry.alias)!; + const jumpId = entry.jumpHostAlias + ? aliasToId.get(entry.jumpHostAlias) + : undefined; + const serverCfg = ServerConfigSchema.parse({ + id: finalId, + name: entry.name, + host: entry.host, + port: entry.port, + username: entry.username, + credentialId: parsed.data.defaultCredentialId, + ...(jumpId && jumpId !== finalId ? { jumpHostId: jumpId } : {}), + }); + configManager.saveConfigText( + `servers/${serverCfg.id}.json`, + JSON.stringify(serverCfg, null, 2), + 'ui', + `Imported from OpenSSH config (${entry.alias})`, + ); + createdIds.push(serverCfg.id); + } + + if (createdIds.length > 0) { + monitoringService.syncServers(); + auditService.log({ + action: 'server.import_ssh_config', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: createdIds.join(','), + status: 'ok', + }); + } + + res.status(201).json({ ...preview, createdIds }); + }, + ); + router.post( '/rotate-keys', requireAuth(authService), @@ -148,113 +300,142 @@ export function createServersRouter(deps: ServersRouterDeps): Router { }, ); - router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - try { - const parsed = ServerConfigSchema.parse(req.body); - const saved = configManager.saveConfigText( - `servers/${parsed.id}.json`, - JSON.stringify(parsed, null, 2), - 'ui', - 'Registered server via UI', - ); - monitoringService.syncServers(); - auditService.log({ - action: 'server.create', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: parsed.id, - status: 'ok', - }); - res.status(201).json({ - server: saved.config, - warnings: saved.warnings, - }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid server configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), + router.post( + '/', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + try { + const parsed = ServerConfigSchema.parse(req.body); + if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { + res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); + return; + } + const saved = configManager.saveConfigText( + `servers/${parsed.id}.json`, + JSON.stringify(parsed, null, 2), + 'ui', + 'Registered server via UI', + ); + monitoringService.syncServers(); + auditService.log({ + action: 'server.create', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: parsed.id, + status: 'ok', }); - return; - } - res.status(400).json({ - error: 'SERVER_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save server', - }); - } - }); - - router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - try { - const parsed = ServerConfigSchema.parse({ - ...(req.body ?? {}), - id: req.params.id, - }); - const saved = configManager.saveConfigText( - `servers/${parsed.id}.json`, - JSON.stringify(parsed, null, 2), - 'ui', - 'Updated server via UI', - ); - sshPool.closeServer(parsed.id); - monitoringService.syncServers(); - auditService.log({ - action: 'server.update', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: parsed.id, - status: 'ok', - }); - res.json({ server: saved.config, warnings: saved.warnings }); - } catch (err) { - if (err instanceof ZodError) { - res.status(400).json({ - error: 'VALIDATION_ERROR', - message: 'Invalid server configuration', - issues: err.issues.map((i) => ({ - path: i.path.join('.') || '(root)', - message: i.message, - })), + res.status(201).json({ + server: saved.config, + warnings: saved.warnings, + }); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'VALIDATION_ERROR', + message: 'Invalid server configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'SERVER_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to save server', }); - return; } - res.status(400).json({ - error: 'SERVER_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to update server', - }); - } - }); + }, + ); - router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => { - const id = String(req.params.id ?? ''); - try { - const deleted = configManager.deleteEntityFile(`servers/${id}.json`); - if (!deleted) { - res.status(404).json({ error: 'SERVER_NOT_FOUND' }); - return; + router.put( + '/:id', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + try { + const parsed = ServerConfigSchema.parse({ + ...(req.body ?? {}), + id: req.params.id, + }); + if (hasJumpCycle(parsed.id, parsed.jumpHostId)) { + res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' }); + return; + } + const saved = configManager.saveConfigText( + `servers/${parsed.id}.json`, + JSON.stringify(parsed, null, 2), + 'ui', + 'Updated server via UI', + ); + sshPool.closeServer(parsed.id); + monitoringService.syncServers(); + auditService.log({ + action: 'server.update', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: parsed.id, + status: 'ok', + }); + res.json({ server: saved.config, warnings: saved.warnings }); + } catch (err) { + if (err instanceof ZodError) { + res.status(400).json({ + error: 'VALIDATION_ERROR', + message: 'Invalid server configuration', + issues: err.issues.map((i) => ({ + path: i.path.join('.') || '(root)', + message: i.message, + })), + }); + return; + } + res.status(400).json({ + error: 'SERVER_SAVE_ERROR', + message: err instanceof Error ? err.message : 'Unable to update server', + }); } - sshPool.closeServer(id); - knownHosts.clearServerPending(id); - monitoringService.syncServers(); - auditService.log({ - action: 'server.delete', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: id, - status: 'ok', - }); - res.json({ deleted: true }); - } catch (err) { - res.status(400).json({ - error: 'SERVER_DELETE_ERROR', - message: err instanceof Error ? err.message : 'Unable to delete server', - }); - } - }); + }, + ); + + router.delete( + '/:id', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const id = String(req.params.id ?? ''); + try { + const deleted = configManager.deleteEntityFile(`servers/${id}.json`); + if (!deleted) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + sshPool.closeServer(id); + knownHosts.clearServerPending(id); + monitoringService.syncServers(); + auditService.log({ + action: 'server.delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: id, + status: 'ok', + }); + res.json({ deleted: true }); + } catch (err) { + res.status(400).json({ + error: 'SERVER_DELETE_ERROR', + message: err instanceof Error ? err.message : 'Unable to delete server', + }); + } + }, + ); router.post( '/:id/reconnect', @@ -286,6 +467,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, + stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body); @@ -405,6 +587,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, + stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body); diff --git a/src/server/ssh/key-manager.ts b/src/server/ssh/key-manager.ts index aad4eca..9380355 100644 --- a/src/server/ssh/key-manager.ts +++ b/src/server/ssh/key-manager.ts @@ -7,13 +7,22 @@ import type { SSHPool } from './ssh-pool.js'; const OPENSSH_KEY_TYPES = new Set([ 'ssh-ed25519', + 'ssh-ed25519-cert-v01@openssh.com', 'ssh-rsa', + 'ssh-rsa-cert-v01@openssh.com', + 'rsa-sha2-256', + 'rsa-sha2-512', 'ssh-dss', 'ecdsa-sha2-nistp256', + 'ecdsa-sha2-nistp256-cert-v01@openssh.com', 'ecdsa-sha2-nistp384', + 'ecdsa-sha2-nistp384-cert-v01@openssh.com', 'ecdsa-sha2-nistp521', + 'ecdsa-sha2-nistp521-cert-v01@openssh.com', 'sk-ssh-ed25519@openssh.com', + 'sk-ssh-ed25519-cert-v01@openssh.com', 'sk-ecdsa-sha2-nistp256@openssh.com', + 'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com', ]); export interface AuthorizedKeyEntry { @@ -135,6 +144,8 @@ function makeRotatedCredentialId(serverId: string): string { } export class KeyManager { + private readonly activeRotations = new Set(); + constructor( private readonly sshPool: SSHPool, private readonly vaultService: VaultService, @@ -277,6 +288,32 @@ export class KeyManager { passphrase: string | undefined, actorIp: string, sessionIdHash: string | null, + ): Promise { + if (this.activeRotations.has(serverId)) { + return { + serverId, + ok: false, + error: `Key rotation already in progress for "${serverId}"`, + }; + } + this.activeRotations.add(serverId); + try { + return await this.rotateSingleServerLocked( + serverId, + passphrase, + actorIp, + sessionIdHash, + ); + } finally { + this.activeRotations.delete(serverId); + } + } + + private async rotateSingleServerLocked( + serverId: string, + passphrase: string | undefined, + actorIp: string, + sessionIdHash: string | null, ): Promise { const server = this.configManager.getServer(serverId); if (!server) { @@ -324,7 +361,7 @@ export class KeyManager { newSecret.passphrase, ); - // Step 4: Verified! Persist updated credentialId in server JSON + // Step 4: Verified! Persist updated credentialId without tearing down live PTY/tunnel sessions const updatedServer = { ...server, credentialId: newCredId }; this.configManager.saveConfigText( `servers/${server.id}.json`, @@ -333,9 +370,6 @@ export class KeyManager { `Atomic SSH key rotation -> ${newCredId}`, ); - // Reconnect pool onto the new key - await this.sshPool.reconnect(server.id); - // Cleanly remove old public key from authorized_keys if it differs if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) { const afterInspect = await this.inspectAuthorizedKeys(server.id); diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index 68b66a7..ab04201 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -12,11 +12,16 @@ export interface KnownHostRecord { updatedAt: number; } +export function normalizeHostForKey(rawHost: string): string { + const clean = rawHost.trim().toLowerCase().replace(/^\[|\]$/g, ''); + return clean.includes(':') ? `[${clean}]` : clean; +} + export function buildHostPortKey(server: Pick): string { - const hostLower = server.host.trim().toLowerCase(); + const hostNormalized = normalizeHostForKey(server.host); return server.jumpHostId - ? `${server.jumpHostId}->${hostLower}:${server.port}` - : `${hostLower}:${server.port}`; + ? `${server.jumpHostId}->${hostNormalized}:${server.port}` + : `${hostNormalized}:${server.port}`; } export function parseHostKeyBuffer(keyBuf: Buffer): { @@ -45,12 +50,30 @@ export class KnownHostsService { private readonly pendingTofu = new Map(); private readonly pendingMismatches = new Map(); private readonly listeners = new Set<() => void>(); + private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>(); constructor( private readonly db: Database.Database, private readonly auditService?: AuditService, ) {} + onHostKeyMismatch(listener: (alert: HostKeyAlert) => void): () => void { + this.mismatchListeners.add(listener); + return () => { + this.mismatchListeners.delete(listener); + }; + } + + private emitMismatch(alert: HostKeyAlert): void { + for (const cb of this.mismatchListeners) { + try { + cb(alert); + } catch { + // Isolate subscriber failures + } + } + } + onChange(listener: () => void): () => void { this.listeners.add(listener); return () => { @@ -63,19 +86,19 @@ export class KnownHostsService { const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf); const now = Date.now(); - const row = this.db + const exactRow = this.db .prepare( - 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ? AND algorithm = ?', ) - .get(hostPortKey) as KnownHostRecord | undefined; + .get(hostPortKey, algorithm) as KnownHostRecord | undefined; - if (row) { - if (row.fingerprint === fingerprint) { + if (exactRow) { + if (exactRow.fingerprint === fingerprint) { const hadPending = this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); this.db - .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?') - .run(now, hostPortKey); + .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?') + .run(now, hostPortKey, algorithm); if (hadPending) this.emitChange(); return true; } @@ -86,7 +109,7 @@ export class KnownHostsService { host: server.host, port: server.port, algorithm, - expectedFingerprint: row.fingerprint, + expectedFingerprint: exactRow.fingerprint, actualFingerprint: fingerprint, detectedAt: now, }; @@ -99,10 +122,12 @@ export class KnownHostsService { status: 'denied', details: { hostPortKey, - expected: row.fingerprint, + algorithm, + expected: exactRow.fingerprint, actual: fingerprint, }, }); + this.emitMismatch(alert); this.emitChange(); return false; } @@ -141,8 +166,9 @@ export class KnownHostsService { actorIp: 'hub', target: server.id, status: 'denied', - details: { hostPortKey, expected, actual: fingerprint }, + details: { hostPortKey, algorithm, expected, actual: fingerprint }, }); + this.emitMismatch(alert); this.emitChange(); return false; } @@ -238,7 +264,7 @@ export class KnownHostsService { listKnownHosts(): KnownHostRecord[] { return this.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', + 'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC', ) .all() as KnownHostRecord[]; } @@ -272,15 +298,21 @@ export class KnownHostsService { this.emitChange(); } - deleteKnownHost(hostPort: string): boolean { - const res = this.db - .prepare('DELETE FROM known_hosts WHERE host_port = ?') - .run(hostPort); + deleteKnownHost(hostPort: string, algorithm?: string): boolean { + const res = algorithm + ? this.db + .prepare('DELETE FROM known_hosts WHERE host_port = ? AND algorithm = ?') + .run(hostPort, algorithm) + : this.db.prepare('DELETE FROM known_hosts WHERE host_port = ?').run(hostPort); for (const [sid, p] of this.pendingTofu.entries()) { - if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid); + if (p.hostPortKey === hostPort && (!algorithm || p.algorithm === algorithm)) { + this.pendingTofu.delete(sid); + } } for (const [sid, m] of this.pendingMismatches.entries()) { - if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid); + if (m.hostPortKey === hostPort && (!algorithm || m.algorithm === algorithm)) { + this.pendingMismatches.delete(sid); + } } if (res.changes > 0) this.emitChange(); return res.changes > 0; diff --git a/src/server/ssh/ssh-config-import.ts b/src/server/ssh/ssh-config-import.ts new file mode 100644 index 0000000..cb300ff --- /dev/null +++ b/src/server/ssh/ssh-config-import.ts @@ -0,0 +1,149 @@ +export interface ParsedOpenSshHost { + alias: string; + id: string; + name: string; + host: string; + port: number; + username: string; + jumpHostAlias?: string; +} + +export interface OpenSshImportPreview { + entries: ParsedOpenSshHost[]; + warnings: string[]; +} + +function slugifyHostId(alias: string): string { + const clean = alias + .toLowerCase() + .replace(/[^a-z0-9._-]+/g, '-') + .replace(/^[^a-z0-9]+|[-_.]+$/g, '') + .slice(0, 64); + return clean || 'srv'; +} + +function stripComment(line: string): string { + let inQuotes = false; + for (let i = 0; i < line.length; i++) { + const ch = line[i]!; + if (ch === '"') inQuotes = !inQuotes; + else if (ch === '#' && !inQuotes) return line.slice(0, i); + } + return line; +} + +function unquoteVal(val: string): string { + const t = val.trim(); + if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) { + return t.slice(1, -1); + } + return t; +} + +export function parseOpenSshConfig(text: string): OpenSshImportPreview { + const warnings: string[] = []; + const rawLines = text.split(/\r?\n/); + + interface DraftBlock { + patterns: string[]; + hostName?: string; + port?: number; + user?: string; + proxyJump?: string; + } + + const blocks: DraftBlock[] = []; + let current: DraftBlock | null = null; + + for (let i = 0; i < rawLines.length; i++) { + const cleaned = stripComment(rawLines[i]!).trim(); + if (!cleaned) continue; + + const eqOrSpace = /^([A-Za-z][A-Za-z0-9]*)\s*(?:=|\s+)\s*(.+)$/.exec(cleaned); + if (!eqOrSpace) { + warnings.push(`Line ${i + 1}: ignored unparseable directive`); + continue; + } + + const key = eqOrSpace[1]!.toLowerCase(); + const rawVal = unquoteVal(eqOrSpace[2]!); + + if (key === 'match') { + current = null; + warnings.push(`Line ${i + 1}: skipped unsupported Match block`); + continue; + } + + if (key === 'host') { + const patterns = rawVal.split(/\s+/).filter(Boolean); + current = { patterns }; + blocks.push(current); + continue; + } + + if (!current) continue; + + if (key === 'hostname') { + current.hostName = rawVal; + } else if (key === 'port') { + const p = Number.parseInt(rawVal, 10); + if (Number.isInteger(p) && p >= 1 && p <= 65535) { + current.port = p; + } else { + warnings.push(`Line ${i + 1}: invalid Port "${rawVal}"`); + } + } else if (key === 'user') { + current.user = rawVal; + } else if (key === 'proxyjump') { + const firstHop = rawVal.split(',')[0]?.trim(); + if (firstHop && firstHop.toLowerCase() !== 'none') { + const atIdx = firstHop.lastIndexOf('@'); + const hopHost = atIdx >= 0 ? firstHop.slice(atIdx + 1) : firstHop; + const colonIdx = hopHost.lastIndexOf(':'); + current.proxyJump = colonIdx > 0 && !hopHost.includes(']') ? hopHost.slice(0, colonIdx) : hopHost; + } + } + } + + const entries: ParsedOpenSshHost[] = []; + const usedIds = new Set(); + + for (const blk of blocks) { + for (const alias of blk.patterns) { + if (alias.includes('*') || alias.includes('?') || alias.startsWith('!')) { + warnings.push(`Skipped wildcard/negated Host pattern "${alias}"`); + continue; + } + const host = (blk.hostName ?? alias).trim(); + if (!host || /\s/.test(host)) { + warnings.push(`Skipped Host "${alias}": invalid host name`); + continue; + } + const username = (blk.user ?? 'root').trim(); + if (!username || /\s/.test(username)) { + warnings.push(`Skipped Host "${alias}": invalid username`); + continue; + } + + let id = slugifyHostId(alias); + if (usedIds.has(id)) { + let n = 2; + while (usedIds.has(`${id.slice(0, 58)}-${n}`)) n++; + id = `${id.slice(0, 58)}-${n}`; + } + usedIds.add(id); + + entries.push({ + alias, + id, + name: alias, + host, + port: blk.port ?? 22, + username, + ...(blk.proxyJump ? { jumpHostAlias: blk.proxyJump } : {}), + }); + } + } + + return { entries, warnings }; +} diff --git a/src/server/ssh/ssh-pool.ts b/src/server/ssh/ssh-pool.ts index 58e4969..3dab1e5 100644 --- a/src/server/ssh/ssh-pool.ts +++ b/src/server/ssh/ssh-pool.ts @@ -7,13 +7,29 @@ import ssh2, { } from 'ssh2'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { + HostKeyAlert, ServerConnectionStatus, ServerRuntimeState, } from '../../shared/ws-protocol.js'; import type { ConfigManager } from '../config/config-manager.js'; import type { VaultService } from '../security/vault.js'; import type { KnownHostsService } from './known-hosts.js'; -import { buildEnvPrefix, prepareSudoExecution } from './sudo.js'; +import { + buildEnvPrefix, + posixSingleQuote, + prepareSudoExecution, + SUDO_PTY_PROMPT, +} from './sudo.js'; + +export interface ServerTestResult { + ok: boolean; + latencyMs: number; + osDetected?: 'linux' | 'bsd' | 'macos'; + hostFingerprint?: string; + tofuRequired?: boolean; + hostKeyMismatch?: HostKeyAlert; + error?: string; +} export interface ExecResult { stdout: string; @@ -58,6 +74,9 @@ const DEFAULT_MAX_BYTES = 2 * 1024 * 1024; export class SSHPool { private readonly connections = new Map(); private readonly inFlight = new Map>(); + private readonly pendingClients = new Map>(); + private readonly serverEpoch = new Map(); + private poolEpoch = 0; private readonly states = new Map(); private readonly reconnectTimers = new Map(); private readonly reconnectAttempts = new Map(); @@ -74,6 +93,24 @@ export class SSHPool { }); } + private getServerEpoch(serverId: string): number { + return this.serverEpoch.get(serverId) ?? 0; + } + + private validateJumpChain(serverId: string): void { + const chain = new Set(); + let currentId: string | undefined = serverId; + while (currentId) { + if (chain.has(currentId)) { + throw new Error(`ProxyJump cycle detected involving "${currentId}"`); + } + chain.add(currentId); + const srv = this.configManager.getServer(currentId); + if (!srv) break; + currentId = srv.jumpHostId; + } + } + onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void { this.stateListeners.add(listener); return () => { @@ -132,6 +169,7 @@ export class SSHPool { if (visited.has(serverId)) { throw new Error(`ProxyJump cycle detected involving "${serverId}"`); } + this.validateJumpChain(serverId); const existing = this.connections.get(serverId); if (existing) { @@ -145,19 +183,42 @@ export class SSHPool { const nextVisited = new Set(visited); nextVisited.add(serverId); + const startPoolEpoch = this.poolEpoch; + const startSrvEpoch = this.getServerEpoch(serverId); - const connectPromise = this.connectServer(server, nextVisited).finally(() => { - this.inFlight.delete(serverId); + const connectPromise = this.connectServer( + server, + nextVisited, + startPoolEpoch, + startSrvEpoch, + ).finally(() => { + if (this.inFlight.get(serverId) === connectPromise) { + this.inFlight.delete(serverId); + } }); this.inFlight.set(serverId, connectPromise); return connectPromise; } + private getSudoPassword(server: ServerConfig): string | undefined { + if (!server.sudoCredentialId) return undefined; + const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId); + if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { + return sudoCred.password; + } + return undefined; + } + private prepareCommand( server: ServerConfig, command: string, - opts: { sudo?: boolean; env?: Record; stdin?: Buffer | string }, - ): { finalCommand: string; stdinBuf?: Buffer } { + opts: { + sudo?: boolean; + env?: Record; + stdin?: Buffer | string; + ptyPrompt?: boolean; + }, + ): { finalCommand: string; stdinBuf?: Buffer; ptyPassword?: string } { const envPrefix = buildEnvPrefix(opts.env); let finalCommand = `${envPrefix}${command}`; let stdinBuf: Buffer | undefined = @@ -168,20 +229,16 @@ export class SSHPool { : Buffer.from(opts.stdin); if (opts.sudo) { - let sudoPassword: string | undefined; - if (server.sudoCredentialId) { - const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId); - if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) { - sudoPassword = sudoCred.password; - } - } + const sudoPassword = this.getSudoPassword(server); const prepared = prepareSudoExecution(finalCommand, { sudoPassword, stdin: stdinBuf, + ptyPrompt: opts.ptyPrompt, }); if (stdinBuf) stdinBuf.fill(0); finalCommand = prepared.command; stdinBuf = prepared.stdin; + return { finalCommand, stdinBuf, ptyPassword: prepared.ptyPassword }; } return { finalCommand, stdinBuf }; @@ -228,7 +285,10 @@ export class SSHPool { throw new Error(`Unknown server "${serverId}"`); } - const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); + const { finalCommand, stdinBuf, ptyPassword } = this.prepareCommand(server, command, { + ...opts, + ptyPrompt: Boolean(opts.pty), + }); return new Promise((resolve, reject) => { const execOpts = opts.pty @@ -248,6 +308,21 @@ export class SSHPool { return; } + let sudoSent = false; + let promptProbeBuf = ''; + const maybeSendPtyPassword = (chunk: Buffer) => { + if (!ptyPassword || sudoSent) return; + promptProbeBuf = (promptProbeBuf + chunk.toString('utf8')).slice(-256); + if (promptProbeBuf.includes(SUDO_PTY_PROMPT)) { + sudoSent = true; + channel.stdin.write(`${ptyPassword}\n`); + } + }; + if (ptyPassword) { + channel.on('data', maybeSendPtyPassword); + channel.stderr?.on('data', maybeSendPtyPassword); + } + let exitCode: number | null = null; let signal: string | undefined; const done = new Promise<{ exitCode: number | null; signal?: string }>( @@ -303,10 +378,94 @@ export class SSHPool { throw new Error(`Unknown server "${serverId}"`); } - const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); + const rawStdinBuf = + opts.stdin === undefined + ? undefined + : typeof opts.stdin === 'string' + ? Buffer.from(opts.stdin, 'utf8') + : Buffer.from(opts.stdin); - const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS; - const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES; + // When both sudo password and non-empty stdin exist, avoid concatenating them into sudo's stdin: + // probe `sudo -n true` first; otherwise stage the payload in a private 0600 temp file. + if (opts.sudo && rawStdinBuf && rawStdinBuf.length > 0) { + const sudoPassword = this.getSudoPassword(server); + const envPrefix = buildEnvPrefix(opts.env); + const fullCmd = `${envPrefix}${command}`; + const quotedCmd = posixSingleQuote(fullCmd); + + if (sudoPassword) { + const noPassProbe = await this.execRaw(client, serverId, 'sudo -n true', undefined, 5_000, 4096); + if (noPassProbe.exitCode === 0) { + try { + return await this.execRaw( + client, + serverId, + `sudo -n sh -c ${quotedCmd}`, + rawStdinBuf, + opts.timeoutMs, + opts.maxBytes, + ); + } finally { + rawStdinBuf.fill(0); + } + } + + const mk = await this.execRaw( + client, + serverId, + 'f=$(mktemp /tmp/.gcoord_in.XXXXXX) && chmod 600 "$f" && printf "%s" "$f"', + undefined, + 10_000, + 1024, + ); + const tmpFile = mk.stdout.trim(); + if (mk.exitCode === 0 && tmpFile.startsWith('/tmp/.gcoord_in.')) { + try { + const stage = await this.execRaw( + client, + serverId, + `cat > ${posixSingleQuote(tmpFile)}`, + rawStdinBuf, + opts.timeoutMs, + 4096, + ); + if (stage.exitCode === 0) { + const pwBuf = Buffer.from(`${sudoPassword}\n`, 'utf8'); + try { + const execCmd = `sudo -S -k -p '' sh -c ${quotedCmd} < ${posixSingleQuote(tmpFile)}`; + return await this.execRaw( + client, + serverId, + execCmd, + pwBuf, + opts.timeoutMs, + opts.maxBytes, + ); + } finally { + pwBuf.fill(0); + } + } + } finally { + rawStdinBuf.fill(0); + await this.execRaw(client, serverId, `rm -f -- ${posixSingleQuote(tmpFile)}`, undefined, 5_000, 1024).catch(() => undefined); + } + } + } + } + rawStdinBuf?.fill(0); + + const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts); + return this.execRaw(client, serverId, finalCommand, stdinBuf, opts.timeoutMs, opts.maxBytes); + } + + private execRaw( + client: Client, + serverId: string, + finalCommand: string, + stdinBuf: Buffer | undefined, + timeoutMs = DEFAULT_EXEC_TIMEOUT_MS, + maxBytes = DEFAULT_MAX_BYTES, + ): Promise { const started = Date.now(); return new Promise((resolve, reject) => { @@ -341,6 +500,7 @@ export class SSHPool { reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)), ); }, timeoutMs); + timer.unref(); if (stdinBuf && stdinBuf.length > 0) { stream.stdin.write(stdinBuf); @@ -501,6 +661,112 @@ export class SSHPool { } } + async testConnection(candidate: ServerConfig): Promise { + const started = Date.now(); + if (!this.vaultService.isRuntimeReady) { + return { ok: false, latencyMs: 0, error: 'Vault is locked' }; + } + const cred = this.vaultService.getRuntimeSecret(candidate.credentialId); + if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { + return { + ok: false, + latencyMs: 0, + error: `Missing or incompatible SSH credential "${candidate.credentialId}" in Vault`, + }; + } + + let hopStream: Duplex | undefined; + const settings = this.configManager.getSettings(); + const client = new ssh2.Client(); + let observedFp: string | undefined; + + try { + if (candidate.jumpHostId) { + const bastion = await this.acquireClient( + candidate.jumpHostId, + new Set([candidate.id]), + ); + hopStream = await forwardOutOnClient( + bastion, + '127.0.0.1', + 0, + candidate.host, + candidate.port, + ); + } + + await new Promise((resolve, reject) => { + let settled = false; + const done = (err?: Error) => { + if (settled) return; + settled = true; + if (err) reject(err); + else resolve(); + }; + client.once('ready', () => done()); + client.once('error', (err) => done(err)); + client.once('close', () => done(new Error('SSH connection closed during test'))); + + const cfg: ConnectConfig = { + username: candidate.username, + readyTimeout: settings.sshReadyTimeoutMs, + hostVerifier: (keyBuf: Buffer) => { + const verified = this.knownHosts.verifyServerHostKey(candidate, keyBuf); + const tofu = this.knownHosts.getPendingTofu(candidate.id); + const mismatch = this.knownHosts.getPendingMismatch(candidate.id); + observedFp = mismatch?.actualFingerprint ?? tofu?.fingerprint; + return verified; + }, + }; + if (cred.type === 'ssh-key') { + cfg.privateKey = cred.privateKey; + if (cred.passphrase) cfg.passphrase = cred.passphrase; + } else { + cfg.password = cred.password; + } + if (hopStream) cfg.sock = hopStream; + else { + cfg.host = candidate.host; + cfg.port = candidate.port; + } + client.connect(cfg); + }); + + const uname = await this.execRaw(client, candidate.id, 'uname -s', undefined, 5_000, 512); + const rawOs = uname.stdout.trim().toLowerCase(); + const osDetected = rawOs.includes('freebsd') || rawOs.includes('openbsd') || rawOs.includes('netbsd') + ? 'bsd' + : rawOs.includes('darwin') + ? 'macos' + : 'linux'; + return { + ok: true, + latencyMs: Date.now() - started, + osDetected, + hostFingerprint: observedFp, + }; + } catch (err) { + const tofu = this.knownHosts.getPendingTofu(candidate.id); + const mismatch = this.knownHosts.getPendingMismatch(candidate.id); + return { + ok: false, + latencyMs: Date.now() - started, + hostFingerprint: mismatch?.actualFingerprint ?? tofu?.fingerprint ?? observedFp, + tofuRequired: Boolean(tofu), + hostKeyMismatch: mismatch, + error: err instanceof Error ? err.message : String(err), + }; + } finally { + try { + client.end(); + client.destroy(); + } catch { + // Ignore cleanup errors + } + hopStream?.destroy(); + } + } + async reconnect(serverId: string): Promise { this.closeServer(serverId); this.reconnectAttempts.delete(serverId); @@ -542,12 +808,27 @@ export class SSHPool { } closeServer(serverId: string): void { + this.serverEpoch.set(serverId, this.getServerEpoch(serverId) + 1); + this.inFlight.delete(serverId); const timer = this.reconnectTimers.get(serverId); if (timer) { clearTimeout(timer); this.reconnectTimers.delete(serverId); } + const pendingSet = this.pendingClients.get(serverId); + if (pendingSet) { + for (const c of [...pendingSet]) { + try { + c.end(); + c.destroy(); + } catch { + // Ignore pending client destroy error + } + } + this.pendingClients.delete(serverId); + } + const conn = this.connections.get(serverId); if (!conn) return; @@ -575,6 +856,8 @@ export class SSHPool { } closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void { + this.poolEpoch += 1; + this.inFlight.clear(); if (reason === 'shutdown') { this.closed = true; } @@ -584,6 +867,18 @@ export class SSHPool { } this.reconnectTimers.clear(); + for (const [id, pendingSet] of [...this.pendingClients.entries()]) { + for (const c of [...pendingSet]) { + try { + c.end(); + c.destroy(); + } catch { + // Ignore destroy error + } + } + this.pendingClients.delete(id); + } + for (const id of [...this.connections.keys()]) { this.closeServer(id); } @@ -604,6 +899,8 @@ export class SSHPool { private async connectServer( server: ServerConfig, visited: Set, + startPoolEpoch: number, + startSrvEpoch: number, ): Promise { const cred = this.vaultService.getRuntimeSecret(server.credentialId); if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) { @@ -617,6 +914,14 @@ export class SSHPool { let hopStream: Duplex | undefined; if (server.jumpHostId) { const bastion = await this.acquireClient(server.jumpHostId, visited); + if ( + this.closed || + !this.vaultService.isRuntimeReady || + this.poolEpoch !== startPoolEpoch || + this.getServerEpoch(server.id) !== startSrvEpoch + ) { + throw new Error('SSH connection aborted due to pool reset or Vault lock'); + } hopStream = await forwardOutOnClient( bastion, '127.0.0.1', @@ -628,6 +933,20 @@ export class SSHPool { const settings = this.configManager.getSettings(); const client = new ssh2.Client(); + let setForServer = this.pendingClients.get(server.id); + if (!setForServer) { + setForServer = new Set(); + this.pendingClients.set(server.id, setForServer); + } + setForServer.add(client); + + const untrackPending = () => { + const s = this.pendingClients.get(server.id); + if (s) { + s.delete(client); + if (s.size === 0) this.pendingClients.delete(server.id); + } + }; return new Promise((resolve, reject) => { let settled = false; @@ -635,6 +954,7 @@ export class SSHPool { const failConnect = (err: Error) => { if (settled) return; settled = true; + untrackPending(); hopStream?.destroy(); try { client.destroy(); @@ -642,6 +962,16 @@ export class SSHPool { // Ignore destroy failure } + if ( + this.closed || + !this.vaultService.isRuntimeReady || + this.poolEpoch !== startPoolEpoch || + this.getServerEpoch(server.id) !== startSrvEpoch + ) { + reject(err); + return; + } + const mismatch = this.knownHosts.getPendingMismatch(server.id); const tofu = this.knownHosts.getPendingTofu(server.id); let status: ServerConnectionStatus = 'disconnected'; @@ -664,8 +994,23 @@ export class SSHPool { }; client.once('ready', () => { - if (settled) { - client.end(); + untrackPending(); + const invalidated = + settled || + this.closed || + !this.vaultService.isRuntimeReady || + this.poolEpoch !== startPoolEpoch || + this.getServerEpoch(server.id) !== startSrvEpoch; + if (invalidated) { + settled = true; + hopStream?.destroy(); + try { + client.end(); + client.destroy(); + } catch { + // Ignore close failure + } + reject(new Error('SSH connection aborted due to Panic Lock, seal, or reset')); return; } settled = true; @@ -710,6 +1055,16 @@ export class SSHPool { } }); + if ( + this.closed || + !this.vaultService.isRuntimeReady || + this.poolEpoch !== startPoolEpoch || + this.getServerEpoch(server.id) !== startSrvEpoch + ) { + failConnect(new Error('SSH connection aborted due to pool reset or Vault lock')); + return; + } + const cfg: ConnectConfig = { username: server.username, keepaliveInterval: settings.sshKeepaliveMs, diff --git a/src/server/ssh/sudo.ts b/src/server/ssh/sudo.ts index 2f8ebee..2867cf8 100644 --- a/src/server/ssh/sudo.ts +++ b/src/server/ssh/sudo.ts @@ -1,3 +1,5 @@ +export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] '; + export function posixSingleQuote(value: string): string { return `'${value.replace(/'/g, "'\\''")}'`; } @@ -16,13 +18,31 @@ export function buildEnvPrefix(env?: Record): string { export function prepareSudoExecution( command: string, - options: { sudoPassword?: string; stdin?: Buffer | string } = {}, -): { command: string; stdin?: Buffer } { + options: { + sudoPassword?: string; + stdin?: Buffer | string; + ptyPrompt?: boolean; + } = {}, +): { command: string; stdin?: Buffer; ptyPassword?: string } { const quoted = posixSingleQuote(command); if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) { + if (options.ptyPrompt) { + const extraStdin = + options.stdin === undefined + ? undefined + : typeof options.stdin === 'string' + ? Buffer.from(options.stdin, 'utf8') + : Buffer.from(options.stdin); + return { + command: `sudo -S -k -p ${posixSingleQuote(SUDO_PTY_PROMPT)} sh -c ${quoted}`, + stdin: extraStdin, + ptyPassword: options.sudoPassword, + }; + } + const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8'); let combined = pwPrefix; - if (options.stdin !== undefined) { + if (options.stdin !== undefined && options.stdin.length > 0) { const extra = typeof options.stdin === 'string' ? Buffer.from(options.stdin, 'utf8') @@ -31,7 +51,7 @@ export function prepareSudoExecution( pwPrefix.fill(0); } return { - command: `sudo -S -p '' sh -c ${quoted}`, + command: `sudo -S -k -p '' sh -c ${quoted}`, stdin: combined, }; } diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 67a03df..3ba7f7c 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -401,7 +401,27 @@ export class MockSshServer { let stdin = rawStdin; // Handle sudo wrappers produced by prepareSudoExecution - if (command.startsWith("sudo -S -p '' sh -c ")) { + if (command.startsWith("sudo -S -k -p '' sh -c ")) { + const nl = stdin.indexOf('\n'); + const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; + this.lastSudoStdin = suppliedPw; + stdin = nl >= 0 ? stdin.slice(nl + 1) : ''; + if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) { + return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 }; + } + command = unquoteSinglePosix(command.slice("sudo -S -k -p '' sh -c ".length)); + } else if (command.startsWith("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ")) { + const nl = stdin.indexOf('\n'); + const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; + this.lastSudoStdin = suppliedPw; + stdin = nl >= 0 ? stdin.slice(nl + 1) : ''; + if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) { + return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 }; + } + command = unquoteSinglePosix( + command.slice("sudo -S -k -p '[gcoord-sudo-prompt] ' sh -c ".length), + ); + } else if (command.startsWith("sudo -S -p '' sh -c ")) { const nl = stdin.indexOf('\n'); const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; this.lastSudoStdin = suppliedPw; From 838e69ba4efe6d33faa8e6e1ccca2be44a7bd3ac Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:42:33 +0000 Subject: [PATCH 07/19] security(pty,sftp): fix PTY cwd injection/recording/crashes & harden + upgrade SFTP manager --- src/server/api/routes/sftp.routes.ts | 190 ++++++++++++++++-- src/server/api/routes/terminal.routes.ts | 46 ++++- src/server/app.ts | 4 +- src/server/ssh/pty-manager.ts | 217 ++++++++++++++++----- src/server/ssh/sftp-service.ts | 235 ++++++++++++++++++++--- tests/helpers/mock-ssh-server.ts | 7 +- 6 files changed, 605 insertions(+), 94 deletions(-) diff --git a/src/server/api/routes/sftp.routes.ts b/src/server/api/routes/sftp.routes.ts index fbf9f93..b24951a 100644 --- a/src/server/api/routes/sftp.routes.ts +++ b/src/server/api/routes/sftp.routes.ts @@ -1,4 +1,4 @@ -import { Router, type Response } from 'express'; +import { Router, type NextFunction, type Request, type RequestHandler, type Response } from 'express'; import { z } from 'zod'; import type { ConfigManager } from '../../config/config-manager.js'; import type { AuditService } from '../../security/audit.js'; @@ -7,6 +7,7 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; import { SftpServiceError, type SftpService } from '../../ssh/sftp-service.js'; @@ -15,6 +16,16 @@ export interface SftpRouterDeps { configManager: ConfigManager; auditService: AuditService; sftpService: SftpService; + stepUpGuard?: RequestHandler; +} + +function buildContentDisposition(fileName: string): string { + const asciiFallback = fileName.replace(/[^\x20-\x7e]|["\\;]/g, '_'); + const rfc5987 = encodeURIComponent(fileName).replace( + /['()*!]/g, + (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, + ); + return `attachment; filename="${asciiFallback}"; filename*=UTF-8''${rfc5987}`; } function sendSftpError(res: Response, err: unknown): void { @@ -22,7 +33,7 @@ function sendSftpError(res: Response, err: unknown): void { const status = err.code === 'NOT_FOUND' ? 404 - : err.code === 'CONFLICT' + : err.code === 'CONFLICT' || err.code === 'ALREADY_EXISTS' ? 409 : err.code === 'FILE_TOO_LARGE' ? 413 @@ -37,7 +48,13 @@ function sendSftpError(res: Response, err: unknown): void { export function createSftpRouter(deps: SftpRouterDeps): Router { const router = Router({ mergeParams: true }); - const { authService, configManager, auditService, sftpService } = deps; + const { + authService, + configManager, + auditService, + sftpService, + stepUpGuard = requireStepUp, + } = deps; const ensureServer = (serverId: string, res: Response): boolean => { if (!configManager.getServer(serverId)) { @@ -47,6 +64,18 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { return true; }; + const conditionalSudoStepUp = (req: Request, res: Response, next: NextFunction) => { + const wantsSudo = + req.query.sudo === '1' || + req.query.sudo === 'true' || + Boolean((req.body as { sudo?: unknown } | undefined)?.sudo); + if (!wantsSudo) { + next(); + return; + } + stepUpGuard(req, res, next); + }; + router.get('/list', requireAuth(authService), async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; @@ -75,6 +104,24 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { } }); + router.get('/search', requireAuth(authService), async (req, res) => { + const serverId = String(req.params.id ?? ''); + if (!ensureServer(serverId, res)) return; + const basePath = typeof req.query.path === 'string' ? req.query.path : '/'; + const q = typeof req.query.q === 'string' ? req.query.q : ''; + const max = req.query.max ? Number(req.query.max) : 100; + if (!q.trim()) { + res.status(400).json({ error: 'MISSING_QUERY' }); + return; + } + try { + const result = await sftpService.searchFiles(serverId, basePath, q, Number.isFinite(max) ? max : 100); + res.json(result); + } catch (err) { + sendSftpError(res, err); + } + }); + router.get('/download', requireAuth(authService), async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; @@ -86,9 +133,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { try { const dl = await sftpService.openDownloadStream(serverId, targetPath); - const safeName = dl.fileName.replace(/["\r\n\\]/g, '_'); res.setHeader('Content-Type', 'application/octet-stream'); - res.setHeader('Content-Disposition', `attachment; filename="${safeName}"`); + res.setHeader('Content-Disposition', buildContentDisposition(dl.fileName)); + res.setHeader('Cache-Control', 'no-store'); if (Number.isFinite(dl.size)) { res.setHeader('Content-Length', String(dl.size)); } @@ -127,11 +174,9 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { try { const arch = await sftpService.streamDirectoryArchive(serverId, targetPath, format); res.setHeader('Content-Type', 'application/octet-stream'); - res.setHeader( - 'Content-Disposition', - `attachment; filename="${arch.archiveFileName}"`, - ); + res.setHeader('Content-Disposition', buildContentDisposition(arch.archiveFileName)); res.setHeader('X-Archive-Format', arch.resolvedFormat); + res.setHeader('Cache-Control', 'no-store'); res.once('close', () => { if (!res.writableEnded) { @@ -183,6 +228,35 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); + router.post( + '/touch', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + async (req, res) => { + const serverId = String(req.params.id ?? ''); + if (!ensureServer(serverId, res)) return; + const parsed = z.object({ path: z.string().min(1) }).safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const created = await sftpService.touchFile(serverId, parsed.data.path); + auditService.log({ + action: 'sftp.touch', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${created}`, + status: 'ok', + }); + res.status(201).json({ ok: true, path: created }); + } catch (err) { + sendSftpError(res, err); + } + }, + ); + router.post( '/mkdir', requireAuth(authService), @@ -221,7 +295,11 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; const parsed = z - .object({ fromPath: z.string().min(1), toPath: z.string().min(1) }) + .object({ + fromPath: z.string().min(1), + toPath: z.string().min(1), + overwrite: z.boolean().optional(), + }) .safeParse(req.body ?? {}); if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); @@ -232,6 +310,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { serverId, parsed.data.fromPath, parsed.data.toPath, + Boolean(parsed.data.overwrite), ); auditService.log({ action: 'sftp.rename', @@ -283,6 +362,50 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); + router.post( + '/chown', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + async (req, res) => { + const serverId = String(req.params.id ?? ''); + if (!ensureServer(serverId, res)) return; + const parsed = z + .object({ + path: z.string().min(1), + uid: z.number().int().min(0), + gid: z.number().int().min(0), + sudo: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + try { + const result = await sftpService.chown( + serverId, + parsed.data.path, + parsed.data.uid, + parsed.data.gid, + Boolean(parsed.data.sudo), + ); + auditService.log({ + action: 'sftp.chown', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${result.path}`, + status: 'ok', + details: { uid: result.uid, gid: result.gid, sudo: Boolean(parsed.data.sudo) }, + }); + res.json({ ok: true, ...result }); + } catch (err) { + sendSftpError(res, err); + } + }, + ); + router.delete( '/entry', requireAuth(authService), @@ -314,7 +437,42 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { }, ); - router.get('/text', requireAuth(authService), async (req, res) => { + router.post( + '/bulk-delete', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + async (req, res) => { + const serverId = String(req.params.id ?? ''); + if (!ensureServer(serverId, res)) return; + const parsed = z + .object({ + paths: z.array(z.string().min(1)).min(1).max(100), + recursive: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const result = await sftpService.bulkDelete( + serverId, + parsed.data.paths, + Boolean(parsed.data.recursive), + ); + auditService.log({ + action: 'sftp.bulk_delete', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: serverId, + status: result.failed.length === 0 ? 'ok' : 'error', + details: { count: result.deleted.length, failedCount: result.failed.length }, + }); + res.json(result); + }, + ); + + router.get('/text', requireAuth(authService), conditionalSudoStepUp, async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; const targetPath = typeof req.query.path === 'string' ? req.query.path : ''; @@ -325,6 +483,15 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { } try { const file = await sftpService.readTextFile(serverId, targetPath, { sudo }); + if (sudo) { + auditService.log({ + action: 'sftp.sudo_read', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${file.path}`, + status: 'ok', + }); + } res.json({ file }); } catch (err) { sendSftpError(res, err); @@ -336,6 +503,7 @@ export function createSftpRouter(deps: SftpRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, + conditionalSudoStepUp, async (req, res) => { const serverId = String(req.params.id ?? ''); if (!ensureServer(serverId, res)) return; diff --git a/src/server/api/routes/terminal.routes.ts b/src/server/api/routes/terminal.routes.ts index 0d3d352..1e2321a 100644 --- a/src/server/api/routes/terminal.routes.ts +++ b/src/server/api/routes/terminal.routes.ts @@ -37,7 +37,11 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { serverId: EntityIdSchema, cols: z.number().int().min(10).max(500).optional(), rows: z.number().int().min(4).max(200).optional(), - cwd: z.string().max(1024).optional(), + cwd: z + .string() + .max(1024) + .refine((v) => !/[\x00-\x1f\x7f]/.test(v), 'Control characters not permitted in cwd') + .optional(), title: z.string().max(120).optional(), }) .safeParse(req.body ?? {}); @@ -70,6 +74,36 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { }, ); + router.post( + '/sessions/:sessionId/reconnect', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + async (req, res) => { + const sessionId = String(req.params.sessionId ?? ''); + try { + const session = await ptyManager.reconnectSession(sessionId); + if (!session) { + res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' }); + return; + } + auditService.log({ + action: 'pty.reconnect', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${session.serverId}:${sessionId}`, + status: 'ok', + }); + res.json({ ok: true, session }); + } catch (err) { + res.status(502).json({ + error: 'PTY_RECONNECT_FAILED', + message: err instanceof Error ? err.message : 'Unable to reconnect PTY session', + }); + } + }, + ); + router.post( '/sessions/:sessionId/resize', requireAuth(authService), @@ -98,7 +132,12 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { router.get('/sessions/:sessionId/export', requireAuth(authService), (req, res) => { const sessionId = String(req.params.sessionId ?? ''); - const format = req.query.format === 'ansi' ? 'ansi' : 'plain'; + const format = + req.query.format === 'ansi' + ? 'ansi' + : req.query.format === 'cast' + ? 'cast' + : 'plain'; const exported = ptyManager.exportScrollback(sessionId, format); if (!exported) { res.status(404).json({ error: 'PTY_SESSION_NOT_FOUND' }); @@ -106,8 +145,9 @@ export function createTerminalRouter(deps: TerminalRouterDeps): Router { } const safeFile = exported.filename.replace(/[^A-Za-z0-9._-]/g, '_'); - res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.setHeader('Content-Type', exported.contentType); res.setHeader('Content-Disposition', `attachment; filename="${safeFile}"`); + res.setHeader('Cache-Control', 'no-store'); res.send(exported.content); }); diff --git a/src/server/app.ts b/src/server/app.ts index 2b2c901..f5d5e0d 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -177,7 +177,7 @@ export async function createGCoordinatorServer( const knownHosts = new KnownHostsService(db, auditService); const sshPool = new SSHPool(configManager, vaultService, knownHosts); const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); - const ptyManager = new PTYManager(sshPool, configManager, wsHub); + const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits); const sftpService = new SftpService(sshPool); const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService); const customSystemsEngine = new CustomSystemsEngine( @@ -564,7 +564,7 @@ export async function createGCoordinatorServer( app.use('/api/ai', createAiRouter({ authService, aiService })); app.use( '/api/servers/:id/sftp', - createSftpRouter({ authService, configManager, auditService, sftpService }), + createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), ); app.use( '/api/servers', diff --git a/src/server/ssh/pty-manager.ts b/src/server/ssh/pty-manager.ts index 87bf2b9..6e79f2f 100644 --- a/src/server/ssh/pty-manager.ts +++ b/src/server/ssh/pty-manager.ts @@ -4,6 +4,7 @@ import type { ClientChannel } from 'ssh2'; import { WS_CHANNELS } from '../../shared/ws-protocol.js'; import type { WsHub } from '../api/ws-hub.js'; import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { SSHPool } from './ssh-pool.js'; import { posixSingleQuote } from './sudo.js'; @@ -34,22 +35,34 @@ export interface OpenPtyParams { } interface ScrollChunk { + offsetMs: number; text: string; bytes: number; } interface InternalPtySession { info: PtySessionInfo; + env?: Record; + sudo?: boolean; channel: ClientChannel; chunks: ScrollChunk[]; stdoutDecoder: StringDecoder; stderrDecoder: StringDecoder; } -const MAX_RETAINED_EXITED_SESSIONS = 20; +export function assertSafeCwd(cwd: string): string { + if (/[\x00-\x1f\x7f]/.test(cwd)) { + throw new Error('Invalid cwd: control characters are not permitted'); + } + const trimmed = cwd.trim(); + if (trimmed.length > 1024) { + throw new Error('Invalid cwd: exceeds 1024 character limit'); + } + return trimmed; +} export function formatRemoteCd(cwd: string): string { - const trimmed = cwd.trim(); + const trimmed = assertSafeCwd(cwd); if (trimmed === '~' || trimmed === '~/') { return 'cd -- "$HOME"'; } @@ -71,7 +84,6 @@ function sliceTrailingUtf8(text: string, maxBytes: number): { text: string; byte return { text, bytes: buf.length }; } let start = buf.length - maxBytes; - // Skip UTF-8 continuation bytes (10xxxxxx) so we never cut inside a codepoint while (start < buf.length && (buf[start]! & 0b1100_0000) === 0b1000_0000) { start++; } @@ -87,6 +99,7 @@ export class PTYManager { private readonly sshPool: SSHPool, private readonly configManager: ConfigManager, private readonly wsHub: WsHub, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) { this.reaperTimer = setInterval(() => { this.reapIdleSessions(); @@ -94,14 +107,12 @@ export class PTYManager { this.reaperTimer.unref(); } - async openSession(params: OpenPtyParams): Promise { - const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80))); - const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24))); - const now = Date.now(); - const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`; - const trimmedCwd = params.cwd?.trim(); - - let channel: ClientChannel; + private async createChannel( + params: OpenPtyParams, + cols: number, + rows: number, + trimmedCwd?: string, + ): Promise { if (params.command) { const cmd = trimmedCwd ? `${formatRemoteCd(trimmedCwd)} && (${params.command})` @@ -111,45 +122,30 @@ export class PTYManager { sudo: params.sudo, pty: { cols, rows, term: 'xterm-256color' }, }); - channel = stream.channel; - } else { - channel = await this.sshPool.openShell(params.serverId, { + stream.done.catch(() => undefined); + return stream.channel; + } + + if (trimmedCwd && trimmedCwd !== '~') { + const channel = await this.sshPool.openShell(params.serverId, { cols, rows, term: 'xterm-256color', }); - if (trimmedCwd && trimmedCwd !== '~') { - channel.write(`${formatRemoteCd(trimmedCwd)}\n`); - } + channel.write(`${formatRemoteCd(trimmedCwd)}\n`); + return channel; } - const title = - params.title?.trim() || - (params.command - ? `${params.serverId}: ${params.command.slice(0, 32)}` - : `${params.serverId} shell`); + return this.sshPool.openShell(params.serverId, { + cols, + rows, + term: 'xterm-256color', + }); + } - const internal: InternalPtySession = { - info: { - sessionId, - serverId: params.serverId, - title, - cwd: trimmedCwd || undefined, - command: params.command, - cols, - rows, - createdAt: now, - lastActivityAt: now, - exited: false, - exitCode: null, - scrollbackBytes: 0, - }, - channel, - chunks: [], - stdoutDecoder: new StringDecoder('utf8'), - stderrDecoder: new StringDecoder('utf8'), - }; - this.sessions.set(sessionId, internal); + private bindChannelHandlers(internal: InternalPtySession): void { + const { channel } = internal; + const { sessionId } = internal.info; channel.on('data', (chunk: Buffer) => { const text = internal.stdoutDecoder.write(chunk); @@ -162,7 +158,7 @@ export class PTYManager { }); const finalizeExit = (code: number | null) => { - if (internal.info.exited) return; + if (internal.channel !== channel || internal.info.exited) return; const tailOut = internal.stdoutDecoder.end(); if (tailOut) this.appendOutput(internal, tailOut); const tailErr = internal.stderrDecoder.end(); @@ -185,7 +181,99 @@ export class PTYManager { channel.on('close', () => { finalizeExit(internal.info.exitCode); }); + channel.on('error', () => { + finalizeExit(internal.info.exitCode); + }); + } + async openSession(params: OpenPtyParams): Promise { + const limits = this.getRuntimeLimits?.(); + const maxActive = limits?.maxActivePtys ?? 32; + const activeCount = [...this.sessions.values()].filter((s) => !s.info.exited).length; + if (activeCount >= maxActive) { + throw new Error(`Active PTY limit (${maxActive}) reached`); + } + + const cols = Math.max(10, Math.min(500, Math.floor(params.cols ?? 80))); + const rows = Math.max(4, Math.min(200, Math.floor(params.rows ?? 24))); + const now = Date.now(); + const sessionId = `pty-${crypto.randomBytes(6).toString('hex')}`; + const trimmedCwd = params.cwd !== undefined ? assertSafeCwd(params.cwd) : undefined; + + const channel = await this.createChannel( + params, + cols, + rows, + trimmedCwd || undefined, + ); + + const title = + params.title?.trim() || + (params.command + ? `${params.serverId}: ${params.command.slice(0, 32)}` + : `${params.serverId} shell`); + + const internal: InternalPtySession = { + info: { + sessionId, + serverId: params.serverId, + title, + cwd: trimmedCwd || undefined, + command: params.command, + cols, + rows, + createdAt: now, + lastActivityAt: now, + exited: false, + exitCode: null, + scrollbackBytes: 0, + }, + env: params.env, + sudo: params.sudo, + channel, + chunks: [], + stdoutDecoder: new StringDecoder('utf8'), + stderrDecoder: new StringDecoder('utf8'), + }; + this.sessions.set(sessionId, internal); + this.bindChannelHandlers(internal); + + return { ...internal.info }; + } + + async reconnectSession(sessionId: string): Promise { + const internal = this.sessions.get(sessionId); + if (!internal) return null; + + const oldChannel = internal.channel; + const channel = await this.createChannel( + { + serverId: internal.info.serverId, + command: internal.info.command, + env: internal.env, + sudo: internal.sudo, + }, + internal.info.cols, + internal.info.rows, + internal.info.cwd, + ); + + internal.channel = channel; + internal.stdoutDecoder = new StringDecoder('utf8'); + internal.stderrDecoder = new StringDecoder('utf8'); + internal.info.exited = false; + internal.info.exitCode = null; + internal.info.lastActivityAt = Date.now(); + this.bindChannelHandlers(internal); + + try { + oldChannel.close(); + oldChannel.destroy(); + } catch { + // Ignore cleanup errors on prior channel + } + + this.appendOutput(internal, '\r\n[gcoord: reconnected PTY session]\r\n'); return { ...internal.info }; } @@ -215,7 +303,6 @@ export class PTYManager { entry.info.cols = clampedCols; entry.info.rows = clampedRows; entry.info.lastActivityAt = Date.now(); - // @types/ssh2: Channel.setWindow(rows, cols, height, width) entry.channel.setWindow(clampedRows, clampedCols, 0, 0); return true; } @@ -228,16 +315,34 @@ export class PTYManager { exportScrollback( sessionId: string, - format: 'plain' | 'ansi' = 'plain', - ): { filename: string; content: string } | null { + format: 'plain' | 'ansi' | 'cast' = 'plain', + ): { filename: string; content: string; contentType: string } | null { const entry = this.sessions.get(sessionId); if (!entry) return null; + if (format === 'cast') { + const header = JSON.stringify({ + version: 2, + width: entry.info.cols, + height: entry.info.rows, + timestamp: Math.floor(entry.info.createdAt / 1000), + title: entry.info.title, + }); + const events = entry.chunks.map((c) => + JSON.stringify([Number((c.offsetMs / 1000).toFixed(3)), 'o', c.text]), + ); + return { + filename: `${entry.info.serverId}-${sessionId}.cast`, + content: `${[header, ...events].join('\n')}\n`, + contentType: 'application/x-asciicast; charset=utf-8', + }; + } const raw = entry.chunks.map((c) => c.text).join(''); const content = format === 'ansi' ? raw : stripAnsiSequences(raw); const ext = format === 'ansi' ? 'ansi.log' : 'txt'; return { filename: `${entry.info.serverId}-${sessionId}.${ext}`, content, + contentType: 'text/plain; charset=utf-8', }; } @@ -275,15 +380,22 @@ export class PTYManager { } private appendOutput(entry: InternalPtySession, text: string): void { - const maxBytes = Math.max(16_384, this.configManager.getSettings().ptyScrollbackBytes); + const configuredMax = this.configManager.getSettings().ptyScrollbackBytes; + const runtimeCap = this.getRuntimeLimits?.()?.defaultPtyScrollbackBytes; + const maxBytes = Math.max( + 16_384, + runtimeCap ? Math.min(configuredMax, runtimeCap) : configuredMax, + ); const rawBytes = Buffer.byteLength(text, 'utf8'); + const now = Date.now(); + const offsetMs = Math.max(0, now - entry.info.createdAt); if (rawBytes >= maxBytes) { const trimmed = sliceTrailingUtf8(text, maxBytes); - entry.chunks = [{ text: trimmed.text, bytes: trimmed.bytes }]; + entry.chunks = [{ offsetMs, text: trimmed.text, bytes: trimmed.bytes }]; entry.info.scrollbackBytes = trimmed.bytes; } else { - entry.chunks.push({ text, bytes: rawBytes }); + entry.chunks.push({ offsetMs, text, bytes: rawBytes }); entry.info.scrollbackBytes += rawBytes; while (entry.info.scrollbackBytes > maxBytes && entry.chunks.length > 0) { const dropped = entry.chunks.shift()!; @@ -291,7 +403,7 @@ export class PTYManager { } } - entry.info.lastActivityAt = Date.now(); + entry.info.lastActivityAt = now; this.wsHub.broadcastChannel(WS_CHANNELS.pty(entry.info.sessionId), { type: 'pty:output', sessionId: entry.info.sessionId, @@ -320,10 +432,11 @@ export class PTYManager { } private pruneExcessExited(): void { + const maxRetained = this.getRuntimeLimits?.()?.maxRetainedExitedPtys ?? 12; const exited = [...this.sessions.values()] .filter((s) => s.info.exited) .sort((a, b) => a.info.lastActivityAt - b.info.lastActivityAt); - while (exited.length > MAX_RETAINED_EXITED_SESSIONS) { + while (exited.length > maxRetained) { const oldest = exited.shift()!; this.sessions.delete(oldest.info.sessionId); } diff --git a/src/server/ssh/sftp-service.ts b/src/server/ssh/sftp-service.ts index ee9ba12..9308d0a 100644 --- a/src/server/ssh/sftp-service.ts +++ b/src/server/ssh/sftp-service.ts @@ -17,6 +17,7 @@ export interface SftpListEntry { mtimeMs: number; uid: number; gid: number; + symlinkTarget?: string; } export interface SftpTextFile { @@ -33,6 +34,8 @@ export class SftpServiceError extends Error { | 'NOT_FOUND' | 'NOT_A_DIRECTORY' | 'IS_A_DIRECTORY' + | 'UNSUPPORTED_FILE_TYPE' + | 'ALREADY_EXISTS' | 'FILE_TOO_LARGE' | 'BINARY_FILE_NOT_EDITABLE' | 'CONFLICT' @@ -104,9 +107,18 @@ export class SftpService { if (item.filename === '.' || item.filename === '..') continue; const mode = item.attrs.mode ?? 0; const type = modeToType(mode); + const itemPath = path.posix.join(resolved, item.filename); + let symlinkTarget: string | undefined; + if (type === 'symlink') { + try { + symlinkTarget = await promisifySftp((cb) => sftp.readlink(itemPath, cb)); + } catch { + symlinkTarget = undefined; + } + } entries.push({ name: item.filename, - path: path.posix.join(resolved, item.filename), + path: itemPath, type, size: item.attrs.size ?? 0, mode, @@ -114,6 +126,7 @@ export class SftpService { mtimeMs: (item.attrs.mtime ?? 0) * 1000, uid: item.attrs.uid ?? 0, gid: item.attrs.gid ?? 0, + ...(symlinkTarget !== undefined ? { symlinkTarget } : {}), }); } @@ -131,18 +144,28 @@ export class SftpService { async statPath(serverId: string, remotePath: string): Promise { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); - const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); - const mode = stats.mode ?? 0; + const lstats = await promisifySftp((cb) => sftp.lstat(resolved, cb)); + const mode = lstats.mode ?? 0; + const type = modeToType(mode); + let symlinkTarget: string | undefined; + if (type === 'symlink') { + try { + symlinkTarget = await promisifySftp((cb) => sftp.readlink(resolved, cb)); + } catch { + symlinkTarget = undefined; + } + } return { name: path.posix.basename(resolved) || '/', path: resolved, - type: modeToType(mode), - size: stats.size ?? 0, + type, + size: lstats.size ?? 0, mode, permissionsOctal: (mode & 0o7777).toString(8).padStart(4, '0'), - mtimeMs: (stats.mtime ?? 0) * 1000, - uid: stats.uid ?? 0, - gid: stats.gid ?? 0, + mtimeMs: (lstats.mtime ?? 0) * 1000, + uid: lstats.uid ?? 0, + gid: lstats.gid ?? 0, + ...(symlinkTarget !== undefined ? { symlinkTarget } : {}), }; }); } @@ -169,12 +192,19 @@ export class SftpService { try { const resolved = await this.resolveRemotePath(sftp, remotePath); const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); - if (modeToType(stats.mode) === 'dir') { + const kind = modeToType(stats.mode); + if (kind === 'dir') { throw new SftpServiceError( 'IS_A_DIRECTORY', 'Cannot download a directory as a single file; use /archive instead.', ); } + if (kind !== 'file') { + throw new SftpServiceError( + 'UNSUPPORTED_FILE_TYPE', + `Refusing to download special/non-regular file: ${resolved}`, + ); + } const stream = sftp.createReadStream(resolved); stream.once('close', cleanup); stream.once('error', cleanup); @@ -199,10 +229,14 @@ export class SftpService { ): Promise<{ path: string; bytesWritten: number }> { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); - const dest = sftp.createWriteStream(resolved); + const tmpPath = path.posix.join( + path.posix.dirname(resolved), + `.gcoord-up-${crypto.randomBytes(6).toString('hex')}`, + ); + const dest = sftp.createWriteStream(tmpPath); let bytesWritten = 0; - return new Promise<{ path: string; bytesWritten: number }>((resolve, reject) => { + await new Promise((resolve, reject) => { let settled = false; const fail = (err: Error) => { if (settled) return; @@ -237,11 +271,41 @@ export class SftpService { dest.on('close', () => { if (settled) return; settled = true; - resolve({ path: resolved, bytesWritten }); + resolve(); }); source.pipe(dest); + }).catch(async (err) => { + await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined); + throw err; }); + + try { + await this.renameSftpPath(sftp, tmpPath, resolved, true); + } catch (err) { + await promisifySftpVoid((cb) => sftp.unlink(tmpPath, cb)).catch(() => undefined); + throw err; + } + + return { path: resolved, bytesWritten }; + }); + } + + async touchFile(serverId: string, remotePath: string): Promise { + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + let exists = false; + try { + await promisifySftp((cb) => sftp.lstat(resolved, cb)); + exists = true; + } catch { + exists = false; + } + if (exists) { + throw new SftpServiceError('ALREADY_EXISTS', `Path already exists: ${resolved}`); + } + await promisifySftpVoid((cb) => sftp.writeFile(resolved, Buffer.alloc(0), cb)); + return resolved; }); } @@ -253,16 +317,43 @@ export class SftpService { }); } - async rename(serverId: string, fromPath: string, toPath: string): Promise<{ from: string; to: string }> { + async rename( + serverId: string, + fromPath: string, + toPath: string, + overwrite = false, + ): Promise<{ from: string; to: string }> { return this.withSftp(serverId, async (sftp) => { const resolvedFrom = await this.resolveRemotePath(sftp, fromPath); const resolvedTo = await this.resolveRemotePath(sftp, toPath); - await this.renameSftpPath(sftp, resolvedFrom, resolvedTo); + if (resolvedFrom === resolvedTo) { + return { from: resolvedFrom, to: resolvedTo }; + } + if (!overwrite) { + let destExists = false; + try { + await promisifySftp((cb) => sftp.lstat(resolvedTo, cb)); + destExists = true; + } catch { + destExists = false; + } + if (destExists) { + throw new SftpServiceError( + 'ALREADY_EXISTS', + `Destination "${resolvedTo}" already exists`, + ); + } + } + await this.renameSftpPath(sftp, resolvedFrom, resolvedTo, overwrite); return { from: resolvedFrom, to: resolvedTo }; }); } - async chmod(serverId: string, remotePath: string, modeInput: string | number): Promise<{ path: string; permissionsOctal: string }> { + async chmod( + serverId: string, + remotePath: string, + modeInput: string | number, + ): Promise<{ path: string; permissionsOctal: string }> { const parsedMode = typeof modeInput === 'number' ? modeInput @@ -283,6 +374,37 @@ export class SftpService { }); } + async chown( + serverId: string, + remotePath: string, + uid: number, + gid: number, + sudo = false, + ): Promise<{ path: string; uid: number; gid: number }> { + if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) { + throw new SftpServiceError('INVALID_MODE', 'uid and gid must be non-negative integers'); + } + + if (sudo) { + const resolved = await this.resolvePathNoStat(serverId, remotePath); + const res = await this.sshPool.exec( + serverId, + `chown ${uid}:${gid} -- ${posixSingleQuote(resolved)}`, + { sudo: true }, + ); + if (res.exitCode !== 0) { + throw new Error(res.stderr.trim() || `chown failed for ${resolved}`); + } + return { path: resolved, uid, gid }; + } + + return this.withSftp(serverId, async (sftp) => { + const resolved = await this.resolveRemotePath(sftp, remotePath); + await promisifySftpVoid((cb) => sftp.chown(resolved, uid, gid, cb)); + return { path: resolved, uid, gid }; + }); + } + async deletePath( serverId: string, remotePath: string, @@ -298,6 +420,51 @@ export class SftpService { }); } + async bulkDelete( + serverId: string, + paths: string[], + recursive = false, + ): Promise<{ deleted: string[]; failed: Array<{ path: string; error: string }> }> { + const deleted: string[] = []; + const failed: Array<{ path: string; error: string }> = []; + for (const p of paths) { + try { + const res = await this.deletePath(serverId, p, recursive); + deleted.push(res); + } catch (err) { + failed.push({ + path: p, + error: err instanceof Error ? err.message : String(err), + }); + } + } + return { deleted, failed }; + } + + async searchFiles( + serverId: string, + basePath: string, + query: string, + maxResults = 100, + ): Promise<{ basePath: string; matches: string[] }> { + const cleanQuery = query.trim(); + if (!cleanQuery || /[\x00\r\n]/.test(cleanQuery)) { + throw new SftpServiceError('INVALID_PATH', 'Invalid search query'); + } + const resolvedBase = await this.resolvePathNoStat(serverId, basePath || '/'); + const escapedPattern = cleanQuery.includes('*') || cleanQuery.includes('?') + ? cleanQuery + : `*${cleanQuery}*`; + const cap = Math.max(1, Math.min(200, maxResults)); + const cmd = `find ${posixSingleQuote(resolvedBase)} -maxdepth 5 -iname ${posixSingleQuote(escapedPattern)} 2>/dev/null | head -n ${cap}`; + const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000, maxBytes: 256 * 1024 }); + const matches = res.stdout + .split(/\r?\n/) + .map((l) => l.trim()) + .filter((l) => l.length > 0 && l !== resolvedBase); + return { basePath: resolvedBase, matches }; + } + async readTextFile( serverId: string, remotePath: string, @@ -341,7 +508,10 @@ export class SftpService { } const buf = Buffer.from(catRes.stdout, 'utf8'); if (buf.includes(0)) { - throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); + throw new SftpServiceError( + 'BINARY_FILE_NOT_EDITABLE', + 'Binary file cannot be opened in inline editor', + ); } return { path: resolved, @@ -355,9 +525,16 @@ export class SftpService { return this.withSftp(serverId, async (sftp) => { const resolved = await this.resolveRemotePath(sftp, remotePath); const stats = await promisifySftp((cb) => sftp.stat(resolved, cb)); - if (modeToType(stats.mode) === 'dir') { + const kind = modeToType(stats.mode); + if (kind === 'dir') { throw new SftpServiceError('IS_A_DIRECTORY', `${resolved} is a directory`); } + if (kind !== 'file') { + throw new SftpServiceError( + 'UNSUPPORTED_FILE_TYPE', + `Refusing to open special/non-regular file: ${resolved}`, + ); + } if ((stats.size ?? 0) > maxBytes) { throw new SftpServiceError( 'FILE_TOO_LARGE', @@ -369,7 +546,10 @@ export class SftpService { throw new SftpServiceError('FILE_TOO_LARGE', 'File exceeds inline editor limit'); } if (buf.includes(0)) { - throw new SftpServiceError('BINARY_FILE_NOT_EDITABLE', 'Binary file cannot be opened in inline editor'); + throw new SftpServiceError( + 'BINARY_FILE_NOT_EDITABLE', + 'Binary file cannot be opened in inline editor', + ); } return { path: resolved, @@ -412,7 +592,7 @@ export class SftpService { const qTmp = posixSingleQuote(tmp); const res = await this.sshPool.exec( serverId, - `umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || chmod --reference=${qDst} ${qTmp} 2>/dev/null || true; } && mv -f ${qTmp} ${qDst}`, + `umask 077 && cat > ${qTmp} && { [ ! -e ${qDst} ] || { chmod --reference=${qDst} ${qTmp} 2>/dev/null; chown --reference=${qDst} ${qTmp} 2>/dev/null; true; }; } && mv -f -- ${qTmp} ${qDst}`, { sudo: true, stdin: newBuf }, ); if (res.exitCode !== 0) { @@ -438,7 +618,6 @@ export class SftpService { } } catch (err) { if (err instanceof SftpServiceError && err.code === 'CONFLICT') throw err; - // File does not yet exist or could not be pre-read } const dir = path.posix.dirname(resolved); @@ -450,7 +629,7 @@ export class SftpService { () => undefined, ); } - await this.renameSftpPath(sftp, tmp, resolved); + await this.renameSftpPath(sftp, tmp, resolved, true); } catch (err) { await promisifySftpVoid((cb) => sftp.unlink(tmp, cb)).catch(() => undefined); throw err; @@ -498,8 +677,10 @@ export class SftpService { const safeName = (resolved === '/' ? 'root' : baseName).replace(/[^A-Za-z0-9._-]/g, '_'); const archiveFileName = `${safeName}.${resolvedFormat}`; - const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T0 -c' : 'gzip -c'; - const cmd = `set -o pipefail 2>/dev/null || true; tar -C ${posixSingleQuote(parentDir)} -cf - ${posixSingleQuote(baseName)} | ${compressCmd}`; + const osDetected = this.sshPool.getState(serverId)?.osDetected; + const oneFsFlag = osDetected !== 'bsd' && osDetected !== 'macos' ? '--one-file-system ' : ''; + const compressCmd = resolvedFormat === 'tar.zst' ? 'zstd -T2 -c' : 'gzip -c'; + const cmd = `set -o pipefail 2>/dev/null || true; tar ${oneFsFlag}-C ${posixSingleQuote(parentDir)} -cf - -- ${posixSingleQuote(baseName)} | ${compressCmd}`; const handle = await this.sshPool.execStream(serverId, cmd); return { @@ -538,6 +719,9 @@ export class SftpService { private async resolveRemotePath(sftp: SFTPWrapper, requestedPath?: string): Promise { const trimmed = requestedPath?.trim() ?? ''; + if (/[\x00\r\n]/.test(trimmed)) { + throw new SftpServiceError('INVALID_PATH', 'Control characters not permitted in path'); + } if (!trimmed || trimmed === '.' || trimmed === '~') { const home = await promisifySftp((cb) => sftp.realpath('.', cb)); return path.posix.normalize(home || '/'); @@ -557,7 +741,12 @@ export class SftpService { sftp: SFTPWrapper, fromPath: string, toPath: string, + overwrite = false, ): Promise { + if (!overwrite) { + await promisifySftpVoid((cb) => sftp.rename(fromPath, toPath, cb)); + return; + } try { await promisifySftpVoid((cb) => sftp.ext_openssh_rename(fromPath, toPath, cb)); } catch { diff --git a/tests/helpers/mock-ssh-server.ts b/tests/helpers/mock-ssh-server.ts index 3ba7f7c..8bdd653 100644 --- a/tests/helpers/mock-ssh-server.ts +++ b/tests/helpers/mock-ssh-server.ts @@ -567,9 +567,10 @@ export class MockSshServer { rawCommand: string, ): { stdout: Buffer; stderr?: string; exitCode: number } | null { // Support streamed SFTP folder archive command in integration tests - const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( - rawCommand, - ); + const tarMatch = + /tar (?:--one-file-system )?-C ('(?:[^']|'\\'')*'|\S+) -cf - (?:-- )?('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( + rawCommand, + ); if (tarMatch) { try { const virtualParent = unquoteSinglePosix(tarMatch[1]!); From ca67c85fbf7994e2c8e515fa2bf252f504e8b664 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:48:53 +0000 Subject: [PATCH 08/19] security(tunnels,proxy): dual-mode isolated proxy origin, direct SSH dialing, HTTPS upstream, SOCKS5 & TTL tunnels --- src/server/api/routes/tunnels.routes.ts | 42 +- src/server/api/ws-hub.ts | 12 + src/server/app.ts | 31 +- src/server/security/auth.ts | 6 +- src/server/security/egress-guard.ts | 20 +- src/server/ssh/tunnel-manager.ts | 1196 ++++++++++++++++++++--- tests/tunnels-and-proxy.test.ts | 71 +- 7 files changed, 1243 insertions(+), 135 deletions(-) diff --git a/src/server/api/routes/tunnels.routes.ts b/src/server/api/routes/tunnels.routes.ts index ca4df39..7d37b6d 100644 --- a/src/server/api/routes/tunnels.routes.ts +++ b/src/server/api/routes/tunnels.routes.ts @@ -10,7 +10,7 @@ import { requireAuth, requireCsrf, } from '../../security/guards.js'; -import type { TunnelManager } from '../../ssh/tunnel-manager.js'; +import { ProxyIsolationError, type TunnelManager } from '../../ssh/tunnel-manager.js'; export interface TunnelsRouterDeps { authService: AuthService; @@ -180,6 +180,46 @@ export function createTunnelsRouter(deps: TunnelsRouterDeps): Router { }, ); + // Issue single-use isolated-origin launch ticket (allowed in Safe Mode for read-only viewing) + router.post( + '/:serverId/:tunnelId/proxy-ticket', + requireAuth(authService), + requireCsrf, + (req, res) => { + const serverId = String(req.params.serverId ?? ''); + const tunnelId = String(req.params.tunnelId ?? ''); + try { + const result = tunnelManager.issueProxyTicket( + req.authSession!.idHash, + serverId, + tunnelId, + { + host: req.headers.host, + protocol: req.protocol, + }, + ); + auditService.log({ + action: 'tunnel.proxy_ticket', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${tunnelId}`, + status: 'ok', + details: { mode: result.mode }, + }); + res.json(result); + } catch (err) { + if (err instanceof ProxyIsolationError) { + res.status(403).json({ error: err.code, message: err.message }); + return; + } + res.status(400).json({ + error: 'PROXY_TICKET_FAILED', + message: err instanceof Error ? err.message : 'Unable to issue proxy ticket', + }); + } + }, + ); + return router; } diff --git a/src/server/api/ws-hub.ts b/src/server/api/ws-hub.ts index 42f80e7..7a5ea04 100644 --- a/src/server/api/ws-hub.ts +++ b/src/server/api/ws-hub.ts @@ -57,6 +57,7 @@ export class WsHub { private readonly clients = new Set(); private readonly pingTimer: NodeJS.Timeout; private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = []; + private readonly hostUpgradeHandlers: Array<(req: IncomingMessage, socket: Duplex, head: Buffer) => boolean> = []; private readonly subscribeListeners = new Set(); private ptyHandlers: WsPtyHandlers | null = null; private aiHandlers: WsAiHandlers | null = null; @@ -119,6 +120,12 @@ export class WsHub { this.upgradeHandlers.push({ prefix, handler }); } + registerHostUpgradeHandler( + matcherHandler: (req: IncomingMessage, socket: Duplex, head: Buffer) => boolean, + ): void { + this.hostUpgradeHandlers.push(matcherHandler); + } + onChannelSubscribe(listener: WsSubscribeListener): () => void { this.subscribeListeners.add(listener); return () => { @@ -181,6 +188,11 @@ export class WsHub { socket: Duplex, head: Buffer, ): void { + for (const matcher of this.hostUpgradeHandlers) { + if (matcher(req, socket, head)) { + return; + } + } const urlPath = (req.url ?? '').split('?')[0] ?? ''; for (const entry of this.upgradeHandlers) { if (urlPath.startsWith(entry.prefix)) { diff --git a/src/server/app.ts b/src/server/app.ts index f5d5e0d..fb19dc9 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -32,7 +32,7 @@ import { KnownHostsService } from './ssh/known-hosts.js'; import { PTYManager } from './ssh/pty-manager.js'; import { SftpService } from './ssh/sftp-service.js'; import { SSHPool } from './ssh/ssh-pool.js'; -import { TunnelManager } from './ssh/tunnel-manager.js'; +import { TunnelManager, extractSubdomainTunnel } 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'; @@ -97,6 +97,7 @@ export interface GCoordinatorInstance { aiService: AiService; wsHub: WsHub; port: number; + proxyPort?: number; close(): Promise; } @@ -179,7 +180,13 @@ export async function createGCoordinatorServer( const keyManager = new KeyManager(sshPool, vaultService, configManager, auditService); const ptyManager = new PTYManager(sshPool, configManager, wsHub, getRuntimeLimits); const sftpService = new SftpService(sshPool); - const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService); + const tunnelManager = new TunnelManager(sshPool, configManager, vaultService, authService, { + getRuntimeLimits, + allowLanTunnels: options.allowLanTunnels, + proxyBaseDomain: options.proxyBaseDomain, + proxyPort: options.proxyPort, + trustCloudflare, + }); const customSystemsEngine = new CustomSystemsEngine( sshPool, configManager, @@ -243,6 +250,12 @@ export async function createGCoordinatorServer( getRuntimeLimits, ); + wsHub.registerHostUpgradeHandler((req, socket, head) => { + const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); + if (!tunnelSub) return false; + tunnelManager.handleSubdomainProxyWs(req, socket, head, tunnelSub); + return true; + }); wsHub.registerUpgradeHandler('/proxy/', (req, socket, head) => { tunnelManager.handleWsProxyUpgrade(req, socket, head); }); @@ -299,6 +312,15 @@ export async function createGCoordinatorServer( } }); + app.use((req, res, next) => { + const tunnelSub = extractSubdomainTunnel(req.headers.host, options.proxyBaseDomain); + if (tunnelSub) { + tunnelManager.handleSubdomainProxyHttp(req, res, tunnelSub); + return; + } + next(); + }); + app.use((req, res, next) => { res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); @@ -331,6 +353,7 @@ export async function createGCoordinatorServer( const jsonParser = express.json({ limit: '2mb' }); const backupJsonParser = express.json({ limit: '16mb' }); + app.use((req, res, next) => { if (req.path.endsWith('/sftp/upload')) { next(); @@ -621,6 +644,8 @@ export async function createGCoordinatorServer( } }); + await tunnelManager.startProxyServer(); + await new Promise((resolve, reject) => { httpServer.once('error', reject); httpServer.listen(options.port, options.host ?? '0.0.0.0', () => { @@ -659,6 +684,7 @@ export async function createGCoordinatorServer( aiService, wsHub, port: actualPort, + proxyPort: tunnelManager.actualProxyPort, async close() { aiService.close(); backupScheduler.close(); @@ -668,6 +694,7 @@ export async function createGCoordinatorServer( monitoringService.close(); customSystemsEngine.close(); tunnelManager.stopAll(); + await tunnelManager.stopProxyServer(); ptyManager.close(); sshPool.closeAll('shutdown'); authService.close(); diff --git a/src/server/security/auth.ts b/src/server/security/auth.ts index 0c33dd8..76c6928 100644 --- a/src/server/security/auth.ts +++ b/src/server/security/auth.ts @@ -758,7 +758,11 @@ export class AuthService { getSessionByToken(sessionToken: string | undefined): AuthSession | null { if (!sessionToken || sessionToken.length < 16) return null; - const idHash = sha256Hex(sessionToken); + return this.getSessionByHash(sha256Hex(sessionToken)); + } + + getSessionByHash(idHash: string | undefined): AuthSession | null { + if (!idHash || idHash.length < 16) return null; const row = this.db .prepare('SELECT * FROM sessions WHERE id_hash = ?') .get(idHash) as SessionRow | undefined; diff --git a/src/server/security/egress-guard.ts b/src/server/security/egress-guard.ts index aae5c4b..adfec66 100644 --- a/src/server/security/egress-guard.ts +++ b/src/server/security/egress-guard.ts @@ -167,10 +167,14 @@ export function isBlockedByDefaultIp(rawIp: string): boolean { return false; } -export async function assertEgressHostAllowed( +/** + * Validate `rawHost` against Zero-Trust egress CIDR rules and return all + * permitted resolved IP addresses in lookup order. + */ +export async function resolveAllowedEgressIps( rawHost: string, allowedCidrs: string[] = [], -): Promise { +): Promise { const { ip: cleanHost } = stripZoneAndBrackets(rawHost); if (!cleanHost) { throw new EgressBlockedError('Empty egress destination host'); @@ -182,7 +186,7 @@ export async function assertEgressHostAllowed( `Egress to non-public IP "${cleanHost}" is blocked by Zero-Trust egress policy`, ); } - return; + return [cleanHost]; } let records: dns.LookupAddress[]; @@ -198,13 +202,23 @@ export async function assertEgressHostAllowed( throw new EgressBlockedError(`Egress host "${cleanHost}" resolved to no addresses`); } + const ips: string[] = []; for (const rec of records) { if (isBlockedByDefaultIp(rec.address) && !isIpInCidrs(rec.address, allowedCidrs)) { throw new EgressBlockedError( `Egress host "${cleanHost}" resolved to blocked address ${rec.address}`, ); } + ips.push(rec.address); } + return ips; +} + +export async function assertEgressHostAllowed( + rawHost: string, + allowedCidrs: string[] = [], +): Promise { + await resolveAllowedEgressIps(rawHost, allowedCidrs); } export async function assertEgressUrlAllowed( diff --git a/src/server/ssh/tunnel-manager.ts b/src/server/ssh/tunnel-manager.ts index 7da4a9c..dea4a30 100644 --- a/src/server/ssh/tunnel-manager.ts +++ b/src/server/ssh/tunnel-manager.ts @@ -1,15 +1,36 @@ +import crypto from 'node:crypto'; import http, { type IncomingMessage } from 'node:http'; import net, { type Socket } from 'node:net'; import type { Duplex } from 'node:stream'; +import tls from 'node:tls'; import type { Request, Response } from 'express'; import type { Client, TcpConnectionDetails } from 'ssh2'; import type { ServerTunnel } from '../../shared/schemas/server.schema.js'; import type { ConfigManager } from '../config/config-manager.js'; -import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; +import { SESSION_COOKIE_NAME, sha256Hex, type AuthService } from '../security/auth.js'; +import { + assertEgressHostAllowed, + resolveAllowedEgressIps, +} from '../security/egress-guard.js'; import { extractCookies } from '../security/guards.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from './ssh-pool.js'; +export const PROXY_SESSION_COOKIE_NAME = 'gcoord_proxy_sid'; + +export class ProxyIsolationError extends Error { + readonly code = 'PROXY_ISOLATION_NOT_CONFIGURED'; +} + +export interface TunnelManagerOptions { + getRuntimeLimits?: () => RuntimeLimits; + allowLanTunnels?: boolean; + proxyBaseDomain?: string; + proxyPort?: number; + trustCloudflare?: boolean; +} + export interface TunnelRuntimeInfo { key: string; serverId: string; @@ -19,6 +40,7 @@ export interface TunnelRuntimeInfo { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; + expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -34,21 +56,45 @@ interface ActiveTunnelHandle { localBoundHost?: string; localBoundPort?: number; remoteBoundPort?: number; + httpProxyActive?: boolean; activeConnections: number; totalConnections: number; bytesIn: number; bytesOut: number; startedAt: number; + expiresAt?: number; lastError?: string; tcpServer?: net.Server; remoteClient?: Client; + remoteReconnectTimer?: NodeJS.Timeout; + ttlTimer?: NodeJS.Timeout; sockets: Set; + manuallyStopped?: boolean; +} + +interface PendingProxyTicket { + tunnelKey: string; + proxyId: string; + sessionIdHash: string; + expiresAt: number; +} + +interface IsolatedProxySession { + tunnelKey: string; + proxyId: string; + sessionIdHash: string; + expiresAt: number; } function makeTunnelKey(serverId: string, tunnelId: string): string { return `${serverId}--${tunnelId}`; } +function isLoopbackHost(host: string): boolean { + const clean = host.trim().toLowerCase().replace(/^\[|\]$/g, ''); + return clean === '127.0.0.1' || clean === '::1' || clean === 'localhost'; +} + function stripHubCookies(cookieHeader: string | string[] | undefined): string | undefined { if (!cookieHeader) return undefined; const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader; @@ -57,24 +103,186 @@ function stripHubCookies(cookieHeader: string | string[] | undefined): string | .map((part) => part.trim()) .filter((part) => { const name = part.split('=')[0]?.trim(); - return name && name !== SESSION_COOKIE_NAME && name !== 'gcoord_csrf'; + return ( + name && + name !== SESSION_COOKIE_NAME && + name !== 'gcoord_csrf' && + name !== PROXY_SESSION_COOKIE_NAME + ); }); return kept.length > 0 ? kept.join('; ') : undefined; } +function sanitizeOutgoingProxyHeaders( + rawHeaders: IncomingMessage['headers'], + targetHost: string, + targetPort: number, + extra: Record = {}, +): http.OutgoingHttpHeaders { + const headers: http.OutgoingHttpHeaders = {}; + for (const [hKey, hVal] of Object.entries(rawHeaders)) { + if (hVal === undefined) continue; + const lower = hKey.toLowerCase(); + if ( + lower === 'connection' || + lower === 'keep-alive' || + lower === 'transfer-encoding' || + lower === 'upgrade' || + lower === 'host' || + lower === 'proxy-connection' || + lower === 'proxy-authorization' || + lower === 'proxy-authenticate' || + lower === 'te' || + lower === 'trailers' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(hVal); + if (filtered) headers.cookie = filtered; + continue; + } + headers[hKey] = hVal; + } + headers.host = `${targetHost}:${targetPort}`; + for (const [k, v] of Object.entries(extra)) { + headers[k] = v; + } + return headers; +} + +function rewriteSetCookieHeaders( + rawSetCookie: string | string[] | undefined, + baseMountPath: string, +): string[] | undefined { + if (!rawSetCookie) return undefined; + const list = Array.isArray(rawSetCookie) ? rawSetCookie : [rawSetCookie]; + const scopedPath = baseMountPath ? `${baseMountPath}/` : '/'; + return list.map((line) => { + const parts = line + .split(';') + .map((p) => p.trim()) + .filter((p) => !/^domain=/i.test(p) && !/^path=/i.test(p)); + parts.push(`Path=${scopedPath}`); + return parts.join('; '); + }); +} + +function rewriteRedirectLocation( + loc: string, + baseMountPath: string, + tunnel: ServerTunnel, +): string { + if (!baseMountPath) { + const originHttp = `http://${tunnel.targetHost}:${tunnel.targetPort}`; + const originHttps = `https://${tunnel.targetHost}:${tunnel.targetPort}`; + if (loc.startsWith(originHttp)) return loc.slice(originHttp.length) || '/'; + if (loc.startsWith(originHttps)) return loc.slice(originHttps.length) || '/'; + return loc; + } + if (loc.startsWith('/') && !loc.startsWith('//')) { + if (loc === baseMountPath || loc.startsWith(`${baseMountPath}/`)) { + return loc; + } + return `${baseMountPath}${loc}`; + } + const targetOrigin = `${tunnel.targetProtocol ?? 'http'}://${tunnel.targetHost}:${tunnel.targetPort}`; + if (loc.startsWith(targetOrigin)) { + const rest = loc.slice(targetOrigin.length) || '/'; + return `${baseMountPath}${rest.startsWith('/') ? rest : `/${rest}`}`; + } + return loc; +} + +export function extractSubdomainTunnel( + hostHeader: string | undefined, + proxyBaseDomain: string | undefined, +): string | null { + if (!hostHeader || !proxyBaseDomain) return null; + const base = proxyBaseDomain.trim().toLowerCase().replace(/^\./, ''); + if (!base) return null; + const hostOnly = hostHeader.trim().toLowerCase().split(':')[0] ?? ''; + const suffix = `.${base}`; + if (!hostOnly.endsWith(suffix)) return null; + const sub = hostOnly.slice(0, -suffix.length); + if (!sub || sub.includes('.') || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(sub)) { + return null; + } + return sub; +} + export class TunnelManager { private readonly active = new Map(); private readonly remoteDispatch = new WeakMap< Client, Map Duplex, reject: () => void) => void> >(); + private readonly pendingTickets = new Map(); + private readonly proxySessions = new Map(); + private proxyHttpServer: http.Server | null = null; + private boundProxyPort: number | undefined; + private readonly getRuntimeLimits?: () => RuntimeLimits; + private readonly allowLanTunnels: boolean; + private readonly proxyBaseDomain?: string; + private readonly configuredProxyPort?: number; + private readonly trustCloudflare: boolean; constructor( private readonly sshPool: SSHPool, private readonly configManager: ConfigManager, private readonly vaultService: VaultService, private readonly authService: AuthService, - ) {} + options: TunnelManagerOptions = {}, + ) { + this.getRuntimeLimits = options.getRuntimeLimits; + this.allowLanTunnels = Boolean(options.allowLanTunnels); + this.proxyBaseDomain = options.proxyBaseDomain?.trim().toLowerCase() || undefined; + this.configuredProxyPort = options.proxyPort; + this.trustCloudflare = Boolean(options.trustCloudflare); + } + + get actualProxyPort(): number | undefined { + return this.boundProxyPort; + } + + get baseDomain(): string | undefined { + return this.proxyBaseDomain; + } + + async startProxyServer(): Promise { + if (this.configuredProxyPort === undefined) return undefined; + if (this.proxyHttpServer) return this.boundProxyPort; + + const srv = http.createServer((req, res) => { + this.handleDedicatedProxyPortHttp(req, res); + }); + srv.on('upgrade', (req, socket, head) => { + this.handleDedicatedProxyPortWs(req, socket, head); + }); + + const bindHost = this.allowLanTunnels ? '0.0.0.0' : '127.0.0.1'; + await new Promise((resolve, reject) => { + srv.once('error', reject); + srv.listen(this.configuredProxyPort!, bindHost, () => { + srv.off('error', reject); + resolve(); + }); + }); + + this.proxyHttpServer = srv; + const addr = srv.address(); + this.boundProxyPort = + typeof addr === 'object' && addr ? addr.port : this.configuredProxyPort; + return this.boundProxyPort; + } + + async stopProxyServer(): Promise { + if (!this.proxyHttpServer) return; + const srv = this.proxyHttpServer; + this.proxyHttpServer = null; + this.boundProxyPort = undefined; + await new Promise((resolve) => srv.close(() => resolve())); + } listTunnels(): TunnelRuntimeInfo[] { const out: TunnelRuntimeInfo[] = []; @@ -134,13 +342,14 @@ export class TunnelManager { if (tunnel.mode === 'remote-tcp') { return this.startRemoteTunnel(serverId, tunnel); } - return this.startLocalListenerTunnel(serverId, tunnel); + return this.startLocalOrHttpTunnel(serverId, tunnel); } async stopTunnel(serverId: string, tunnelId: string): Promise { const key = makeTunnelKey(serverId, tunnelId); const handle = this.active.get(key); if (!handle) return false; + handle.manuallyStopped = true; this.active.delete(key); await this.teardownHandle(handle); return true; @@ -149,6 +358,7 @@ export class TunnelManager { stopServerTunnels(serverId: string): void { for (const [key, handle] of this.active.entries()) { if (handle.serverId === serverId) { + handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } @@ -157,19 +367,22 @@ export class TunnelManager { stopAll(): void { for (const [key, handle] of this.active.entries()) { + handle.manuallyStopped = true; this.active.delete(key); void this.teardownHandle(handle); } + this.pendingTickets.clear(); + this.proxySessions.clear(); } resolveProxyTarget(idOrKey: string): TunnelRuntimeInfo | undefined { const direct = this.active.get(idOrKey); - if (direct && direct.tunnel.mode === 'http-proxy' && direct.localBoundPort) { + if (direct && direct.tunnel.mode === 'http-proxy' && direct.httpProxyActive) { return this.toRuntimeInfo(direct.serverId, direct.tunnel, direct); } const matches = [...this.active.values()].filter( - (h) => h.tunnel.mode === 'http-proxy' && h.localBoundPort && h.tunnel.id === idOrKey, + (h) => h.tunnel.mode === 'http-proxy' && h.httpProxyActive && h.tunnel.id === idOrKey, ); if (matches.length === 1) { const m = matches[0]!; @@ -178,9 +391,311 @@ export class TunnelManager { return undefined; } + issueProxyTicket( + sessionIdHash: string, + serverId: string, + tunnelId: string, + reqMeta: { host?: string; protocol?: string }, + ): { + ticket?: string; + launchUrl: string; + mode: 'subdomain' | 'port' | 'same-origin'; + expiresInSec: number; + } { + const key = makeTunnelKey(serverId, tunnelId); + const live = this.active.get(key); + if (!live || live.tunnel.mode !== 'http-proxy' || !live.httpProxyActive) { + throw new Error(`HTTP proxy tunnel "${tunnelId}" on "${serverId}" is not active`); + } + + this.sweepProxyAuthState(); + const proxyId = this.computeProxyId(serverId, live.tunnel); + const proto = reqMeta.protocol === 'https' || this.trustCloudflare ? 'https' : 'http'; + const rawHostOnly = (reqMeta.host ?? '127.0.0.1').split(':')[0]?.trim() || '127.0.0.1'; + + if (this.proxyBaseDomain) { + const ticket = crypto.randomBytes(24).toString('base64url'); + this.pendingTickets.set(sha256Hex(ticket), { + tunnelKey: key, + proxyId, + sessionIdHash, + expiresAt: Date.now() + 30_000, + }); + return { + ticket, + launchUrl: `${proto}://${proxyId}.${this.proxyBaseDomain}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, + mode: 'subdomain', + expiresInSec: 30, + }; + } + + if (this.boundProxyPort !== undefined) { + const ticket = crypto.randomBytes(24).toString('base64url'); + this.pendingTickets.set(sha256Hex(ticket), { + tunnelKey: key, + proxyId, + sessionIdHash, + expiresAt: Date.now() + 30_000, + }); + return { + ticket, + launchUrl: `http://${rawHostOnly}:${this.boundProxyPort}/__gcoord_ticket?ticket=${encodeURIComponent(ticket)}`, + mode: 'port', + expiresInSec: 30, + }; + } + + if (this.configManager.getSettings().security.allowSameOriginProxy) { + return { + launchUrl: `/proxy/${encodeURIComponent(proxyId)}/`, + mode: 'same-origin', + expiresInSec: 0, + }; + } + + throw new ProxyIsolationError( + 'Same-origin /proxy is disabled. Configure GCOORD_PROXY_BASE_DOMAIN or GCOORD_PROXY_PORT, or explicitly enable security.allowSameOriginProxy.', + ); + } + + private redeemTicket( + ticket: string, + expectedProxyId?: string, + ): { proxySid: string; redirectPath: string } | null { + this.sweepProxyAuthState(); + if (!ticket) return null; + const hash = sha256Hex(ticket); + const entry = this.pendingTickets.get(hash); + if (!entry) return null; + this.pendingTickets.delete(hash); + if (entry.expiresAt <= Date.now()) return null; + if (expectedProxyId && entry.proxyId !== expectedProxyId) return null; + if (!this.authService.getSessionByHash(entry.sessionIdHash)) return null; + + const proxySid = crypto.randomBytes(32).toString('base64url'); + this.proxySessions.set(sha256Hex(proxySid), { + tunnelKey: entry.tunnelKey, + proxyId: entry.proxyId, + sessionIdHash: entry.sessionIdHash, + expiresAt: Date.now() + 12 * 60 * 60 * 1000, + }); + return { + proxySid, + redirectPath: expectedProxyId ? '/' : `/proxy/${encodeURIComponent(entry.proxyId)}/`, + }; + } + + private resolveIsolatedSession( + req: IncomingMessage, + expectedProxyIdOrKey: string, + ): { safeMode: boolean; target: TunnelRuntimeInfo; live: ActiveTunnelHandle } | { errorStatus: number; code: string } { + this.sweepProxyAuthState(); + const cookies = extractCookies(req.headers.cookie); + const proxySid = cookies[PROXY_SESSION_COOKIE_NAME]; + if (!proxySid) { + return { errorStatus: 401, code: 'PROXY_AUTH_REQUIRED' }; + } + const sess = this.proxySessions.get(sha256Hex(proxySid)); + if (!sess || sess.expiresAt <= Date.now()) { + this.proxySessions.delete(sha256Hex(proxySid)); + return { errorStatus: 401, code: 'PROXY_SESSION_EXPIRED' }; + } + const authSess = this.authService.getSessionByHash(sess.sessionIdHash); + if (!authSess) { + this.proxySessions.delete(sha256Hex(proxySid)); + return { errorStatus: 401, code: 'HUB_SESSION_REVOKED' }; + } + const target = this.resolveProxyTarget(expectedProxyIdOrKey); + const live = target ? this.active.get(target.key) : undefined; + if (!target || !live || target.key !== sess.tunnelKey) { + return { errorStatus: 403, code: 'PROXY_TUNNEL_SCOPE_MISMATCH' }; + } + return { safeMode: authSess.safeMode, target, live }; + } + + private sweepProxyAuthState(): void { + const now = Date.now(); + for (const [k, v] of this.pendingTickets.entries()) { + if (v.expiresAt <= now) this.pendingTickets.delete(k); + } + if (this.pendingTickets.size > 500) { + for (const k of [...this.pendingTickets.keys()].slice(0, this.pendingTickets.size - 500)) { + this.pendingTickets.delete(k); + } + } + for (const [k, v] of this.proxySessions.entries()) { + if (v.expiresAt <= now) this.proxySessions.delete(k); + } + } + + private handleDedicatedProxyPortHttp(req: IncomingMessage, res: Response | http.ServerResponse): void { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('Referrer-Policy', 'no-referrer'); + const urlObj = new URL(req.url ?? '/', 'http://127.0.0.1'); + + if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { + const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? ''); + if (!redeemed) { + res.writeHead(401, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: 'INVALID_OR_EXPIRED_TICKET' })); + return; + } + res.writeHead(302, { + Location: redeemed.redirectPath, + 'Cache-Control': 'no-store', + 'Set-Cookie': `${PROXY_SESSION_COOKIE_NAME}=${redeemed.proxySid}; HttpOnly; SameSite=Lax; Path=/`, + }); + res.end(); + return; + } + + const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); + if (!match) { + res.writeHead(404, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'NOT_FOUND' })); + return; + } + + const idOrKey = decodeURIComponent(match[1]!); + const authRes = this.resolveIsolatedSession(req, idOrKey); + if ('errorStatus' in authRes) { + res.writeHead(authRes.errorStatus, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }); + res.end(JSON.stringify({ error: authRes.code })); + return; + } + + const method = (req.method ?? 'GET').toUpperCase(); + if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { + res.writeHead(423, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'SAFE_MODE_ACTIVE' })); + return; + } + + const subPath = `${match[2] || '/'}${urlObj.search}`; + void this.forwardHttpStream(req, res, authRes.target, authRes.live, subPath, `/proxy/${idOrKey}`); + } + + private handleDedicatedProxyPortWs(req: IncomingMessage, socket: Duplex, head: Buffer): void { + const urlObj = new URL(req.url ?? '/', `http://${req.headers.host ?? '127.0.0.1'}`); + const origin = req.headers.origin; + const host = req.headers.host; + if (origin) { + try { + const u = new URL(origin); + if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + + const match = /^\/proxy\/([^/]+)(\/.*)?$/.exec(urlObj.pathname); + if (!match) { + socket.write('HTTP/1.1 404 Not Found\r\n\r\n'); + socket.destroy(); + return; + } + const idOrKey = decodeURIComponent(match[1]!); + const authRes = this.resolveIsolatedSession(req, idOrKey); + if ('errorStatus' in authRes) { + socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); + socket.destroy(); + return; + } + if (authRes.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + const subPath = `${match[2] || '/'}${urlObj.search}`; + void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, subPath); + } + + handleSubdomainProxyHttp(req: Request, res: Response, tunnelSub: string): void { + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('Referrer-Policy', 'no-referrer'); + const urlObj = new URL(req.originalUrl, 'http://localhost'); + + if (urlObj.pathname === '/__gcoord_ticket' && req.method === 'GET') { + const redeemed = this.redeemTicket(urlObj.searchParams.get('ticket') ?? '', tunnelSub); + if (!redeemed) { + res.status(401).json({ error: 'INVALID_OR_EXPIRED_TICKET' }); + return; + } + const secure = Boolean(this.trustCloudflare || req.secure); + res.cookie(PROXY_SESSION_COOKIE_NAME, redeemed.proxySid, { + httpOnly: true, + sameSite: 'lax', + secure, + path: '/', + }); + res.redirect(302, '/'); + return; + } + + const authRes = this.resolveIsolatedSession(req, tunnelSub); + if ('errorStatus' in authRes) { + res.status(authRes.errorStatus).json({ error: authRes.code }); + return; + } + + const method = req.method.toUpperCase(); + if (authRes.safeMode && method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { + res.status(423).json({ error: 'SAFE_MODE_ACTIVE' }); + return; + } + + void this.forwardHttpStream(req, res, authRes.target, authRes.live, req.originalUrl, ''); + } + + handleSubdomainProxyWs(req: IncomingMessage, socket: Duplex, head: Buffer, tunnelSub: string): void { + const origin = req.headers.origin; + const host = req.headers.host; + if (origin) { + try { + const u = new URL(origin); + if (!host || u.host !== host || (u.protocol !== 'http:' && u.protocol !== 'https:')) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } catch { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + } + const authRes = this.resolveIsolatedSession(req, tunnelSub); + if ('errorStatus' in authRes) { + socket.write(`HTTP/1.1 ${authRes.errorStatus} Unauthorized\r\n\r\n`); + socket.destroy(); + return; + } + if (authRes.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + void this.forwardWsStream(req, socket, head, authRes.target, authRes.live, req.url ?? '/'); + } + handleHttpProxy(req: Request, res: Response, idOrKey: string, subPath: string): void { + if (!this.configManager.getSettings().security.allowSameOriginProxy) { + res.status(403).json({ + error: 'PROXY_ORIGIN_ISOLATION_REQUIRED', + message: 'Same-origin /proxy is disabled by default; launch via /proxy-ticket or enable security.allowSameOriginProxy.', + }); + return; + } + const target = this.resolveProxyTarget(idOrKey); - if (!target || !target.localBoundPort) { + const live = target ? this.active.get(target.key) : undefined; + if (!target || !live || !live.httpProxyActive) { res.status(502).json({ error: 'TUNNEL_NOT_ACTIVE', message: `HTTP proxy tunnel "${idOrKey}" is not active`, @@ -188,64 +703,8 @@ export class TunnelManager { return; } - const live = this.active.get(target.key); - const qsIndex = req.originalUrl.indexOf('?'); - const qs = qsIndex >= 0 ? req.originalUrl.slice(qsIndex) : ''; - const upstreamPath = `${subPath.startsWith('/') ? subPath : `/${subPath}`}${qs}`; - - const headers: http.OutgoingHttpHeaders = {}; - for (const [hKey, hVal] of Object.entries(req.headers)) { - if (hVal === undefined) continue; - const lower = hKey.toLowerCase(); - if ( - lower === 'connection' || - lower === 'keep-alive' || - lower === 'transfer-encoding' || - lower === 'upgrade' || - lower === 'host' - ) { - continue; - } - if (lower === 'cookie') { - const filtered = stripHubCookies(hVal); - if (filtered) headers.cookie = filtered; - continue; - } - headers[hKey] = hVal; - } - headers.host = `${target.tunnel.targetHost}:${target.tunnel.targetPort}`; - headers['x-forwarded-host'] = req.headers.host ?? ''; - headers['x-forwarded-proto'] = req.protocol; - headers['x-forwarded-prefix'] = `/proxy/${idOrKey}`; - - const proxyReq = http.request( - { - host: '127.0.0.1', - port: target.localBoundPort, - method: req.method, - path: upstreamPath, - headers, - }, - (proxyRes) => { - const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; - if (typeof resHeaders.location === 'string' && resHeaders.location.startsWith('/')) { - resHeaders.location = `/proxy/${idOrKey}${resHeaders.location}`; - } - res.writeHead(proxyRes.statusCode ?? 502, resHeaders); - proxyRes.pipe(res); - }, - ); - - proxyReq.on('error', (err) => { - if (live) live.lastError = err.message; - if (!res.headersSent) { - res.status(502).json({ error: 'UPSTREAM_PROXY_ERROR', message: err.message }); - } else { - res.end(); - } - }); - - req.pipe(proxyReq); + const cleanSub = subPath.startsWith('/') ? subPath : `/${subPath}`; + void this.forwardHttpStream(req, res, target, live, cleanSub, `/proxy/${idOrKey}`); } handleWsProxyUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { @@ -260,9 +719,14 @@ export class TunnelManager { const origin = req.headers.origin; const host = req.headers.host; - if (origin && host) { + if (origin) { try { - if (new URL(origin).host !== host) { + const originUrl = new URL(origin); + if ( + !host || + originUrl.host !== host || + (originUrl.protocol !== 'http:' && originUrl.protocol !== 'https:') + ) { socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); socket.destroy(); return; @@ -282,69 +746,337 @@ export class TunnelManager { return; } + if (!this.configManager.getSettings().security.allowSameOriginProxy) { + socket.write('HTTP/1.1 403 Forbidden\r\n\r\n'); + socket.destroy(); + return; + } + + if (session.safeMode) { + socket.write('HTTP/1.1 423 Locked\r\n\r\n'); + socket.destroy(); + return; + } + const idOrKey = decodeURIComponent(match[1]!); - const subPath = match[2] || '/'; + const subPath = `${match[2] || '/'}${parsedUrl.search}`; const target = this.resolveProxyTarget(idOrKey); const live = target ? this.active.get(target.key) : undefined; - if (!target || !live || !target.localBoundPort) { + if (!target || !live || !live.httpProxyActive) { socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); socket.destroy(); return; } - const upstreamPath = `${subPath}${parsedUrl.search}`; - const upstream = net.connect(target.localBoundPort, '127.0.0.1', () => { - const headerLines: string[] = [ - `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, - `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, - ]; - for (const [k, v] of Object.entries(req.headers)) { - if (v === undefined) continue; - const lower = k.toLowerCase(); - if (lower === 'host') continue; - if (lower === 'cookie') { - const filtered = stripHubCookies(v); - if (filtered) headerLines.push(`Cookie: ${filtered}`); - continue; - } - const vals = Array.isArray(v) ? v : [v]; - for (const item of vals) { - headerLines.push(`${k}: ${item}`); - } - } - upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); - if (head.length > 0) upstream.write(head); + void this.forwardWsStream(req, socket, head, target, live, subPath); + } - live.sockets.add(socket); - live.sockets.add(upstream); - socket.pipe(upstream); - upstream.pipe(socket); + private getGlobalActiveConnections(): number { + let total = 0; + for (const h of this.active.values()) total += h.activeConnections; + return total; + } + + private canAcceptSocket(handle: ActiveTunnelHandle): boolean { + const limits = this.getRuntimeLimits?.(); + const perTunnel = limits?.maxTunnelSocketsPerTunnel ?? 64; + const globalMax = limits?.maxGlobalTunnelSockets ?? 256; + return ( + handle.activeConnections < perTunnel && + this.getGlobalActiveConnections() < globalMax + ); + } + + private async forwardHttpStream( + req: IncomingMessage, + res: Response | http.ServerResponse, + target: TunnelRuntimeInfo, + live: ActiveTunnelHandle, + upstreamPath: string, + baseMountPath: string, + ): Promise { + if (!this.canAcceptSocket(live)) { + res.writeHead(503, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'TUNNEL_SOCKET_LIMIT_REACHED' })); + return; + } + + let sshStream: Duplex; + try { + sshStream = await this.sshPool.forwardOutStream( + live.serverId, + target.tunnel.targetHost, + target.tunnel.targetPort, + ); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + live.lastError = msg; + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: msg })); + } + return; + } + + live.activeConnections += 1; + live.totalConnections += 1; + live.sockets.add(sshStream); + + let decremented = false; + const markClosed = () => { + live.sockets.delete(sshStream); + if (!decremented) { + decremented = true; + live.activeConnections = Math.max(0, live.activeConnections - 1); + } + }; + sshStream.once('close', markClosed); + // Prevent unhandled 'error' events if raw SSH channel errors during TLS wrap or teardown. + sshStream.on('error', () => undefined); + + const headers = sanitizeOutgoingProxyHeaders( + req.headers, + target.tunnel.targetHost, + target.tunnel.targetPort, + { + 'x-forwarded-host': String(req.headers.host ?? ''), + 'x-forwarded-proto': this.trustCloudflare ? 'https' : 'http', + ...(baseMountPath ? { 'x-forwarded-prefix': baseMountPath } : {}), + }, + ); + + const useHttps = target.tunnel.targetProtocol === 'https'; + const serverName = + target.tunnel.tlsServerName || + (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); + + const createConnection = (): Duplex => { + if (!useHttps) return sshStream; + const tlsSock = tls.connect({ + socket: sshStream, + servername: serverName, + rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, + }); + live.sockets.add(tlsSock); + tlsSock.once('close', () => live.sockets.delete(tlsSock)); + return tlsSock; + }; + + const agent = new http.Agent({ keepAlive: false }); + (agent as unknown as { createConnection: () => Duplex }).createConnection = createConnection; + + const reqOpts: http.RequestOptions = { + method: req.method, + path: upstreamPath.startsWith('/') ? upstreamPath : `/${upstreamPath}`, + headers, + agent, + }; + + const proxyReq = http.request(reqOpts, (proxyRes) => { + const resHeaders: http.OutgoingHttpHeaders = { ...proxyRes.headers }; + delete resHeaders['proxy-authenticate']; + delete resHeaders['proxy-connection']; + if (typeof resHeaders.location === 'string') { + resHeaders.location = rewriteRedirectLocation( + resHeaders.location, + baseMountPath, + target.tunnel, + ); + } + const rewrittenCookies = rewriteSetCookieHeaders(resHeaders['set-cookie'], baseMountPath); + if (rewrittenCookies) { + resHeaders['set-cookie'] = rewrittenCookies; + } + + res.writeHead(proxyRes.statusCode ?? 502, resHeaders); + proxyRes.on('data', (chunk: Buffer) => { + live.bytesIn += chunk.length; + }); + proxyRes.pipe(res); }); + req.on('data', (chunk: Buffer) => { + live.bytesOut += chunk.length; + }); + + proxyReq.on('error', (err) => { + live.lastError = err.message; + markClosed(); + if (!res.headersSent) { + res.writeHead(502, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ error: 'UPSTREAM_PROXY_ERROR', message: err.message })); + } else { + res.end(); + } + }); + + res.once('close', () => { + if (!res.writableEnded) { + proxyReq.destroy(); + sshStream.destroy(); + } + }); + + req.pipe(proxyReq); + } + + private async forwardWsStream( + req: IncomingMessage, + socket: Duplex, + head: Buffer, + target: TunnelRuntimeInfo, + live: ActiveTunnelHandle, + upstreamPath: string, + ): Promise { + if (!this.canAcceptSocket(live)) { + socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n'); + socket.destroy(); + return; + } + + let sshStream: Duplex; + try { + sshStream = await this.sshPool.forwardOutStream( + live.serverId, + target.tunnel.targetHost, + target.tunnel.targetPort, + ); + } catch (err) { + live.lastError = err instanceof Error ? err.message : String(err); + socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + socket.destroy(); + return; + } + + let upstream: Duplex = sshStream; + if (target.tunnel.targetProtocol === 'https') { + const serverName = + target.tunnel.tlsServerName || + (!net.isIP(target.tunnel.targetHost) ? target.tunnel.targetHost : undefined); + try { + upstream = await new Promise((resolve, reject) => { + const tSock = tls.connect( + { + socket: sshStream, + servername: serverName, + rejectUnauthorized: target.tunnel.tlsRejectUnauthorized ?? true, + }, + () => resolve(tSock), + ); + tSock.once('error', reject); + }); + } catch (err) { + live.lastError = err instanceof Error ? err.message : String(err); + sshStream.destroy(); + socket.write('HTTP/1.1 502 Bad Gateway\r\n\r\n'); + socket.destroy(); + return; + } + } + + const headerLines: string[] = [ + `${req.method ?? 'GET'} ${upstreamPath} HTTP/1.1`, + `Host: ${target.tunnel.targetHost}:${target.tunnel.targetPort}`, + ]; + for (const [k, v] of Object.entries(req.headers)) { + if (v === undefined) continue; + const lower = k.toLowerCase(); + if ( + lower === 'host' || + lower === 'proxy-authorization' || + lower === 'proxy-connection' + ) { + continue; + } + if (lower === 'cookie') { + const filtered = stripHubCookies(v); + if (filtered) headerLines.push(`Cookie: ${filtered}`); + continue; + } + const vals = Array.isArray(v) ? v : [v]; + for (const item of vals) { + headerLines.push(`${k}: ${item}`); + } + } + + live.activeConnections += 1; + live.totalConnections += 1; + live.sockets.add(socket); + live.sockets.add(upstream); + + let cleaned = false; const cleanup = () => { + if (cleaned) return; + cleaned = true; live.sockets.delete(socket); live.sockets.delete(upstream); socket.destroy(); upstream.destroy(); + if (upstream !== sshStream) sshStream.destroy(); + live.activeConnections = Math.max(0, live.activeConnections - 1); }; + + socket.on('data', (c: Buffer) => { + live.bytesOut += c.length; + }); + upstream.on('data', (c: Buffer) => { + live.bytesIn += c.length; + }); + + upstream.write(`${headerLines.join('\r\n')}\r\n\r\n`); + if (head.length > 0) upstream.write(head); + + socket.pipe(upstream); + upstream.pipe(socket); upstream.on('error', cleanup); upstream.on('close', cleanup); socket.on('error', cleanup); socket.on('close', cleanup); } - private async startLocalListenerTunnel( + private scheduleTtl(handle: ActiveTunnelHandle): void { + if (!handle.tunnel.ttlSec) return; + const ttlMs = handle.tunnel.ttlSec * 1000; + handle.expiresAt = Date.now() + ttlMs; + handle.ttlTimer = setTimeout(() => { + void this.stopTunnel(handle.serverId, handle.tunnel.id); + }, ttlMs); + handle.ttlTimer.unref(); + } + + private async startLocalOrHttpTunnel( serverId: string, tunnel: ServerTunnel, ): Promise { - // Verify SSH reachability upfront so callers get immediate handshake/TOFU/vault feedback await this.sshPool.acquireClient(serverId); - - const bindHost = - tunnel.mode === 'http-proxy' ? '127.0.0.1' : tunnel.bindHost ?? '127.0.0.1'; - const bindPort = tunnel.mode === 'http-proxy' ? 0 : tunnel.bindPort ?? 0; const key = makeTunnelKey(serverId, tunnel.id); + if (tunnel.mode === 'http-proxy') { + const handle: ActiveTunnelHandle = { + key, + serverId, + tunnel, + httpProxyActive: true, + activeConnections: 0, + totalConnections: 0, + bytesIn: 0, + bytesOut: 0, + startedAt: Date.now(), + sockets: new Set(), + }; + this.scheduleTtl(handle); + this.active.set(key, handle); + return this.toRuntimeInfo(serverId, tunnel, handle); + } + + const bindHost = tunnel.bindHost ?? '127.0.0.1'; + if (!this.allowLanTunnels && !isLoopbackHost(bindHost)) { + throw new Error( + `Non-loopback bindHost "${bindHost}" requires GCOORD_ALLOW_LAN_TUNELS=true`, + ); + } + const bindPort = tunnel.bindPort ?? 0; + const handle: ActiveTunnelHandle = { key, serverId, @@ -359,7 +1091,11 @@ export class TunnelManager { }; const tcpServer = net.createServer((clientSocket: Socket) => { - this.bridgeLocalSocket(handle, clientSocket); + if (tunnel.mode === 'socks5') { + this.bridgeSocks5Socket(handle, clientSocket); + } else { + this.bridgeLocalSocket(handle, clientSocket); + } }); handle.tcpServer = tcpServer; @@ -379,11 +1115,163 @@ export class TunnelManager { handle.lastError = err.message; }); + this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } + private bridgeSocks5Socket(handle: ActiveTunnelHandle, clientSocket: Socket): void { + if (!this.canAcceptSocket(handle)) { + clientSocket.destroy(); + return; + } + + handle.activeConnections += 1; + handle.totalConnections += 1; + handle.sockets.add(clientSocket); + + let decremented = false; + const closeSocket = () => { + handle.sockets.delete(clientSocket); + clientSocket.destroy(); + if (!decremented) { + decremented = true; + handle.activeConnections = Math.max(0, handle.activeConnections - 1); + } + }; + + let stage: 'greeting' | 'request' | 'connected' = 'greeting'; + let buf = Buffer.alloc(0); + + const sendSocksError = (rep: number) => { + try { + clientSocket.write(Buffer.from([0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); + } catch { + // Ignore write error + } + closeSocket(); + }; + + const onData = (chunk: Buffer) => { + if (stage === 'connected') return; + buf = Buffer.concat([buf, chunk]); + if (buf.length > 1024) { + closeSocket(); + return; + } + + if (stage === 'greeting') { + if (buf.length < 2) return; + const ver = buf[0]!; + const nMethods = buf[1]!; + if (ver !== 0x05) { + closeSocket(); + return; + } + if (buf.length < 2 + nMethods) return; + const methods = buf.subarray(2, 2 + nMethods); + buf = buf.subarray(2 + nMethods); + if (!methods.includes(0x00)) { + clientSocket.write(Buffer.from([0x05, 0xff])); + closeSocket(); + return; + } + clientSocket.write(Buffer.from([0x05, 0x00])); + stage = 'request'; + } + + if (stage === 'request') { + if (buf.length < 4) return; + const ver = buf[0]!; + const cmd = buf[1]!; + const atyp = buf[3]!; + if (ver !== 0x05 || cmd !== 0x01) { + sendSocksError(0x07); + return; + } + + let dstHost = ''; + let offset = 4; + if (atyp === 0x01) { + if (buf.length < offset + 4 + 2) return; + dstHost = `${buf[offset]!}.${buf[offset + 1]!}.${buf[offset + 2]!}.${buf[offset + 3]!}`; + offset += 4; + } else if (atyp === 0x03) { + if (buf.length < offset + 1) return; + const len = buf[offset]!; + offset += 1; + if (buf.length < offset + len + 2) return; + dstHost = buf.subarray(offset, offset + len).toString('utf8'); + offset += len; + } else if (atyp === 0x04) { + if (buf.length < offset + 16 + 2) return; + const parts: string[] = []; + for (let i = 0; i < 16; i += 2) { + parts.push(buf.readUInt16BE(offset + i).toString(16)); + } + dstHost = parts.join(':'); + offset += 16; + } else { + sendSocksError(0x08); + return; + } + + const dstPort = buf.readUInt16BE(offset); + const remaining = buf.subarray(offset + 2); + stage = 'connected'; + clientSocket.off('data', onData); + + this.sshPool + .forwardOutStream(handle.serverId, dstHost, dstPort) + .then((sshStream) => { + if (clientSocket.destroyed || !this.active.has(handle.key)) { + sshStream.destroy(); + closeSocket(); + return; + } + handle.sockets.add(sshStream); + clientSocket.write(Buffer.from([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0])); + if (remaining.length > 0) { + sshStream.write(remaining); + handle.bytesOut += remaining.length; + } + clientSocket.on('data', (c: Buffer) => { + handle.bytesOut += c.length; + }); + sshStream.on('data', (c: Buffer) => { + handle.bytesIn += c.length; + }); + clientSocket.pipe(sshStream); + sshStream.pipe(clientSocket); + + const cleanup = () => { + handle.sockets.delete(sshStream); + sshStream.destroy(); + closeSocket(); + }; + sshStream.once('close', cleanup); + sshStream.once('error', cleanup); + clientSocket.once('close', cleanup); + clientSocket.once('error', cleanup); + }) + .catch((err) => { + handle.lastError = err instanceof Error ? err.message : String(err); + sendSocksError(0x05); + }); + } + }; + + clientSocket.on('data', onData); + clientSocket.once('error', closeSocket); + clientSocket.once('close', closeSocket); + } + private bridgeLocalSocket(handle: ActiveTunnelHandle, clientSocket: Socket): void { + if (!this.canAcceptSocket(handle)) { + clientSocket.destroy(); + return; + } + handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(clientSocket); @@ -440,6 +1328,9 @@ export class TunnelManager { serverId: string, tunnel: ServerTunnel, ): Promise { + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + await assertEgressHostAllowed(tunnel.targetHost, allowedCidrs); + const client = await this.sshPool.acquireClient(serverId); const bindHost = tunnel.bindHost ?? '127.0.0.1'; const bindPort = tunnel.bindPort ?? 0; @@ -484,47 +1375,92 @@ export class TunnelManager { }); handle.remoteBoundPort = actualPort; - portMap.set(actualPort, (_details, accept, _reject) => { + portMap.set(actualPort, (_details, accept, reject) => { + if (!this.canAcceptSocket(handle)) { + reject(); + return; + } + const channel = accept(); handle.activeConnections += 1; handle.totalConnections += 1; handle.sockets.add(channel); - const targetSock = net.connect(tunnel.targetPort, tunnel.targetHost); - handle.sockets.add(targetSock); - let decremented = false; - const cleanup = () => { + const cleanupBase = () => { handle.sockets.delete(channel); - handle.sockets.delete(targetSock); channel.destroy(); - targetSock.destroy(); if (!decremented) { decremented = true; handle.activeConnections = Math.max(0, handle.activeConnections - 1); } }; - channel.on('data', (chunk: Buffer) => { - handle.bytesIn += chunk.length; - }); - targetSock.on('data', (chunk: Buffer) => { - handle.bytesOut += chunk.length; - }); + const curCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + resolveAllowedEgressIps(tunnel.targetHost, curCidrs) + .then((resolvedIps: string[]) => { + if (!this.active.has(handle.key)) { + cleanupBase(); + return; + } + const targetSock = net.connect(tunnel.targetPort, resolvedIps[0]!); + handle.sockets.add(targetSock); - channel.pipe(targetSock); - targetSock.pipe(channel); - channel.once('close', cleanup); - channel.once('error', cleanup); - targetSock.once('close', cleanup); - targetSock.once('error', cleanup); + const cleanupAll = () => { + handle.sockets.delete(targetSock); + targetSock.destroy(); + cleanupBase(); + }; + + channel.on('data', (chunk: Buffer) => { + handle.bytesIn += chunk.length; + }); + targetSock.on('data', (chunk: Buffer) => { + handle.bytesOut += chunk.length; + }); + + channel.pipe(targetSock); + targetSock.pipe(channel); + channel.once('close', cleanupAll); + channel.once('error', cleanupAll); + targetSock.once('close', cleanupAll); + targetSock.once('error', cleanupAll); + }) + .catch((err: unknown) => { + handle.lastError = err instanceof Error ? err.message : String(err); + cleanupBase(); + }); }); + client.once('close', () => { + if (this.active.get(key) === handle && !handle.manuallyStopped) { + this.active.delete(key); + void this.teardownHandle(handle); + if (tunnel.autoStart && this.vaultService.isRuntimeReady) { + const timer = setTimeout(() => { + void this.startTunnel(serverId, tunnel.id).catch(() => undefined); + }, 5_000); + timer.unref(); + handle.remoteReconnectTimer = timer; + } + } + }); + + this.scheduleTtl(handle); this.active.set(key, handle); return this.toRuntimeInfo(serverId, tunnel, handle); } private async teardownHandle(handle: ActiveTunnelHandle): Promise { + if (handle.ttlTimer) { + clearTimeout(handle.ttlTimer); + handle.ttlTimer = undefined; + } + if (handle.remoteReconnectTimer) { + clearTimeout(handle.remoteReconnectTimer); + handle.remoteReconnectTimer = undefined; + } + for (const sock of handle.sockets) { try { sock.destroy(); @@ -550,17 +1486,22 @@ export class TunnelManager { } } + private computeProxyId(serverId: string, tunnel: ServerTunnel): string { + const key = makeTunnelKey(serverId, tunnel.id); + const sameIdCount = this.configManager + .listServers() + .flatMap((s) => s.tunnels) + .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; + return sameIdCount <= 1 ? tunnel.id : key; + } + private toRuntimeInfo( serverId: string, tunnel: ServerTunnel, live?: ActiveTunnelHandle, ): TunnelRuntimeInfo { const key = makeTunnelKey(serverId, tunnel.id); - const sameIdCount = this.configManager - .listServers() - .flatMap((s) => s.tunnels) - .filter((t) => t.id === tunnel.id && t.mode === 'http-proxy').length; - const proxyId = sameIdCount <= 1 ? tunnel.id : key; + const proxyId = this.computeProxyId(serverId, tunnel); return { key, serverId, @@ -570,9 +1511,10 @@ export class TunnelManager { localBoundPort: live?.localBoundPort, remoteBoundPort: live?.remoteBoundPort, proxyPath: - tunnel.mode === 'http-proxy' && live?.localBoundPort + tunnel.mode === 'http-proxy' && live?.httpProxyActive ? `/proxy/${proxyId}/` : undefined, + expiresAt: live?.expiresAt, activeConnections: live?.activeConnections ?? 0, totalConnections: live?.totalConnections ?? 0, bytesIn: live?.bytesIn ?? 0, diff --git a/tests/tunnels-and-proxy.test.ts b/tests/tunnels-and-proxy.test.ts index 9ae5a40..cc4bc20 100644 --- a/tests/tunnels-and-proxy.test.ts +++ b/tests/tunnels-and-proxy.test.ts @@ -97,6 +97,7 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC dataDir, port: 0, host: '127.0.0.1', + proxyPort: 0, publicDir: path.resolve('dist/public'), watchConfig: false, }); @@ -210,6 +211,46 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC const unauthProxy = await fetch(`${baseUrl}/proxy/web-ui/hello`); expect(unauthProxy.status).toBe(401); + // Same-origin /proxy is blocked with 403 by default; test isolated proxyPort ticket flow first! + const blockedSameOrigin = await api('/proxy/web-ui/hello'); + expect(blockedSameOrigin.status).toBe(403); + expect(blockedSameOrigin.data.error).toBe('PROXY_ORIGIN_ISOLATION_REQUIRED'); + + const ticketRes = await api('/api/tunnels/app1/web-ui/proxy-ticket', { + method: 'POST', + body: {}, + }); + expect(ticketRes.status).toBe(200); + expect(ticketRes.data.mode).toBe('port'); + const launchUrl = String(ticketRes.data.launchUrl); + const proxyBaseUrl = `http://127.0.0.1:${server.proxyPort}`; + + // Redeem single-use ticket on isolated proxy origin to receive scoped gcoord_proxy_sid cookie + const proxyJar = new CookieJar(); + const ticketHit = await fetch(launchUrl, { redirect: 'manual' }); + expect(ticketHit.status).toBe(302); + proxyJar.updateFrom(ticketHit); + expect(proxyJar.header()).toContain('gcoord_proxy_sid='); + + const isoHello = await fetch(`${proxyBaseUrl}/proxy/web-ui/hello`, { + headers: { Cookie: proxyJar.header() }, + }); + expect(isoHello.status).toBe(200); + const isoHelloData = (await isoHello.json()) as { ok: boolean }; + expect(isoHelloData.ok).toBe(true); + expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_sid'); + expect(upstream.getLastCookie() ?? '').not.toContain('gcoord_proxy_sid'); + + // Also enable allowSameOriginProxy explicitly to test same-origin backwards compatibility + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { allowSameOriginProxy: true }, + }) + ).status, + ).toBe(200); + // Authenticated GET & POST JSON stream through proxy without exposing hub session cookies const authedHello = await api('/proxy/web-ui/hello'); expect(authedHello.status).toBe(200); @@ -304,7 +345,35 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC expect(localHttp.status).toBe(200); expect(((await localHttp.json()) as { ok: boolean }).ok).toBe(true); - // 3. Remote TCP (R) tunnel via forwardIn + // 3. Remote TCP (R) tunnel targets 127.0.0.1 -> blocked by Zero-Trust egress guard unless allowlisted + const blockedRemoteTcp = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'app1', + tunnel: { + id: 'tcp-remote', + name: 'Remote TCP Reverse', + mode: 'remote-tcp', + bindHost: '127.0.0.1', + targetHost: '127.0.0.1', + targetPort: upstream.port, + autoStart: false, + }, + start: true, + }, + }); + expect(blockedRemoteTcp.data.startError).toBeTruthy(); + + // Allow 127.0.0.1/32 in egressAllowedCidrs -> Remote TCP (R) starts and forwards cleanly + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }) + ).status, + ).toBe(200); + const remoteTcpRes = await api('/api/tunnels', { method: 'POST', body: { From dbf7144c5da4ef7e8355a9730f2b00ef42057708 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Fri, 27 Nov 2026 22:53:15 +0000 Subject: [PATCH 09/19] feat(monitoring,inspector,metrics): fix rollup/probe bugs, add net/disk/probe history, TLS expiry & Prometheus /metrics --- src/server/api/routes/config.routes.ts | 48 ++- src/server/api/routes/servers.routes.ts | 133 ++++++- src/server/app.ts | 15 +- src/server/monitoring/collectors.ts | 113 ++++-- src/server/monitoring/inspector.ts | 73 +++- src/server/monitoring/monitoring-service.ts | 385 +++++++++++++++----- src/server/monitoring/probes.ts | 168 +++++++-- src/server/monitoring/prometheus.ts | 180 +++++++++ src/shared/schemas/settings.schema.ts | 1 + src/shared/ws-protocol.ts | 1 + tests/monitoring-and-probes.test.ts | 11 +- 11 files changed, 954 insertions(+), 174 deletions(-) create mode 100644 src/server/monitoring/prometheus.ts diff --git a/src/server/api/routes/config.routes.ts b/src/server/api/routes/config.routes.ts index ef1b955..b9c6eef 100644 --- a/src/server/api/routes/config.routes.ts +++ b/src/server/api/routes/config.routes.ts @@ -1,8 +1,9 @@ +import crypto from 'node:crypto'; import { Router, type RequestHandler } from 'express'; import { ZodError, 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 { sha256Hex, type AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, @@ -237,5 +238,50 @@ export function createConfigRouter(deps: ConfigRouterDeps): Router { }, ); + router.post( + '/prometheus-token', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (req, res) => { + const parsed = z + .object({ enable: z.boolean().optional() }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const token = crypto.randomBytes(32).toString('base64url'); + const tokenHash = sha256Hex(token); + const next = structuredClone(configManager.getSettings()); + next.metrics.prometheusTokenHash = tokenHash; + if (parsed.data.enable !== undefined) { + next.metrics.prometheusEnabled = parsed.data.enable; + } else { + next.metrics.prometheusEnabled = true; + } + configManager.saveConfigText( + 'settings.json', + JSON.stringify(next, null, 2), + 'ui', + 'Rotate Prometheus metrics Bearer token', + ); + auditService.log({ + action: 'metrics.prometheus_token_rotate', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: 'settings.json', + status: 'ok', + details: { prometheusEnabled: next.metrics.prometheusEnabled }, + }); + res.json({ + token, + tokenHash, + prometheusEnabled: next.metrics.prometheusEnabled, + }); + }, + ); + return router; } diff --git a/src/server/api/routes/servers.routes.ts b/src/server/api/routes/servers.routes.ts index d91ba04..b177717 100644 --- a/src/server/api/routes/servers.routes.ts +++ b/src/server/api/routes/servers.routes.ts @@ -548,23 +548,140 @@ export function createServersRouter(deps: ServersRouterDeps): Router { }); }); - router.get('/:id/inspect', requireAuth(authService), async (req, res) => { + router.get('/:id/inspect', requireAuth(authService), (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { res.status(404).json({ error: 'SERVER_NOT_FOUND' }); return; } - try { - const result = await serverInspector.inspect(id); - res.json(result); - } catch (err) { - res.status(502).json({ - error: 'INSPECT_FAILED', - message: err instanceof Error ? err.message : 'Server inspection failed', + const sort = String(req.query.sort ?? 'cpu') === 'mem' ? 'mem' : 'cpu'; + const useSudo = req.query.sudo === 'true' || req.query.sudo === '1'; + + const executeInspect = async () => { + try { + const result = await serverInspector.inspect(id, { sort, useSudo }); + res.json(result); + } catch (err) { + res.status(502).json({ + error: 'INSPECT_FAILED', + message: err instanceof Error ? err.message : 'Server inspection failed', + }); + } + }; + + if (useSudo) { + stepUpGuard(req, res, () => { + void executeInspect(); }); + return; } + void executeInspect(); }); + router.post( + '/:id/processes/:pid/signal', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + async (req, res) => { + const id = String(req.params.id ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + const rawPid = String(req.params.pid ?? ''); + if (!/^[1-9][0-9]{0,7}$/.test(rawPid)) { + res.status(400).json({ error: 'INVALID_PID' }); + return; + } + const parsed = z + .object({ + signal: z.enum(['SIGTERM', 'SIGKILL']).default('SIGTERM'), + sudo: z.boolean().optional(), + }) + .safeParse(req.body ?? {}); + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } + const pid = Number(rawPid); + try { + const result = await serverInspector.signalProcess(id, pid, parsed.data.signal, { + useSudo: parsed.data.sudo, + }); + auditService.log({ + action: 'server.process_signal', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${id}:${pid}`, + status: result.ok ? 'ok' : 'error', + details: { signal: parsed.data.signal, sudo: Boolean(parsed.data.sudo) }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'SIGNAL_FAILED', + message: err instanceof Error ? err.message : 'Unable to send process signal', + }); + } + }, + ); + + router.get('/:id/probes/history', requireAuth(authService), (req, res) => { + const id = String(req.params.id ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + const rawRange = String(req.query.range ?? '24h') as MetricRange; + const hoursMap: Record = { + '1h': 1, + '6h': 6, + '24h': 24, + '7d': 168, + '30d': 720, + }; + const hours = hoursMap[rawRange] ?? 24; + const limit = Math.max(1, Math.min(1000, Number(req.query.limit) || 200)); + const samples = monitoringService.queryProbeHistory( + id, + Date.now() - hours * 3600_000, + limit, + ); + res.json({ serverId: id, samples }); + }); + + router.post( + '/:id/probes/:probeId/run', + requireAuth(authService), + requireCsrf, + async (req, res) => { + const id = String(req.params.id ?? ''); + const probeId = String(req.params.probeId ?? ''); + if (!configManager.getServer(id)) { + res.status(404).json({ error: 'SERVER_NOT_FOUND' }); + return; + } + try { + const sample = await monitoringService.runProbeNow(id, probeId); + auditService.log({ + action: 'server.probe_run', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${id}:${probeId}`, + status: sample.ok ? 'ok' : 'error', + }); + res.json({ serverId: id, sample }); + } catch (err) { + res.status(404).json({ + error: 'PROBE_RUN_FAILED', + message: err instanceof Error ? err.message : 'Unable to run probe', + }); + } + }, + ); + router.get('/:id/keys', requireAuth(authService), async (req, res) => { const id = String(req.params.id ?? ''); if (!configManager.getServer(id)) { diff --git a/src/server/app.ts b/src/server/app.ts index fb19dc9..b51d6b0 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -15,6 +15,7 @@ import { applyDatabaseThrottlePragmas, openDatabase } from './db/database.js'; import { ServerInspector } from './monitoring/inspector.js'; import { MonitoringService } from './monitoring/monitoring-service.js'; import { ProbeRunner } from './monitoring/probes.js'; +import { createPrometheusHandler } from './monitoring/prometheus.js'; import { AuditService } from './security/audit.js'; import { AuthService } from './security/auth.js'; import { BackupScheduler } from './security/backup-scheduler.js'; @@ -195,13 +196,14 @@ export async function createGCoordinatorServer( wsHub, ); const serverInspector = new ServerInspector(sshPool, configManager); - const probeRunner = new ProbeRunner(sshPool); + const probeRunner = new ProbeRunner(sshPool, configManager); const monitoringService = new MonitoringService( db, configManager, vaultService, sshPool, probeRunner, + getRuntimeLimits, ); const transferEngine = new TransferEngine(sshPool, sftpService, configManager); const workflowEngine = new WorkflowEngine( @@ -612,6 +614,17 @@ export async function createGCoordinatorServer( createConfigRouter({ authService, configManager, auditService, stepUpGuard }), ); app.use('/api/audit', createAuditRouter(authService, auditService)); + app.get( + '/metrics', + createPrometheusHandler({ + configManager, + vaultService, + sshPool, + monitoringService, + tunnelManager, + alertEngine, + }), + ); app.use('/api', (_req, res) => { res.status(404).json({ error: 'API_ROUTE_NOT_FOUND' }); diff --git a/src/server/monitoring/collectors.ts b/src/server/monitoring/collectors.ts index b1a7220..5faee22 100644 --- a/src/server/monitoring/collectors.ts +++ b/src/server/monitoring/collectors.ts @@ -56,20 +56,67 @@ export const LINUX_METRIC_CMD = [ ].join('; '); export const BSD_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl -n hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null', + 'printf "===SYSCTL===\\n"; sysctl hw.physmem hw.pagesize vm.loadavg kern.boottime kern.cp_time 2>/dev/null || true', 'printf "===VMSTAT===\\n"; vmstat -H 2>/dev/null || vmstat', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null', 'printf "===DF===\\n"; df -kT 2>/dev/null || df -kP', ].join('; '); export const MACOS_METRIC_CMD = [ - 'printf "===SYSCTL===\\n"; sysctl -n hw.memsize hw.pagesize vm.loadavg kern.boottime', + 'printf "===SYSCTL===\\n"; sysctl hw.memsize hw.pagesize vm.loadavg kern.boottime 2>/dev/null || true', 'printf "===VMSTAT===\\n"; vm_stat', 'printf "===TOP===\\n"; top -l 1 -n 0 2>/dev/null | grep -i "CPU usage" || true', 'printf "===NET===\\n"; netstat -ibn 2>/dev/null || netstat -ib', 'printf "===DF===\\n"; df -kP', ].join('; '); +const VIRTUAL_NIC_PREFIXES = [ + 'lo', + 'veth', + 'docker', + 'br-', + 'tun', + 'tap', + 'wg', + 'virbr', + 'dummy', + 'cilium', + 'flannel', + 'cni', + 'vxlan', + 'ifb', +]; + +function isVirtualNic(iface: string): boolean { + const clean = iface.trim().replace(/:$/, '').toLowerCase(); + return VIRTUAL_NIC_PREFIXES.some( + (p) => clean === p || (p.endsWith('-') ? clean.startsWith(p) : clean.startsWith(p)), + ); +} + +/** + * Parse `sysctl` sections supporting both `key: val` / `key=val` (resilient to + * missing keys across BSD/macOS versions) and legacy unlabeled positional lines. + */ +function parseSysctlMap(rawText: string, positionalKeys: string[]): Map { + const out = new Map(); + const lines = rawText + .split(/\r?\n/) + .map((l) => l.trim()) + .filter(Boolean); + let posIdx = 0; + for (const line of lines) { + const kv = /^([a-zA-Z][a-zA-Z0-9_.]*)\s*[:=]\s*(.+)$/.exec(line); + if (kv) { + out.set(kv[1]!, kv[2]!.trim()); + } else if (posIdx < positionalKeys.length) { + out.set(positionalKeys[posIdx]!, line); + posIdx += 1; + } + } + return out; +} + function splitSections(stdout: string): Record { const sections: Record = {}; let current = ''; @@ -137,6 +184,7 @@ function parseDfLines( if ( fsName === 'devfs' || fsName === 'map' || + fsName.startsWith('/dev/loop') || !Number.isFinite(totalKb) || totalKb <= 0 ) { @@ -205,9 +253,12 @@ export function parseLinuxOutput( Math.floor(Number((sec.UPTIME ?? '0').trim().split(/\s+/)[0]) || 0), ); - // Network RX/TX across non-loopback interfaces - let netRxBytes = 0; - let netTxBytes = 0; + // Network RX/TX prioritizing physical NICs and excluding loopback/virtual bridges + let physRxBytes = 0; + let physTxBytes = 0; + let hasPhys = false; + let fallbackRxBytes = 0; + let fallbackTxBytes = 0; for (const line of (sec.NET ?? '').split(/\r?\n/)) { const colon = line.indexOf(':'); if (colon <= 0) continue; @@ -215,10 +266,19 @@ export function parseLinuxOutput( if (iface === 'lo' || iface.startsWith('lo:')) continue; const cols = line.slice(colon + 1).trim().split(/\s+/); if (cols.length >= 9) { - netRxBytes += Number(cols[0]) || 0; - netTxBytes += Number(cols[8]) || 0; + const rx = Number(cols[0]) || 0; + const tx = Number(cols[8]) || 0; + fallbackRxBytes += rx; + fallbackTxBytes += tx; + if (!isVirtualNic(iface)) { + hasPhys = true; + physRxBytes += rx; + physTxBytes += tx; + } } } + const netRxBytes = hasPhys ? physRxBytes : fallbackRxBytes; + const netTxBytes = hasPhys ? physTxBytes : fallbackTxBytes; let netRxBps = 0; let netTxBps = 0; @@ -267,25 +327,28 @@ export function parseBsdOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctlLines = (sec.SYSCTL ?? '') - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean); + const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ + 'hw.physmem', + 'hw.pagesize', + 'vm.loadavg', + 'kern.boottime', + 'kern.cp_time', + ]); - const physMemBytes = Number(sysctlLines[0]) || 0; - const pageSize = Number(sysctlLines[1]) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const physMemBytes = Number(sysctl.get('hw.physmem')) || 0; + const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } let cpuTotal = 0; let cpuIdle = 0; - const cpNums = (sysctlLines[4] ?? '') + const cpNums = (sysctl.get('kern.cp_time') ?? '') .split(/\s+/) .map((n) => Number(n) || 0); if (cpNums.length >= 5) { @@ -369,18 +432,20 @@ export function parseMacOsOutput( nowMs = Date.now(), ): CollectOutput { const sec = splitSections(stdout); - const sysctlLines = (sec.SYSCTL ?? '') - .split(/\r?\n/) - .map((l) => l.trim()) - .filter(Boolean); + const sysctl = parseSysctlMap(sec.SYSCTL ?? '', [ + 'hw.memsize', + 'hw.pagesize', + 'vm.loadavg', + 'kern.boottime', + ]); - const memBytes = Number(sysctlLines[0]) || 0; - const pageSize = Number(sysctlLines[1]) || 4096; - const loadMatch = /([\d.]+)/.exec(sysctlLines[2] ?? '0'); + const memBytes = Number(sysctl.get('hw.memsize')) || 0; + const pageSize = Number(sysctl.get('hw.pagesize')) || 4096; + const loadMatch = /([\d.]+)/.exec(sysctl.get('vm.loadavg') ?? '0'); const load1m = round2(Number(loadMatch?.[1] ?? 0)); let uptimeSec = 0; - const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctlLines[3] ?? ''); + const bootSecMatch = /sec\s*=\s*(\d+)/.exec(sysctl.get('kern.boottime') ?? ''); if (bootSecMatch) { uptimeSec = Math.max(0, Math.floor(nowMs / 1000) - Number(bootSecMatch[1]!)); } diff --git a/src/server/monitoring/inspector.ts b/src/server/monitoring/inspector.ts index 518de1a..3246dcc 100644 --- a/src/server/monitoring/inspector.ts +++ b/src/server/monitoring/inspector.ts @@ -26,25 +26,30 @@ export interface ServerInspectionResult { serverId: string; os: OsType; collectedAt: number; + sort: 'cpu' | 'mem'; processes: ProcessEntry[]; ports: PortEntry[]; thermals: ThermalEntry[]; } -const LINUX_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=-%cpu 2>/dev/null | head -n 26 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 26', - 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', - 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', -].join('; '); +function buildLinuxInspectCmd(sort: 'cpu' | 'mem'): string { + const linuxSort = sort === 'mem' ? '-rss' : '-%cpu'; + const bsdFlag = sort === 'mem' ? '-m' : '-r'; + return [ + `printf "===PROCS===\\n"; ps -eo pid,user:24,%cpu,%mem,rss,args --sort=${linuxSort} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args ${bsdFlag} 2>/dev/null | head -n 41 || ps -Ao pid,user,pcpu,pmem,rss,args | head -n 41`, + 'printf "===PORTS===\\n"; ss -tulnp 2>/dev/null || netstat -tulnp 2>/dev/null || true', + 'printf "===THERMAL===\\n"; for z in /sys/class/thermal/thermal_zone*; do [ -r "$z/temp" ] && printf "%s:%s\\n" "$(cat "$z/type" 2>/dev/null || basename "$z")" "$(cat "$z/temp")"; done 2>/dev/null || true', + ].join('; '); +} const BSD_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 26', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command 2>/dev/null | head -n 41', 'printf "===PORTS===\\n"; sockstat -l 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; sysctl dev.cpu 2>/dev/null | grep temperature || true', ].join('; '); const MACOS_INSPECT_CMD = [ - 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 26', + 'printf "===PROCS===\\n"; ps -axo pid,user,%cpu,%mem,rss,command | head -n 41', 'printf "===PORTS===\\n"; lsof -nP -iTCP -sTCP:LISTEN 2>/dev/null || netstat -an 2>/dev/null || true', 'printf "===THERMAL===\\n"; true', ].join('; '); @@ -54,6 +59,7 @@ export function parseInspectorOutput( os: OsType, stdout: string, collectedAt = Date.now(), + sort: 'cpu' | 'mem' = 'cpu', ): ServerInspectionResult { const sections: Record = {}; let current = ''; @@ -85,6 +91,12 @@ export function parseInspectorOutput( }); } + processes.sort((a, b) => + sort === 'mem' + ? b.memPct - a.memPct || b.rssMb - a.rssMb || b.cpuPct - a.cpuPct + : b.cpuPct - a.cpuPct || b.memPct - a.memPct, + ); + // Ports const ports: PortEntry[] = []; const portLines = sections.PORTS ?? []; @@ -98,7 +110,6 @@ export function parseInspectorOutput( } const cols = trimmed.split(/\s+/); if (/^(tcp|udp|tcp4|tcp6|udp4|udp6)/i.test(cols[0] ?? '')) { - // ss -tulnp format: Netid State Recv-Q Send-Q Local Peer Process if (cols.length >= 6 && (cols[1] === 'LISTEN' || cols[1] === 'UNCONN')) { ports.push({ proto: cols[0]!, @@ -113,14 +124,12 @@ export function parseInspectorOutput( }); } } else if (cols.length >= 9 && cols[cols.length - 1] === '(LISTEN)') { - // lsof format ports.push({ proto: cols[7] ?? 'TCP', localAddress: cols[8] ?? '', process: `${cols[0]}(${cols[1]})`, }); } else if (cols.length >= 6 && /^\d+$/.test(cols[2] ?? '')) { - // sockstat -l: USER COMMAND PID FD PROTO LOCAL FOREIGN ports.push({ proto: cols[4] ?? 'tcp', localAddress: cols[5] ?? '', @@ -144,7 +153,7 @@ export function parseInspectorOutput( thermals.push({ zone, tempC }); } - return { serverId, os, collectedAt, processes, ports, thermals }; + return { serverId, os, collectedAt, sort, processes, ports, thermals }; } export class ServerInspector { @@ -153,11 +162,15 @@ export class ServerInspector { private readonly configManager: ConfigManager, ) {} - async inspect(serverId: string): Promise { + async inspect( + serverId: string, + opts: { sort?: 'cpu' | 'mem'; useSudo?: boolean } = {}, + ): Promise { const server = this.configManager.getServer(serverId); if (!server) { throw new Error(`Unknown server "${serverId}"`); } + const sort = opts.sort === 'mem' ? 'mem' : 'cpu'; const runtime = this.sshPool.getState(serverId); const os = await detectServerOs(this.sshPool, server, runtime?.osDetected); const cmd = @@ -165,9 +178,39 @@ export class ServerInspector { ? MACOS_INSPECT_CMD : os === 'bsd' ? BSD_INSPECT_CMD - : LINUX_INSPECT_CMD; + : buildLinuxInspectCmd(sort); - const res = await this.sshPool.exec(serverId, cmd, { timeoutMs: 15_000 }); - return parseInspectorOutput(serverId, os, res.stdout); + const res = await this.sshPool.exec(serverId, cmd, { + timeoutMs: 15_000, + sudo: opts.useSudo, + }); + return parseInspectorOutput(serverId, os, res.stdout, Date.now(), sort); + } + + async signalProcess( + serverId: string, + pid: number, + signal: 'SIGTERM' | 'SIGKILL', + opts: { useSudo?: boolean } = {}, + ): Promise<{ ok: boolean; pid: number; signal: string; stderr: string }> { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + if (!Number.isInteger(pid) || pid < 1 || pid > 99_999_999) { + throw new Error('Invalid PID'); + } + const sigName = signal === 'SIGKILL' ? 'KILL' : 'TERM'; + const res = await this.sshPool.exec( + serverId, + `kill -s ${sigName} ${pid}`, + { timeoutMs: 10_000, sudo: opts.useSudo }, + ); + return { + ok: res.exitCode === 0, + pid, + signal, + stderr: res.stderr.trim(), + }; } } diff --git a/src/server/monitoring/monitoring-service.ts b/src/server/monitoring/monitoring-service.ts index 1a69daa..29a02b1 100644 --- a/src/server/monitoring/monitoring-service.ts +++ b/src/server/monitoring/monitoring-service.ts @@ -6,6 +6,7 @@ import type { ProbeSample, } from '../../shared/ws-protocol.js'; import type { ConfigManager } from '../config/config-manager.js'; +import type { RuntimeLimits } from '../config/runtime-limits.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -37,6 +38,7 @@ export interface MonitoringTickEvent { interface ServerTimers { metricTimer: NodeJS.Timeout | null; warmupTimer: NodeJS.Timeout | null; + staggerTimer: NodeJS.Timeout | null; probeTimers: Map; pollingMetrics: boolean; } @@ -54,6 +56,8 @@ export class MonitoringService { >(); private maintenanceTimer: NodeJS.Timeout | null = null; private stopped = false; + private inFlightPolls = 0; + private readonly pollQueue: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -61,6 +65,7 @@ export class MonitoringService { private readonly vaultService: VaultService, private readonly sshPool: SSHPool, private readonly probeRunner: ProbeRunner, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} onTick(listener: (event: MonitoringTickEvent) => void): () => void { @@ -96,6 +101,7 @@ export class MonitoringService { for (const timers of this.serverTimers.values()) { if (timers.metricTimer) clearInterval(timers.metricTimer); if (timers.warmupTimer) clearTimeout(timers.warmupTimer); + if (timers.staggerTimer) clearTimeout(timers.staggerTimer); for (const pt of timers.probeTimers.values()) clearInterval(pt); } this.serverTimers.clear(); @@ -104,6 +110,9 @@ export class MonitoringService { close(): void { this.stopped = true; this.stopAll(); + while (this.pollQueue.length > 0) { + this.pollQueue.shift()?.(); + } if (this.maintenanceTimer) { clearInterval(this.maintenanceTimer); this.maintenanceTimer = null; @@ -119,10 +128,10 @@ export class MonitoringService { return; } - for (const server of this.configManager.listServers()) { - if (!server.enabled) continue; - this.scheduleServer(server); - } + const enabledServers = this.configManager.listServers().filter((s) => s.enabled); + enabledServers.forEach((server, idx) => { + this.scheduleServer(server, idx); + }); } getLatest(serverId: string): LatestServerTelemetry | undefined { @@ -138,45 +147,105 @@ export class MonitoringService { return this.executeMetricPoll(server); } + async runProbeNow(serverId: string, probeId: string): Promise { + const server = this.configManager.getServer(serverId); + if (!server) { + throw new Error(`Unknown server "${serverId}"`); + } + const probe = server.probes.find((p) => p.id === probeId); + if (!probe) { + throw new Error(`Unknown probe "${probeId}" on server "${serverId}"`); + } + return this.runAndPersistProbe(server, probe); + } + runMaintenance(nowMs = Date.now()): void { const settings = this.configManager.getSettings(); const rawCutoff = nowMs - settings.rawRetentionHours * 3600_000; const rollupCutoff = nowMs - settings.rollupRetentionDays * 86_400_000; + const auditCutoff = nowMs - settings.auditRetentionDays * 86_400_000; + const workflowCutoff = nowMs - settings.workflowRunRetentionDays * 86_400_000; + const alertCutoff = nowMs - settings.alertEventRetentionDays * 86_400_000; const tx = this.db.transaction(() => { - // Aggregate hourly rollups from raw metrics + // Stage 1: Aggregate 1h rollups preserving any partial bucket spanning rawCutoff this.db .prepare( - `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + `INSERT INTO metrics_rollup ( + bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, + mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct + ) SELECT - (ts / 3600000) * 3600000 AS bucket_ts, + (r.ts / 3600000) * 3600000 AS bucket_ts, '1h' AS granularity, - server_id, - MIN(cpu_pct), - AVG(cpu_pct), - MAX(cpu_pct), - COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), - MAX(load_1m) - FROM metrics_raw - GROUP BY server_id, (ts / 3600000) * 3600000`, + r.server_id, + MIN(r.cpu_pct), + AVG(r.cpu_pct), + MAX(r.cpu_pct), + COALESCE(AVG(CASE WHEN r.mem_total_mb > 0 THEN (r.mem_used_mb * 100.0 / r.mem_total_mb) ELSE 0 END), 0), + MAX(r.load_1m), + AVG(r.net_rx_bps), + AVG(r.net_tx_bps), + COALESCE(MAX(d.max_disk_pct), 0) + FROM metrics_raw r + LEFT JOIN ( + SELECT server_id, ts, MAX(used_pct) AS max_disk_pct + FROM metrics_disks + GROUP BY server_id, ts + ) d ON d.server_id = r.server_id AND d.ts = r.ts + GROUP BY r.server_id, (r.ts / 3600000) * 3600000 + ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET + cpu_min = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_min ELSE MIN(metrics_rollup.cpu_min, excluded.cpu_min) END, + cpu_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_max ELSE MAX(metrics_rollup.cpu_max, excluded.cpu_max) END, + load_max = CASE WHEN excluded.bucket_ts >= ? THEN excluded.load_max ELSE MAX(metrics_rollup.load_max, excluded.load_max) END, + disk_max_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.disk_max_pct ELSE MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct) END, + cpu_avg = CASE WHEN excluded.bucket_ts >= ? THEN excluded.cpu_avg ELSE metrics_rollup.cpu_avg END, + mem_avg_pct = CASE WHEN excluded.bucket_ts >= ? THEN excluded.mem_avg_pct ELSE metrics_rollup.mem_avg_pct END, + net_rx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_rx_avg_bps ELSE metrics_rollup.net_rx_avg_bps END, + net_tx_avg_bps = CASE WHEN excluded.bucket_ts >= ? THEN excluded.net_tx_avg_bps ELSE metrics_rollup.net_tx_avg_bps END`, ) - .run(); + .run( + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + rawCutoff, + ); - // Aggregate daily rollups + // Stage 2: Aggregate 1d rollups from complete 1h buckets so raw pruning never truncates a day this.db .prepare( - `INSERT OR REPLACE INTO metrics_rollup (bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, mem_avg_pct, load_max) + `INSERT INTO metrics_rollup ( + bucket_ts, granularity, server_id, cpu_min, cpu_avg, cpu_max, + mem_avg_pct, load_max, net_rx_avg_bps, net_tx_avg_bps, disk_max_pct + ) SELECT - (ts / 86400000) * 86400000 AS bucket_ts, + (bucket_ts / 86400000) * 86400000 AS day_ts, '1d' AS granularity, server_id, - MIN(cpu_pct), - AVG(cpu_pct), - MAX(cpu_pct), - COALESCE(AVG(CASE WHEN mem_total_mb > 0 THEN (mem_used_mb * 100.0 / mem_total_mb) ELSE 0 END), 0), - MAX(load_1m) - FROM metrics_raw - GROUP BY server_id, (ts / 86400000) * 86400000`, + MIN(cpu_min), + AVG(cpu_avg), + MAX(cpu_max), + AVG(mem_avg_pct), + MAX(load_max), + AVG(net_rx_avg_bps), + AVG(net_tx_avg_bps), + MAX(disk_max_pct) + FROM metrics_rollup + WHERE granularity = '1h' + GROUP BY server_id, (bucket_ts / 86400000) * 86400000 + ON CONFLICT(server_id, granularity, bucket_ts) DO UPDATE SET + cpu_min = MIN(metrics_rollup.cpu_min, excluded.cpu_min), + cpu_max = MAX(metrics_rollup.cpu_max, excluded.cpu_max), + load_max = MAX(metrics_rollup.load_max, excluded.load_max), + disk_max_pct = MAX(metrics_rollup.disk_max_pct, excluded.disk_max_pct), + cpu_avg = excluded.cpu_avg, + mem_avg_pct = excluded.mem_avg_pct, + net_rx_avg_bps = excluded.net_rx_avg_bps, + net_tx_avg_bps = excluded.net_tx_avg_bps`, ) .run(); @@ -184,16 +253,65 @@ export class MonitoringService { this.db.prepare('DELETE FROM metrics_disks WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM probe_results WHERE ts < ?').run(rawCutoff); this.db.prepare('DELETE FROM metrics_rollup WHERE bucket_ts < ?').run(rollupCutoff); + this.db.prepare('DELETE FROM audit_log WHERE ts < ?').run(auditCutoff); + this.db + .prepare('DELETE FROM workflow_runs WHERE finished_at IS NOT NULL AND started_at < ?') + .run(workflowCutoff); + this.db + .prepare( + "DELETE FROM alert_events WHERE state = 'resolved' AND COALESCE(resolved_at, triggered_at) < ?", + ) + .run(alertCutoff); + this.db.prepare('DELETE FROM alert_silences WHERE expires_at < ?').run(nowMs); + this.db + .prepare('DELETE FROM broadcast_jobs WHERE finished_at IS NOT NULL AND started_at < ?') + .run(workflowCutoff); }); tx(); } + queryProbeHistory( + serverId: string, + sinceMs = Date.now() - 24 * 3600_000, + limit = 200, + ): Array { + const safeLimit = Math.max(1, Math.min(1000, Math.floor(limit))); + const rows = this.db + .prepare( + `SELECT ts, probe_id AS probeId, ok AS okInt, status_code AS statusCode, + latency_ms AS latencyMs, error + FROM probe_results + WHERE server_id = ? AND ts >= ? + ORDER BY ts DESC + LIMIT ?`, + ) + .all(serverId, sinceMs, safeLimit) as Array<{ + ts: number; + probeId: string; + okInt: number; + statusCode: number | null; + latencyMs: number; + error: string | null; + }>; + + return rows.reverse().map((r) => ({ + ts: r.ts, + probeId: r.probeId, + ok: r.okInt === 1, + statusCode: r.statusCode ?? undefined, + latencyMs: r.latencyMs, + error: r.error ?? undefined, + })); + } + queryHistory(serverId: string, range: MetricRange = '1h'): { range: MetricRange; granularity: 'raw' | '1h' | '1d'; points: Array>; latestDisks: DiskSample[]; latestProbes: Array; + probeHistory: Array; + diskHistory: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>; } { const now = Date.now(); const rangeMs: Record = { @@ -223,7 +341,9 @@ export class MonitoringService { points = this.db .prepare( `SELECT bucket_ts AS ts, cpu_min AS cpuMin, cpu_avg AS cpuAvg, cpu_max AS cpuMax, - mem_avg_pct AS memAvgPct, load_max AS loadMax + mem_avg_pct AS memAvgPct, load_max AS loadMax, + net_rx_avg_bps AS netRxAvgBps, net_tx_avg_bps AS netTxAvgBps, + disk_max_pct AS diskMaxPct FROM metrics_rollup WHERE server_id = ? AND granularity = ? AND bucket_ts >= ? ORDER BY bucket_ts ASC`, @@ -240,6 +360,22 @@ export class MonitoringService { ) .all(serverId, serverId) as DiskSample[]; + const diskHistory = this.db + .prepare( + `SELECT ts, mount_point AS mountPoint, used_pct AS usedPct, used_mb AS usedMb, total_mb AS totalMb + FROM metrics_disks + WHERE server_id = ? AND ts >= ? + ORDER BY ts ASC + LIMIT 500`, + ) + .all(serverId, since) as Array<{ + ts: number; + mountPoint: string; + usedPct: number; + usedMb: number; + totalMb: number; + }>; + const latestProbes = this.db .prepare( `SELECT p.probe_id AS probeId, p.ok AS okInt, p.status_code AS statusCode, @@ -262,6 +398,8 @@ export class MonitoringService { ts: number; }>; + const probeHistory = this.queryProbeHistory(serverId, since, 200); + return { range, granularity, @@ -275,50 +413,88 @@ export class MonitoringService { error: r.error ?? undefined, ts: r.ts, })), + probeHistory, + diskHistory, }; } - private scheduleServer(server: ServerConfig): void { + private async withPollSlot(fn: () => Promise): Promise { + const limit = Math.max(1, this.getRuntimeLimits?.().maxConcurrentMetricPolls ?? 4); + if (this.inFlightPolls >= limit) { + await new Promise((resolve) => { + this.pollQueue.push(resolve); + }); + } + this.inFlightPolls += 1; + try { + return await fn(); + } finally { + this.inFlightPolls = Math.max(0, this.inFlightPolls - 1); + const next = this.pollQueue.shift(); + if (next) next(); + } + } + + private scheduleServer(server: ServerConfig, index: number): void { const timers: ServerTimers = { metricTimer: null, warmupTimer: null, + staggerTimer: null, probeTimers: new Map(), pollingMetrics: false, }; this.serverTimers.set(server.id, timers); - // Kick initial poll asynchronously without delaying syncServers() - const hadDelta = this.deltaStates.has(server.id); - void this.executeMetricPoll(server).then((ev) => { - if ( - ev && - !hadDelta && - !this.stopped && - this.serverTimers.get(server.id) === timers && - server.pollIntervalSec >= 3 - ) { - const wt = setTimeout(() => { - timers.warmupTimer = null; - void this.executeMetricPoll(server); - }, 1000); - wt.unref(); - timers.warmupTimer = wt; - } - }); + const limits = this.getRuntimeLimits?.(); + const staggerMs = + limits?.staggerPolls && index > 0 ? Math.min(index * 120, 2_500) : 0; - timers.metricTimer = setInterval(() => { - void this.executeMetricPoll(server); - }, server.pollIntervalSec * 1000); - timers.metricTimer.unref(); + const kickInitialAndStartTimer = () => { + if (this.stopped || this.serverTimers.get(server.id) !== timers) return; - for (const probe of server.probes) { - if (!probe.enabled) continue; - void this.executeProbe(server, probe.id); - const pt = setInterval(() => { + const hadDelta = this.deltaStates.has(server.id); + void this.executeMetricPoll(server).then((ev) => { + if ( + ev && + !hadDelta && + !this.stopped && + this.serverTimers.get(server.id) === timers && + server.pollIntervalSec >= 3 + ) { + const wt = setTimeout(() => { + timers.warmupTimer = null; + void this.executeMetricPoll(server); + }, 1000); + wt.unref(); + timers.warmupTimer = wt; + } + }); + + timers.metricTimer = setInterval(() => { + void this.executeMetricPoll(server); + }, server.pollIntervalSec * 1000); + timers.metricTimer.unref(); + + for (const probe of server.probes) { + if (!probe.enabled) continue; void this.executeProbe(server, probe.id); - }, probe.intervalSec * 1000); - pt.unref(); - timers.probeTimers.set(probe.id, pt); + const pt = setInterval(() => { + void this.executeProbe(server, probe.id); + }, probe.intervalSec * 1000); + pt.unref(); + timers.probeTimers.set(probe.id, pt); + } + }; + + if (staggerMs > 0) { + const st = setTimeout(() => { + timers.staggerTimer = null; + kickInitialAndStartTimer(); + }, staggerMs); + st.unref(); + timers.staggerTimer = st; + } else { + kickInitialAndStartTimer(); } } @@ -332,51 +508,55 @@ export class MonitoringService { if (timerState) timerState.pollingMetrics = true; try { - const os = await detectServerOs( - this.sshPool, - server, - this.osCache.get(server.id), - ); - this.osCache.set(server.id, os); + return await this.withPollSlot(async () => { + if (this.stopped || !this.vaultService.isRuntimeReady) return null; - const collected = await collectServerMetrics( - this.sshPool, - server, - os, - this.deltaStates.get(server.id), - ); - this.deltaStates.set(server.id, collected.nextState); + const os = await detectServerOs( + this.sshPool, + server, + this.osCache.get(server.id), + ); + this.osCache.set(server.id, os); - this.persistMetricSample(server.id, collected.sample, collected.disks); + const collected = await collectServerMetrics( + this.sshPool, + server, + os, + this.deltaStates.get(server.id), + ); + this.deltaStates.set(server.id, collected.nextState); - const prevLatest = this.latest.get(server.id) ?? { - serverId: server.id, - disks: [], - probes: {}, - }; - this.latest.set(server.id, { - ...prevLatest, - os, - sample: collected.sample, - disks: collected.disks, - lastError: undefined, - }); + this.persistMetricSample(server.id, collected.sample, collected.disks); - const probes = Object.values(this.latest.get(server.id)!.probes); - const event: MonitoringTickEvent = { - serverId: server.id, - sample: collected.sample, - disks: collected.disks, - probes, - }; - for (const listener of this.tickListeners) { - try { - listener(event); - } catch { - // Isolate listener errors + const prevLatest = this.latest.get(server.id) ?? { + serverId: server.id, + disks: [], + probes: {}, + }; + this.latest.set(server.id, { + ...prevLatest, + os, + sample: collected.sample, + disks: collected.disks, + lastError: undefined, + }); + + const probes = Object.values(this.latest.get(server.id)!.probes); + const event: MonitoringTickEvent = { + serverId: server.id, + sample: collected.sample, + disks: collected.disks, + probes, + }; + for (const listener of this.tickListeners) { + try { + listener(event); + } catch { + // Isolate listener errors + } } - } - return event; + return event; + }); } catch (err) { const prevLatest = this.latest.get(server.id) ?? { serverId: server.id, @@ -397,8 +577,16 @@ export class MonitoringService { if (this.stopped || !this.vaultService.isRuntimeReady) return; const probe = server.probes.find((p) => p.id === probeId); if (!probe || !probe.enabled) return; + await this.runAndPersistProbe(server, probe); + } - const sample = await this.probeRunner.runProbe(server.id, probe); + private async runAndPersistProbe( + server: ServerConfig, + probe: ServerConfig['probes'][number], + ): Promise { + const sample = await this.withPollSlot(() => + this.probeRunner.runProbe(server.id, probe), + ); const ts = Date.now(); this.db .prepare( @@ -430,6 +618,7 @@ export class MonitoringService { // Isolate probe listener errors } } + return sample; } private hydrateLatestFromDb(): void { diff --git a/src/server/monitoring/probes.ts b/src/server/monitoring/probes.ts index 02d5bed..b09f3aa 100644 --- a/src/server/monitoring/probes.ts +++ b/src/server/monitoring/probes.ts @@ -3,36 +3,93 @@ import tls from 'node:tls'; import type { Duplex } from 'node:stream'; import type { ServerProbe } from '../../shared/schemas/server.schema.js'; import type { ProbeSample } from '../../shared/ws-protocol.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import { + fetchWithEgressGuard, + resolveAllowedEgressIps, +} from '../security/egress-guard.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; +const MAX_PROBE_BODY_BYTES = 128 * 1024; + +function decodeChunkedIfNeeded(head: string, body: string): string { + if (!/^transfer-encoding:\s*chunked\b/im.test(head)) return body; + let idx = 0; + let out = ''; + while (idx < body.length) { + const lineEnd = body.indexOf('\r\n', idx); + if (lineEnd < 0) break; + const sizeHex = body.slice(idx, lineEnd).split(';')[0]!.trim(); + const size = Number.parseInt(sizeHex, 16); + if (!Number.isFinite(size) || size <= 0) break; + idx = lineEnd + 2; + out += body.slice(idx, idx + size); + idx += size + 2; + } + return out || body; +} + +async function readResponseTextCapped( + res: Response, + maxBytes = MAX_PROBE_BODY_BYTES, +): Promise { + if (!res.body) return ''; + const reader = res.body.getReader(); + const chunks: Buffer[] = []; + let total = 0; + try { + while (total < maxBytes) { + const { value, done } = await reader.read(); + if (done || !value) break; + const take = Math.min(value.byteLength, maxBytes - total); + chunks.push(Buffer.from(value.subarray(0, take))); + total += take; + if (total >= maxBytes) { + await reader.cancel().catch(() => undefined); + break; + } + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks).toString('utf8'); +} + function readHttpFromStream( stream: Duplex, url: URL, timeoutMs: number, -): Promise<{ statusCode: number; body: string }> { + tlsOpts: { rejectUnauthorized?: boolean } = {}, +): Promise<{ statusCode: number; body: string; certExpiryDays?: number }> { return new Promise((resolve, reject) => { let settled = false; + let certExpiryDays: number | undefined; const timer = setTimeout(() => { if (settled) return; settled = true; stream.destroy(); - reject(new Error(`Target HTTP probe timed out after ${timeoutMs}ms`)); + reject(new Error(`HTTP probe timed out after ${timeoutMs}ms`)); }, timeoutMs); + const servername = net.isIP(url.hostname) ? undefined : url.hostname; const transport: Duplex = url.protocol === 'https:' - ? tls.connect({ socket: stream, servername: url.hostname }) + ? tls.connect({ + socket: stream, + servername, + rejectUnauthorized: tlsOpts.rejectUnauthorized ?? true, + }) : stream; const chunks: Buffer[] = []; let total = 0; - const maxBytes = 256 * 1024; const done = (err?: Error) => { if (settled) return; settled = true; clearTimeout(timer); transport.destroy(); + stream.destroy(); if (err) { reject(err); return; @@ -40,36 +97,53 @@ function readHttpFromStream( const raw = Buffer.concat(chunks).toString('utf8'); const headerEnd = raw.indexOf('\r\n\r\n'); const head = headerEnd >= 0 ? raw.slice(0, headerEnd) : raw; - const body = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; + const rawBody = headerEnd >= 0 ? raw.slice(headerEnd + 4) : ''; const statusLine = head.split('\r\n')[0] ?? ''; const m = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/.exec(statusLine); if (!m) { reject(new Error(`Invalid HTTP response line: ${statusLine}`)); return; } - resolve({ statusCode: Number(m[1]), body }); + resolve({ + statusCode: Number(m[1]), + body: decodeChunkedIfNeeded(head, rawBody), + certExpiryDays, + }); }; transport.on('data', (chunk: Buffer) => { - if (total < maxBytes) { - chunks.push(chunk.subarray(0, maxBytes - total)); + if (total < MAX_PROBE_BODY_BYTES) { + chunks.push(chunk.subarray(0, MAX_PROBE_BODY_BYTES - total)); total += chunk.length; + } else { + transport.destroy(); } }); transport.once('end', () => done()); transport.once('close', () => done()); transport.once('error', (err) => done(err)); + if (transport !== stream) { + stream.once('error', (err) => done(err)); + } const pathAndQuery = `${url.pathname || '/'}${url.search || ''}`; const hostHeader = url.port ? `${url.hostname}:${url.port}` : url.hostname; const reqText = `GET ${pathAndQuery} HTTP/1.1\r\n` + `Host: ${hostHeader}\r\n` + - `User-Agent: GCoordinator-Probe/1.0\r\n` + + `User-Agent: GCoordinator-Probe/1.1\r\n` + + `Accept-Encoding: identity\r\n` + `Connection: close\r\n\r\n`; if (url.protocol === 'https:') { (transport as tls.TLSSocket).once('secureConnect', () => { + const cert = (transport as tls.TLSSocket).getPeerCertificate(false); + if (cert && typeof cert.valid_to === 'string') { + const expMs = Date.parse(cert.valid_to); + if (Number.isFinite(expMs)) { + certExpiryDays = Math.floor((expMs - Date.now()) / 86_400_000); + } + } transport.write(reqText); }); } else { @@ -79,16 +153,26 @@ function readHttpFromStream( } export class ProbeRunner { - constructor(private readonly sshPool: SSHPool) {} + constructor( + private readonly sshPool: SSHPool, + private readonly configManager?: ConfigManager, + ) {} + + runSingleProbe(serverId: string, probe: ServerProbe): Promise { + return this.runProbe(serverId, probe); + } async runProbe(serverId: string, probe: ServerProbe): Promise { const started = Date.now(); + const allowedCidrs = this.configManager?.getSettings().security.egressAllowedCidrs ?? []; + try { if (probe.type === 'tcp') { if (probe.from === 'hub') { + const ips = await resolveAllowedEgressIps(probe.host, allowedCidrs); await new Promise((resolve, reject) => { const sock = net.createConnection({ - host: probe.host, + host: ips[0]!, port: probe.port, }); const timer = setTimeout(() => { @@ -125,19 +209,35 @@ export class ProbeRunner { } // HTTP(S) probe + const parsedUrl = new URL(probe.url); let statusCode: number; let body: string; + let certExpiryDays: number | undefined; if (probe.from === 'hub') { - const res = await fetch(probe.url, { - method: 'GET', - redirect: 'manual', - signal: AbortSignal.timeout(probe.timeoutMs), - }); - statusCode = res.status; - body = await res.text(); + if ( + parsedUrl.protocol === 'https:' && + (probe.tlsRejectUnauthorized === false || probe.tlsCheckExpiryDays !== undefined) + ) { + const ips = await resolveAllowedEgressIps(parsedUrl.hostname, allowedCidrs); + const port = parsedUrl.port ? Number(parsedUrl.port) : 443; + const sock = net.createConnection({ host: ips[0]!, port }); + const resp = await readHttpFromStream(sock, parsedUrl, probe.timeoutMs, { + rejectUnauthorized: probe.tlsRejectUnauthorized, + }); + statusCode = resp.statusCode; + body = resp.body; + certExpiryDays = resp.certExpiryDays; + } else { + const res = await fetchWithEgressGuard( + probe.url, + { method: 'GET', redirect: 'manual' }, + { allowedCidrs, timeoutMs: probe.timeoutMs }, + ); + statusCode = res.status; + body = await readResponseTextCapped(res, MAX_PROBE_BODY_BYTES); + } } else { - const parsedUrl = new URL(probe.url); const port = parsedUrl.port ? Number(parsedUrl.port) : parsedUrl.protocol === 'https:' @@ -149,24 +249,40 @@ export class ProbeRunner { port, probe.timeoutMs, ); - const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs); + const resp = await readHttpFromStream(stream, parsedUrl, probe.timeoutMs, { + rejectUnauthorized: probe.tlsRejectUnauthorized, + }); statusCode = resp.statusCode; body = resp.body; + certExpiryDays = resp.certExpiryDays; } const statusOk = statusCode === probe.expectedStatus; const bodyOk = probe.bodyIncludes ? body.includes(probe.bodyIncludes) : true; - const ok = statusOk && bodyOk; + const certOk = + probe.tlsCheckExpiryDays !== undefined && certExpiryDays !== undefined + ? certExpiryDays >= probe.tlsCheckExpiryDays + : true; + const ok = statusOk && bodyOk && certOk; + + let error: string | undefined; + if (!ok) { + if (!statusOk) { + error = `Expected HTTP ${probe.expectedStatus}, got ${statusCode}`; + } else if (!bodyOk) { + error = `Response body missing substring "${probe.bodyIncludes}"`; + } else { + error = `TLS certificate expires in ${certExpiryDays}d (threshold ${probe.tlsCheckExpiryDays}d)`; + } + } + return { probeId: probe.id, ok, statusCode, latencyMs: Date.now() - started, - error: ok - ? undefined - : !statusOk - ? `Expected HTTP ${probe.expectedStatus}, got ${statusCode}` - : `Response body missing substring "${probe.bodyIncludes}"`, + certExpiryDays, + error, }; } catch (err) { return { diff --git a/src/server/monitoring/prometheus.ts b/src/server/monitoring/prometheus.ts new file mode 100644 index 0000000..a69692c --- /dev/null +++ b/src/server/monitoring/prometheus.ts @@ -0,0 +1,180 @@ +import crypto from 'node:crypto'; +import type { Request, Response } from 'express'; +import type { AlertEngine } from '../alerts/alert-engine.js'; +import type { ConfigManager } from '../config/config-manager.js'; +import { sha256Hex } from '../security/auth.js'; +import type { VaultService } from '../security/vault.js'; +import type { SSHPool } from '../ssh/ssh-pool.js'; +import type { TunnelManager } from '../ssh/tunnel-manager.js'; +import type { MonitoringService } from './monitoring-service.js'; + +export interface PrometheusHandlerDeps { + configManager: ConfigManager; + vaultService: VaultService; + sshPool: SSHPool; + monitoringService: MonitoringService; + tunnelManager: TunnelManager; + alertEngine: AlertEngine; +} + +function escapePromLabel(val: string): string { + return val.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n'); +} + +function labels(pairs: Record): string { + const parts = Object.entries(pairs).map( + ([k, v]) => `${k}="${escapePromLabel(v)}"`, + ); + return parts.length > 0 ? `{${parts.join(',')}}` : ''; +} + +function constantTimeTokenMatch(provided: string, expectedSha256Hex: string): boolean { + if (!/^[a-f0-9]{64}$/i.test(expectedSha256Hex)) return false; + const providedDigest = Buffer.from(sha256Hex(provided), 'hex'); + const expectedDigest = Buffer.from(expectedSha256Hex.toLowerCase(), 'hex'); + if (providedDigest.length !== expectedDigest.length) return false; + return crypto.timingSafeEqual(providedDigest, expectedDigest); +} + +export function createPrometheusHandler(deps: PrometheusHandlerDeps) { + const { + configManager, + vaultService, + sshPool, + monitoringService, + tunnelManager, + alertEngine, + } = deps; + + return (req: Request, res: Response): void => { + const settings = configManager.getSettings(); + if (!settings.metrics.prometheusEnabled) { + res.status(404).json({ error: 'METRICS_DISABLED' }); + return; + } + + const authHeader = typeof req.headers.authorization === 'string' ? req.headers.authorization : ''; + const bearerMatch = /^Bearer\s+(.+)$/i.exec(authHeader.trim()); + const providedToken = bearerMatch?.[1]?.trim() ?? ''; + + let authorized = false; + if (providedToken) { + if (settings.metrics.prometheusSecretRef && vaultService.isRuntimeReady) { + const cred = vaultService.getRuntimeSecret(settings.metrics.prometheusSecretRef); + const rawSecret = + cred?.type === 'api-token' + ? cred.token + : cred?.type === 'webhook-secret' + ? cred.secret + : undefined; + if (rawSecret) { + authorized = constantTimeTokenMatch(providedToken, sha256Hex(rawSecret)); + } + } + if (!authorized && settings.metrics.prometheusTokenHash) { + authorized = constantTimeTokenMatch(providedToken, settings.metrics.prometheusTokenHash); + } + } + + if (!authorized) { + res.setHeader('WWW-Authenticate', 'Bearer realm="GCoordinator"'); + res.status(401).json({ error: 'METRICS_UNAUTHORIZED' }); + return; + } + + const lines: string[] = []; + const metric = (name: string, help: string, type: 'gauge' | 'counter', rows: string[]) => { + lines.push(`# HELP ${name} ${help}`); + lines.push(`# TYPE ${name} ${type}`); + lines.push(...rows); + }; + + const states = new Map(sshPool.getStates().map((s) => [s.serverId, s])); + const servers = configManager.listServers(); + + const upRows: string[] = []; + const cpuRows: string[] = []; + const memUsedRows: string[] = []; + const memTotalRows: string[] = []; + const load1Rows: string[] = []; + const uptimeRows: string[] = []; + const netRxRows: string[] = []; + const netTxRows: string[] = []; + const diskRows: string[] = []; + const probeUpRows: string[] = []; + const probeLatencyRows: string[] = []; + const probeTlsExpiryRows: string[] = []; + + for (const srv of servers) { + const state = states.get(srv.id); + const isUp = state?.status === 'connected' ? 1 : 0; + const baseLabels = labels({ server_id: srv.id, name: srv.name }); + upRows.push(`gcoordinator_server_up${baseLabels} ${isUp}`); + + const latest = monitoringService.getLatest(srv.id); + if (latest?.sample) { + const s = latest.sample; + cpuRows.push(`gcoordinator_server_cpu_percent${baseLabels} ${s.cpuPct}`); + memUsedRows.push( + `gcoordinator_server_memory_used_bytes${baseLabels} ${Math.round(s.memUsedMb * 1024 * 1024)}`, + ); + memTotalRows.push( + `gcoordinator_server_memory_total_bytes${baseLabels} ${Math.round(s.memTotalMb * 1024 * 1024)}`, + ); + load1Rows.push(`gcoordinator_server_load1${baseLabels} ${s.load1m}`); + uptimeRows.push(`gcoordinator_server_uptime_seconds${baseLabels} ${s.uptimeSec}`); + netRxRows.push(`gcoordinator_server_net_rx_bytes_per_sec${baseLabels} ${s.netRxBps}`); + netTxRows.push(`gcoordinator_server_net_tx_bytes_per_sec${baseLabels} ${s.netTxBps}`); + } + if (latest?.disks) { + for (const d of latest.disks) { + const dl = labels({ server_id: srv.id, mount: d.mountPoint }); + diskRows.push(`gcoordinator_server_disk_used_percent${dl} ${d.usedPct}`); + } + } + if (latest?.probes) { + for (const p of Object.values(latest.probes)) { + const pl = labels({ server_id: srv.id, probe_id: p.probeId }); + probeUpRows.push(`gcoordinator_probe_up${pl} ${p.ok ? 1 : 0}`); + probeLatencyRows.push(`gcoordinator_probe_latency_ms${pl} ${p.latencyMs}`); + if (typeof p.certExpiryDays === 'number') { + probeTlsExpiryRows.push(`gcoordinator_probe_tls_expiry_days${pl} ${p.certExpiryDays}`); + } + } + } + } + + metric('gcoordinator_server_up', 'Server SSH reachability (1=connected, 0=disconnected)', 'gauge', upRows); + metric('gcoordinator_server_cpu_percent', 'Latest sampled CPU utilization percentage', 'gauge', cpuRows); + metric('gcoordinator_server_memory_used_bytes', 'Latest sampled memory used in bytes', 'gauge', memUsedRows); + metric('gcoordinator_server_memory_total_bytes', 'Total RAM in bytes', 'gauge', memTotalRows); + metric('gcoordinator_server_load1', 'Latest 1-minute load average', 'gauge', load1Rows); + metric('gcoordinator_server_uptime_seconds', 'Server uptime in seconds', 'gauge', uptimeRows); + metric('gcoordinator_server_net_rx_bytes_per_sec', 'Network receive throughput B/s', 'gauge', netRxRows); + metric('gcoordinator_server_net_tx_bytes_per_sec', 'Network transmit throughput B/s', 'gauge', netTxRows); + metric('gcoordinator_server_disk_used_percent', 'Disk filesystem usage percentage', 'gauge', diskRows); + metric('gcoordinator_probe_up', 'Latest health probe result (1=ok, 0=fail)', 'gauge', probeUpRows); + metric('gcoordinator_probe_latency_ms', 'Latest health probe latency in ms', 'gauge', probeLatencyRows); + if (probeTlsExpiryRows.length > 0) { + metric('gcoordinator_probe_tls_expiry_days', 'Days remaining until TLS certificate expiry', 'gauge', probeTlsExpiryRows); + } + + const activeTunnels = tunnelManager.listTunnels().filter((t) => t.active).length; + metric('gcoordinator_tunnels_active', 'Number of currently active SSH tunnels', 'gauge', [ + `gcoordinator_tunnels_active ${activeTunnels}`, + ]); + metric('gcoordinator_alerts_active', 'Number of active unresolved alert incidents', 'gauge', [ + `gcoordinator_alerts_active ${alertEngine.getActiveCount()}`, + ]); + metric('gcoordinator_process_resident_memory_bytes', 'Hub Node.js resident set size bytes', 'gauge', [ + `gcoordinator_process_resident_memory_bytes ${process.memoryUsage().rss}`, + ]); + metric('gcoordinator_process_uptime_seconds', 'Hub Node.js process uptime in seconds', 'gauge', [ + `gcoordinator_process_uptime_seconds ${Math.round(process.uptime())}`, + ]); + + res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8'); + res.setHeader('Cache-Control', 'no-store'); + res.send(`${lines.join('\n')}\n`); + }; +} diff --git a/src/shared/schemas/settings.schema.ts b/src/shared/schemas/settings.schema.ts index 811b3e9..003e01c 100644 --- a/src/shared/schemas/settings.schema.ts +++ b/src/shared/schemas/settings.schema.ts @@ -86,6 +86,7 @@ export const SettingsSchema = z.object({ .object({ prometheusEnabled: z.boolean().default(false), prometheusSecretRef: EntityIdSchema.optional(), + prometheusTokenHash: z.string().regex(/^[a-f0-9]{64}$/).optional(), }) .default({ prometheusEnabled: false }), security: SecuritySettingsSchema.default({}), diff --git a/src/shared/ws-protocol.ts b/src/shared/ws-protocol.ts index 0dc686c..6a8092a 100644 --- a/src/shared/ws-protocol.ts +++ b/src/shared/ws-protocol.ts @@ -49,6 +49,7 @@ export interface ProbeSample { ok: boolean; statusCode?: number; latencyMs: number; + certExpiryDays?: number; error?: string; } diff --git a/tests/monitoring-and-probes.test.ts b/tests/monitoring-and-probes.test.ts index 46d8097..c15573e 100644 --- a/tests/monitoring-and-probes.test.ts +++ b/tests/monitoring-and-probes.test.ts @@ -170,7 +170,7 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () await cfg.init({ watch: false }); const knownHosts = new KnownHostsService(db, audit); const sshPool = new SSHPool(cfg, vault, knownHosts); - const probeRunner = new ProbeRunner(sshPool); + const probeRunner = new ProbeRunner(sshPool, cfg); const inspector = new ServerInspector(sshPool, cfg); const monitoring = new MonitoringService(db, cfg, vault, sshPool, probeRunner); @@ -222,6 +222,15 @@ describe('OS Collectors, ServerInspector, Health Probes & MonitoringService', () ); const serverCfg = cfg.getServer('linux-01')!; + // Hub loopback HTTP probe is blocked by default Zero-Trust egress policy until explicitly allowlisted + const hubProbe = serverCfg.probes.find((p) => p.id === 'hub-http')!; + const deniedSample = await probeRunner.runProbe('linux-01', hubProbe); + expect(deniedSample.ok).toBe(false); + + const nextSettings = cfg.getSettings(); + nextSettings.security.egressAllowedCidrs = ['127.0.0.1/32']; + cfg.saveConfigText('settings.json', JSON.stringify(nextSettings, null, 2)); + for (const p of serverCfg.probes) { const sample = await probeRunner.runProbe('linux-01', p); expect(sample.ok).toBe(true); From d5822c9eca0cd27deddff1363f9ada3b6fcabaa2 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:02:09 +0000 Subject: [PATCH 10/19] feat(systems): harden CustomSystemsEngine/presets, add systemd editableFiles, parallel inspection & action inputs --- src/server/api/routes/systems.routes.ts | 93 +++-- src/server/app.ts | 8 +- src/server/config/presets.ts | 4 +- src/server/systems/parsers.ts | 14 +- src/server/systems/systems-engine.ts | 464 ++++++++++++++++++++---- 5 files changed, 468 insertions(+), 115 deletions(-) diff --git a/src/server/api/routes/systems.routes.ts b/src/server/api/routes/systems.routes.ts index 7ddb676..d63c03e 100644 --- a/src/server/api/routes/systems.routes.ts +++ b/src/server/api/routes/systems.routes.ts @@ -1,4 +1,4 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { z } from 'zod'; import type { AuditService } from '../../security/audit.js'; import type { AuthService } from '../../security/auth.js'; @@ -6,6 +6,7 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; import type { CustomSystemsEngine } from '../../systems/systems-engine.js'; @@ -13,11 +14,12 @@ export interface SystemsRouterDeps { authService: AuthService; auditService: AuditService; systemsEngine: CustomSystemsEngine; + stepUpGuard?: RequestHandler; } export function createSystemsRouter(deps: SystemsRouterDeps): Router { const router = Router(); - const { authService, auditService, systemsEngine } = deps; + const { authService, auditService, systemsEngine, stepUpGuard = requireStepUp } = deps; router.get('/', requireAuth(authService), (_req, res) => { res.json({ systems: systemsEngine.listSystemsOverview() }); @@ -153,7 +155,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, - async (req, res) => { + (req, res) => { const systemId = String(req.params.systemId ?? ''); const serverId = String(req.params.serverId ?? ''); const actionId = String(req.params.actionId ?? ''); @@ -161,6 +163,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { .object({ itemName: z.string().min(1).optional(), subItemName: z.string().min(1).optional(), + inputs: z.record(z.unknown()).optional(), cols: z.number().int().min(10).max(500).optional(), rows: z.number().int().min(4).max(200).optional(), }) @@ -170,43 +173,75 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router { return; } - try { - const result = await systemsEngine.executeAction({ - serverId, - systemId, - actionId, - ...parsed.data, - }); - auditService.log({ - action: 'system.action', - actorIp: req.clientIp ?? 'unknown', - sessionIdHash: req.authSession!.idHash, - target: `${serverId}:${systemId}:${actionId}`, - status: 'ok', - details: { - itemName: parsed.data.itemName, - subItemName: parsed.data.subItemName, - mode: result.mode, - }, - }); - res.json(result); - } catch (err) { - res.status(400).json({ - error: 'SYSTEM_ACTION_FAILED', - message: err instanceof Error ? err.message : 'Unable to execute system action', + const actionMeta = systemsEngine.getActionMeta(systemId, actionId); + const execute = async () => { + try { + const result = await systemsEngine.executeAction({ + serverId, + systemId, + actionId, + ...parsed.data, + }); + const secretInputKeys = new Set( + (actionMeta?.inputs ?? []).filter((i) => i.type === 'secret').map((i) => i.name), + ); + const sanitizedInputs = parsed.data.inputs + ? Object.fromEntries( + Object.entries(parsed.data.inputs).map(([k, v]) => [ + k, + secretInputKeys.has(k) ? '[REDACTED]' : v, + ]), + ) + : undefined; + auditService.log({ + action: 'system.action', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: `${serverId}:${systemId}:${actionId}`, + status: 'ok', + details: { + itemName: parsed.data.itemName, + subItemName: parsed.data.subItemName, + inputs: sanitizedInputs, + mode: result.mode, + }, + }); + res.json(result); + } catch (err) { + res.status(400).json({ + error: 'SYSTEM_ACTION_FAILED', + message: err instanceof Error ? err.message : 'Unable to execute system action', + }); + } + }; + + if (actionMeta?.confirm || actionMeta?.sudo) { + stepUpGuard(req, res, () => { + void execute(); }); + return; } + void execute(); }, ); + // Cancelling a running stream must work even if Safe Mode was just toggled on router.post( '/streams/:jobId/cancel', requireAuth(authService), requireCsrf, - enforceSafeMode, (req, res) => { const jobId = String(req.params.jobId ?? ''); - res.json({ cancelled: systemsEngine.cancelStream(jobId) }); + const cancelled = systemsEngine.cancelStream(jobId); + auditService.log({ + action: 'system.stream_cancel', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: jobId, + status: 'ok', + details: { cancelled }, + }); + res.json({ cancelled }); }, ); diff --git a/src/server/app.ts b/src/server/app.ts index b51d6b0..ea238e2 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -194,6 +194,7 @@ export async function createGCoordinatorServer( vaultService, ptyManager, wsHub, + getRuntimeLimits, ); const serverInspector = new ServerInspector(sshPool, configManager); const probeRunner = new ProbeRunner(sshPool, configManager); @@ -566,7 +567,12 @@ export async function createGCoordinatorServer( ); app.use( '/api/systems', - createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }), + createSystemsRouter({ + authService, + auditService, + systemsEngine: customSystemsEngine, + stepUpGuard, + }), ); app.use( '/api/workflows', diff --git a/src/server/config/presets.ts b/src/server/config/presets.ts index b603c41..5579fa3 100644 --- a/src/server/config/presets.ts +++ b/src/server/config/presets.ts @@ -138,12 +138,12 @@ export const PRESET_SYSTEMS: SystemConfig[] = [ discovery: { type: 'command', command: - 'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'{print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }', + 'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'NF && $1 !~ /^UNIT$/ {print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E -- "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }', parser: 'lines', }, status: { command: - 'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {gsub(/"/,"\\\\\"",$2); printf "\\"%s\\":\\"%s\\"",$1,$2} END{printf "}\\n"}\'', + 'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID,FragmentPath,DropInPaths --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {key=$1; sub(/^[^=]*=/,""); gsub(/\\\\/,"\\\\\\\\"); gsub(/"/,"\\\\\""); gsub(/\\t/," "); printf "\\"%s\\":\\"%s\\"",key,$0} END{printf "}\\n"}\'', parser: 'json', health: { field: 'ActiveState', diff --git a/src/server/systems/parsers.ts b/src/server/systems/parsers.ts index 1f7a4ce..aa9d85e 100644 --- a/src/server/systems/parsers.ts +++ b/src/server/systems/parsers.ts @@ -17,6 +17,7 @@ export interface ParsedStatusResult { subItems: ParsedSubItem[]; rawSummary: string; exitCode: number | null; + raw?: Record; } export interface ScannedFolderMatch { @@ -25,10 +26,11 @@ export interface ScannedFolderMatch { } export function globToRegExp(pattern: string): RegExp { - const escaped = pattern + const collapsed = pattern.slice(0, 128).replace(/\*+/g, '*'); + const escaped = collapsed .replace(/[.+^${}()|[\]\\]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/\?/g, '.'); + .replace(/\*/g, '[^/]*') + .replace(/\?/g, '[^/]'); return new RegExp(`^${escaped}$`); } @@ -314,6 +316,7 @@ export function parseStatusOutput( subItems: [], rawSummary: summarizeRecord(rec), exitCode, + raw: rec, }; } } catch { @@ -327,15 +330,16 @@ export function parseStatusOutput( } if (statusCfg.parser === 'regex') { + const bounded = trimmed.length > 262_144 ? trimmed.slice(0, 262_144) : trimmed; const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null; - const matched = re ? re.test(trimmed) : trimmed.length > 0; + const matched = re ? re.test(bounded) : bounded.length > 0; const exitOk = statusCfg.health?.healthyExitCodes ? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode) : exitCode === null || exitCode === 0; return { health: exitOk && matched ? 'ok' : 'down', subItems: [], - rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '), + rawSummary: bounded.split(/\r?\n/).slice(0, 4).join(' | '), exitCode, }; } diff --git a/src/server/systems/systems-engine.ts b/src/server/systems/systems-engine.ts index b6ff48a..3ec5092 100644 --- a/src/server/systems/systems-engine.ts +++ b/src/server/systems/systems-engine.ts @@ -5,6 +5,7 @@ import type { SystemAction, SystemConfig } from '../../shared/schemas/system.sch 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 { RuntimeLimits } from '../config/runtime-limits.js'; import type { VaultService } from '../security/vault.js'; import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -64,19 +65,65 @@ interface ActiveStreamJob { bufferBytes: number; done: boolean; abort: () => void; + timeoutTimer?: NodeJS.Timeout; + idleTimer?: NodeJS.Timeout; } -const MAX_STREAM_REPLAY_BYTES = 128 * 1024; const MAX_RETAINED_DONE_STREAMS = 25; +const MAX_DISCOVERED_ITEMS = 500; +const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); +const SUBITEM_SAFE_RE = /^[A-Za-z0-9._][A-Za-z0-9._:@/-]{0,127}$/; export function isValidRelativeOverlayFile(fileName: string): boolean { const clean = fileName.trim(); - if (!clean) return false; - if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false; - if (/[\s'"$;|&<>()`]/.test(clean)) return false; + if (!clean || clean.length > 255) return false; + if (FORBIDDEN_KEYS.has(clean)) return false; + if (clean.startsWith('-') || clean.includes('/') || clean.includes('\\') || clean.includes('..')) { + return false; + } + if (/[\x00-\x1f\x7f\s'"$;|&<>()`{}!*?[\]]/.test(clean)) return false; + return /^[A-Za-z0-9._][A-Za-z0-9._+-]*$/.test(clean); +} + +function isValidSubItemName(subItem: string): boolean { + const clean = subItem.trim(); + if (!clean || clean.startsWith('-') || clean.includes('..')) return false; + if (/[\x00-\x1f\x7f]/.test(clean)) return false; + return SUBITEM_SAFE_RE.test(clean); +} + +function isValidAbsolutePath(p: string): boolean { + if (!p.startsWith('/') || p.includes('..')) return false; + if (/[\x00-\x1f\x7f]/.test(p)) return false; return true; } +function assertSafeKey(key: string, label = 'key'): void { + if (!key || FORBIDDEN_KEYS.has(key) || /[\x00-\x1f\x7f]/.test(key)) { + throw new Error(`Unsafe ${label}: "${key}"`); + } +} + +async function runPool( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + if (items.length === 0) return []; + const cap = Math.max(1, Math.min(items.length, concurrency)); + const results = new Array(items.length); + let cursor = 0; + + const runners = Array.from({ length: cap }, async () => { + while (cursor < items.length) { + const idx = cursor++; + results[idx] = await worker(items[idx]!); + } + }); + await Promise.all(runners); + return results; +} + function expandShellRoot(root: string): string { const trimmed = root.trim(); if (trimmed === '~' || trimmed === '~/') return '"$HOME"'; @@ -85,20 +132,27 @@ function expandShellRoot(root: string): string { } function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string { + const safeDepth = Math.max(1, Math.min(5, Math.floor(maxDepth))); const rootArgs = roots.map(expandShellRoot).join(' '); - const casePatterns = matchFiles - .map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, '')) - .filter(Boolean) - .join('|') || '*'; + const casePatterns = + matchFiles + .map((p) => p.replace(/[^A-Za-z0-9._*?-]/g, '')) + .filter((p) => p && !p.startsWith('-')) + .slice(0, 32) + .join('|') || '*'; return [ + `TAB=$(printf '\\t'); CR=$(printf '\\r')`, `for r in ${rootArgs}; do`, + ` case "$r" in -*) r="./$r" ;; esac`, ` [ -d "$r" ] || continue`, - ` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`, + ` find "$r" -maxdepth ${safeDepth} -type d 2>/dev/null | while IFS= read -r d; do`, + ` case "$d" in *"$TAB"*|*"$CR"*) continue ;; esac`, ` matched=0`, ` for f in "$d"/* "$d"/.*; do`, ` [ -f "$f" ] || continue`, ` b=\${f##*/}`, + ` [ "$b" = "." ] || [ "$b" = ".." ] && continue`, ` case "$b" in`, ` ${casePatterns}) matched=1; break ;;`, ` esac`, @@ -116,6 +170,16 @@ function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: st ].join('\n'); } +function substituteActionInputs( + command: string, + inputs: Record, +): string { + return command.replace(/\{\{\s*input\.([a-zA-Z0-9._-]+)\s*\}\}/g, (_match, key: string) => { + assertSafeKey(key, 'input name'); + return posixSingleQuote(inputs[key] ?? ''); + }); +} + export class CustomSystemsEngine { private readonly cache = new Map(); private readonly streamJobs = new Map(); @@ -128,6 +192,7 @@ export class CustomSystemsEngine { private readonly vaultService: VaultService, private readonly ptyManager: PTYManager, private readonly wsHub: WsHub, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void { @@ -137,6 +202,11 @@ export class CustomSystemsEngine { }; } + getActionMeta(systemId: string, actionId: string): SystemAction | undefined { + const sys = this.configManager.getSystem(systemId); + return sys?.actions.find((a) => a.id === actionId); + } + getStreamReplayFrames(jobId: string): ServerWsFrame[] { const job = this.streamJobs.get(jobId); return job ? [...job.frames] : []; @@ -199,10 +269,12 @@ export class CustomSystemsEngine { .filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId)) .filter((s) => !opts.serverId || s.id === opts.serverId); - const snapshots = await Promise.all( - targets.map((srv) => - this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), - ), + const concurrency = Math.max( + 1, + this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2, + ); + const snapshots = await runPool(targets, concurrency, (srv) => + this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), ); return { system, snapshots }; @@ -247,7 +319,7 @@ export class CustomSystemsEngine { 'ok', ), }; - this.cache.set(cacheKey, snapshot); + this.setCacheBounded(cacheKey, snapshot); this.emitHealth(snapshot); return snapshot; } catch (err) { @@ -261,16 +333,68 @@ export class CustomSystemsEngine { items: [], systemHealth: 'down', }; + this.emitHealth(snapshot); return snapshot; } } + private resolveActionInputs( + action: SystemAction, + suppliedInputs?: Record, + ): { resolved: Record; secretNames: Set } { + const supplied = suppliedInputs ?? {}; + for (const k of Object.keys(supplied)) { + assertSafeKey(k, 'input parameter'); + } + + const resolved: Record = {}; + const secretNames = new Set(); + for (const def of action.inputs ?? []) { + assertSafeKey(def.name, 'input definition'); + if (def.type === 'secret') secretNames.add(def.name); + + let rawVal = Object.hasOwn(supplied, def.name) ? supplied[def.name] : def.default; + if (rawVal === undefined || rawVal === null || rawVal === '') { + if (def.required) { + throw new Error(`Missing required input "${def.name}" for action "${action.id}"`); + } + continue; + } + + if (def.type === 'number') { + const n = Number(rawVal); + if (!Number.isFinite(n)) { + throw new Error(`Input "${def.name}" must be a finite number`); + } + rawVal = String(n); + } else if (def.type === 'boolean') { + rawVal = rawVal === true || rawVal === 'true' ? 'true' : 'false'; + } else { + const str = String(rawVal); + if (/[\x00]/.test(str)) { + throw new Error(`Input "${def.name}" contains NUL bytes`); + } + if (def.type === 'select' && def.options && def.options.length > 0) { + if (!def.options.includes(str)) { + throw new Error(`Input "${def.name}" value is not in allowed options`); + } + } + rawVal = str; + } + + resolved[def.name] = String(rawVal); + } + + return { resolved, secretNames }; + } + private resolveActionContext(params: { serverId: string; systemId: string; actionId: string; itemName?: string; subItemName?: string; + inputs?: Record; }) { return (async () => { const system = this.configManager.getSystem(params.systemId); @@ -287,7 +411,13 @@ export class CustomSystemsEngine { throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); } + if (params.itemName) assertSafeKey(params.itemName, 'itemName'); + if (params.subItemName && !isValidSubItemName(params.subItemName)) { + throw new Error(`Invalid subItemName "${params.subItemName}"`); + } + const resolvedParams = this.resolveParams(system, attachment.params); + const { resolved: actionInputs } = this.resolveActionInputs(action, params.inputs); let item: DiscoveredSystemItem | undefined; if (action.scope === 'item' || action.scope === 'subitem') { @@ -299,8 +429,18 @@ export class CustomSystemsEngine { if (!item) { throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); } - if (action.scope === 'subitem' && !params.subItemName) { - throw new Error(`Action "${action.id}" requires subItemName`); + if (action.scope === 'subitem') { + if (!params.subItemName) { + throw new Error(`Action "${action.id}" requires subItemName`); + } + if ( + item.status.subItems.length > 0 && + !item.status.subItems.some((s) => s.name === params.subItemName) + ) { + throw new Error( + `Sub-item "${params.subItemName}" was not discovered under "${item.name}"`, + ); + } } } @@ -310,13 +450,15 @@ export class CustomSystemsEngine { resolvedParams, item, params.subItemName, + actionInputs, ); + const substitutedCmd = substituteActionInputs(action.command, actionInputs); const execCmd = item?.dir - ? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` - : action.command; + ? `cd -- ${posixSingleQuote(item.dir)} && ${substitutedCmd}` + : substitutedCmd; - return { system, server, action, item, env, execCmd }; + return { system, server, action, item, env, execCmd, substitutedCmd }; })(); } @@ -326,6 +468,7 @@ export class CustomSystemsEngine { actionId: string; itemName?: string; subItemName?: string; + inputs?: Record; timeoutMs?: number; signal?: AbortSignal; onChunk?: (stream: 'stdout' | 'stderr', text: string) => void; @@ -344,7 +487,7 @@ export class CustomSystemsEngine { throw new Error('Interactive PTY actions cannot run unattended in workflows'); } - const timeoutMs = params.timeoutMs ?? 300_000; + const timeoutMs = params.timeoutMs ?? (action.timeoutSec ?? 300) * 1000; const started = Date.now(); const handle = await this.sshPool.execStream(server.id, execCmd, { env, @@ -434,17 +577,18 @@ export class CustomSystemsEngine { actionId: string; itemName?: string; subItemName?: string; + inputs?: Record; cols?: number; rows?: number; }): Promise { - const { system, server, action, item, env, execCmd } = + const { system, server, action, item, env, execCmd, substitutedCmd } = await this.resolveActionContext(params); if (action.mode === 'oneshot') { const res = await this.sshPool.exec(server.id, execCmd, { env, sudo: action.sudo, - timeoutMs: 120_000, + timeoutMs: (action.timeoutSec ?? 120) * 1000, }); this.invalidateCache(server.id, system.id); return { @@ -460,7 +604,7 @@ export class CustomSystemsEngine { const session = await this.ptyManager.openSession({ serverId: server.id, cwd: item?.dir, - command: action.command, + command: substitutedCmd, env, sudo: action.sudo, cols: params.cols, @@ -471,13 +615,14 @@ export class CustomSystemsEngine { return { mode: 'interactive', session }; } - // Stream mode + // Stream mode with timeout & idle reaper const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`; const handle = await this.sshPool.execStream(server.id, execCmd, { env, sudo: action.sudo, }); + const maxReplayBytes = this.getRuntimeLimits?.().streamReplayBytes ?? 128 * 1024; const job: ActiveStreamJob = { jobId, serverId: server.id, @@ -489,12 +634,23 @@ export class CustomSystemsEngine { }; this.streamJobs.set(jobId, job); + const clearJobTimers = () => { + if (job.timeoutTimer) { + clearTimeout(job.timeoutTimer); + job.timeoutTimer = undefined; + } + if (job.idleTimer) { + clearTimeout(job.idleTimer); + job.idleTimer = undefined; + } + }; + const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => { const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data }; const bytes = Buffer.byteLength(data, 'utf8'); job.frames.push(frame); job.bufferBytes += bytes; - while (job.bufferBytes > MAX_STREAM_REPLAY_BYTES && job.frames.length > 0) { + while (job.bufferBytes > maxReplayBytes && job.frames.length > 0) { const dropped = job.frames.shift()!; if (dropped.type === 'stream:chunk') { job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); @@ -503,6 +659,28 @@ export class CustomSystemsEngine { this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame); }; + const maxStreamMs = (action.timeoutSec ?? 600) * 1000; + job.timeoutTimer = setTimeout(() => { + if (job.done) return; + pushFrame( + 'meta', + JSON.stringify({ event: 'timeout', message: `Stream exceeded ${maxStreamMs}ms limit` }), + ); + handle.abort(); + }, maxStreamMs); + job.timeoutTimer.unref(); + + const bumpIdleTimer = () => { + if (job.idleTimer) clearTimeout(job.idleTimer); + job.idleTimer = setTimeout(() => { + if (job.done) return; + pushFrame('meta', JSON.stringify({ event: 'timeout', message: 'Stream idle timeout' })); + handle.abort(); + }, Math.min(maxStreamMs, 300_000)); + job.idleTimer.unref(); + }; + bumpIdleTimer(); + pushFrame( 'meta', JSON.stringify({ @@ -516,21 +694,25 @@ export class CustomSystemsEngine { ); handle.channel.on('data', (chunk: Buffer) => { + bumpIdleTimer(); pushFrame('stdout', chunk.toString('utf8')); }); handle.channel.stderr?.on('data', (chunk: Buffer) => { + bumpIdleTimer(); pushFrame('stderr', chunk.toString('utf8')); }); void handle.done .then(({ exitCode, signal }) => { job.done = true; + clearJobTimers(); this.invalidateCache(server.id, system.id); pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal })); this.pruneStreamJobs(); }) .catch((err) => { job.done = true; + clearJobTimers(); this.invalidateCache(server.id, system.id); pushFrame( 'meta', @@ -556,10 +738,11 @@ export class CustomSystemsEngine { throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); } + const validatedParams = this.validateAndResolveParamsStrict(system, params); const existing = server.systems.find((a) => a.systemId === systemId); const nextSystems = existing - ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a)) - : [...server.systems, { systemId, params, itemOverrides: {} }]; + ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params: validatedParams } : a)) + : [...server.systems, { systemId, params: validatedParams, itemOverrides: {} }]; const updated: ServerConfig = { ...server, systems: nextSystems }; this.configManager.saveConfigText( @@ -599,18 +782,38 @@ export class CustomSystemsEngine { itemName: string, activeFiles: string[], ): ServerConfig { + assertSafeKey(itemName, 'itemName'); + const system = this.configManager.getSystem(systemId); const server = this.configManager.getServer(serverId); - if (!server) { - throw new Error(`Unknown server "${serverId}"`); + if (!system || !server) { + throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); } - const cleanFiles = activeFiles.map((f) => f.trim()).filter(Boolean); + const cleanFiles = [...new Set(activeFiles.map((f) => f.trim()).filter(Boolean))]; if (cleanFiles.length === 0) { throw new Error('At least one active file must be selected'); } + + const cachedItem = this.cache + .get(`${serverId}:${systemId}`) + ?.items.find((i) => i.name === itemName); + const selectableRegexes = + system.discovery.type === 'folder-scan' + ? (system.discovery.selectableFiles ?? system.discovery.matchFiles).map(globToRegExp) + : []; + for (const file of cleanFiles) { if (!isValidRelativeOverlayFile(file)) { throw new Error(`Invalid overlay filename: "${file}"`); } + if (cachedItem && cachedItem.selectableFiles.length > 0) { + if (!cachedItem.selectableFiles.includes(file)) { + throw new Error(`Overlay file "${file}" was not discovered for item "${itemName}"`); + } + } else if (selectableRegexes.length > 0) { + if (!selectableRegexes.some((re) => re.test(file))) { + throw new Error(`Overlay file "${file}" does not match selectableFiles patterns`); + } + } } const hasAtt = server.systems.some((a) => a.systemId === systemId); @@ -620,20 +823,20 @@ export class CustomSystemsEngine { const updated: ServerConfig = { ...server, - systems: server.systems.map((att) => - att.systemId === systemId - ? { - ...att, - itemOverrides: { - ...att.itemOverrides, - [itemName]: { - ...(att.itemOverrides[itemName] ?? {}), - activeFiles: cleanFiles, - }, - }, - } - : att, - ), + systems: server.systems.map((att) => { + if (att.systemId !== systemId) return att; + const safeOverrides: Record = + Object.create(null); + for (const [k, v] of Object.entries(att.itemOverrides ?? {})) { + if (FORBIDDEN_KEYS.has(k)) continue; + safeOverrides[k] = v; + } + safeOverrides[itemName] = { + ...(Object.hasOwn(att.itemOverrides, itemName) ? att.itemOverrides[itemName] : {}), + activeFiles: cleanFiles, + }; + return { ...att, itemOverrides: safeOverrides }; + }), }; this.configManager.saveConfigText( @@ -679,6 +882,8 @@ export class CustomSystemsEngine { for (const job of this.streamJobs.values()) { if (!job.done) { job.done = true; + if (job.timeoutTimer) clearTimeout(job.timeoutTimer); + if (job.idleTimer) clearTimeout(job.idleTimer); job.abort(); } } @@ -690,6 +895,17 @@ export class CustomSystemsEngine { this.cache.clear(); } + private setCacheBounded(key: string, snapshot: ServerSystemSnapshot): void { + const maxEntries = Math.max(8, this.getRuntimeLimits?.().maxSystemCacheEntries ?? 64); + if (this.cache.has(key)) this.cache.delete(key); + this.cache.set(key, snapshot); + while (this.cache.size > maxEntries) { + const oldestKey = this.cache.keys().next().value; + if (!oldestKey) break; + this.cache.delete(oldestKey); + } + } + private async discoverAndInspectItems( server: ServerConfig, system: SystemConfig, @@ -697,6 +913,10 @@ export class CustomSystemsEngine { params: Record, ): Promise { const baseEnv = this.buildExecutionEnv(server.id, system.id, params); + const concurrency = Math.max( + 1, + this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2, + ); if (system.discovery.type === 'folder-scan') { const rawRoots = params[system.discovery.rootsParam]; @@ -713,7 +933,7 @@ export class CustomSystemsEngine { system.discovery.matchFiles, ); const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv }); - const rawMatches = parseFolderScanOutput(scanRes.stdout); + const rawMatches = parseFolderScanOutput(scanRes.stdout).slice(0, MAX_DISCOVERED_ITEMS); const matchRegexes = system.discovery.matchFiles.map(globToRegExp); const selectableRegexes = ( @@ -724,33 +944,45 @@ export class CustomSystemsEngine { .map(globToRegExp); const usedNames = new Map(); - const items: DiscoveredSystemItem[] = []; + const draftItems: DiscoveredSystemItem[] = []; for (const m of rawMatches) { - const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f))); + if (/[\x00-\x1f\x7f]/.test(m.dir)) continue; + const safeFiles = m.files.filter( + (f) => !/[\x00-\x1f\x7f]/.test(f) && !f.startsWith('-'), + ); + const matchedFiles = safeFiles.filter((f) => matchRegexes.some((re) => re.test(f))); if (matchedFiles.length === 0) continue; let baseName = path.posix.basename(m.dir) || 'root'; + if (FORBIDDEN_KEYS.has(baseName)) baseName = `item-${baseName}`; const seenCount = (usedNames.get(baseName) ?? 0) + 1; usedNames.set(baseName, seenCount); if (seenCount > 1) { baseName = `${baseName}-${seenCount}`; } - const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f))); - const editableFiles = m.files + const selectableFiles = safeFiles.filter( + (f) => isValidRelativeOverlayFile(f) && selectableRegexes.some((re) => re.test(f)), + ); + const editableFiles = safeFiles .filter((f) => editableRegexes.some((re) => re.test(f))) .map((f) => path.posix.join(m.dir, f)); - const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) => - isValidRelativeOverlayFile(f), + const overrideRaw = Object.hasOwn(attachment.itemOverrides, baseName) + ? attachment.itemOverrides[baseName]?.activeFiles + : undefined; + const overrideFiles = overrideRaw?.filter( + (f) => + isValidRelativeOverlayFile(f) && + (selectableFiles.length === 0 || selectableFiles.includes(f)), ); const activeFiles = overrideFiles && overrideFiles.length > 0 ? overrideFiles : [matchedFiles[0]!]; - const draftItem: DiscoveredSystemItem = { + draftItems.push({ name: baseName, dir: m.dir, activeFiles, @@ -762,12 +994,14 @@ export class CustomSystemsEngine { rawSummary: '', exitCode: null, }, - }; + }); + } + await runPool(draftItems, concurrency, async (draftItem) => { const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const statusRes = await this.sshPool.exec( server.id, - `cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`, + `cd -- ${posixSingleQuote(draftItem.dir!)} && ${system.status.command}`, { env: itemEnv }, ); draftItem.status = parseStatusOutput( @@ -776,32 +1010,33 @@ export class CustomSystemsEngine { statusRes.exitCode, system.status, ); - items.push(draftItem); - } + }); - return items; + return draftItems; } // command discovery const discRes = await this.sshPool.exec(server.id, system.discovery.command, { env: baseEnv, }); - const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser); - const items: DiscoveredSystemItem[] = []; + const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser) + .filter((n) => !FORBIDDEN_KEYS.has(n) && !/[\x00-\x1f\x7f]/.test(n)) + .slice(0, MAX_DISCOVERED_ITEMS); - for (const itemName of names) { - const draftItem: DiscoveredSystemItem = { - name: itemName, - activeFiles: [], - selectableFiles: [], - editableFiles: [], - status: { - health: 'unknown', - subItems: [], - rawSummary: '', - exitCode: null, - }, - }; + const draftItems: DiscoveredSystemItem[] = names.map((itemName) => ({ + name: itemName, + activeFiles: [], + selectableFiles: [], + editableFiles: [], + status: { + health: 'unknown', + subItems: [], + rawSummary: '', + exitCode: null, + }, + })); + + await runPool(draftItems, concurrency, async (draftItem) => { const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const statusRes = await this.sshPool.exec(server.id, system.status.command, { env: itemEnv, @@ -812,25 +1047,88 @@ export class CustomSystemsEngine { statusRes.exitCode, system.status, ); - items.push(draftItem); - } - return items; + // Populate editableFiles dynamically from systemd FragmentPath / DropInPaths when present + const raw = draftItem.status.raw; + if (raw) { + const dynamicPaths: string[] = []; + if (typeof raw.FragmentPath === 'string' && isValidAbsolutePath(raw.FragmentPath.trim())) { + dynamicPaths.push(raw.FragmentPath.trim()); + } + if (typeof raw.DropInPaths === 'string') { + for (const dp of raw.DropInPaths.trim().split(/\s+/)) { + if (dp && isValidAbsolutePath(dp)) dynamicPaths.push(dp); + } + } + if (dynamicPaths.length > 0) { + draftItem.editableFiles = [...new Set(dynamicPaths)]; + } + } + }); + + return draftItems; + } + + private validateAndResolveParamsStrict( + system: SystemConfig, + supplied: Record, + ): Record { + for (const k of Object.keys(supplied)) { + assertSafeKey(k, 'param name'); + } + const out: Record = Object.create(null); + for (const def of system.params) { + assertSafeKey(def.name, 'param definition'); + const hasVal = Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined; + const val = hasVal ? supplied[def.name] : def.default; + + if (val === undefined) { + if (def.required) { + throw new Error(`Missing required system param "${def.name}"`); + } + continue; + } + + if (def.type === 'string') { + if (typeof val !== 'string' || /[\x00]/.test(val)) { + throw new Error(`Param "${def.name}" must be a valid string`); + } + out[def.name] = val; + } else if (def.type === 'number') { + const num = typeof val === 'number' ? val : Number(val); + if (!Number.isFinite(num)) { + throw new Error(`Param "${def.name}" must be a finite number`); + } + out[def.name] = num; + } else if (def.type === 'boolean') { + if (typeof val !== 'boolean') { + throw new Error(`Param "${def.name}" must be a boolean`); + } + out[def.name] = val; + } else if (def.type === 'string[]') { + if (!Array.isArray(val) || !val.every((x) => typeof x === 'string' && !/[\x00]/.test(x))) { + throw new Error(`Param "${def.name}" must be an array of strings`); + } + out[def.name] = [...val]; + } + } + return { ...out }; } private resolveParams( system: SystemConfig, supplied: Record, ): Record { - const out: Record = {}; + const out: Record = Object.create(null); for (const def of system.params) { - if (supplied[def.name] !== undefined) { + if (FORBIDDEN_KEYS.has(def.name)) continue; + if (Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined) { out[def.name] = supplied[def.name]; } else if (def.default !== undefined) { out[def.name] = structuredClone(def.default); } } - return out; + return { ...out }; } private buildExecutionEnv( @@ -839,6 +1137,7 @@ export class CustomSystemsEngine { params: Record, item?: DiscoveredSystemItem, subItem?: string, + actionInputs?: Record, ): Record { const env: Record = { GCOORD_SERVER_ID: serverId, @@ -846,10 +1145,19 @@ export class CustomSystemsEngine { }; for (const [k, v] of Object.entries(params)) { + if (FORBIDDEN_KEYS.has(k)) continue; const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? ''); } + if (actionInputs) { + for (const [k, v] of Object.entries(actionInputs)) { + if (FORBIDDEN_KEYS.has(k)) continue; + const envKey = `GCOORD_INPUT_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; + env[envKey] = v; + } + } + if (item) { env.GCOORD_ITEM_NAME = item.name; if (item.dir) { From 2b878c1d9983d533595cb1ca54675d63f9c52371 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:06:04 +0000 Subject: [PATCH 11/19] feat(workflows,transfers,broadcast): harden templates/rsync/SFTP-transfer, add http/notify steps, retries, secret inputs & broadcast history --- src/server/alerts/alert-engine.ts | 6 +- src/server/api/routes/workflows.routes.ts | 45 +- src/server/app.ts | 5 +- src/server/automation/broadcast-service.ts | 280 ++++++++- src/server/automation/template.ts | 239 ++++++- src/server/automation/transfer-engine.ts | 101 ++- src/server/automation/workflow-engine.ts | 690 ++++++++++++++++++--- src/server/ssh/known-hosts.ts | 19 + 8 files changed, 1217 insertions(+), 168 deletions(-) diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index 93bd169..ba8189f 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -83,10 +83,10 @@ export class AlertEngine { this.stopped = false; this.hydrateOpenIncidents(); - this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId) => { + this.workflowEngine.setFailureNotifier(async (channelId, message, _workflowId, meta) => { await this.sendDirectChannelMessage(channelId, { - severity: 'critical', - title: 'Workflow Execution Failure', + severity: meta?.severity ?? 'critical', + title: meta?.title ?? 'Workflow Execution Failure', message, state: 'firing', }); diff --git a/src/server/api/routes/workflows.routes.ts b/src/server/api/routes/workflows.routes.ts index 34c7809..cea3718 100644 --- a/src/server/api/routes/workflows.routes.ts +++ b/src/server/api/routes/workflows.routes.ts @@ -147,7 +147,8 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }); router.get('/runs/:runId', requireAuth(authService), (req, res) => { - const detail = workflowEngine.getRunDetail(String(req.params.runId ?? '')); + const includeLogs = req.query.includeLogs !== 'false' && req.query.includeLogs !== '0'; + const detail = workflowEngine.getRunDetail(String(req.params.runId ?? ''), { includeLogs }); if (!detail) { res.status(404).json({ error: 'RUN_NOT_FOUND' }); return; @@ -155,11 +156,20 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json(detail); }); + router.get('/runs/:runId/steps/:stepId/logs', requireAuth(authService), (req, res) => { + const runId = String(req.params.runId ?? ''); + const stepId = String(req.params.stepId ?? ''); + const offset = Number(req.query.offset) || 0; + const limit = Number(req.query.limit) || 50; + const result = workflowEngine.getStepLogs(runId, { stepId, offset, limit }); + res.json(result); + }); + + // Cancelling a running workflow must remain available under Safe Mode router.post( '/runs/:runId/cancel', requireAuth(authService), requireCsrf, - enforceSafeMode, (req, res) => { const runId = String(req.params.runId ?? ''); const cancelled = workflowEngine.cancelRun(runId, 'admin'); @@ -248,6 +258,7 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }), }) .safeParse(req.body ?? {}); + if (!parsed.success) { res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); return; @@ -269,6 +280,24 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { }, ); + router.get('/broadcast/history', requireAuth(authService), (req, res) => { + const limit = Number(req.query.limit) || 50; + res.json({ jobs: broadcastService.listHistory(limit) }); + }); + + router.get('/broadcast/:jobId/export', requireAuth(authService), (req, res) => { + const jobId = String(req.params.jobId ?? ''); + const format = String(req.query.format ?? 'json') === 'csv' ? 'csv' : 'json'; + const exported = broadcastService.exportBroadcast(jobId, format); + if (!exported) { + res.status(404).json({ error: 'BROADCAST_NOT_FOUND' }); + return; + } + res.setHeader('Content-Type', exported.contentType); + res.setHeader('Content-Disposition', `attachment; filename="${exported.filename}"`); + res.send(exported.body); + }); + router.get('/broadcast/:jobId', requireAuth(authService), (req, res) => { const job = broadcastService.getBroadcastResult(String(req.params.jobId ?? '')); if (!job) { @@ -278,14 +307,22 @@ export function createWorkflowsRouter(deps: WorkflowsRouterDeps): Router { res.json({ job }); }); + // Cancelling a running broadcast must remain available under Safe Mode router.post( '/broadcast/:jobId/cancel', requireAuth(authService), requireCsrf, - enforceSafeMode, (req, res) => { const jobId = String(req.params.jobId ?? ''); - res.json({ cancelled: broadcastService.cancelBroadcast(jobId) }); + const cancelled = broadcastService.cancelBroadcast(jobId); + auditService.log({ + action: 'broadcast.cancel', + actorIp: req.clientIp ?? 'unknown', + sessionIdHash: req.authSession!.idHash, + target: jobId, + status: cancelled ? 'ok' : 'error', + }); + res.json({ cancelled }); }, ); diff --git a/src/server/app.ts b/src/server/app.ts index ea238e2..b35ebd0 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -206,7 +206,7 @@ export async function createGCoordinatorServer( probeRunner, getRuntimeLimits, ); - const transferEngine = new TransferEngine(sshPool, sftpService, configManager); + const transferEngine = new TransferEngine(sshPool, sftpService, configManager, knownHosts); const workflowEngine = new WorkflowEngine( db, configManager, @@ -217,6 +217,7 @@ export async function createGCoordinatorServer( transferEngine, wsHub, auditService, + getRuntimeLimits, ); const broadcastService = new BroadcastService( configManager, @@ -224,6 +225,8 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, + db, + getRuntimeLimits, ); const alertEngine = new AlertEngine( db, diff --git a/src/server/automation/broadcast-service.ts b/src/server/automation/broadcast-service.ts index 4909164..69d9804 100644 --- a/src/server/automation/broadcast-service.ts +++ b/src/server/automation/broadcast-service.ts @@ -1,7 +1,9 @@ import crypto from 'node:crypto'; +import type Database from 'better-sqlite3'; 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 { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -9,6 +11,8 @@ import { BufferedStreamEmitter } from './stream-buffer.js'; import { buildWorkflowEnv, interpolateShellCommandSafe, + maskSecretInputsForStorage, + redactWorkflowSecrets, resolveTargetServers, validateAndResolveInputs, } from './template.js'; @@ -38,10 +42,14 @@ export interface BroadcastJobSummary { interface ActiveBroadcastJob extends BroadcastJobSummary { emitter: BufferedStreamEmitter; abortController: AbortController; + secretValues: string[]; } -const MAX_RETAINED_BROADCASTS = 25; -const MAX_OUTPUT_PER_SERVER = 256 * 1024; +function csvSafeCell(val: unknown): string { + const s = val === null || val === undefined ? '' : String(val); + const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; + return `"${safe.replace(/"/g, '""')}"`; +} async function runPool( items: T[], @@ -68,6 +76,8 @@ export class BroadcastService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly db?: Database.Database, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getStreamReplayFrames(jobId: string): ServerWsFrame[] { @@ -76,17 +86,178 @@ export class BroadcastService { getBroadcastResult(jobId: string): BroadcastJobSummary | undefined { const job = this.jobs.get(jobId); - if (!job) return undefined; + if (job) { + 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 })), + }; + } + + if (!this.db) return undefined; + const row = this.db + .prepare( + `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, + started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson + FROM broadcast_jobs + WHERE job_id = ?`, + ) + .get(jobId) as + | { + jobId: string; + command: string; + snippetId: string | null; + status: string; + startedAt: number; + finishedAt: number | null; + resultsJson: string; + } + | undefined; + if (!row) return undefined; + + let targets: BroadcastTargetResult[] = []; + try { + targets = JSON.parse(row.resultsJson) as BroadcastTargetResult[]; + } catch { + targets = []; + } + 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 })), + jobId: row.jobId, + snippetId: row.snippetId ?? undefined, + command: row.command, + sudo: false, + createdAt: row.startedAt, + finishedAt: row.finishedAt, + cancelled: row.status === 'cancelled', + done: row.finishedAt !== null || row.status !== 'running', + targets, + }; + } + + listHistory(limit = 50): Array<{ + jobId: string; + snippetId?: string; + command: string; + status: string; + startedAt: number; + finishedAt: number | null; + targetCount: number; + okCount: number; + }> { + if (!this.db) { + return [...this.jobs.values()] + .sort((a, b) => b.createdAt - a.createdAt) + .slice(0, limit) + .map((j) => ({ + jobId: j.jobId, + snippetId: j.snippetId, + command: j.command, + status: j.cancelled + ? 'cancelled' + : !j.done + ? 'running' + : j.targets.every((t) => t.status === 'ok') + ? 'ok' + : 'error', + startedAt: j.createdAt, + finishedAt: j.finishedAt, + targetCount: j.targets.length, + okCount: j.targets.filter((t) => t.status === 'ok').length, + })); + } + + const safeLimit = Math.max(1, Math.min(200, Math.floor(limit))); + const rows = this.db + .prepare( + `SELECT job_id AS jobId, command, snippet_id AS snippetId, status, + started_at AS startedAt, finished_at AS finishedAt, results_json AS resultsJson + FROM broadcast_jobs + ORDER BY started_at DESC + LIMIT ?`, + ) + .all(safeLimit) as Array<{ + jobId: string; + command: string; + snippetId: string | null; + status: string; + startedAt: number; + finishedAt: number | null; + resultsJson: string; + }>; + + return rows.map((r) => { + const live = this.jobs.get(r.jobId); + const targets = live + ? live.targets + : (() => { + try { + return JSON.parse(r.resultsJson) as BroadcastTargetResult[]; + } catch { + return []; + } + })(); + return { + jobId: r.jobId, + snippetId: r.snippetId ?? undefined, + command: r.command, + status: live + ? live.cancelled + ? 'cancelled' + : !live.done + ? 'running' + : live.targets.every((t) => t.status === 'ok') + ? 'ok' + : 'error' + : r.status, + startedAt: r.startedAt, + finishedAt: live ? live.finishedAt : r.finishedAt, + targetCount: targets.length, + okCount: targets.filter((t) => t.status === 'ok').length, + }; + }); + } + + exportBroadcast( + jobId: string, + format: 'json' | 'csv' = 'json', + ): { contentType: string; filename: string; body: string } | null { + const job = this.getBroadcastResult(jobId); + if (!job) return null; + + if (format === 'csv') { + const header = 'jobId,serverId,serverName,status,exitCode,durationMs,stdout,stderr'; + const rows = job.targets.map((t) => + [ + job.jobId, + t.serverId, + t.serverName, + t.status, + t.exitCode ?? '', + t.durationMs, + t.stdout, + t.stderr, + ] + .map(csvSafeCell) + .join(','), + ); + return { + contentType: 'text/csv; charset=utf-8', + filename: `${job.jobId}.csv`, + body: `${[header, ...rows].join('\n')}\n`, + }; + } + + return { + contentType: 'application/json; charset=utf-8', + filename: `${job.jobId}.json`, + body: JSON.stringify(job, null, 2), }; } @@ -125,6 +296,7 @@ export class BroadcastService { let rawCommand = opts.command?.trim() ?? ''; let sudo = Boolean(opts.sudo); let resolvedInputs: Record = {}; + let secretValues: string[] = []; if (opts.snippetId) { const snip = this.configManager @@ -134,6 +306,7 @@ export class BroadcastService { throw new Error(`Unknown command snippet "${opts.snippetId}"`); } resolvedInputs = validateAndResolveInputs(snip.inputs, opts.inputs ?? {}); + secretValues = maskSecretInputsForStorage(snip.inputs, resolvedInputs).secretValues; rawCommand = snip.command; sudo = opts.sudo ?? snip.sudo; } else { @@ -141,14 +314,14 @@ export class BroadcastService { 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); - } + resolvedInputs = validateAndResolveInputs([], opts.inputs); } } + const limits = this.getRuntimeLimits?.(); const baseCtx = { inputs: resolvedInputs }; const renderedCommand = interpolateShellCommandSafe(rawCommand, baseCtx); + const displayCommand = redactWorkflowSecrets(renderedCommand, secretValues); const allServers = this.configManager.listServers(); let matchedServers = resolveTargetServers(opts.target, allServers, baseCtx); @@ -168,7 +341,11 @@ export class BroadcastService { } const jobId = `bcast-${crypto.randomBytes(6).toString('hex')}`; - const emitter = new BufferedStreamEmitter(this.wsHub, jobId); + const emitter = new BufferedStreamEmitter( + this.wsHub, + jobId, + limits?.streamReplayBytes, + ); const abortController = new AbortController(); const targets: BroadcastTargetResult[] = matchedServers.map((s) => ({ @@ -184,7 +361,7 @@ export class BroadcastService { const job: ActiveBroadcastJob = { jobId, snippetId: opts.snippetId, - command: renderedCommand, + command: displayCommand, sudo, createdAt: Date.now(), finishedAt: null, @@ -193,9 +370,12 @@ export class BroadcastService { targets, emitter, abortController, + secretValues, }; this.jobs.set(jobId, job); + this.persistBroadcastRow(job, 'running'); + this.auditService.log({ action: 'broadcast.start', actorIp: opts.actorIp, @@ -211,12 +391,14 @@ export class BroadcastService { emitter.pushMeta({ event: 'start', jobId, - command: renderedCommand, + command: displayCommand, targets: targets.map((t) => ({ serverId: t.serverId, serverName: t.serverName })), }); + const maxStepLogBytes = limits?.maxStepLogBytes ?? 256 * 1024; const timeoutMs = (opts.timeoutSec ?? 120) * 1000; - const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, 32)); + const concurrencyCap = limits?.maxWorkflowStepTargets ?? 32; + const concurrency = Math.max(1, Math.min(opts.concurrency ?? 4, concurrencyCap)); void runPool(matchedServers, concurrency, async (srv) => { const targetEntry = job.targets.find((t) => t.serverId === srv.id)!; @@ -239,6 +421,7 @@ export class BroadcastService { const env = buildWorkflowEnv({ inputs: resolvedInputs, serverId: srv.id, + serverMeta: { id: srv.id, name: srv.name, host: srv.host, port: srv.port }, }); try { @@ -253,9 +436,9 @@ export class BroadcastService { 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); + const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); + if (outBytes < maxStepLogBytes) { + const slice = chunk.subarray(0, maxStepLogBytes - outBytes); outChunks.push(slice); outBytes += slice.length; } @@ -269,9 +452,9 @@ export class BroadcastService { }); 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); + const text = redactWorkflowSecrets(chunk.toString('utf8'), secretValues); + if (errBytes < maxStepLogBytes) { + const slice = chunk.subarray(0, maxStepLogBytes - errBytes); errChunks.push(slice); errBytes += slice.length; } @@ -296,8 +479,14 @@ export class BroadcastService { try { const { exitCode } = await handle.done; - targetEntry.stdout = Buffer.concat(outChunks).toString('utf8'); - targetEntry.stderr = Buffer.concat(errChunks).toString('utf8'); + targetEntry.stdout = redactWorkflowSecrets( + Buffer.concat(outChunks).toString('utf8'), + secretValues, + ); + targetEntry.stderr = redactWorkflowSecrets( + Buffer.concat(errChunks).toString('utf8'), + secretValues, + ); targetEntry.durationMs = Date.now() - started; targetEntry.exitCode = exitCode; @@ -316,7 +505,10 @@ export class BroadcastService { } catch (err) { targetEntry.durationMs = Date.now() - started; targetEntry.status = abortController.signal.aborted ? 'cancelled' : 'error'; - const msg = err instanceof Error ? err.message : String(err); + const msg = redactWorkflowSecrets( + err instanceof Error ? err.message : String(err), + secretValues, + ); targetEntry.stderr = targetEntry.stderr ? `${targetEntry.stderr}\n${msg}` : msg; emitter.push('stderr', `[${srv.id}] ${msg}\n`); } @@ -332,6 +524,12 @@ export class BroadcastService { job.done = true; job.finishedAt = Date.now(); const okCount = job.targets.filter((t) => t.status === 'ok').length; + const finalStatus = job.cancelled + ? 'cancelled' + : okCount === job.targets.length + ? 'ok' + : 'error'; + this.persistBroadcastRow(job, finalStatus); emitter.pushMeta({ event: 'done', cancelled: job.cancelled, @@ -344,9 +542,33 @@ export class BroadcastService { return this.getBroadcastResult(jobId)!; } + private persistBroadcastRow(job: ActiveBroadcastJob, status: string): void { + if (!this.db) return; + this.db + .prepare( + `INSERT INTO broadcast_jobs (job_id, command, snippet_id, targets_json, status, started_at, finished_at, results_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(job_id) DO UPDATE SET + status = excluded.status, + finished_at = excluded.finished_at, + results_json = excluded.results_json`, + ) + .run( + job.jobId, + job.command, + job.snippetId ?? null, + JSON.stringify(job.targets.map((t) => t.serverId)), + status, + job.createdAt, + job.finishedAt, + JSON.stringify(job.targets), + ); + } + private pruneJobs(): void { + const maxRam = Math.max(1, this.getRuntimeLimits?.().maxRamBroadcastJobs ?? 5); const done = [...this.jobs.values()].filter((j) => j.done); - while (done.length > MAX_RETAINED_BROADCASTS) { + while (done.length > maxRam) { const oldest = done.shift()!; this.jobs.delete(oldest.jobId); } diff --git a/src/server/automation/template.ts b/src/server/automation/template.ts index a890e2f..4dd7b86 100644 --- a/src/server/automation/template.ts +++ b/src/server/automation/template.ts @@ -10,13 +10,17 @@ export interface StepOutputSummary { export interface TemplateContext { workflowId?: string; runId?: string; + triggerSource?: string; serverId?: string; + serverMeta?: { id: string; name: string; host: string; port: number }; inputs: Record; stepOutputs?: Map; captures?: Map; eventMeta?: Record; } +const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + export function toEnvIdent(raw: string): string { return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase(); } @@ -27,8 +31,15 @@ export function validateAndResolveInputs( ): Record { const out: Record = {}; + for (const k of Object.keys(supplied)) { + if (FORBIDDEN_KEYS.has(k)) { + throw new Error(`Unsafe input parameter name "${k}"`); + } + } + for (const def of defs) { - const raw = supplied[def.name]; + if (FORBIDDEN_KEYS.has(def.name)) continue; + const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined; const hasSupplied = raw !== undefined && raw !== null && raw !== ''; const candidate = hasSupplied ? raw : def.default; @@ -61,6 +72,9 @@ export function validateAndResolveInputs( } const strVal = String(candidate); + if (/[\x00]/.test(strVal)) { + throw new Error(`Input "${def.name}" contains NUL bytes`); + } if (def.type === 'select' && def.options && def.options.length > 0) { if (!def.options.includes(strVal)) { throw new Error( @@ -72,14 +86,48 @@ export function validateAndResolveInputs( } for (const [k, v] of Object.entries(supplied)) { - if (!(k in out) && v !== undefined && v !== null) { - out[k] = String(v); + if (FORBIDDEN_KEYS.has(k)) continue; + if (!Object.hasOwn(out, k) && v !== undefined && v !== null) { + const s = String(v); + if (/[\x00]/.test(s)) { + throw new Error(`Input "${k}" contains NUL bytes`); + } + out[k] = s; } } return out; } +export function maskSecretInputsForStorage( + defs: InputDef[], + resolved: Record, +): { masked: Record; secretValues: string[] } { + const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name)); + const masked: Record = {}; + const secretValues: string[] = []; + for (const [k, v] of Object.entries(resolved)) { + if (secretKeys.has(k) && v.length > 0) { + masked[k] = '***REDACTED***'; + secretValues.push(v); + } else { + masked[k] = v; + } + } + return { masked, secretValues }; +} + +export function redactWorkflowSecrets(text: string, secretValues: string[]): string { + if (!text || secretValues.length === 0) return text; + let out = text; + for (const sec of secretValues) { + if (sec.length >= 2 && out.includes(sec)) { + out = out.split(sec).join('***REDACTED***'); + } + } + return out; +} + export function buildWorkflowEnv(ctx: TemplateContext): Record { const env: Record = {}; if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId; @@ -87,6 +135,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId; for (const [k, v] of Object.entries(ctx.inputs)) { + if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v; } @@ -106,6 +155,7 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { if (ctx.eventMeta) { for (const [k, v] of Object.entries(ctx.eventMeta)) { + if (FORBIDDEN_KEYS.has(k)) continue; env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v; } } @@ -113,45 +163,188 @@ export function buildWorkflowEnv(ctx: TemplateContext): Record { return env; } -function resolveTemplateToken(rawExpr: string, ctx: TemplateContext): string { +/** + * Resolve ONLY recognized GCoordinator template namespaces so Go/Docker format + * templates like `{{.Names}}` or `{{json .}}` are left completely untouched. + */ +export function resolveTemplateToken( + rawExpr: string, + ctx: TemplateContext, +): { matched: boolean; value: string } { const expr = rawExpr.trim(); - if (expr.startsWith('inputs.')) { - const key = expr.slice('inputs.'.length); - return ctx.inputs[key] ?? ''; + if (!expr || expr.startsWith('.')) return { matched: false, value: '' }; + const parts = expr.split('.'); + if (parts.some((p) => FORBIDDEN_KEYS.has(p))) { + return { matched: false, value: '' }; } - if (expr.startsWith('steps.')) { - const rest = expr.slice('steps.'.length); + + if (expr.startsWith('inputs.') || expr.startsWith('input.')) { + const key = expr.slice(expr.indexOf('.') + 1); + if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return { matched: false, value: '' }; + return { + matched: true, + value: Object.hasOwn(ctx.inputs, key) ? ctx.inputs[key]! : '', + }; + } + + if (expr.startsWith('steps.') || expr.startsWith('step.')) { + const rest = expr.slice(expr.indexOf('.') + 1); 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 (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' }; + if (field === 'exitCode') { + return { + matched: true, + value: out && out.exitCode !== null ? String(out.exitCode) : '', + }; + } } + return { matched: false, value: '' }; } - if (expr.startsWith('captures.')) { - const key = expr.slice('captures.'.length); - return (ctx.captures?.get(key) ?? '').trim(); + + if (expr.startsWith('captures.') || expr.startsWith('capture.')) { + const key = expr.slice(expr.indexOf('.') + 1); + return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() }; } + if (expr.startsWith('event.')) { const key = expr.slice('event.'.length); - return ctx.eventMeta?.[key] ?? ''; + return { + matched: true, + value: ctx.eventMeta && Object.hasOwn(ctx.eventMeta, key) ? ctx.eventMeta[key]! : '', + }; } - return (ctx.captures?.get(expr) ?? ctx.inputs[expr] ?? '').trim(); + + if (expr.startsWith('server.')) { + const field = expr.slice('server.'.length); + if (field === 'id') return { matched: true, value: ctx.serverMeta?.id ?? ctx.serverId ?? '' }; + if (field === 'name') return { matched: true, value: ctx.serverMeta?.name ?? '' }; + if (field === 'host') return { matched: true, value: ctx.serverMeta?.host ?? '' }; + if (field === 'port') { + return { + matched: true, + value: ctx.serverMeta ? String(ctx.serverMeta.port) : '', + }; + } + return { matched: false, value: '' }; + } + + if (expr === 'run.id') return { matched: true, value: ctx.runId ?? '' }; + if (expr === 'run.workflowId') return { matched: true, value: ctx.workflowId ?? '' }; + if (expr === 'trigger.source') return { matched: true, value: ctx.triggerSource ?? '' }; + if (expr.startsWith('env.')) { + const key = expr.slice('env.'.length); + const env = buildWorkflowEnv(ctx); + return { matched: true, value: Object.hasOwn(env, key) ? env[key]! : '' }; + } + + if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(expr)) { + if (ctx.captures?.has(expr)) { + return { matched: true, value: (ctx.captures.get(expr) ?? '').trim() }; + } + if (Object.hasOwn(ctx.inputs, expr)) { + return { matched: true, value: ctx.inputs[expr]! }; + } + } + + return { matched: false, value: '' }; } export function interpolateValuePlain(template: string, ctx: TemplateContext): string { - return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => - resolveTemplateToken(expr, ctx), - ); + return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => { + const res = resolveTemplateToken(expr, ctx); + return res.matched ? res.value : full; + }); } +function escapeDoubleQuotedShell(val: string): string { + return val.replace(/([\\"$`])/g, '\\$1'); +} + +function escapeInsideSingleQuotedShell(val: string): string { + return val.replace(/'/g, "'\\''"); +} + +/** + * Quote-aware shell template substitution: + * - Unquoted `{{token}}`: wrapped in `posixSingleQuote(...)` + * - Inside `'...'`: safely single-quote escaped without outer quotes + * - Inside `"..."`: escaped for `$`, `"`, `\`, `` ` `` + * - Unrecognized `{{.Names}}` Go templates remain byte-for-byte untouched + */ export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string { - return template.replace(/\{\{([^{}]+)\}\}/g, (_match, expr: string) => - posixSingleQuote(resolveTemplateToken(expr, ctx)), - ); + let out = ''; + let quote: 'none' | 'single' | 'double' = 'none'; + let i = 0; + + while (i < template.length) { + const ch = template[i]!; + if (quote === 'none') { + if (ch === '\\' && i + 1 < template.length) { + out += template.slice(i, i + 2); + i += 2; + continue; + } + if (ch === "'") { + quote = 'single'; + out += ch; + i += 1; + continue; + } + if (ch === '"') { + quote = 'double'; + out += ch; + i += 1; + continue; + } + } else if (quote === 'single') { + if (ch === "'") { + quote = 'none'; + out += ch; + i += 1; + continue; + } + } else if (quote === 'double') { + if (ch === '\\' && i + 1 < template.length) { + out += template.slice(i, i + 2); + i += 2; + continue; + } + if (ch === '"') { + quote = 'none'; + out += ch; + i += 1; + continue; + } + } + + if (ch === '{' && template[i + 1] === '{') { + const closeIdx = template.indexOf('}}', i + 2); + if (closeIdx > i + 1) { + const expr = template.slice(i + 2, closeIdx); + const resolved = resolveTemplateToken(expr, ctx); + if (!resolved.matched) { + out += template.slice(i, closeIdx + 2); + } else if (quote === 'single') { + out += escapeInsideSingleQuotedShell(resolved.value); + } else if (quote === 'double') { + out += escapeDoubleQuotedShell(resolved.value); + } else { + out += posixSingleQuote(resolved.value); + } + i = closeIdx + 2; + continue; + } + } + + out += ch; + i += 1; + } + + return out; } export function resolveTargetServers( diff --git a/src/server/automation/transfer-engine.ts b/src/server/automation/transfer-engine.ts index 88acdeb..a52b1b8 100644 --- a/src/server/automation/transfer-engine.ts +++ b/src/server/automation/transfer-engine.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto'; import path from 'node:path'; import type { FileEntryWithStats, SFTPWrapper, Stats } from 'ssh2'; import type { ConfigManager } from '../config/config-manager.js'; +import type { KnownHostsService } from '../ssh/known-hosts.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { posixSingleQuote } from '../ssh/sudo.js'; @@ -15,8 +16,42 @@ export interface TransferResult { durationMs: number; } +const FILE_TYPE_MASK = 0o170000; +const MODE_DIR = 0o040000; +const MODE_REG = 0o100000; + function isDirMode(mode: number): boolean { - return (mode & 0o170000) === 0o040000; + return (mode & FILE_TYPE_MASK) === MODE_DIR; +} + +function isRegularMode(mode: number): boolean { + return (mode & FILE_TYPE_MASK) === MODE_REG; +} + +function assertSafeRemotePath(rawPath: string, label: string): string { + const trimmed = rawPath.trim(); + if (!trimmed || /[\x00-\x1f\x7f]/.test(trimmed)) { + throw new Error(`Invalid ${label} path`); + } + const parts = trimmed.split('/'); + if (parts.some((seg) => seg === '..')) { + throw new Error(`${label} path cannot contain ".." traversal segments`); + } + return trimmed; +} + +function sanitizeRsyncExcludes(excludes?: string[]): string[] { + if (!excludes || excludes.length === 0) return []; + const out: string[] = []; + for (const raw of excludes) { + const clean = raw.trim(); + if (!clean) continue; + if (/[\x00-\x1f\x7f]/.test(clean) || clean.startsWith('-')) { + throw new Error(`Invalid rsync exclude pattern: "${clean}"`); + } + out.push(clean); + } + return out; } function promisifySftp( @@ -46,6 +81,7 @@ export class TransferEngine { private readonly sshPool: SSHPool, private readonly _sftpService: SftpService, private readonly configManager: ConfigManager, + private readonly knownHosts?: KnownHostsService, ) { void this._sftpService; } @@ -54,6 +90,8 @@ export class TransferEngine { mode: 'hub-relayed' | 'direct'; source: { serverId: string; path: string }; destination: { serverId: string; path: string }; + delete?: boolean; + exclude?: string[]; sudo?: boolean; timeoutMs?: number; signal?: AbortSignal; @@ -72,12 +110,29 @@ export class TransferEngine { throw new Error(`Destination server "${opts.destination.serverId}" not found or disabled`); } + const safeSrcPath = assertSafeRemotePath(opts.source.path, 'source'); + const safeDstPath = assertSafeRemotePath(opts.destination.path, 'destination'); const started = Date.now(); const timeoutMs = opts.timeoutMs ?? 600_000; if (opts.mode === 'direct') { - const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; - const cmd = `rsync -az -e ${posixSingleQuote(sshOpt)} -- ${posixSingleQuote(opts.source.path)} ${posixSingleQuote(`${dstServer.username}@${dstServer.host}:${opts.destination.path}`)}`; + const safeExcludes = sanitizeRsyncExcludes(opts.exclude); + const excludeFlags = safeExcludes + .map((ex) => `--exclude=${posixSingleQuote(ex)} `) + .join(''); + const deleteFlag = opts.delete ? '--delete ' : ''; + const dstTarget = `${dstServer.username}@${dstServer.host}:${safeDstPath}`; + const khLine = this.knownHosts?.getOpenSshKnownHostLine(dstServer); + + let cmd: string; + if (khLine) { + const sshCmd = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=yes -o UserKnownHostsFile=$_kh`; + cmd = `_kh=$(mktemp /tmp/.gcoord_kh.XXXXXX) && chmod 600 "$_kh" && trap 'rm -f -- "$_kh"' EXIT && printf '%s\\n' ${posixSingleQuote(khLine)} > "$_kh" && rsync -az -s --stats -e "${sshCmd}" ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; + } else { + const sshOpt = `ssh -p ${dstServer.port} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`; + cmd = `rsync -az -s --stats -e ${posixSingleQuote(sshOpt)} ${deleteFlag}${excludeFlags}-- ${posixSingleQuote(safeSrcPath)} ${posixSingleQuote(dstTarget)}`; + } + opts.onProgress?.(`Running direct rsync on ${srcServer.id}...`); const handle = await this.sshPool.execStream(srcServer.id, cmd, { @@ -157,8 +212,8 @@ export class TransferEngine { return { mode: 'direct', - sourcePath: opts.source.path, - destinationPath: opts.destination.path, + sourcePath: safeSrcPath, + destinationPath: safeDstPath, filesTransferred: 1, bytesTransferred: 0, durationMs: Date.now() - started, @@ -201,16 +256,21 @@ export class TransferEngine { opts.signal?.addEventListener('abort', onAbort, { once: true }); try { - const trimmedDest = opts.destination.path.trim(); + const trimmedDest = safeDstPath; const destEndsWithSlash = trimmedDest.length > 1 && trimmedDest.endsWith('/'); - const resolvedSrc = await this.resolveRemotePath(srcSftp, opts.source.path); - const resolvedDest = await this.resolveRemotePath(dstSftp, opts.destination.path); + const resolvedSrc = await this.resolveRemotePath(srcSftp, safeSrcPath); + const resolvedDest = await this.resolveRemotePath(dstSftp, safeDstPath); + + const srcStat = await promisifySftp((cb) => srcSftp.lstat(resolvedSrc, cb)); + const srcMode = srcStat.mode ?? 0; + if (!isDirMode(srcMode) && !isRegularMode(srcMode)) { + throw new Error(`Refusing SFTP transfer of non-regular/symlink source "${resolvedSrc}"`); + } - const srcStat = await promisifySftp((cb) => srcSftp.stat(resolvedSrc, cb)); let filesTransferred = 0; let bytesTransferred = 0; - if (isDirMode(srcStat.mode ?? 0)) { + if (isDirMode(srcMode)) { const dstStat = await promisifySftp((cb) => dstSftp!.stat(resolvedDest, cb)).catch( () => null, ); @@ -254,7 +314,7 @@ export class TransferEngine { dstSftp, resolvedSrc, targetFile, - srcStat.mode ?? 0o644, + srcMode || 0o644, activeStreams, () => timedOutOrAborted, opts.onProgress, @@ -341,10 +401,21 @@ export class TransferEngine { let files = 0; let bytes = 0; for (const entry of entries) { - if (entry.filename === '.' || entry.filename === '..') continue; + if ( + entry.filename === '.' || + entry.filename === '..' || + entry.filename.includes('/') || + entry.filename.includes('\0') + ) { + continue; + } const srcChild = path.posix.join(srcDir, entry.filename); const dstChild = path.posix.join(dstDir, entry.filename); - const mode = entry.attrs.mode ?? 0; + let mode = entry.attrs.mode ?? 0; + if (mode === 0) { + const ls = await promisifySftp((cb) => srcSftp.lstat(srcChild, cb)).catch(() => null); + mode = ls?.mode ?? 0; + } if (isDirMode(mode)) { const sub = await this.copyDirectoryRecursive( @@ -358,7 +429,7 @@ export class TransferEngine { ); files += sub.files; bytes += sub.bytes; - } else { + } else if (isRegularMode(mode)) { const copied = await this.copySingleFile( srcSftp, dstSftp, @@ -371,6 +442,8 @@ export class TransferEngine { ); files += 1; bytes += copied; + } else { + onProgress?.(`Skipping non-regular entry ${srcChild}`); } } return { files, bytes }; diff --git a/src/server/automation/workflow-engine.ts b/src/server/automation/workflow-engine.ts index d1de18a..7bd8312 100644 --- a/src/server/automation/workflow-engine.ts +++ b/src/server/automation/workflow-engine.ts @@ -1,17 +1,19 @@ import crypto from 'node:crypto'; import type Database from 'better-sqlite3'; import { Cron } from 'croner'; +import type { z } from 'zod'; 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 { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SftpService } from '../ssh/sftp-service.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; @@ -22,7 +24,10 @@ import { buildWorkflowEnv, interpolateShellCommandSafe, interpolateValuePlain, + maskSecretInputsForStorage, + redactWorkflowSecrets, resolveTargetServers, + resolveTemplateToken, validateAndResolveInputs, type StepOutputSummary, type TemplateContext, @@ -113,6 +118,8 @@ interface QueuedRunRequest { workflow: WorkflowConfig; triggerSource: string; inputs: Record; + maskedInputsJson: string; + secretValues: string[]; eventMeta?: Record; actorIp: string; sessionIdHash: string | null; @@ -124,9 +131,10 @@ export type FailureNotifierFn = ( channelId: string, message: string, workflowId: string, + meta?: { title?: string; severity?: 'warn' | 'critical' }, ) => Promise; -const MAX_OUTPUT_CHARS = 256 * 1024; +const MAX_HTTP_STEP_BYTES = 128 * 1024; const MAX_RETAINED_STREAM_RUNS = 30; function normalizeDep(dep: StepDependency): { @@ -137,6 +145,90 @@ function normalizeDep(dep: StepDependency): { return { stepId: dep.stepId, on: dep.on }; } +function unquoteLiteral(raw: string): string { + const s = raw.trim(); + if ( + (s.startsWith("'") && s.endsWith("'") && s.length >= 2) || + (s.startsWith('"') && s.endsWith('"') && s.length >= 2) + ) { + return s.slice(1, -1); + } + return s; +} + +function resolveWhenOperand(raw: string, ctx: TemplateContext): string { + const trimmed = raw.trim(); + if ( + (trimmed.startsWith("'") && trimmed.endsWith("'")) || + (trimmed.startsWith('"') && trimmed.endsWith('"')) + ) { + return unquoteLiteral(trimmed); + } + if (trimmed.startsWith('{{') && trimmed.endsWith('}}')) { + const inner = trimmed.slice(2, -2); + const tok = resolveTemplateToken(inner, ctx); + return tok.matched ? tok.value : ''; + } + const direct = resolveTemplateToken(trimmed, ctx); + if (direct.matched) return direct.value; + return trimmed; +} + +function evaluateStepWhen( + whenExpr: string | undefined, + deps: Array<{ stepId: string; on: 'success' | 'failure' | 'always' }>, + terminalState: Map, + ctx: TemplateContext, +): boolean { + if (!whenExpr) return true; + const expr = whenExpr.trim(); + if (!expr || expr === 'always' || expr === 'true') return true; + if (expr === 'false') return false; + if (expr === 'success') { + return deps.every((d) => terminalState.get(d.stepId) === 'succeeded'); + } + if (expr === 'failure') { + return deps.some((d) => terminalState.get(d.stepId) === 'failed'); + } + + const eqMatch = /^(.+?)\s*(==|!=)\s*(.+)$/.exec(expr); + if (eqMatch) { + const left = resolveWhenOperand(eqMatch[1]!, ctx); + const op = eqMatch[2]!; + const right = resolveWhenOperand(eqMatch[3]!, ctx); + return op === '==' ? left === right : left !== right; + } + + const negated = expr.startsWith('!'); + const inner = negated ? expr.slice(1).trim() : expr; + const val = resolveWhenOperand(inner, ctx).trim().toLowerCase(); + const truthy = val !== '' && val !== 'false' && val !== '0'; + return negated ? !truthy : truthy; +} + +async function readResponseCapped(res: Response, maxBytes = MAX_HTTP_STEP_BYTES): Promise { + if (!res.body) return ''; + const reader = res.body.getReader(); + const chunks: Buffer[] = []; + let total = 0; + try { + while (total < maxBytes) { + const { value, done } = await reader.read(); + if (done || !value) break; + const take = Math.min(value.byteLength, maxBytes - total); + chunks.push(Buffer.from(value.subarray(0, take))); + total += take; + if (total >= maxBytes) { + await reader.cancel().catch(() => undefined); + break; + } + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks).toString('utf8'); +} + async function runWithConcurrency( items: T[], concurrency: number, @@ -153,13 +245,33 @@ async function runWithConcurrency( await Promise.all(workers); } +async function sleepAbortable(ms: number, signal: AbortSignal): Promise { + if (ms <= 0) return; + if (signal.aborted) throw new Error('Cancelled'); + await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(t); + reject(new Error('Cancelled')); + }; + const t = setTimeout(() => { + signal.removeEventListener('abort', onAbort); + resolve(); + }, ms); + t.unref(); + signal.addEventListener('abort', onAbort, { once: true }); + }); +} + export class WorkflowEngine { private readonly cronJobs = new Map(); private readonly activeByWorkflow = new Map(); private readonly queueByWorkflow = new Map(); private readonly runsById = new Map(); + private readonly secretValuesByRun = new Map(); private failureNotifier: FailureNotifierFn | null = null; private closed = false; + private runningSlots = 0; + private readonly slotWaiters: Array<() => void> = []; constructor( private readonly db: Database.Database, @@ -171,6 +283,7 @@ export class WorkflowEngine { private readonly transferEngine: TransferEngine, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} setFailureNotifier(fn: FailureNotifierFn): void { @@ -180,7 +293,14 @@ export class WorkflowEngine { getStreamReplayFrames(jobId: string): ServerWsFrame[] { if (!jobId.startsWith('wf:')) return []; const runId = jobId.slice(3); - return this.runsById.get(runId)?.emitter.getReplayFrames() ?? []; + const control = this.runsById.get(runId); + if (!control) return []; + const secrets = this.secretValuesByRun.get(runId) ?? []; + return control.emitter.getReplayFrames().map((frame) => + frame.type === 'stream:chunk' + ? { ...frame, data: redactWorkflowSecrets(frame.data, secrets) } + : frame, + ); } start(): void { @@ -195,21 +315,31 @@ export class WorkflowEngine { 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); + try { + 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); + } catch (err) { + this.auditService.log({ + action: 'workflow.cron_error', + actorIp: 'scheduler', + target: wfId, + status: 'error', + details: { message: err instanceof Error ? err.message : String(err) }, + }); + } } } @@ -231,6 +361,9 @@ export class WorkflowEngine { for (const run of this.activeByWorkflow.values()) { this.cancelRun(run.runId, 'panic_lock'); } + while (this.slotWaiters.length > 0) { + this.slotWaiters.shift()?.(); + } } close(): void { @@ -329,7 +462,50 @@ export class WorkflowEngine { .all(capped) as WorkflowRunRecord[]; } - getRunDetail(runId: string): { + getStepLogs( + runId: string, + opts: { stepId?: string; offset?: number; limit?: number } = {}, + ): { logs: WorkflowStepLogRecord[]; total: number } { + const safeOffset = Math.max(0, Math.floor(opts.offset ?? 0)); + const safeLimit = Math.max(1, Math.min(200, Math.floor(opts.limit ?? 50))); + if (opts.stepId) { + const totalRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ? AND step_id = ?') + .get(runId, opts.stepId) as { cnt: number }; + const logs = 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 = ? AND step_id = ? + ORDER BY id ASC + LIMIT ? OFFSET ?`, + ) + .all(runId, opts.stepId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; + return { logs, total: totalRow.cnt }; + } + const totalRow = this.db + .prepare('SELECT COUNT(*) AS cnt FROM workflow_step_logs WHERE run_id = ?') + .get(runId) as { cnt: number }; + const logs = 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 + LIMIT ? OFFSET ?`, + ) + .all(runId, safeLimit, safeOffset) as WorkflowStepLogRecord[]; + return { logs, total: totalRow.cnt }; + } + + getRunDetail( + runId: string, + opts: { includeLogs?: boolean } = {}, + ): { run: WorkflowRunRecord; stepLogs: WorkflowStepLogRecord[]; workflow: WorkflowConfig | null; @@ -345,16 +521,19 @@ export class WorkflowEngine { .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[]; + const stepLogs = + opts.includeLogs === false + ? [] + : (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, @@ -435,6 +614,8 @@ export class WorkflowEngine { } const inputs = validateAndResolveInputs(wf.inputs, opts.inputs ?? {}); + const { masked, secretValues } = maskSecretInputsForStorage(wf.inputs, inputs); + const maskedInputsJson = JSON.stringify(masked); const runId = `run-${crypto.randomBytes(6).toString('hex')}`; const now = Date.now(); const depth = opts.onFailureDepth ?? 0; @@ -449,7 +630,7 @@ export class WorkflowEngine { `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)); + .run(runId, wf.id, opts.triggerSource, now, now, maskedInputsJson); this.broadcastRunFrame({ runId, @@ -463,19 +644,26 @@ export class WorkflowEngine { } if (wf.overlapPolicy === 'queue') { + const q = this.queueByWorkflow.get(wf.id) ?? []; + const maxQueue = Math.max(1, this.getRuntimeLimits?.().maxWorkflowQueue ?? 10); + if (q.length >= maxQueue) { + throw new Error(`Workflow "${wf.id}" queue is full (${maxQueue} pending runs)`); + } + 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)); + .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); - const q = this.queueByWorkflow.get(wf.id) ?? []; q.push({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, + maskedInputsJson, + secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -518,13 +706,15 @@ export class WorkflowEngine { `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)); + .run(runId, wf.id, opts.triggerSource, now, maskedInputsJson); this.startExecution({ runId, workflow: wf, triggerSource: opts.triggerSource, inputs, + maskedInputsJson, + secretValues, eventMeta: opts.eventMeta, actorIp, sessionIdHash, @@ -577,12 +767,12 @@ export class WorkflowEngine { throw new Error(`Unknown workflow "${String(workflowInput)}"`); } - const inputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const rawInputs = validateAndResolveInputs(wf.inputs, suppliedInputs); + const { masked: inputs } = maskSecretInputsForStorage(wf.inputs, rawInputs); 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 => { @@ -694,8 +884,46 @@ export class WorkflowEngine { }; } + private async withGlobalWorkflowSlot( + signal: AbortSignal, + fn: () => Promise, + ): Promise { + const maxConcurrent = Math.max(1, this.getRuntimeLimits?.().maxConcurrentWorkflows ?? 2); + if (this.runningSlots >= maxConcurrent) { + await new Promise((resolve, reject) => { + if (signal.aborted) { + reject(new Error('Cancelled before acquiring workflow execution slot')); + return; + } + const wake = () => { + signal.removeEventListener('abort', onAbort); + resolve(); + }; + const onAbort = () => { + const idx = this.slotWaiters.indexOf(wake); + if (idx >= 0) this.slotWaiters.splice(idx, 1); + reject(new Error('Cancelled while waiting for workflow execution slot')); + }; + this.slotWaiters.push(wake); + signal.addEventListener('abort', onAbort, { once: true }); + }); + } + this.runningSlots += 1; + try { + return await fn(); + } finally { + this.runningSlots = Math.max(0, this.runningSlots - 1); + const next = this.slotWaiters.shift(); + if (next) next(); + } + } + private startExecution(req: QueuedRunRequest): void { - const emitter = new BufferedStreamEmitter(this.wsHub, `wf:${req.runId}`); + const emitter = new BufferedStreamEmitter( + this.wsHub, + `wf:${req.runId}`, + this.getRuntimeLimits?.().streamReplayBytes, + ); const abortController = new AbortController(); const control: ActiveRunControl = { runId: req.runId, @@ -708,6 +936,7 @@ export class WorkflowEngine { this.activeByWorkflow.set(req.workflow.id, control); this.runsById.set(req.runId, control); + this.secretValuesByRun.set(req.runId, req.secretValues); this.auditService.log({ action: 'workflow.start', @@ -733,7 +962,9 @@ export class WorkflowEngine { triggerSource: req.triggerSource, }); - void this.executeDag(req, control) + void this.withGlobalWorkflowSlot(abortController.signal, () => + this.executeDag(req, control), + ) .then((finalStatus) => { control.done = true; control.status = finalStatus; @@ -749,7 +980,10 @@ export class WorkflowEngine { }) .catch((err) => { control.done = true; - const msg = err instanceof Error ? err.message : String(err); + const msg = redactWorkflowSecrets( + err instanceof Error ? err.message : String(err), + req.secretValues, + ); emitter.push('stderr', `${msg}\n`); control.status = abortController.signal.aborted ? 'cancelled' : 'failed'; this.markRunFinished( @@ -847,6 +1081,21 @@ export class WorkflowEngine { } } + if (eligible && step.when) { + const whenCtx: TemplateContext = { + workflowId: wf.id, + runId: req.runId, + triggerSource: req.triggerSource, + inputs: req.inputs, + stepOutputs, + captures, + eventMeta: req.eventMeta, + }; + if (!evaluateStepWhen(step.when, deps, terminalState, whenCtx)) { + eligible = false; + } + } + if (!eligible) { terminalState.set(step.id, 'skipped'); madeProgress = true; @@ -855,7 +1104,7 @@ export class WorkflowEngine { madeProgress = true; const p = (async () => { - const ok = await this.runSingleStep( + const ok = await this.runStepWithRetries( wf, step, allServers, @@ -912,6 +1161,45 @@ export class WorkflowEngine { return hasFatalFailure ? 'failed' : 'succeeded'; } + private async runStepWithRetries( + wf: WorkflowConfig, + step: WorkflowStep, + allServers: ServerConfig[], + req: QueuedRunRequest, + control: ActiveRunControl, + stepOutputs: Map, + captures: Map, + ): Promise { + const maxRetries = Math.max(0, Math.min(5, step.retries ?? 0)); + const backoffMs = Math.max(500, Math.min(300_000, (step.retryBackoffSec ?? 5) * 1000)); + + for (let attempt = 0; attempt <= maxRetries; attempt++) { + const attemptOutcome = await this.runSingleStep( + wf, + step, + allServers, + req, + control, + stepOutputs, + captures, + ); + if (attemptOutcome.ok) return true; + if (attempt >= maxRetries || attemptOutcome.timedOut || control.abortController.signal.aborted) { + return false; + } + control.emitter.push( + 'stderr', + `[${step.id}] Attempt ${attempt + 1}/${maxRetries + 1} failed; retrying in ${Math.round(backoffMs / 1000)}s...\n`, + ); + try { + await sleepAbortable(backoffMs, control.abortController.signal); + } catch { + return false; + } + } + return false; + } + private async handleStepFailure( wf: WorkflowConfig, step: WorkflowStep, @@ -968,12 +1256,12 @@ export class WorkflowEngine { control: ActiveRunControl, stepOutputs: Map, captures: Map, - ): Promise { + ): Promise<{ ok: boolean; timedOut: boolean }> { const timeoutMs = (step.timeoutSec ?? 300) * 1000; const stepAbort = new AbortController(); const onParentAbort = () => stepAbort.abort(); if (control.abortController.signal.aborted) { - return false; + return { ok: false, timedOut: false }; } control.abortController.signal.addEventListener('abort', onParentAbort, { once: true }); @@ -984,16 +1272,27 @@ export class WorkflowEngine { }, timeoutMs); stepTimer.unref(); - const makeCtx = (serverId?: string): TemplateContext => ({ + const secrets = req.secretValues; + const safeEmit = (stream: 'stdout' | 'stderr', text: string) => { + control.emitter.push(stream, redactWorkflowSecrets(text, secrets)); + }; + + const makeCtx = (srv?: ServerConfig): TemplateContext => ({ workflowId: wf.id, runId: req.runId, - serverId, + triggerSource: req.triggerSource, + serverId: srv?.id, + serverMeta: srv + ? { id: srv.id, name: srv.name, host: srv.host, port: srv.port } + : undefined, inputs: req.inputs, stepOutputs, captures, eventMeta: req.eventMeta, }); + const maxTargetCap = Math.max(1, this.getRuntimeLimits?.().maxWorkflowStepTargets ?? 16); + control.emitter.pushMeta({ event: 'step-start', stepId: step.id, type: step.type }); try { @@ -1010,12 +1309,12 @@ export class WorkflowEngine { mode: step.mode, source: { serverId: srcServerId, path: srcPath }, destination: { serverId: dstServerId, path: dstPath }, + delete: step.delete, + exclude: step.exclude, sudo: step.sudo, timeoutMs, signal: stepAbort.signal, - onProgress: (msg) => { - control.emitter.push('stdout', `[${step.id}] ${msg}\n`); - }, + onProgress: (msg) => safeEmit('stdout', `[${step.id}] ${msg}\n`), }); const summaryJson = JSON.stringify(xfer); this.recordStepLog( @@ -1026,18 +1325,19 @@ export class WorkflowEngine { xfer.durationMs, summaryJson, '', + secrets, ); 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; + return { ok: true, timedOut: false }; } 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`); + safeEmit('stderr', `[${step.id}] ${msg}\n`); this.recordStepLog( req.runId, step.id, @@ -1046,40 +1346,192 @@ export class WorkflowEngine { Date.now() - started, '', msg, + secrets, ); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut }; } } - if (step.type === 'http' || step.type === 'notify') { - const msg = `Step type "${step.type}" handler not yet wired`; - control.emitter.push('stderr', `[${step.id}] ${msg}\n`); - this.recordStepLog(req.runId, step.id, 'hub', 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 === 'http') { + const started = Date.now(); + const ctx = makeCtx(); + const localSecrets = [...secrets]; + try { + const targetUrl = interpolateValuePlain(step.url, ctx).trim(); + let stepSecret: string | undefined; + if (step.secretRef) { + const cred = this.vaultService.getRuntimeSecret(step.secretRef); + if (!cred || (cred.type !== 'api-token' && cred.type !== 'webhook-secret')) { + throw new Error( + `HTTP step secretRef "${step.secretRef}" must be an api-token or webhook-secret`, + ); + } + stepSecret = cred.type === 'api-token' ? cred.token : cred.secret; + if (stepSecret) localSecrets.push(stepSecret); + } + + const headers: Record = {}; + let usedSecretInHeaders = false; + if (step.headers) { + for (const [k, v] of Object.entries(step.headers)) { + let renderedVal = interpolateValuePlain(v, ctx); + if (stepSecret && renderedVal.includes('{{secret}}')) { + renderedVal = renderedVal.split('{{secret}}').join(stepSecret); + usedSecretInHeaders = true; + } + headers[k] = renderedVal; + } + } + if (stepSecret && !usedSecretInHeaders && !Object.keys(headers).some((k) => k.toLowerCase() === 'authorization')) { + headers.Authorization = `Bearer ${stepSecret}`; + } + + let reqBody: string | undefined; + if (step.body !== undefined && step.method !== 'GET') { + reqBody = interpolateValuePlain(step.body, ctx); + if (stepSecret && reqBody.includes('{{secret}}')) { + reqBody = reqBody.split('{{secret}}').join(stepSecret); + } + if (!Object.keys(headers).some((k) => k.toLowerCase() === 'content-type')) { + headers['Content-Type'] = 'application/json'; + } + } + + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + targetUrl, + { + method: step.method, + headers, + body: reqBody, + signal: stepAbort.signal, + }, + { allowedCidrs, timeoutMs }, + ); + const bodyText = redactWorkflowSecrets( + await readResponseCapped(res, MAX_HTTP_STEP_BYTES), + localSecrets, + ); + const ok = + step.expectedStatus !== undefined ? res.status === step.expectedStatus : res.ok; + + safeEmit(ok ? 'stdout' : 'stderr', `[${step.id}] HTTP ${res.status}\n${bodyText}\n`); + this.recordStepLog( + req.runId, + step.id, + 'http', + ok ? 0 : 1, + Date.now() - started, + bodyText, + ok ? '' : `HTTP status ${res.status}`, + localSecrets, + ); + stepOutputs.set(step.id, { stdout: bodyText, exitCode: ok ? 0 : 1 }); + if (step.captureAs && ok) captures.set(step.captureAs, bodyText.trim()); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok }); + return { ok, timedOut: false }; + } catch (err) { + const msg = redactWorkflowSecrets( + timedOut + ? `HTTP step timed out after ${timeoutMs}ms` + : err instanceof Error + ? err.message + : String(err), + localSecrets, + ); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + 'http', + 1, + Date.now() - started, + '', + msg, + localSecrets, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut }; + } + } + + if (step.type === 'notify') { + const started = Date.now(); + const ctx = makeCtx(); + const title = redactWorkflowSecrets(interpolateValuePlain(step.title, ctx), secrets); + const message = redactWorkflowSecrets(interpolateValuePlain(step.message, ctx), secrets); + if (!this.failureNotifier) { + const msg = 'Alert notification handler is not wired'; + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'notify', 1, 0, '', msg, secrets); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut: false }; + } + try { + for (const channelId of step.channelIds) { + await this.failureNotifier(channelId, message, wf.id, { + title, + severity: step.severity, + }); + } + const summary = `Notified channels: ${step.channelIds.join(', ')}`; + safeEmit('stdout', `[${step.id}] ${summary}\n`); + this.recordStepLog( + req.runId, + step.id, + 'notify', + 0, + Date.now() - started, + summary, + '', + secrets, + ); + stepOutputs.set(step.id, { stdout: summary, exitCode: 0 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: true }); + return { ok: true, timedOut: false }; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + 'notify', + 1, + Date.now() - started, + '', + msg, + secrets, + ); + stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); + control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); + return { ok: false, timedOut: 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); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut: false }; } if (step.type === 'exec') { let allOk = true; const stdouts: string[] = []; let lastExit: number | null = 0; + let lastNonZero: number | null = null; + const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, step.concurrency ?? wf.concurrency, async (srv) => { + await runWithConcurrency(targets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const env = buildWorkflowEnv(ctx); const cmd = interpolateShellCommandSafe(step.command, ctx); try { @@ -1087,8 +1539,8 @@ export class WorkflowEngine { 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}`), + onStdout: (txt) => safeEmit('stdout', `[${step.id}@${srv.id}] ${txt}`), + onStderr: (txt) => safeEmit('stderr', `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1098,37 +1550,52 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - stdouts.push(res.stdout); + stdouts.push(redactWorkflowSecrets(res.stdout, secrets)); lastExit = res.exitCode; - if (res.exitCode !== 0) allOk = false; + if (res.exitCode !== 0) { + allOk = false; + lastNonZero = res.exitCode; + } } catch (err) { allOk = false; lastExit = 1; + lastNonZero = 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); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); const joined = stdouts.join('\n'); - stepOutputs.set(step.id, { stdout: joined, exitCode: lastExit }); + stepOutputs.set(step.id, { stdout: joined, exitCode: lastNonZero ?? lastExit }); if (step.captureAs && allOk) captures.set(step.captureAs, joined.trim()); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: allOk }); - return allOk; + return { ok: allOk, timedOut }; } if (step.type === 'read-file') { let allOk = true; const contents: string[] = []; + const concurrency = Math.min(wf.concurrency, maxTargetCap); - await runWithConcurrency(targets, wf.concurrency, async (srv) => { + await runWithConcurrency(targets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const remotePath = interpolateValuePlain(step.path, ctx); const tailRaw = typeof step.tailLines === 'number' @@ -1138,11 +1605,17 @@ export class WorkflowEngine { : undefined; try { + if (stepAbort.signal.aborted) { + throw new Error('Workflow step aborted'); + } let text = ''; try { const fileRes = await this.sftpService.readTextFile(srv.id, remotePath, { sudo: step.sudo, }); + if (stepAbort.signal.aborted) { + throw new Error('Workflow step aborted'); + } text = fileRes.content; if (tailRaw && Number.isFinite(tailRaw) && tailRaw > 0) { const lines = text.replace(/\n$/, '').split(/\r?\n/); @@ -1165,7 +1638,7 @@ export class WorkflowEngine { } } - control.emitter.push('stdout', `[${step.id}@${srv.id}] ${text}`); + safeEmit('stdout', `[${step.id}@${srv.id}] ${text}`); this.recordStepLog( req.runId, step.id, @@ -1174,13 +1647,23 @@ export class WorkflowEngine { Date.now() - started, text, '', + secrets, ); - contents.push(text); + contents.push(redactWorkflowSecrets(text, secrets)); } 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); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); @@ -1188,7 +1671,7 @@ export class WorkflowEngine { 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; + return { ok: allOk, timedOut }; } // system-action step @@ -1197,21 +1680,22 @@ export class WorkflowEngine { ); 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); + safeEmit('stderr', `[${step.id}] ${msg}\n`); + this.recordStepLog(req.runId, step.id, 'none', 1, 0, '', msg, secrets); stepOutputs.set(step.id, { stdout: '', exitCode: 1 }); control.emitter.pushMeta({ event: 'step-exit', stepId: step.id, ok: false }); - return false; + return { ok: false, timedOut: false }; } const system = this.configManager.getSystem(step.systemId); const actionDef = system?.actions.find((a) => a.id === step.action); let allOk = true; const sysOutputs: string[] = []; + const concurrency = Math.min(step.concurrency ?? wf.concurrency, maxTargetCap); - await runWithConcurrency(attachedTargets, step.concurrency ?? wf.concurrency, async (srv) => { + await runWithConcurrency(attachedTargets, concurrency, async (srv) => { const started = Date.now(); - const ctx = makeCtx(srv.id); + const ctx = makeCtx(srv); const itemSpec = interpolateValuePlain(step.item, ctx); const subItemVal = step.subItem ? interpolateValuePlain(step.subItem, ctx) : undefined; @@ -1223,7 +1707,7 @@ export class WorkflowEngine { actionId: step.action, timeoutMs, signal: stepAbort.signal, - onChunk: (st, txt) => control.emitter.push(st, `[${step.id}@${srv.id}] ${txt}`), + onChunk: (st, txt) => safeEmit(st, `[${step.id}@${srv.id}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1233,8 +1717,9 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - sysOutputs.push(res.stdout); + sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); if (res.exitCode !== 0) allOk = false; return; } @@ -1258,6 +1743,7 @@ export class WorkflowEngine { Date.now() - started, `No discovered items for ${step.systemId}`, '', + secrets, ); return; } @@ -1272,7 +1758,7 @@ export class WorkflowEngine { timeoutMs, signal: stepAbort.signal, onChunk: (st, txt) => - control.emitter.push(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), + safeEmit(st, `[${step.id}@${srv.id}/${itemName}] ${txt}`), }); this.recordStepLog( req.runId, @@ -1282,15 +1768,25 @@ export class WorkflowEngine { res.durationMs, res.stdout, res.stderr, + secrets, ); - sysOutputs.push(res.stdout); + sysOutputs.push(redactWorkflowSecrets(res.stdout, secrets)); 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); + safeEmit('stderr', `[${step.id}@${srv.id}] ${msg}\n`); + this.recordStepLog( + req.runId, + step.id, + srv.id, + 1, + Date.now() - started, + '', + msg, + secrets, + ); } }); @@ -1298,7 +1794,7 @@ export class WorkflowEngine { 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; + return { ok: allOk, timedOut }; } finally { clearTimeout(stepTimer); control.abortController.signal.removeEventListener('abort', onParentAbort); @@ -1320,6 +1816,7 @@ export class WorkflowEngine { throw new Error('Workflow step aborted'); } + const maxBytes = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; const started = Date.now(); const handle = await this.sshPool.execStream(serverId, command, { env: opts.env, @@ -1352,15 +1849,15 @@ export class WorkflowEngine { 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)); + if (outLen < maxBytes) { + outChunks.push(chunk.subarray(0, maxBytes - 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)); + if (errLen < maxBytes) { + errChunks.push(chunk.subarray(0, maxBytes - errLen)); errLen += chunk.length; } opts.onStderr?.(chunk.toString('utf8')); @@ -1397,7 +1894,11 @@ export class WorkflowEngine { durationMs: number, stdout: string, stderr: string, + secrets: string[] = [], ): void { + const maxLog = this.getRuntimeLimits?.().maxStepLogBytes ?? 256 * 1024; + const cleanOut = redactWorkflowSecrets(stdout, secrets).slice(0, maxLog); + const cleanErr = redactWorkflowSecrets(stderr, secrets).slice(0, maxLog); this.db .prepare( `INSERT INTO workflow_step_logs (run_id, step_id, server_id, exit_code, duration_ms, stdout, stderr, created_at) @@ -1409,8 +1910,8 @@ export class WorkflowEngine { serverId, exitCode, Math.max(0, Math.round(durationMs)), - stdout.slice(0, MAX_OUTPUT_CHARS), - stderr.slice(0, MAX_OUTPUT_CHARS), + cleanOut, + cleanErr, Date.now(), ); } @@ -1461,6 +1962,7 @@ export class WorkflowEngine { while (doneRuns.length > MAX_RETAINED_STREAM_RUNS) { const oldest = doneRuns.shift()!; this.runsById.delete(oldest.runId); + this.secretValuesByRun.delete(oldest.runId); } } } diff --git a/src/server/ssh/known-hosts.ts b/src/server/ssh/known-hosts.ts index ab04201..6d2e6bf 100644 --- a/src/server/ssh/known-hosts.ts +++ b/src/server/ssh/known-hosts.ts @@ -49,6 +49,7 @@ export function parseHostKeyBuffer(keyBuf: Buffer): { export class KnownHostsService { private readonly pendingTofu = new Map(); private readonly pendingMismatches = new Map(); + private readonly verifiedOpenSshKeys = new Map(); private readonly listeners = new Set<() => void>(); private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>(); @@ -96,6 +97,7 @@ export class KnownHostsService { if (exactRow.fingerprint === fingerprint) { const hadPending = this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id); + this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.db .prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?') .run(now, hostPortKey, algorithm); @@ -137,6 +139,7 @@ export class KnownHostsService { const expected = server.hostKeyFingerprint.trim(); if (expected === fingerprint) { this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now); + this.recordOpenSshKey(server, hostPortKey, algorithm, keyBuf); this.pendingTofu.delete(server.id); this.pendingMismatches.delete(server.id); this.auditService?.log({ @@ -335,6 +338,22 @@ export class KnownHostsService { .run(hostPortKey, algorithm, fingerprint, now, now); } + private recordOpenSshKey( + server: Pick, + hostPortKey: string, + algorithm: string, + keyBuf: Buffer, + ): void { + const cleanHost = normalizeHostForKey(server.host); + const hostToken = server.port === 22 ? cleanHost : `${cleanHost.startsWith('[') ? cleanHost : `[${cleanHost}]`}:${server.port}`; + const line = `${hostToken} ${algorithm} ${keyBuf.toString('base64')}`; + this.verifiedOpenSshKeys.set(server.id, { hostPortKey, line }); + } + + getOpenSshKnownHostLine(server: Pick): string | undefined { + return this.verifiedOpenSshKeys.get(server.id)?.line; + } + private emitChange(): void { for (const listener of this.listeners) { try { From 67137056f819784da1f561973e876ada958a0a1b Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:09:46 +0000 Subject: [PATCH 12/19] security(alerts,ai): fix secret exfiltration, ReDoS/redactor bypasses, probe double-counting & add Security Event Alerting --- src/server/ai/ai-service.ts | 115 +++++++++--- src/server/ai/guides.ts | 8 +- src/server/ai/redactor.ts | 205 ++++++++++++++++----- src/server/alerts/alert-engine.ts | 237 +++++++++++++++++++++---- src/server/api/routes/ai.routes.ts | 56 +++--- src/server/api/routes/alerts.routes.ts | 81 +++++---- src/server/app.ts | 50 +++++- src/shared/schemas/alerts.schema.ts | 6 + tests/ai-assistant.test.ts | 13 ++ tests/alerts-engine.test.ts | 13 ++ tests/workflows-and-transfer.test.ts | 2 +- 11 files changed, 613 insertions(+), 173 deletions(-) diff --git a/src/server/ai/ai-service.ts b/src/server/ai/ai-service.ts index fd9c629..61af7b6 100644 --- a/src/server/ai/ai-service.ts +++ b/src/server/ai/ai-service.ts @@ -13,7 +13,9 @@ 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 { RuntimeLimits } from '../config/runtime-limits.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import { @@ -31,6 +33,14 @@ export class AiDisabledError extends Error { } } +export class AiOverloadError extends Error { + readonly code = 'AI_CONCURRENCY_LIMIT'; + readonly status = 503; + constructor(limit: number) { + super(`Too many concurrent AI streams (limit: ${limit}). Retry shortly.`); + } +} + export interface ChatMessageInput { role: 'user' | 'assistant'; content: string; @@ -64,6 +74,7 @@ export class AiService { private readonly sshPool: SSHPool, private readonly wsHub: WsHub, private readonly auditService: AuditService, + private readonly getRuntimeLimits?: () => RuntimeLimits, ) {} getReplayFrames(chatId: string): ServerWsFrame[] { @@ -93,11 +104,8 @@ export class AiService { 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; + if (!cred || cred.type !== 'api-token') return undefined; + return cred.token; } previewContext(opts: { @@ -168,6 +176,12 @@ export class AiService { throw new AiDisabledError(); } + const activeStreams = [...this.chats.values()].filter((c) => !c.done).length; + const maxStreams = Math.max(1, this.getRuntimeLimits?.().maxConcurrentAiStreams ?? 2); + if (activeStreams >= maxStreams) { + throw new AiOverloadError(maxStreams); + } + const knownSecrets = collectVaultSecretStrings(this.vaultService); const guide = buildSurfaceGuideAndInventory( opts.surface, @@ -289,19 +303,26 @@ export class AiService { headers.Authorization = `Bearer ${bearerToken}`; } - const res = await fetch(endpointUrl, { - method: 'POST', - headers, - body: JSON.stringify({ model, stream: true, messages }), - signal: chat.abortController.signal, - }); + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const aiCfg = this.configManager.getSettings().ai; + const res = await fetchWithEgressGuard( + endpointUrl, + { + method: 'POST', + headers, + body: JSON.stringify({ model, stream: true, messages, max_tokens: aiCfg.maxTokens }), + signal: chat.abortController.signal, + }, + { allowedCidrs, timeoutMs: (aiCfg.timeoutSec ?? 90) * 1000 }, + ); if (!res.ok) { const errBody = await res.text().catch(() => ''); + const cleanErr = bearerToken ? errBody.split(bearerToken).join('[REDACTED]') : errBody; this.emitDelta(chat, { chunk: '', done: true, - error: `LLM endpoint HTTP ${res.status}${errBody ? `: ${errBody.slice(0, 240)}` : ''}`, + error: `LLM endpoint HTTP ${res.status}${cleanErr ? `: ${cleanErr.slice(0, 240)}` : ''}`, }); return; } @@ -323,12 +344,22 @@ export class AiService { const reader = res.body.getReader(); const decoder = new TextDecoder(); let buf = ''; + const MAX_SSE_LINE_BUF = 256 * 1024; let doneSent = false; while (true) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); + if (buf.length > MAX_SSE_LINE_BUF) { + await reader.cancel().catch(() => undefined); + this.emitDelta(chat, { + chunk: '', + done: true, + error: 'AI SSE line buffer exceeded 256 KiB limit', + }); + return; + } let nlIdx: number; while ((nlIdx = buf.indexOf('\n')) >= 0) { @@ -371,11 +402,11 @@ export class AiService { this.emitDelta(chat, { chunk: '', done: true }); } } catch (err) { + const rawErr = err instanceof Error ? err.message : String(err); + const safeErr = bearerToken ? rawErr.split(bearerToken).join('[REDACTED]') : rawErr; const msg = chat.abortController.signal.aborted ? 'Generation cancelled' - : err instanceof Error - ? err.message - : String(err); + : safeErr; this.emitDelta(chat, { chunk: '', done: true, @@ -413,24 +444,29 @@ export class AiService { 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 allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + url, + { + method: 'POST', + headers, + body: JSON.stringify({ + model, + stream: false, + max_tokens: 16, + messages: [{ role: 'user', content: 'Reply with OK' }], + }), + }, + { allowedCidrs, timeoutMs: 10_000 }, + ); const latencyMs = Date.now() - started; if (!res.ok) { const text = await res.text().catch(() => ''); + const cleanText = bearer ? text.split(bearer).join('[REDACTED]') : text; return { ok: false, latencyMs, - error: `HTTP ${res.status}${text ? `: ${text.slice(0, 180)}` : ''}`, + error: `HTTP ${res.status}${cleanText ? `: ${cleanText.slice(0, 180)}` : ''}`, }; } const data = (await res.json().catch(() => ({}))) as { @@ -440,10 +476,11 @@ export class AiService { data.choices?.[0]?.message?.content ?? data.choices?.[0]?.text ?? 'Connected'; return { ok: true, latencyMs, replyPreview: String(preview).trim().slice(0, 120) }; } catch (err) { + const rawErr = err instanceof Error ? err.message : String(err); return { ok: false, latencyMs: Date.now() - started, - error: err instanceof Error ? err.message : String(err), + error: bearer ? rawErr.split(bearer).join('[REDACTED]') : rawErr, }; } } @@ -486,9 +523,29 @@ export class AiService { }; } + if ( + opts.targetId && + rawObj && + typeof rawObj === 'object' && + !Array.isArray(rawObj) + ) { + const suppliedId = (rawObj as Record).id; + if (suppliedId !== undefined && suppliedId !== opts.targetId) { + return { + valid: false, + issues: [ + { + path: 'id', + message: `Draft id "${String(suppliedId)}" does not match locked targetId "${opts.targetId}"`, + }, + ], + }; + } + } + const withOptionalId = (obj: unknown) => opts.targetId && obj && typeof obj === 'object' && !Array.isArray(obj) - ? { ...(obj as Record), id: (obj as Record).id ?? opts.targetId } + ? { ...(obj as Record), id: opts.targetId } : obj; let targetPath: string; diff --git a/src/server/ai/guides.ts b/src/server/ai/guides.ts index 5d3b16f..4906066 100644 --- a/src/server/ai/guides.ts +++ b/src/server/ai/guides.ts @@ -26,7 +26,8 @@ export function buildSurfaceGuideAndInventory( targetPath?: string; } = {}, ): SurfaceGuideResult { - const { configManager, vaultService, sshPool } = deps; + const { configManager, sshPool } = deps; + void deps.vaultService; const servers = configManager.listServers(); const systems = configManager.listSystems(); const snippets = configManager.getSnippets().snippets; @@ -51,10 +52,6 @@ export function buildSurfaceGuideAndInventory( 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' @@ -67,7 +64,6 @@ export function buildSurfaceGuideAndInventory( 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 } : {}), }, diff --git a/src/server/ai/redactor.ts b/src/server/ai/redactor.ts index 43a4fe8..dc4b5bb 100644 --- a/src/server/ai/redactor.ts +++ b/src/server/ai/redactor.ts @@ -6,9 +6,7 @@ export interface RedactionResult { truncated: boolean; } -function escapeRegExp(literal: string): string { - return literal.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} +const MIN_VAULT_SECRET_LEN = 4; export function collectVaultSecretStrings(vaultService: VaultService): string[] { if (!vaultService.isRuntimeReady) return []; @@ -18,21 +16,21 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] 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); + if (cred.password.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.password); } else if (cred.type === 'webhook-secret') { - if (cred.secret.length >= 6) collected.add(cred.secret); + if (cred.secret.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.secret); } else if (cred.type === 'api-token') { - if (cred.token.length >= 6) collected.add(cred.token); + if (cred.token.length >= MIN_VAULT_SECRET_LEN) collected.add(cred.token); } else if (cred.type === 'ssh-key') { const trimmed = cred.privateKey.trim(); - if (trimmed.length >= 6) collected.add(trimmed); + if (trimmed.length >= MIN_VAULT_SECRET_LEN) 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) { + if (cred.passphrase && cred.passphrase.length >= MIN_VAULT_SECRET_LEN) { collected.add(cred.passphrase); } } @@ -44,6 +42,119 @@ export function collectVaultSecretStrings(vaultService: VaultService): string[] return [...collected].sort((a, b) => b.length - a.length); } +function replaceLiteralLinear( + text: string, + needle: string, + replacement: string, +): { text: string; hits: number } { + if (!needle) return { text, hits: 0 }; + let idx = text.indexOf(needle); + if (idx < 0) return { text, hits: 0 }; + let out = ''; + let last = 0; + let hits = 0; + while (idx >= 0) { + out += text.slice(last, idx) + replacement; + last = idx + needle.length; + hits += 1; + idx = text.indexOf(needle, last); + } + out += text.slice(last); + return { text: out, hits }; +} + +/** + * Linear-time PEM private key block scanner (catches both complete blocks and + * truncated logs containing only `-----BEGIN ... PRIVATE KEY-----` headers). + */ +function stripPemPrivateKeys(input: string): { text: string; hits: number } { + const beginMarker = '-----BEGIN '; + let idx = input.indexOf(beginMarker); + if (idx < 0) return { text: input, hits: 0 }; + + let out = ''; + let last = 0; + let hits = 0; + + while (idx >= 0) { + const headerEnd = input.indexOf('-----', idx + beginMarker.length); + if (headerEnd < 0 || headerEnd - idx > 80) break; + const headerSlice = input.slice(idx + beginMarker.length, headerEnd); + if (!/PRIVATE KEY$/i.test(headerSlice)) { + idx = input.indexOf(beginMarker, headerEnd + 5); + continue; + } + + const endHeader = `-----END ${headerSlice}-----`; + const footerPos = input.indexOf(endHeader, headerEnd + 5); + let blockEnd: number; + if (footerPos >= 0) { + blockEnd = footerPos + endHeader.length; + } else { + // Truncated PEM: strip from BEGIN header up to a blank line or 8 KiB + const blank = input.indexOf('\n\n', headerEnd + 5); + blockEnd = + blank >= 0 + ? blank + : Math.min(input.length, headerEnd + 5 + 8192); + } + + out += input.slice(last, idx) + '[REDACTED_PRIVATE_KEY]'; + hits += 1; + last = blockEnd; + idx = input.indexOf(beginMarker, last); + } + + out += input.slice(last); + return { text: out, hits }; +} + +/** + * Linear-time O(n) JSON `"secretKey": "secretVal"` scrubber without ReDoS-prone + * nested escape quantifiers. + */ +function stripJsonSecretValues(input: string): { text: string; hits: number } { + const keyRe = + /"[A-Za-z0-9_-]{0,40}(?:password|passwd|secret|token|apiKey|api_key|privateKey|private_key|passphrase|accessKey|secretKey|client_secret|refresh_token)[A-Za-z0-9_-]{0,40}"\s*:\s*"/gi; + let out = ''; + let last = 0; + let hits = 0; + let m: RegExpExecArray | null; + + while ((m = keyRe.exec(input)) !== null) { + const valStart = m.index + m[0].length; + if (valStart < last) continue; + + // Scan forward strictly once in O(k) checking backslash escapes + let pos = valStart; + let closed = false; + while (pos < input.length) { + const ch = input.charCodeAt(pos); + if (ch === 92 /* '\\' */) { + pos += 2; + continue; + } + if (ch === 34 /* '"' */) { + closed = true; + break; + } + if (ch === 10 || ch === 13) break; + pos += 1; + } + + const valSlice = input.slice(valStart, pos); + if (valSlice.includes('[REDACTED')) continue; + + out += input.slice(last, valStart) + '[REDACTED_SECRET]' + (closed ? '"' : ''); + hits += 1; + last = closed ? pos + 1 : pos; + keyRe.lastIndex = last; + } + + out += input.slice(last); + return { text: out, hits }; +} + export function redactSecrets( input: string, knownSecrets: string[] = [], @@ -52,27 +163,22 @@ export function redactSecrets( 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]'; - }); + // 1. Complete & truncated PEM / OpenSSH private keys in O(n) + const pem = stripPemPrivateKeys(text); + text = pem.text; + redactedCount += pem.hits; - // 2. Strip known secrets currently held in Vault + // 2. Vault secrets >= 4 chars in O(n * m) 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]'; - }); + if (secret.length < MIN_VAULT_SECRET_LEN) continue; + const res = replaceLiteralLinear(text, secret, '[REDACTED_VAULT_SECRET]'); + text = res.text; + redactedCount += res.hits; } - // 3. Strip HTTP Authorization / Bearer / custom secret headers + // 3. HTTP Authorization / Cookie / Proxy / custom secret headers text = text.replace( - /\b(Authorization\s*:\s*(?:Bearer|Basic)\s+)([^\r\n]+)/gi, + /\b((?:Proxy-)?Authorization\s*:\s*(?:Bearer|Basic|Token)\s+)([^\r\n]{1,1024})/gi, (_m, prefix: string, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; @@ -80,25 +186,45 @@ export function redactSecrets( }, ); text = text.replace( - /\bBearer\s+([A-Za-z0-9._~+/=-]{12,})/g, - (_m, val: string) => { + /\b(Cookie|Set-Cookie|X-API-Key|X-Auth-Token|X-Telegram-Bot-Token|X-Access-Token)\s*:\s*([^\r\n]{1,1024})/gi, + (_m, key: string, val: string) => { if (val.includes('[REDACTED')) return _m; redactedCount += 1; - return 'Bearer [REDACTED_TOKEN]'; + return `${key}: [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; + /\b(?:Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,1024})/g, + (full, val: string) => { + if (val.includes('[REDACTED')) return full; redactedCount += 1; - return `${prefix}[REDACTED_TOKEN]`; + return full.startsWith('Basic') ? 'Basic [REDACTED_TOKEN]' : 'Bearer [REDACTED_TOKEN]'; }, ); - // 4. Strip .env / shell KEY=value secret assignments + // 4. URL embedded credentials (user:pass@host) 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, + /([a-zA-Z][a-zA-Z0-9+.-]{1,15}:\/\/[^:/\s@]{1,64}:)([^/\s@]{1,256})@/g, + (_m, prefix: string, pw: string) => { + if (pw.includes('[REDACTED')) return _m; + redactedCount += 1; + return `${prefix}[REDACTED_SECRET]@`; + }, + ); + + // 5. Known API/cloud token formats + text = text.replace( + /\b(?:sk-[A-Za-z0-9_-]{12,256}|gh[pou]_[A-Za-z0-9]{12,256}|github_pat_[A-Za-z0-9_]{16,256}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{10,256}|AIza[0-9A-Za-z_-]{20,64}|glpat-[A-Za-z0-9_-]{12,256})/g, + (tok) => { + if (tok.includes('[REDACTED')) return tok; + redactedCount += 1; + return '[REDACTED_TOKEN]'; + }, + ); + + // 6. .env / shell KEY=value secret assignments (linear bounded match) + text = text.replace( + /(^|[\s;|&])([A-Za-z0-9_]{0,48}(?:PASSWORD|PASSWD|SECRET|TOKEN|API_KEY|APIKEY|PRIVATE_KEY|PASSPHRASE|ACCESS_KEY|CREDENTIAL)[A-Za-z0-9_]{0,48})=([^\s\r\n]{1,512}|"[^"\r\n]{0,512}"|'[^'\r\n]{0,512}')/gim, (_m, lead: string, key: string, rawVal: string) => { if (rawVal.includes('[REDACTED')) return _m; redactedCount += 1; @@ -106,15 +232,10 @@ export function redactSecrets( }, ); - // 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]"`; - }, - ); + // 7. JSON "key": "secret" string properties in O(n) + const jsonRes = stripJsonSecretValues(text); + text = jsonRes.text; + redactedCount += jsonRes.hits; const cap = Math.max(256, maxChars); let truncated = false; diff --git a/src/server/alerts/alert-engine.ts b/src/server/alerts/alert-engine.ts index ba8189f..765e58f 100644 --- a/src/server/alerts/alert-engine.ts +++ b/src/server/alerts/alert-engine.ts @@ -5,6 +5,7 @@ import type { AlertChannel, AlertRule, AlertRuleTargetSchema, + SecurityEventKind, } from '../../shared/schemas/alerts.schema.js'; import type { ServerConfig } from '../../shared/schemas/server.schema.js'; import type { z } from 'zod'; @@ -17,6 +18,7 @@ import type { MonitoringTickEvent, } from '../monitoring/monitoring-service.js'; import type { AuditService } from '../security/audit.js'; +import { fetchWithEgressGuard } from '../security/egress-guard.js'; import type { VaultService } from '../security/vault.js'; import type { SSHPool } from '../ssh/ssh-pool.js'; import type { @@ -63,6 +65,7 @@ export class AlertEngine { private readonly emittedOffline = new Set(); private readonly prevProbeOk = new Map(); private readonly prevSystemDown = new Set(); + private readonly channelCircuit = new Map(); private readonly unsubs: Array<() => void> = []; private sweepTimer: NodeJS.Timeout | null = null; private stopped = false; @@ -298,16 +301,20 @@ export class AlertEngine { 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(), - }); + 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(), + }, + { bypassCircuitBreaker: true }, + ); this.auditService.log({ action: 'alert.test_channel', @@ -355,10 +362,6 @@ export class AlertEngine { } } } - - for (const probe of event.probes) { - await this.evaluateProbe(server.id, probe, nowMs); - } } async evaluateProbe( @@ -688,7 +691,151 @@ export class AlertEngine { } } + syncWithConfig(): void { + const alerts = this.configManager.getAlerts(); + const activeRuleIds = new Set(alerts.rules.filter((r) => r.enabled).map((r) => r.id)); + const activeServerIds = new Set( + this.configManager.listServers().filter((s) => s.enabled).map((s) => s.id), + ); + const now = Date.now(); + let changed = false; + + for (const [key, state] of this.incidents.entries()) { + const parts = key.split('::'); + const ruleId = parts[0] ?? ''; + const serverId = parts[1] ?? ''; + if (!activeRuleIds.has(ruleId) || (serverId !== 'hub' && !activeServerIds.has(serverId))) { + if (state.firingEventId) { + this.db + .prepare(`UPDATE alert_events SET state = 'resolved', resolved_at = ? WHERE id = ? AND state = 'firing'`) + .run(now, state.firingEventId); + changed = true; + } + this.incidents.delete(key); + } + } + + if (changed) { + this.wsHub.broadcastChannel(WS_CHANNELS.ALERTS, { + type: 'alerts:update', + activeCount: this.getActiveCount(), + }); + } + } + + async emitSecurityEvent( + eventType: SecurityEventKind | string, + payload: { + serverId?: string; + ip?: string; + message?: string; + details?: Record; + } = {}, + nowMs = Date.now(), + ): Promise { + if (this.stopped) return; + + const aliasMap: Record = { + 'auth.lockout': ['auth.lockout', 'login_burst'], + login_burst: ['login_burst', 'auth.lockout'], + 'auth.totp_replay': ['auth.totp_replay', 'login_burst'], + 'auth.recovery_code_used': ['auth.recovery_code_used', 'new_ip_login'], + 'auth.session_idle_expired': ['auth.session_idle_expired'], + 'ssh.host_key_mismatch': ['ssh.host_key_mismatch'], + 'vault.panic_lock': ['vault.panic_lock', 'panic_lock'], + panic_lock: ['panic_lock', 'vault.panic_lock'], + }; + const matchSet = new Set(aliasMap[eventType] ?? [eventType]); + + const rules = this.configManager + .getAlerts() + .rules.filter( + (r) => + r.enabled && + r.kind === 'security-event' && + r.events.some((ev) => matchSet.has(ev)), + ); + + if (rules.length === 0) return; + + const server = payload.serverId ? this.configManager.getServer(payload.serverId) : undefined; + const msgSuffix = + payload.message ?? + (payload.ip ? `source IP ${payload.ip}` : 'hub security boundary'); + const summaryMsg = `SECURITY [${eventType}]: ${msgSuffix}`; + + for (const rule of rules) { + if (rule.kind !== 'security-event') continue; + if (server && !this.matchesTarget(rule.target, server)) continue; + + const incKey = `${rule.id}::${server?.id ?? 'hub'}::sec::${eventType}`; + const state = this.incidents.get(incKey) ?? { consecutiveFailures: 0 }; + const inCooldown = + state.lastNotifiedAt !== undefined && + nowMs - state.lastNotifiedAt < rule.cooldownSec * 1000; + const silences = this.listSilences(nowMs); + const silenced = silences.some( + (s) => + s.scopeType === 'all' || + (s.scopeType === 'rule' && s.targetId === rule.id) || + (server && s.scopeType === 'server' && s.targetId === server.id), + ); + + const eventId = `evt-${crypto.randomBytes(6).toString('hex')}`; + const initialStatus = silenced ? 'suppressed' : inCooldown ? 'cooldown' : '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 ?? null, + rule.severity, + summaryMsg, + initialStatus, + nowMs, + incKey, + ); + + 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: summaryMsg, + ts: nowMs, + }, + }); + + if (!silenced && !inCooldown && rule.channelIds.length > 0) { + state.lastNotifiedAt = nowMs; + this.incidents.set(incKey, state); + const statusText = await this.dispatchRuleChannels(rule.channelIds, { + id: eventId, + ruleId: rule.id, + serverId: server?.id ?? 'hub', + severity: rule.severity, + title: `[SECURITY ${rule.severity.toUpperCase()}] ${rule.name}`, + message: summaryMsg, + state: 'firing', + ts: nowMs, + }); + this.db + .prepare('UPDATE alert_events SET webhook_status = ? WHERE id = ?') + .run(statusText, eventId); + } + } + } + private matchesTarget(target: AlertRuleTarget, server: ServerConfig): boolean { + if (target.all) return true; + if (!target.serverId && (!target.tags || target.tags.length === 0)) return false; 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; @@ -751,11 +898,8 @@ export class AlertEngine { 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; + if (!cred || cred.type !== 'webhook-secret') return null; + return cred.secret; } private async dispatchToChannel( @@ -770,15 +914,30 @@ export class AlertEngine { state: 'firing' | 'resolved'; ts: number; }, + opts: { bypassCircuitBreaker?: boolean } = {}, ): Promise<{ ok: boolean; statusCode?: number; error?: string }> { - const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; - if (!secret && !channel.url) { - return { ok: false, error: `Missing vault secret "${channel.secretRef ?? ''}"` }; + const cb = this.channelCircuit.get(channel.id); + if (!opts.bypassCircuitBreaker && cb && cb.openUntil > Date.now()) { + return { ok: false, error: 'Channel circuit breaker temporarily open after repeated failures' }; } + const secret = channel.secretRef ? this.readChannelSecret(channel.secretRef) : null; + if (channel.secretRef && !secret) { + return { + ok: false, + error: `Missing or incompatible webhook-secret "${channel.secretRef}" in Vault`, + }; + } + if (!secret && !channel.url) { + return { ok: false, error: 'Missing alert channel URL and webhook-secret' }; + } + + const redactErr = (raw: string): string => + secret && secret.length > 0 ? raw.split(secret).join('[REDACTED]') : raw; + try { let targetUrl = channel.url ?? ''; - let method = 'POST'; + const method = 'POST'; const headers: Record = {}; let body: string; @@ -831,24 +990,42 @@ export class AlertEngine { body = JSON.stringify(payload); } - const res = await fetch(targetUrl, { - method, - headers, - body, - signal: AbortSignal.timeout(10_000), - }); + const allowedCidrs = this.configManager.getSettings().security.egressAllowedCidrs; + const res = await fetchWithEgressGuard( + targetUrl, + { method, headers, body }, + { allowedCidrs, timeoutMs: 10_000 }, + ); + + if (res.ok) { + this.channelCircuit.delete(channel.id); + } else { + this.recordChannelFailure(channel.id); + } + return { ok: res.ok, statusCode: res.status, error: res.ok ? undefined : `HTTP ${res.status}`, }; } catch (err) { + this.recordChannelFailure(channel.id); return { ok: false, - error: err instanceof Error ? err.message : String(err), + error: redactErr(err instanceof Error ? err.message : String(err)), }; } } + + private recordChannelFailure(channelId: string): void { + const cur = this.channelCircuit.get(channelId) ?? { failures: 0, openUntil: 0 }; + cur.failures += 1; + if (cur.failures >= 5) { + cur.openUntil = Date.now() + 60_000; + cur.failures = 0; + } + this.channelCircuit.set(channelId, cur); + } } function compareOp( diff --git a/src/server/api/routes/ai.routes.ts b/src/server/api/routes/ai.routes.ts index 6f45cec..0fdb554 100644 --- a/src/server/api/routes/ai.routes.ts +++ b/src/server/api/routes/ai.routes.ts @@ -1,23 +1,30 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { z } from 'zod'; import { EntityIdSchema } from '../../../shared/schemas/common.js'; -import { AiDisabledError, AiDraftKindSchema, type AiService } from '../../ai/ai-service.js'; +import { + AiDisabledError, + AiDraftKindSchema, + AiOverloadError, + type AiService, +} from '../../ai/ai-service.js'; import { AiSurfaceSchema } from '../../ai/guides.js'; import type { AuthService } from '../../security/auth.js'; import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface AiRouterDeps { authService: AuthService; aiService: AiService; + stepUpGuard?: RequestHandler; } export function createAiRouter(deps: AiRouterDeps): Router { const router = Router(); - const { authService, aiService } = deps; + const { authService, aiService, stepUpGuard = requireStepUp } = deps; // Read-only context redaction & preview (Safe-Mode exempt) router.post('/context-preview', requireAuth(authService), requireCsrf, (req, res) => { @@ -56,8 +63,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { 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) => { + // Read-only draft streaming: Safe-Mode exempt, stepUpGuard protects Vault API token egress + router.post('/chat', requireAuth(authService), requireCsrf, stepUpGuard, (req, res) => { const parsed = z .object({ chatId: z.string().min(1).max(64).optional(), @@ -90,8 +97,8 @@ export function createAiRouter(deps: AiRouterDeps): Router { }); res.status(202).json(started); } catch (err) { - if (err instanceof AiDisabledError) { - res.status(403).json({ error: err.code, message: err.message }); + if (err instanceof AiDisabledError || err instanceof AiOverloadError) { + res.status(err.status).json({ error: err.code, message: err.message }); return; } res.status(400).json({ @@ -106,22 +113,29 @@ export function createAiRouter(deps: AiRouterDeps): Router { 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 ?? {}); + router.post( + '/test', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + 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; - } + if (!parsed.success) { + res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues }); + return; + } - res.json(await aiService.testEndpoint(parsed.data)); - }); + res.json(await aiService.testEndpoint(parsed.data)); + }, + ); return router; } diff --git a/src/server/api/routes/alerts.routes.ts b/src/server/api/routes/alerts.routes.ts index bfb82f7..0b2c345 100644 --- a/src/server/api/routes/alerts.routes.ts +++ b/src/server/api/routes/alerts.routes.ts @@ -1,4 +1,4 @@ -import { Router } from 'express'; +import { Router, type RequestHandler } from 'express'; import { ZodError, z } from 'zod'; import { AlertsFileSchema } from '../../../shared/schemas/alerts.schema.js'; import type { AlertEngine } from '../../alerts/alert-engine.js'; @@ -9,6 +9,7 @@ import { enforceSafeMode, requireAuth, requireCsrf, + requireStepUp, } from '../../security/guards.js'; export interface AlertsRouterDeps { @@ -16,11 +17,13 @@ export interface AlertsRouterDeps { configManager: ConfigManager; auditService: AuditService; alertEngine: AlertEngine; + stepUpGuard?: RequestHandler; } export function createAlertsRouter(deps: AlertsRouterDeps): Router { const router = Router(); - const { authService, configManager, auditService, alertEngine } = deps; + const { authService, configManager, auditService, alertEngine, stepUpGuard = requireStepUp } = + deps; router.get('/', requireAuth(authService), (req, res) => { const limit = typeof req.query.limit === 'string' ? Number(req.query.limit) : 50; @@ -30,41 +33,48 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { }); }); - 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, - })), + router.put( + '/config', + requireAuth(authService), + requireCsrf, + enforceSafeMode, + stepUpGuard, + (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', }); - return; } - res.status(400).json({ - error: 'ALERTS_SAVE_ERROR', - message: err instanceof Error ? err.message : 'Unable to save alerts configuration', - }); - } - }); + }, + ); router.post( '/silences', @@ -122,6 +132,7 @@ export function createAlertsRouter(deps: AlertsRouterDeps): Router { requireAuth(authService), requireCsrf, enforceSafeMode, + stepUpGuard, async (req, res) => { const id = String(req.params.id ?? ''); try { diff --git a/src/server/app.ts b/src/server/app.ts index b35ebd0..5e525b2 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -245,6 +245,7 @@ export async function createGCoordinatorServer( sshPool, wsHub, auditService, + getRuntimeLimits, ); const backupScheduler = new BackupScheduler( dataDir, @@ -396,6 +397,21 @@ export async function createGCoordinatorServer( }); }); + authService.setSecurityEventListener((ev) => { + void alertEngine.emitSecurityEvent(ev.type, { + ip: ev.ip, + details: ev.details, + message: `${ev.type}${ev.ip ? ` from ${ev.ip}` : ''}`, + }); + }); + + knownHosts.onHostKeyMismatch((alert) => { + void alertEngine.emitSecurityEvent('ssh.host_key_mismatch', { + serverId: alert.serverId, + message: `Host key mismatch on ${alert.hostPortKey} (${alert.algorithm})`, + }); + }); + monitoringService.start(); void tunnelManager.syncAutoStart(); customSystemsEngine.syncBackgroundChecks(); @@ -419,6 +435,9 @@ export async function createGCoordinatorServer( }); vaultService.onPanicLock(() => { + void alertEngine.emitSecurityEvent('vault.panic_lock', { + message: 'Emergency Panic Lock activated', + }); aiService.cancelAll(); backupScheduler.stop(); alertEngine.handlePanicLock(); @@ -442,6 +461,9 @@ export async function createGCoordinatorServer( warnings: event.warnings, errors: event.errors, }); + if (event.entityType === 'alerts' || event.entityType === 'server' || event.entityType === 'all') { + alertEngine.syncWithConfig(); + } if ( event.entityType === 'server' || event.entityType === 'system' || @@ -456,22 +478,32 @@ export async function createGCoordinatorServer( customSystemsEngine.invalidateCache(event.id); } else if (event.entityType === 'system' && event.id) { customSystemsEngine.invalidateCache(undefined, event.id); - } else { + } else if (event.entityType === 'all') { customSystemsEngine.invalidateCache(); } - if (event.entityType === 'settings') { + if (event.entityType === 'settings' || event.entityType === 'all') { applyDatabaseThrottlePragmas(db, getRuntimeLimits()); if (!configManager.getSettings().security.enableEmergencySecretsBackup) { recoveryStore.wipeAll(); } else { authService.syncRecovery(); } + backupScheduler.sync(); + } + if (event.entityType === 'server' || event.entityType === 'all') { + monitoringService.syncServers(); + void tunnelManager.syncAutoStart(); + } + if ( + event.entityType === 'server' || + event.entityType === 'system' || + event.entityType === 'all' + ) { + customSystemsEngine.syncBackgroundChecks(); + } + if (event.entityType === 'workflow' || event.entityType === 'all') { + workflowEngine.syncCronJobs(); } - monitoringService.syncServers(); - customSystemsEngine.syncBackgroundChecks(); - workflowEngine.syncCronJobs(); - backupScheduler.sync(); - void tunnelManager.syncAutoStart(); } }); @@ -593,9 +625,9 @@ export async function createGCoordinatorServer( ); app.use( '/api/alerts', - createAlertsRouter({ authService, configManager, auditService, alertEngine }), + createAlertsRouter({ authService, configManager, auditService, alertEngine, stepUpGuard }), ); - app.use('/api/ai', createAiRouter({ authService, aiService })); + app.use('/api/ai', createAiRouter({ authService, aiService, stepUpGuard })); app.use( '/api/servers/:id/sftp', createSftpRouter({ authService, configManager, auditService, sftpService, stepUpGuard }), diff --git a/src/shared/schemas/alerts.schema.ts b/src/shared/schemas/alerts.schema.ts index 1c0959f..26f751b 100644 --- a/src/shared/schemas/alerts.schema.ts +++ b/src/shared/schemas/alerts.schema.ts @@ -58,6 +58,12 @@ export const SecurityEventKindSchema = z.enum([ 'panic_lock', 'key_rotation', 'backup_restore', + 'auth.lockout', + 'auth.totp_replay', + 'auth.recovery_code_used', + 'auth.session_idle_expired', + 'ssh.host_key_mismatch', + 'vault.panic_lock', ]); export const AlertRuleSchema = z.discriminatedUnion('kind', [ diff --git a/tests/ai-assistant.test.ts b/tests/ai-assistant.test.ts index 48d5181..66f40b7 100644 --- a/tests/ai-assistant.test.ts +++ b/tests/ai-assistant.test.ts @@ -287,6 +287,19 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide // Write-lock Vault -> AI runtime secret still works via VaultService.getRuntimeSecret expect((await api('/api/vault/lock', { method: 'POST' })).data.state).toBe('locked'); + // Default Zero-Trust egress policy blocks outbound calls to loopback until allowlisted + const blockedEp = await api('/api/ai/test', { method: 'POST', body: {} }); + expect(blockedEp.data.ok).toBe(false); + + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }) + ).status, + ).toBe(200); + const testEp = await api('/api/ai/test', { method: 'POST', body: {} }); expect(testEp.status).toBe(200); expect(testEp.data.ok).toBe(true); diff --git a/tests/alerts-engine.test.ts b/tests/alerts-engine.test.ts index 59f6380..c1caaca 100644 --- a/tests/alerts-engine.test.ts +++ b/tests/alerts-engine.test.ts @@ -415,6 +415,19 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () => expect(lockRes.data.state).toBe('locked'); expect(lockRes.data.runtimeReady).toBe(true); + // Default Zero-Trust egress policy blocks webhook dispatch to 127.0.0.1 until allowlisted + const deniedWebhook = await api('/api/alerts/channels/ch-discord/test', { method: 'POST' }); + expect(deniedWebhook.data.ok).toBe(false); + + expect( + ( + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }) + ).status, + ).toBe(200); + // --- 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' }); diff --git a/tests/workflows-and-transfer.test.ts b/tests/workflows-and-transfer.test.ts index ec1e5f2..70b63be 100644 --- a/tests/workflows-and-transfer.test.ts +++ b/tests/workflows-and-transfer.test.ts @@ -607,7 +607,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers 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'); + expect(dagDetail.run.status, JSON.stringify(dagDetail.stepLogs)).toBe('succeeded'); const logByStep = new Map(dagDetail.stepLogs.map((l) => [l.stepId, l])); expect(logByStep.get('gen-token')?.stdout).toBe('tok-v42'); From 3a28a2332f62c4517bd9fb7d1b9d4cf5f9efff75 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:14:44 +0000 Subject: [PATCH 13/19] refactor(client): view unmount lifecycle, WS unsubscribe, lazy-split core views, Toast bus, Command Palette & diff hunks --- src/client/build.ts | 54 +++- src/client/css/base.css | 84 ++++++ src/client/index.html | 15 ++ src/client/ts/command-palette.ts | 161 ++++++++++++ src/client/ts/dialogs.ts | 57 +++- src/client/ts/main.ts | 364 ++++++++++++++++++-------- src/client/ts/state.ts | 37 +++ src/client/ts/toast.ts | 42 +++ src/client/ts/views/dashboard-view.ts | 9 + src/client/ts/ws-client.ts | 68 ++++- src/shared/diff.ts | 72 ++++- 11 files changed, 831 insertions(+), 132 deletions(-) create mode 100644 src/client/ts/command-palette.ts create mode 100644 src/client/ts/toast.ts diff --git a/src/client/build.ts b/src/client/build.ts index e17addc..6745406 100644 --- a/src/client/build.ts +++ b/src/client/build.ts @@ -8,17 +8,52 @@ const LAZY_CHUNK_BUDGET_BYTES = 20 * 1024; const clientDir = path.resolve('src/client'); const outDir = path.resolve('dist/public'); +function normalizeOutKey(rawPath: string): string { + const rel = path.relative(outDir, path.resolve(rawPath)); + return rel.replace(/\\/g, '/'); +} + +function collectSyncImports( + metaOutputs: Record, + entryKey: string, +): string[] { + const visited = new Set(); + const queue: string[] = [entryKey]; + + while (queue.length > 0) { + const cur = queue.shift()!; + if (visited.has(cur)) continue; + visited.add(cur); + + const matchEntry = Object.entries(metaOutputs).find( + ([outPath]) => normalizeOutKey(outPath) === cur, + ); + if (!matchEntry) continue; + + for (const imp of matchEntry[1].imports) { + if (imp.kind !== 'import-statement') continue; + const targetKey = normalizeOutKey(imp.path); + if (!visited.has(targetKey)) { + queue.push(targetKey); + } + } + } + + return [...visited]; +} + async function buildClient(): Promise { fs.rmSync(outDir, { recursive: true, force: true }); fs.mkdirSync(outDir, { recursive: true }); - await esbuild.build({ + const jsResult = await esbuild.build({ entryPoints: [path.join(clientDir, 'ts', 'main.ts')], bundle: true, format: 'esm', splitting: true, minify: true, sourcemap: false, + metafile: true, target: 'es2020', outdir: outDir, entryNames: '[name]', @@ -46,18 +81,22 @@ async function buildClient(): Promise { fs.copyFileSync(path.join(clientDir, asset), path.join(outDir, asset)); } - const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js']; + const syncJsChunks = jsResult.metafile + ? collectSyncImports(jsResult.metafile.outputs, 'main.js').filter((k) => k !== 'main.js') + : []; + + const coreAssets = ['index.html', 'themes.css', 'base.css', 'main.js', ...syncJsChunks]; let totalRaw = 0; let totalGzip = 0; for (const file of coreAssets) { - const buf = fs.readFileSync(path.join(outDir, file)); + const fullPath = path.join(outDir, file); + if (!fs.existsSync(fullPath)) continue; + const buf = fs.readFileSync(fullPath); const gz = zlib.gzipSync(buf, { level: 9 }); totalRaw += buf.length; totalGzip += gz.length; - console.log( - ` ${file.padEnd(14)} raw=${buf.length}B gzip=${gz.length}B`, - ); + console.log(` ${file.padEnd(24)} raw=${buf.length}B gzip=${gz.length}B`); } const chunksDir = path.join(outDir, 'chunks'); @@ -65,7 +104,8 @@ async function buildClient(): Promise { for (const chunk of fs.readdirSync(chunksDir).sort()) { 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`); + const syncTag = syncJsChunks.includes(`chunks/${chunk}`) ? ' [sync-core]' : ''; + console.log(` chunks/${chunk.padEnd(28)} raw=${cBuf.length}B gzip=${cGz.length}B${syncTag}`); 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 1077214..41699fb 100644 --- a/src/client/css/base.css +++ b/src/client/css/base.css @@ -699,3 +699,87 @@ dialog.ai-drawer[open] { padding: 6px 10px; } } + +.sr-only-focusable:focus { + position: static; + width: auto; + height: auto; + overflow: visible; + clip: auto; + white-space: normal; + display: inline-block; + margin-bottom: 6px; + padding: 6px 10px; + border: 1px solid var(--accent); + background: var(--bg-panel); + color: var(--accent); +} + +.toast-region { + position: fixed; + right: 12px; + bottom: 12px; + z-index: 40; + display: flex; + flex-direction: column; + gap: 6px; + max-width: min(380px, calc(100vw - 24px)); + pointer-events: none; +} + +.toast-item { + pointer-events: auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 8px 10px; + border: 1px solid var(--border); + background: var(--bg-panel); + color: var(--fg); + font-size: 0.85rem; +} + +.toast-ok { + border-color: var(--ok); +} + +.toast-warn { + border-color: var(--warn); +} + +.toast-err { + border-color: var(--err); +} + +.cmd-palette-list { + display: flex; + flex-direction: column; + gap: 4px; + max-height: 55vh; + overflow-y: auto; + margin-top: 8px; +} + +.cmd-palette-item { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + text-align: left; +} + +.cmd-palette-item.active { + border-color: var(--accent); + background: var(--bg-elevated); + color: var(--accent); +} + +.diff-hunk-sep { + padding: 2px 6px; + margin: 4px 0; + border-top: 1px dashed var(--border); + border-bottom: 1px dashed var(--border); + color: var(--fg-muted); + font-size: 0.78rem; +} diff --git a/src/client/index.html b/src/client/index.html index 2484694..4342508 100644 --- a/src/client/index.html +++ b/src/client/index.html @@ -13,6 +13,7 @@
+ Skip to main content
+

+
diff --git a/src/client/ts/charts.ts b/src/client/ts/charts.ts index b4b79a1..36ed648 100644 --- a/src/client/ts/charts.ts +++ b/src/client/ts/charts.ts @@ -97,3 +97,44 @@ export function createRangeChartSvg( svg.appendChild(poly); return svg; } + +export function createDualRangeChartSvg( + seriesA: number[], + seriesB: number[], + options: { colorA?: string; colorB?: string; maxVal?: number } = {}, +): SVGSVGElement { + const computedMax = + options.maxVal ?? + Math.max( + 1, + ...seriesA.map((v) => (Number.isFinite(v) ? v : 0)), + ...seriesB.map((v) => (Number.isFinite(v) ? v : 0)), + ); + + const svg = document.createElementNS(SVG_NS, 'svg'); + svg.setAttribute('viewBox', '0 0 600 120'); + svg.setAttribute('preserveAspectRatio', 'none'); + svg.setAttribute('class', 'chart-svg'); + + const midLine = document.createElementNS(SVG_NS, 'line'); + midLine.setAttribute('x1', '0'); + midLine.setAttribute('y1', '60'); + midLine.setAttribute('x2', '600'); + midLine.setAttribute('y2', '60'); + midLine.setAttribute('stroke', 'var(--border)'); + midLine.setAttribute('stroke-dasharray', '4 4'); + svg.appendChild(midLine); + + const addLine = (vals: number[], stroke: string) => { + const poly = document.createElementNS(SVG_NS, 'polyline'); + poly.setAttribute('fill', 'none'); + poly.setAttribute('stroke', stroke); + poly.setAttribute('stroke-width', '2'); + poly.setAttribute('points', buildPolylinePoints(vals, 600, 120, 0, computedMax)); + svg.appendChild(poly); + }; + + addLine(seriesA, options.colorA ?? 'var(--accent)'); + addLine(seriesB, options.colorB ?? 'var(--warn)'); + return svg; +} diff --git a/src/client/ts/views/dashboard-view.ts b/src/client/ts/views/dashboard-view.ts index 291d23a..3410724 100644 --- a/src/client/ts/views/dashboard-view.ts +++ b/src/client/ts/views/dashboard-view.ts @@ -21,8 +21,11 @@ import { type ClientState, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; const sparkHistory = new Map(); +let fleetFilter: 'all' | 'connected' | 'issues' = 'all'; +let fleetSearch = ''; function statusBadgeClass(status: string): string { if (status === 'connected') return 'badge badge-ok'; @@ -65,11 +68,18 @@ function renderProbesInto(container: Element, probes: ProbeSample[]): void { container.replaceChildren(); if (probes.length === 0) return; for (const p of probes) { + const tlsNote = + p.certExpiryDays !== undefined ? ` TLS:${p.certExpiryDays}d` : ''; + const cls = !p.ok || (p.certExpiryDays !== undefined && p.certExpiryDays <= 0) + ? 'badge-err' + : p.certExpiryDays !== undefined && p.certExpiryDays <= 14 + ? 'badge-warn' + : 'badge-ok'; container.append( el( 'span', - { class: `badge ${p.ok ? 'badge-ok' : 'badge-err'}` }, - `${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}`, + { class: `badge ${cls}` }, + `${p.probeId}: ${p.ok ? `OK ${Math.round(p.latencyMs)}ms` : 'FAIL'}${tlsNote}`, ), ); } @@ -123,6 +133,7 @@ export function patchDashboardServerStates(states: ServerRuntimeState[]): boolea badge.textContent = `[${st.status.toUpperCase()}]`; badge.className = statusBadgeClass(st.status); } + card.setAttribute('data-status', st.status); const osBadge = card.querySelector('[data-field="os"]'); if (osBadge && st.osDetected) { osBadge.textContent = st.osDetected; @@ -142,12 +153,16 @@ async function openRegisterServerDialog( const form = document.getElementById('dialog-srv-form') as HTMLFormElement; const credSelect = document.getElementById('srv-cred') as HTMLSelectElement; const jumpSelect = document.getElementById('srv-jump') as HTMLSelectElement; + const testMsgEl = document.getElementById('srv-test-msg') as HTMLElement; const errEl = document.getElementById('srv-reg-err') as HTMLElement; + const testBtn = document.getElementById('srv-test-conn-btn') as HTMLButtonElement; const closeBtn = document.getElementById('srv-reg-close') as HTMLButtonElement; const cancelBtn = document.getElementById('srv-reg-cancel') as HTMLButtonElement; form.reset(); errEl.textContent = ''; + testMsgEl.textContent = ''; + testMsgEl.className = 'form-msg'; credSelect.replaceChildren(); try { @@ -174,8 +189,69 @@ async function openRegisterServerDialog( jumpSelect.append(el('option', { value: s.config.id }, `${s.config.id} (${s.config.host})`)); } + const buildPayload = () => { + const fd = new FormData(form); + const id = String(fd.get('id') ?? '').trim(); + const tagsRaw = String(fd.get('tags') ?? ''); + const tags = tagsRaw + .split(',') + .map((t) => t.trim()) + .filter(Boolean); + return { + id, + name: String(fd.get('name') ?? id).trim(), + host: String(fd.get('host') ?? '').trim(), + port: Number(fd.get('port') ?? 22), + username: String(fd.get('username') ?? '').trim(), + credentialId: String(fd.get('credentialId') ?? '').trim(), + jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined, + osHint: String(fd.get('osHint') ?? 'auto'), + pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10), + tags, + }; + }; + + const onTestConn = async () => { + errEl.textContent = ''; + testBtn.disabled = true; + testMsgEl.className = 'form-msg muted'; + testMsgEl.textContent = 'Testing SSH handshake...'; + try { + const payload = buildPayload(); + const res = await apiFetch<{ + ok: boolean; + latencyMs: number; + osDetected?: string; + hostFingerprint?: string; + tofuRequired?: boolean; + hostKeyMismatch?: { expectedFingerprint: string; actualFingerprint: string }; + error?: string; + }>('/api/servers/test-connection', { + method: 'POST', + body: payload, + }); + if (res.ok) { + testMsgEl.className = 'form-msg ok-text'; + testMsgEl.textContent = `Connected in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown OS'})${res.hostFingerprint ? ` · fp ${res.hostFingerprint}` : ''}`; + } else { + testMsgEl.className = res.hostKeyMismatch ? 'form-msg err-text' : 'form-msg warn-text'; + testMsgEl.textContent = res.hostKeyMismatch + ? `HOST KEY MISMATCH: ${res.hostKeyMismatch.actualFingerprint}` + : res.tofuRequired + ? `TOFU required (${res.hostFingerprint ?? 'unknown fingerprint'}): ${res.error ?? 'save then approve TOFU'}` + : res.error ?? 'Connection test failed'; + } + } catch (err) { + testMsgEl.className = 'form-msg err-text'; + testMsgEl.textContent = extractErrorMessage(err); + } finally { + testBtn.disabled = false; + } + }; + const cleanup = () => { form.removeEventListener('submit', onSubmit); + testBtn.removeEventListener('click', onTestConn); closeBtn.removeEventListener('click', onClose); cancelBtn.removeEventListener('click', onClose); dialog.removeEventListener('close', onDialogClose); @@ -190,34 +266,18 @@ async function openRegisterServerDialog( const onSubmit = async (ev: Event) => { ev.preventDefault(); errEl.textContent = ''; - const fd = new FormData(form); - const id = String(fd.get('id') ?? '').trim(); - const tagsRaw = String(fd.get('tags') ?? ''); - const tags = tagsRaw - .split(',') - .map((t) => t.trim()) - .filter(Boolean); + const payload = buildPayload(); try { await apiFetch('/api/servers', { method: 'POST', - body: { - id, - name: String(fd.get('name') ?? id).trim(), - host: String(fd.get('host') ?? '').trim(), - port: Number(fd.get('port') ?? 22), - username: String(fd.get('username') ?? '').trim(), - credentialId: String(fd.get('credentialId') ?? '').trim(), - jumpHostId: String(fd.get('jumpHostId') ?? '').trim() || undefined, - osHint: String(fd.get('osHint') ?? 'auto'), - pollIntervalSec: Number(fd.get('pollIntervalSec') ?? 10), - tags, - }, + body: payload, }); - await apiFetch(`/api/servers/${encodeURIComponent(id)}/reconnect`, { + await apiFetch(`/api/servers/${encodeURIComponent(payload.id)}/reconnect`, { method: 'POST', }).catch(() => undefined); if (dialog.open) dialog.close(); + showToast(`Server "${payload.id}" registered.`, 'ok'); await onRegistered(); } catch (err) { errEl.textContent = extractErrorMessage(err); @@ -225,12 +285,106 @@ async function openRegisterServerDialog( }; form.addEventListener('submit', onSubmit); + testBtn.addEventListener('click', onTestConn); closeBtn.addEventListener('click', onClose); cancelBtn.addEventListener('click', onClose); dialog.addEventListener('close', onDialogClose); dialog.showModal(); } +async function openImportSshConfigDialog(onImported: () => Promise): Promise { + const dlg = el('dialog', { class: 'dialog-wide', 'aria-labelledby': 'imp-ssh-title' }); + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close'); + const credSelect = el('select', { class: 'input-sm' }); + const textarea = el('textarea', { + rows: 8, + class: 'code-editor', + placeholder: 'Host prod-web\n HostName 10.0.1.12\n User ops\n Port 22', + }) as HTMLTextAreaElement; + const msgEl = el('p', { class: 'form-msg' }); + const previewBox = el('div', { class: 'stack' }); + const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview'); + const applyBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Import Hosts'); + + try { + const creds = await apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials'); + for (const c of creds.credentials.filter((x) => x.type === 'ssh-key' || x.type === 'ssh-password')) { + credSelect.append(el('option', { value: c.id }, `${c.id} (${c.type})`)); + } + } catch { + // Vault may be locked or empty + } + if (credSelect.options.length === 0) { + credSelect.append(el('option', { value: '' }, 'No SSH credential (unlock Vault first)')); + } + + const close = () => { + if (dlg.open) dlg.close(); + dlg.remove(); + }; + closeBtn.addEventListener('click', close); + dlg.addEventListener('close', () => dlg.remove()); + + const runImport = async (apply: boolean) => { + msgEl.className = 'form-msg muted'; + msgEl.textContent = apply ? 'Importing hosts...' : 'Parsing SSH config...'; + previewBox.replaceChildren(); + try { + const res = await apiFetch<{ + entries: Array<{ alias: string; id: string; host: string; port: number; username: string; jumpHostAlias?: string }>; + warnings: string[]; + createdIds: string[]; + }>('/api/servers/import-ssh-config', { + method: 'POST', + body: { + configText: textarea.value, + defaultCredentialId: credSelect.value || undefined, + apply, + }, + }); + if (res.warnings.length > 0) { + previewBox.append(el('div', { class: 'warn-text mono' }, `Warnings: ${res.warnings.join(' | ')}`)); + } + if (res.entries.length === 0) { + previewBox.append(el('div', { class: 'muted' }, 'No concrete Host blocks found.')); + } else { + for (const e of res.entries) { + previewBox.append( + el('div', { class: 'mono' }, `${e.alias} -> ${e.username}@${e.host}:${e.port}${e.jumpHostAlias ? ` (via ${e.jumpHostAlias})` : ''}`), + ); + } + } + if (apply) { + msgEl.className = 'form-msg ok-text'; + msgEl.textContent = `Imported ${res.createdIds.length} server(s): ${res.createdIds.join(', ')}`; + showToast(`Imported ${res.createdIds.length} server(s) from SSH config.`, 'ok'); + close(); + await onImported(); + } else { + msgEl.className = 'form-msg ok-text'; + msgEl.textContent = `Previewed ${res.entries.length} host(s).`; + } + } catch (err) { + msgEl.className = 'form-msg err-text'; + msgEl.textContent = extractErrorMessage(err); + } + }; + + previewBtn.addEventListener('click', () => void runImport(false)); + applyBtn.addEventListener('click', () => void runImport(true)); + + dlg.append( + el('div', { class: 'row-between' }, el('h1', { id: 'imp-ssh-title' }, 'Import OpenSSH Config'), closeBtn), + el('div', { class: 'row' }, el('label', {}, 'Default SSH Credential:'), credSelect), + textarea, + msgEl, + previewBox, + el('div', { class: 'dialog-actions' }, previewBtn, applyBtn), + ); + document.body.append(dlg); + dlg.showModal(); +} + export async function renderDashboardView( root: HTMLElement, state: ClientState, @@ -303,18 +457,90 @@ export async function renderDashboardView( void renderDashboardView(root, state); }); + const importSshBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm mutating-action' }, + 'Import SSH Config', + ); + importSshBtn.addEventListener('click', () => { + void openImportSshConfigDialog(() => renderDashboardView(root, state)); + }); + + const connCount = servers.filter((s) => s.runtime.status === 'connected').length; + const issueCount = servers.length - connCount; + const vaultSummary = !state.vaultRuntimeReady ? 'Vault: sealed (master key required)' : state.vaultState === 'unlocked' ? 'Vault: unlocked (editable)' : 'Vault: locked (collectors & secrets active)'; + const filterSearchInput = el('input', { + type: 'search', + class: 'input-sm', + placeholder: 'Filter host / tag / name...', + value: fleetSearch, + 'aria-label': 'Filter servers', + }) as HTMLInputElement; + + const filterButtons = (['all', 'connected', 'issues'] as const).map((mode) => { + const label = + mode === 'all' + ? `All (${servers.length})` + : mode === 'connected' + ? `Connected (${connCount})` + : `Issues (${issueCount})`; + const b = el( + 'button', + { type: 'button', class: `btn btn-sm${fleetFilter === mode ? ' btn-primary' : ''}` }, + label, + ); + b.addEventListener('click', () => { + fleetFilter = mode; + applyFleetFilter(); + for (const btn of filterButtons) btn.classList.remove('btn-primary'); + b.classList.add('btn-primary'); + }); + return b; + }); + + const applyFleetFilter = () => { + const q = fleetSearch.trim().toLowerCase(); + for (const card of root.querySelectorAll('[data-server-card]')) { + const st = card.getAttribute('data-status') ?? ''; + const hay = card.getAttribute('data-search') ?? ''; + const matchMode = + fleetFilter === 'all' + ? true + : fleetFilter === 'connected' + ? st === 'connected' + : st !== 'connected'; + const matchQ = !q || hay.includes(q); + (card as HTMLElement).hidden = !(matchMode && matchQ); + } + }; + + filterSearchInput.addEventListener('input', () => { + fleetSearch = filterSearchInput.value; + applyFleetFilter(); + }); + root.append( el( 'div', - { class: 'panel row-between' }, - el('div', {}, el('h1', {}, `Fleet Monitor (${servers.length} servers)`), el('span', { class: 'muted' }, vaultSummary)), - el('div', { class: 'row' }, registerBtn, rotateFleetBtn, refreshBtn), + { class: 'panel stack' }, + el( + 'div', + { class: 'row-between' }, + el('div', {}, el('h1', {}, `Fleet Monitor (${connCount}/${servers.length} connected)`), el('span', { class: 'muted' }, vaultSummary)), + el('div', { class: 'row' }, registerBtn, importSshBtn, rotateFleetBtn, refreshBtn), + ), + el( + 'div', + { class: 'row-between' }, + el('div', { class: 'row' }, ...filterButtons), + filterSearchInput, + ), ), actionStatus, ); @@ -523,7 +749,12 @@ export async function renderDashboardView( const card = el( 'article', - { class: 'panel panel-region', 'data-server-card': config.id }, + { + class: 'panel panel-region', + 'data-server-card': config.id, + 'data-status': runtime.status, + 'data-search': `${config.id} ${config.name} ${config.host} ${config.tags.join(' ')}`.toLowerCase(), + }, el( 'div', { class: 'row-between' }, @@ -568,4 +799,5 @@ export async function renderDashboardView( grid.append(card); } root.append(grid); + applyFleetFilter(); } diff --git a/src/client/ts/views/server-detail-view.ts b/src/client/ts/views/server-detail-view.ts index cec3ce4..b9b9b8c 100644 --- a/src/client/ts/views/server-detail-view.ts +++ b/src/client/ts/views/server-detail-view.ts @@ -1,19 +1,23 @@ import type { DiskSample, ProbeSample } from '../../../shared/ws-protocol.js'; import { apiFetch } from '../api.js'; -import { createRangeChartSvg } from '../charts.js'; +import { createDualRangeChartSvg, createRangeChartSvg } from '../charts.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, + fmtBytesPerSec, fmtTime, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; type DetailTab = 'metrics' | 'inspector' | 'keys' | 'tunnels'; let activeTab: DetailTab = 'metrics'; let activeRange: '1h' | '6h' | '24h' | '7d' | '30d' = '1h'; let procSortBy: 'cpu' | 'mem' = 'cpu'; +let inspectSudo = false; +let showAllKnownHosts = false; export async function renderServerDetailView( root: HTMLElement, @@ -37,6 +41,36 @@ export async function renderServerDetailView( } const header = el('section', { class: 'panel' }); + const testConnBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm mutating-action' }, + 'Test SSH', + ); + testConnBtn.addEventListener('click', async () => { + testConnBtn.disabled = true; + try { + const res = await apiFetch<{ + ok: boolean; + latencyMs: number; + osDetected?: string; + hostFingerprint?: string; + error?: string; + }>('/api/servers/test-connection', { + method: 'POST', + body: entry.config, + }); + if (res.ok) { + showToast(`SSH OK in ${Math.round(res.latencyMs)}ms (${res.osDetected ?? 'unknown'})`, 'ok'); + } else { + showToast(`SSH test failed: ${res.error ?? 'unknown error'}`, 'err'); + } + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } finally { + testConnBtn.disabled = false; + } + }); + const reconnBtn = el( 'button', { type: 'button', class: 'btn btn-sm mutating-action' }, @@ -110,6 +144,7 @@ export async function renderServerDetailView( 'div', { class: 'row' }, el('span', { class: 'badge' }, `[${entry.runtime.status.toUpperCase()}]`), + testConnBtn, reconnBtn, delBtn, el('a', { href: '#dashboard', class: 'btn btn-sm' }, '← Dashboard'), @@ -127,7 +162,7 @@ export async function renderServerDetailView( } else if (activeTab === 'inspector') { await renderInspectorTab(body, serverId); } else if (activeTab === 'keys') { - await renderKeysTab(body, serverId); + await renderKeysTab(body, serverId, `${entry.config.host}:${entry.config.port}`); } else { const { renderTunnelsPanel } = await import('./tunnels-panel.js'); await renderTunnelsPanel(body, serverId); @@ -135,13 +170,20 @@ export async function renderServerDetailView( } async function renderMetricsTab(body: HTMLElement, serverId: string): Promise { - const data = await apiFetch<{ - range: string; - granularity: 'raw' | '1h' | '1d'; - points: Array>; - latestDisks: DiskSample[]; - latestProbes: Array; - }>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`); + const [data, probeHistRes] = await Promise.all([ + apiFetch<{ + range: string; + granularity: 'raw' | '1h' | '1d'; + points: Array>; + latestDisks: DiskSample[]; + latestProbes: Array; + probeHistory?: Array; + diskHistory?: Array<{ ts: number; mountPoint: string; usedPct: number; usedMb: number; totalMb: number }>; + }>(`/api/servers/${encodeURIComponent(serverId)}/metrics?range=${activeRange}`), + apiFetch<{ samples: Array }>( + `/api/servers/${encodeURIComponent(serverId)}/probes/history?range=${activeRange}`, + ).catch(() => ({ samples: [] })), + ]); const rangeBar = el( 'div', @@ -173,6 +215,22 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise p.load1m ?? p.loadMax ?? 0); + const netRxSeries = data.points.map((p) => p.netRxBps ?? p.netRxAvgBps ?? 0); + const netTxSeries = data.points.map((p) => p.netTxBps ?? p.netTxAvgBps ?? 0); + + const diskMaxByTs = new Map(); + for (const d of data.diskHistory ?? []) { + const prev = diskMaxByTs.get(d.ts) ?? 0; + if (d.usedPct > prev) diskMaxByTs.set(d.ts, d.usedPct); + } + const diskSeries = data.points.some((p) => p.diskMaxPct !== undefined) + ? data.points.map((p) => p.diskMaxPct ?? 0) + : [...diskMaxByTs.entries()].sort((a, b) => a[0] - b[0]).map((x) => x[1]); + + const probeHistory = probeHistRes.samples.length > 0 ? probeHistRes.samples : (data.probeHistory ?? []); + const probeLatencySeries = probeHistory.map((p) => p.latencyMs ?? 0); + const lastRx = netRxSeries.at(-1) ?? 0; + const lastTx = netTxSeries.at(-1) ?? 0; const chartsGrid = el( 'div', @@ -180,6 +238,25 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise p.ok).length; + const failProbes = probeHistory.length - okProbes; + probePanel.append( + el( + 'div', + { class: 'row-between' }, + el('h2', {}, 'Endpoint Health Probes'), + el( + 'span', + { class: 'muted mono' }, + probeHistory.length > 0 ? `${probeHistory.length} checks (${okProbes} ok / ${failProbes} fail in ${activeRange})` : 'No probe history in range', + ), + ), + ); const pTable = el('table'); - pTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Probe ID'), el('th', {}, 'Status'), el('th', {}, 'HTTP Code'), el('th', {}, 'Latency'), el('th', {}, 'Checked At'), el('th', {}, 'Detail')))); + pTable.append( + el( + 'thead', + {}, + el( + 'tr', + {}, + el('th', {}, 'Probe ID'), + el('th', {}, 'Status'), + el('th', {}, 'HTTP Code'), + el('th', {}, 'Latency'), + el('th', {}, 'TLS Expiry'), + el('th', {}, 'Checked At'), + el('th', {}, 'Detail'), + el('th', {}, 'Action'), + ), + ), + ); const pBody = el('tbody'); if (data.latestProbes.length === 0) { - pBody.append(el('tr', {}, el('td', { colspan: 6, class: 'muted' }, 'No probe results recorded yet.'))); + pBody.append(el('tr', {}, el('td', { colspan: 8, class: 'muted' }, 'No probe results recorded yet.'))); } else { for (const p of data.latestProbes) { + const tlsBadge = + p.certExpiryDays !== undefined + ? el( + 'span', + { + class: `badge ${ + p.certExpiryDays <= 0 + ? 'badge-err' + : p.certExpiryDays <= 14 + ? 'badge-warn' + : 'badge-ok' + }`, + }, + `${p.certExpiryDays}d`, + ) + : el('span', { class: 'muted' }, '—'); + const runBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Run Now'); + runBtn.addEventListener('click', async () => { + runBtn.disabled = true; + try { + const runRes = await apiFetch<{ sample: ProbeSample }>( + `/api/servers/${encodeURIComponent(serverId)}/probes/${encodeURIComponent(p.probeId)}/run`, + { method: 'POST', body: {} }, + ); + showToast( + `Probe "${p.probeId}": ${runRes.sample.ok ? `OK (${Math.round(runRes.sample.latencyMs)}ms)` : runRes.sample.error ?? 'FAIL'}`, + runRes.sample.ok ? 'ok' : 'err', + ); + body.replaceChildren(); + await renderMetricsTab(body, serverId); + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } finally { + runBtn.disabled = false; + } + }); pBody.append( el( 'tr', @@ -220,8 +363,10 @@ async function renderMetricsTab(body: HTMLElement, serverId: string): Promise { const sortCpuBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'cpu' ? ' btn-primary' : ''}` }, 'Sort CPU'); const sortMemBtn = el('button', { type: 'button', class: `btn btn-sm${procSortBy === 'mem' ? ' btn-primary' : ''}` }, 'Sort RAM'); + const sudoBtn = el( + 'button', + { type: 'button', class: `btn btn-sm mutating-action${inspectSudo ? ' btn-primary' : ''}` }, + inspectSudo ? 'Sudo: ON' : '+Sudo', + ); const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh Snapshot'); sortCpuBtn.addEventListener('click', () => { @@ -246,13 +396,18 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< body.replaceChildren(); void renderInspectorTab(body, serverId); }); + sudoBtn.addEventListener('click', () => { + inspectSudo = !inspectSudo; + body.replaceChildren(); + void renderInspectorTab(body, serverId); + }); refreshBtn.addEventListener('click', () => { body.replaceChildren(); void renderInspectorTab(body, serverId); }); body.append( - el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, refreshBtn)), + el('div', { class: 'panel row-between' }, el('strong', {}, 'On-Demand Server Inspector'), el('div', { class: 'row' }, sortCpuBtn, sortMemBtn, sudoBtn, refreshBtn)), ); try { @@ -262,18 +417,53 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< processes: Array<{ pid: number; user: string; cpuPct: number; memPct: number; rssMb: number; command: string }>; ports: Array<{ proto: string; localAddress: string; process: string }>; thermals: Array<{ zone: string; tempC: number }>; - }>(`/api/servers/${encodeURIComponent(serverId)}/inspect`); + }>(`/api/servers/${encodeURIComponent(serverId)}/inspect?sort=${procSortBy}&sudo=${inspectSudo ? 'true' : 'false'}`); const sortedProcs = [...res.processes].sort((a, b) => procSortBy === 'cpu' ? b.cpuPct - a.cpuPct : b.memPct - a.memPct, ); const procTable = el('table'); - procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command')))); + procTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'PID'), el('th', {}, 'User'), el('th', {}, 'CPU%'), el('th', {}, 'MEM%'), el('th', {}, 'RSS'), el('th', {}, 'Command'), el('th', {}, 'Signal')))); const pBody = el('tbody'); for (const p of sortedProcs) { + const makeSigBtn = (sig: 'SIGTERM' | 'SIGKILL', cls: string) => { + const b = el('button', { type: 'button', class: `btn btn-sm ${cls} mutating-action` }, sig === 'SIGTERM' ? 'TERM' : 'KILL'); + b.addEventListener('click', async () => { + const ok = await confirmDialog( + 'dialog-confirm', + `Send ${sig} to PID ${p.pid} (${p.command.slice(0, 48)}) on ${serverId}?`, + ); + if (!ok) return; + try { + const sigRes = await apiFetch<{ ok: boolean; error?: string }>( + `/api/servers/${encodeURIComponent(serverId)}/processes/${p.pid}/signal`, + { method: 'POST', body: { signal: sig, sudo: inspectSudo } }, + ); + showToast( + sigRes.ok ? `Sent ${sig} to PID ${p.pid}.` : `Signal ${sig} failed: ${sigRes.error ?? 'error'}`, + sigRes.ok ? 'ok' : 'err', + ); + body.replaceChildren(); + await renderInspectorTab(body, serverId); + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }); + return b; + }; pBody.append( - el('tr', {}, el('td', { class: 'mono' }, String(p.pid)), el('td', { class: 'mono' }, p.user), el('td', { class: 'mono' }, `${p.cpuPct}`), el('td', { class: 'mono' }, `${p.memPct}`), el('td', { class: 'mono' }, `${p.rssMb}M`), el('td', { class: 'mono' }, p.command.slice(0, 90))), + el( + 'tr', + {}, + el('td', { class: 'mono' }, String(p.pid)), + el('td', { class: 'mono' }, p.user), + el('td', { class: 'mono' }, `${p.cpuPct}`), + el('td', { class: 'mono' }, `${p.memPct}`), + el('td', { class: 'mono' }, `${p.rssMb}M`), + el('td', { class: 'mono' }, p.command.slice(0, 90)), + el('td', {}, el('div', { class: 'row' }, makeSigBtn('SIGTERM', ''), makeSigBtn('SIGKILL', 'btn-danger'))), + ), ); } procTable.append(pBody); @@ -306,7 +496,7 @@ async function renderInspectorTab(body: HTMLElement, serverId: string): Promise< } } -async function renderKeysTab(body: HTMLElement, serverId: string): Promise { +async function renderKeysTab(body: HTMLElement, serverId: string, hostPortKey: string): Promise { const msg = el('p', { class: 'form-msg' }); const rotateBtn = el( 'button', @@ -330,7 +520,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise const r = res.results[0]; if (r?.ok) { body.replaceChildren(); - await renderKeysTab(body, serverId); + await renderKeysTab(body, serverId, hostPortKey); } else { msg.className = 'form-msg err-text'; msg.textContent = `Rotation failed (rolledBack=${String(r?.rolledBack)}): ${r?.error ?? 'unknown'}`; @@ -359,7 +549,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise body: { credentialId: deploySelect.value }, }); body.replaceChildren(); - await renderKeysTab(body, serverId); + await renderKeysTab(body, serverId, hostPortKey); } catch (err) { msg.className = 'form-msg err-text'; msg.textContent = extractErrorMessage(err); @@ -376,6 +566,72 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise msg, ); + // Known Hosts (Multi-Algo) + try { + const khRes = await apiFetch<{ + knownHosts: Array<{ hostPort: string; algorithm: string; fingerprint: string; updatedAt: number }>; + }>('/api/servers/known-hosts'); + const filteredKh = showAllKnownHosts + ? khRes.knownHosts + : khRes.knownHosts.filter((kh) => kh.hostPort === hostPortKey); + const scopeBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm' }, + showAllKnownHosts ? `Filter ${hostPortKey}` : `Show All (${khRes.knownHosts.length})`, + ); + scopeBtn.addEventListener('click', () => { + showAllKnownHosts = !showAllKnownHosts; + body.replaceChildren(); + void renderKeysTab(body, serverId, hostPortKey); + }); + const khTable = el('table'); + khTable.append(el('thead', {}, el('tr', {}, el('th', {}, 'Host:Port'), el('th', {}, 'Algorithm'), el('th', {}, 'Fingerprint'), el('th', {}, 'Updated'), el('th', {}, 'Action')))); + const khBody = el('tbody'); + if (filteredKh.length === 0) { + khBody.append(el('tr', {}, el('td', { colspan: 5, class: 'muted' }, 'No trusted host keys in scope.'))); + } else { + for (const kh of filteredKh) { + const delKhBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); + delKhBtn.addEventListener('click', async () => { + const ok = await confirmDialog( + 'dialog-confirm', + `Remove trusted ${kh.algorithm} key for ${kh.hostPort}? Next connection will require TOFU approval.`, + ); + if (!ok) return; + await apiFetch( + `/api/servers/known-hosts?hostPort=${encodeURIComponent(kh.hostPort)}&algorithm=${encodeURIComponent(kh.algorithm)}`, + { method: 'DELETE' }, + ); + showToast(`Deleted ${kh.algorithm} key for ${kh.hostPort}.`, 'ok'); + body.replaceChildren(); + await renderKeysTab(body, serverId, hostPortKey); + }); + khBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, kh.hostPort), + el('td', { class: 'mono' }, kh.algorithm), + el('td', { class: 'mono' }, kh.fingerprint), + el('td', { class: 'mono' }, fmtTime(kh.updatedAt)), + el('td', {}, delKhBtn), + ), + ); + } + } + khTable.append(khBody); + body.append( + el( + 'section', + { class: 'panel' }, + el('div', { class: 'row-between' }, el('h2', {}, 'Trusted Host Keys (known_hosts)'), scopeBtn), + el('div', { class: 'table-wrap' }, khTable), + ), + ); + } catch (err) { + body.append(el('div', { class: 'panel err-text' }, extractErrorMessage(err))); + } + try { const res = await apiFetch<{ entries: Array<{ @@ -410,7 +666,7 @@ async function renderKeysTab(body: HTMLElement, serverId: string): Promise body: { fingerprint: k.fingerprint }, }); body.replaceChildren(); - await renderKeysTab(body, serverId); + await renderKeysTab(body, serverId, hostPortKey); }); } kBody.append( From 5b09c8ada157fb2efb08b1d1adf17959a1f8fd08 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:17:39 +0000 Subject: [PATCH 15/19] feat(client): upgrade Terminal (.cast v2, reconnect, cleanup) & AI drawer (cancel, targetId) --- src/client/ts/views/ai-drawer.ts | 34 +++++++++-- src/client/ts/views/terminal-view.ts | 87 +++++++++++++++++++++++++--- 2 files changed, 109 insertions(+), 12 deletions(-) diff --git a/src/client/ts/views/ai-drawer.ts b/src/client/ts/views/ai-drawer.ts index d3620f7..fb0048e 100644 --- a/src/client/ts/views/ai-drawer.ts +++ b/src/client/ts/views/ai-drawer.ts @@ -7,6 +7,7 @@ import { extractErrorMessage, type ClientState, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; export type ClientAiSurface = 'workflows' | 'systems' | 'snippets' | 'logs' | 'setup'; @@ -27,6 +28,7 @@ export interface OpenAiDrawerOptions { contextText?: string; serverId?: string; targetPath?: string; + targetId?: string; defaultDraftKind?: ClientAiDraftKind; onInsertTerminalText?: (cmd: string) => void; onApplied?: () => Promise | void; @@ -103,18 +105,29 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< 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 stopBtn = el('button', { type: 'button', class: 'btn btn-danger btn-sm', disabled: true }, 'Cancel Stream'); const history: Array<{ role: 'user' | 'assistant'; content: string }> = []; let activeChatId: string | null = null; let currentReply = ''; let unsubWs: (() => void) | null = null; + let unsubChannel: (() => void) | null = null; + + const releaseChannel = () => { + if (unsubChannel) { + unsubChannel(); + unsubChannel = null; + } + }; const cleanup = () => { if (activeChatId) { - opts.wsClient.send({ type: 'ai:cancel', chatId: activeChatId }); + const cid = activeChatId; + opts.wsClient.send({ type: 'ai:cancel', chatId: cid }); + void apiFetch(`/api/ai/chat/${encodeURIComponent(cid)}/cancel`, { method: 'POST' }).catch(() => undefined); activeChatId = null; } + releaseChannel(); if (unsubWs) { unsubWs(); unsubWs = null; @@ -170,7 +183,11 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< | { valid: false; issues: Array<{ path: string; message: string }> } >('/api/ai/validate-draft', { method: 'POST', - body: { kind: draftKindSel.value, jsonText: jsonBlock }, + body: { + kind: draftKindSel.value, + jsonText: jsonBlock, + ...(opts.targetId ? { targetId: opts.targetId } : {}), + }, }); draftOutputBox.replaceChildren(); @@ -238,11 +255,14 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< if (currentReply) history.push({ role: 'assistant', content: currentReply }); appendBoundedStreamText(streamPre, '\n'); activeChatId = null; + releaseChannel(); sendBtn.disabled = false; stopBtn.disabled = true; if (!frame.error) { statusLine.className = 'form-msg ok-text'; statusLine.textContent = 'Response complete. Review any extracted draft below.'; + } else { + showToast(frame.error, 'err'); } refreshDraftActions(); } @@ -301,13 +321,17 @@ export async function openAiAssistantDrawer(opts: OpenAiDrawerOptions): Promise< }, }); activeChatId = started.chatId; - opts.wsClient.subscribe([`ai:${started.chatId}`]); + releaseChannel(); + unsubChannel = opts.wsClient.subscribe([`ai:${started.chatId}`]); } catch (err) { history.pop(); + releaseChannel(); sendBtn.disabled = false; stopBtn.disabled = true; + const errMsg = extractErrorMessage(err); statusLine.className = 'form-msg err-text'; - statusLine.textContent = extractErrorMessage(err); + statusLine.textContent = errMsg; + showToast(errMsg, 'err'); } }); diff --git a/src/client/ts/views/terminal-view.ts b/src/client/ts/views/terminal-view.ts index 3bf01db..d5486b0 100644 --- a/src/client/ts/views/terminal-view.ts +++ b/src/client/ts/views/terminal-view.ts @@ -3,7 +3,16 @@ 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, isAiEnabled, type ClientState, type ServerEntry } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + isAiEnabled, + registerViewCleanup, + type ClientState, + type ServerEntry, +} from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; import { clearTerminalComposition, @@ -175,6 +184,7 @@ export async function renderTerminalView( root.replaceChildren(); const q = state.routeQuery ?? {}; + const targetServer = q.server ?? q.serverId; const [sessionsRes, serversRes] = await Promise.all([ apiFetch<{ sessions: PtySessionInfo[] }>('/api/terminal/sessions'), apiFetch<{ servers: ServerEntry[] }>('/api/servers'), @@ -185,13 +195,13 @@ export async function renderTerminalView( if (q.session && sessions.some((s) => s.sessionId === q.session)) { activeSessionId = q.session; - } else if (q.server && q.cwd !== undefined && servers.some((s) => s.config.id === q.server)) { + } else if (targetServer && q.cwd !== undefined && servers.some((s) => s.config.id === targetServer)) { // Open-Terminal-Here shortcut if not disabled by Safe Mode if (!state.safeMode) { try { const created = await apiFetch<{ session: PtySessionInfo }>('/api/terminal/sessions', { method: 'POST', - body: { serverId: q.server, cwd: q.cwd, cols: 90, rows: 26 }, + body: { serverId: targetServer, cwd: q.cwd, cols: 90, rows: 26 }, }); sessions = [created.session, ...sessions]; activeSessionId = created.session.sessionId; @@ -213,7 +223,7 @@ export async function renderTerminalView( serverSel.append( el( 'option', - { value: s.config.id, selected: q.server === s.config.id }, + { value: s.config.id, selected: targetServer === s.config.id }, `${s.config.name} (${s.config.id})`, ), ); @@ -282,6 +292,15 @@ export async function renderTerminalView( el('div', { class: 'row' }, serverSel, cwdInput, openShellBtn), ), tabsRow, + ...(state.safeMode + ? [ + el( + 'p', + { class: 'warn-text mono' }, + '[SAFE MODE] Read-only terminal view: keyboard input, reconnect, and session creation are locked.', + ), + ] + : []), msgEl, ), ); @@ -318,6 +337,40 @@ export async function renderTerminalView( }, 'Export ANSI', ); + const exportCastBtn = el( + 'a', + { + href: `/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/export?format=cast`, + class: 'btn btn-sm', + download: '', + }, + 'Export .cast', + ); + const reconnectPtyBtn = el( + 'button', + { + type: 'button', + class: 'btn btn-sm btn-primary mutating-action', + hidden: !current.exited, + }, + 'Reconnect Session', + ); + reconnectPtyBtn.addEventListener('click', async () => { + reconnectPtyBtn.disabled = true; + try { + await apiFetch(`/api/terminal/sessions/${encodeURIComponent(current.sessionId)}/reconnect`, { + method: 'POST', + body: {}, + }); + showToast('PTY session reconnected.', 'ok'); + await renderTerminalView(root, state, wsClient); + } catch (err) { + msgEl.className = 'form-msg err-text'; + msgEl.textContent = extractErrorMessage(err); + showToast(extractErrorMessage(err), 'err'); + reconnectPtyBtn.disabled = false; + } + }); let term: Terminal | null = null; let fitAddon: FitAddon | null = null; @@ -490,7 +543,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, ...(aiTermBtn ? [aiTermBtn] : []), exportPlainBtn, exportAnsiBtn, closeTabBtn), + el('div', { class: 'row' }, fontMinusBtn, fontPlusBtn, fitBtn, snippetsBtn, ...(aiTermBtn ? [aiTermBtn] : []), reconnectPtyBtn, exportPlainBtn, exportAnsiBtn, exportCastBtn, closeTabBtn), ), el('div', { class: 'term-shell' }, termContainer, touchBar), ), @@ -630,6 +683,14 @@ export async function renderTerminalView( typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; ro?.observe(termContainer); + const themeObs = + typeof MutationObserver !== 'undefined' + ? new MutationObserver(() => { + if (term) term.options.theme = readXtermTheme(); + }) + : null; + themeObs?.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => { if (!term || !termContainer.isConnected) return; if (frame.type === 'pty:output' && frame.sessionId === current.sessionId) { @@ -638,6 +699,8 @@ export async function renderTerminalView( } term.write(frame.data); } else if (frame.type === 'pty:exit' && frame.sessionId === current.sessionId) { + current.exited = true; + reconnectPtyBtn.hidden = false; term.writeln(`\r\n[Session exited with code ${String(frame.exitCode)}]`); } else if (frame.type === 'error' && frame.code === 'SAFE_MODE_ACTIVE') { msgEl.className = 'form-msg warn-text'; @@ -645,9 +708,17 @@ export async function renderTerminalView( } }); - currentCleanup = () => { + const unsubChannel = wsClient.subscribe([`pty:${current.sessionId}`]); + + let cleaned = false; + const disposeTerminalView = () => { + if (cleaned) return; + cleaned = true; + currentCleanup = null; if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); + unsubChannel(); unsubFrame(); + themeObs?.disconnect(); ro?.disconnect(); window.removeEventListener('resize', scheduleFit); window.visualViewport?.removeEventListener('resize', scheduleFit); @@ -657,7 +728,9 @@ export async function renderTerminalView( term?.dispose(); }; - wsClient.subscribe([`pty:${current.sessionId}`]); + currentCleanup = disposeTerminalView; + registerViewCleanup(disposeTerminalView); + wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, From f7d2abe3de56a2a4af5f82a59ba45d8040fb58f3 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:19:15 +0000 Subject: [PATCH 16/19] feat(client): upgrade SFTP manager & Tunnels/Proxy panel for v1.1 --- src/client/ts/views/sftp-view.ts | 257 +++++++++++++++++++++++++-- src/client/ts/views/tunnels-panel.ts | 211 ++++++++++++++++++---- 2 files changed, 414 insertions(+), 54 deletions(-) diff --git a/src/client/ts/views/sftp-view.ts b/src/client/ts/views/sftp-view.ts index 3359bf3..585203d 100644 --- a/src/client/ts/views/sftp-view.ts +++ b/src/client/ts/views/sftp-view.ts @@ -1,7 +1,15 @@ -import { computeLineDiff } from '../../../shared/diff.js'; +import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js'; import { apiFetch, apiUploadBinary } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + registerViewCleanup, + type ClientState, + type ServerEntry, +} from '../state.js'; +import { showToast } from '../toast.js'; import { renderTunnelsPanel } from './tunnels-panel.js'; interface SftpEntry { @@ -12,6 +20,9 @@ interface SftpEntry { mode: number; permissionsOctal: string; mtimeMs: number; + uid?: number; + gid?: number; + symlinkTarget?: string; } interface SftpTextPayload { @@ -27,6 +38,8 @@ let currentServerId = ''; let currentPath = ''; let activeEdit: SftpTextPayload | null = null; let activeEditSudo = false; +let searchMatches: string[] | null = null; +let lastSearchQuery = ''; function fmtFileSize(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`; @@ -42,16 +55,35 @@ function showSftpDiffDialog( onConfirm: (force: boolean) => Promise, ): void { const diff = computeLineDiff(originalText, nextText, 'remote', 'edited'); + const collapsed = diff.collapsedLines ?? collapseDiffHunks(diff.lines); + const hasHunk = collapsed.some((e) => e.type === 'hunk'); + let expanded = !hasHunk; + const dialog = document.createElement('dialog'); dialog.className = 'dialog-wide'; dialog.setAttribute('aria-labelledby', 'sftp-diff-title'); const pre = el('pre', { class: 'diff-body mono' }); - for (const line of diff.lines) { - const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; - const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' '; - pre.append(el('div', { class: cls }, `${prefix}${line.text}`)); - } + const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff'); + const renderDiffBody = () => { + pre.replaceChildren(); + const src = expanded ? diff.lines : collapsed; + for (const entry of src) { + if (entry.type === 'hunk') { + pre.append(el('div', { class: 'diff-hunk-sep' }, entry.text)); + } else { + const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : ''; + const prefix = entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '; + pre.append(el('div', { class: cls }, `${prefix}${entry.text}`)); + } + } + toggleDiffBtn.textContent = expanded ? 'Collapse Context' : 'Expand Full Diff'; + }; + toggleDiffBtn.addEventListener('click', () => { + expanded = !expanded; + renderDiffBody(); + }); + renderDiffBody(); const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); const forceWrap = el('div', { hidden: true }); @@ -83,7 +115,7 @@ function showSftpDiffDialog( dialog.append( el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn), - el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), + el('div', { class: 'row-between' }, el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), toggleDiffBtn), pre, errEl, el('div', { class: 'dialog-actions' }, forceWrap, writeBtn), @@ -138,9 +170,13 @@ export async function renderSftpView( return; } - if (q.server && servers.some((s) => s.config.id === q.server)) { - if (currentServerId !== q.server) currentPath = ''; - currentServerId = q.server; + const targetServer = q.server ?? q.serverId; + if (targetServer && servers.some((s) => s.config.id === targetServer)) { + if (currentServerId !== targetServer) { + currentPath = ''; + searchMatches = null; + } + currentServerId = targetServer; } else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) { currentServerId = servers[0]!.config.id; } @@ -185,6 +221,7 @@ export async function renderSftpView( const goPath = (nextPath: string) => { currentPath = nextPath; activeEdit = null; + searchMatches = null; void renderSftpView(root, state); }; goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~')); @@ -199,6 +236,7 @@ export async function renderSftpView( refreshBtn.addEventListener('click', () => void renderSftpView(root, state)); const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder'); + const touchBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ File'); const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' }); const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files'); uploadBtn.addEventListener('click', () => uploadInput.click()); @@ -257,6 +295,63 @@ export async function renderSftpView( } }); + touchBtn.addEventListener('click', async () => { + const name = window.prompt('New empty file name:'); + if (!name || !name.trim()) return; + const target = currentPath === '/' ? `/${name.trim()}` : `${currentPath}/${name.trim()}`; + try { + await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/touch`, { + method: 'POST', + body: { path: target }, + }); + showToast(`Created ${target}`, 'ok'); + await renderSftpView(root, state); + } catch (err) { + statusMsg.className = 'form-msg err-text'; + statusMsg.textContent = extractErrorMessage(err); + } + }); + + const searchInput = el('input', { + type: 'search', + class: 'input-sm', + value: lastSearchQuery, + placeholder: 'Search files recursively (e.g. *.conf)...', + 'aria-label': 'Search remote files', + }) as HTMLInputElement; + const searchBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Search'); + const clearSearchBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: searchMatches === null }, 'Clear Search'); + + const runSearch = async () => { + const qStr = searchInput.value.trim(); + if (!qStr) return; + lastSearchQuery = qStr; + statusMsg.className = 'form-msg muted'; + statusMsg.textContent = `Searching ${currentPath || '/'} for "${qStr}"...`; + try { + const sRes = await apiFetch<{ basePath: string; matches: string[] }>( + `/api/servers/${encodeURIComponent(currentServerId)}/sftp/search?path=${encodeURIComponent(currentPath || '/')}&q=${encodeURIComponent(qStr)}&max=100`, + ); + searchMatches = sRes.matches; + await renderSftpView(root, state); + } catch (err) { + statusMsg.className = 'form-msg err-text'; + statusMsg.textContent = extractErrorMessage(err); + } + }; + searchBtn.addEventListener('click', () => void runSearch()); + searchInput.addEventListener('keydown', (ev) => { + if (ev.key === 'Enter') { + ev.preventDefault(); + void runSearch(); + } + }); + clearSearchBtn.addEventListener('click', () => { + searchMatches = null; + lastSearchQuery = ''; + void renderSftpView(root, state); + }); + const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`; const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`; const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`; @@ -292,13 +387,46 @@ export async function renderSftpView( el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'), el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'), mkdirBtn, + touchBtn, uploadBtn, uploadInput, ), + el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn), statusMsg, ); root.append(topPanel); + if (searchMatches !== null) { + const sBox = el('section', { class: 'panel stack' }); + sBox.append(el('strong', {}, `Search Results for "${lastSearchQuery}" (${searchMatches.length})`)); + if (searchMatches.length === 0) { + sBox.append(el('p', { class: 'muted' }, 'No matching files or directories found (max depth 5).')); + } else { + for (const m of searchMatches) { + const openEd = el('button', { type: 'button', class: 'btn btn-sm' }, 'Edit'); + openEd.addEventListener('click', async () => { + try { + const loaded = await apiFetch<{ file: SftpTextPayload }>( + `/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(m)}&sudo=0`, + ); + activeEditSudo = false; + activeEdit = loaded.file; + await renderSftpView(root, state); + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }); + const jumpDir = el('button', { type: 'button', class: 'btn btn-sm' }, 'Open Dir'); + jumpDir.addEventListener('click', () => { + const idx = m.lastIndexOf('/'); + goPath(idx > 0 ? m.slice(0, idx) : '/'); + }); + sBox.append(el('div', { class: 'row-between' }, el('span', { class: 'mono' }, m), el('div', { class: 'row' }, openEd, jumpDir))); + } + } + root.append(sBox); + } + // Inline Editor with Pre-Save Diff if (activeEdit) { const editBox = el('section', { class: 'panel' }); @@ -320,8 +448,7 @@ export async function renderSftpView( } }); - const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save'); - saveBtn.addEventListener('click', () => { + const triggerSaveDiff = () => { if (!activeEdit) return; showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => { const res = await apiFetch<{ path: string; sha256: string; size: number }>( @@ -340,8 +467,18 @@ export async function renderSftpView( activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size }; statusMsg.className = 'form-msg ok-text'; statusMsg.textContent = `Saved ${res.path} (${res.size} B)`; + showToast(`Saved ${res.path}`, 'ok'); }); - }); + }; + + const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save'); + saveBtn.addEventListener('click', triggerSaveDiff); + + const onCtrlS = () => { + if (textarea.isConnected && !state.safeMode) triggerSaveDiff(); + }; + window.addEventListener('gcoord:save', onCtrlS); + registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS)); const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor'); closeEdBtn.addEventListener('click', () => { @@ -379,6 +516,42 @@ export async function renderSftpView( } }); + const selectedPaths = new Set(); + const bulkDelBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action', disabled: true }, + 'Delete Selected (0)', + ); + const updateBulkBtn = () => { + bulkDelBtn.textContent = `Delete Selected (${selectedPaths.size})`; + bulkDelBtn.disabled = selectedPaths.size === 0; + }; + bulkDelBtn.addEventListener('click', async () => { + if (selectedPaths.size === 0) return; + const ok = await confirmDialog( + 'dialog-confirm', + `Bulk delete ${selectedPaths.size} selected item(s)? Directories will be deleted recursively.`, + ); + if (!ok) return; + try { + const bRes = await apiFetch<{ deleted: string[]; failed: Array<{ path: string; error: string }> }>( + `/api/servers/${encodeURIComponent(currentServerId)}/sftp/bulk-delete`, + { + method: 'POST', + body: { paths: [...selectedPaths], recursive: true }, + }, + ); + showToast( + `Bulk delete: ${bRes.deleted.length} removed${bRes.failed.length ? `, ${bRes.failed.length} failed` : ''}.`, + bRes.failed.length ? 'warn' : 'ok', + ); + await renderSftpView(root, state); + } catch (err) { + statusMsg.className = 'form-msg err-text'; + statusMsg.textContent = extractErrorMessage(err); + } + }); + const tbl = el('table'); tbl.append( el( @@ -387,10 +560,11 @@ export async function renderSftpView( el( 'tr', {}, + el('th', {}, 'Sel'), el('th', {}, 'Name'), el('th', {}, 'Type'), el('th', {}, 'Size'), - el('th', {}, 'Mode'), + el('th', {}, 'Mode / Owner'), el('th', {}, 'Modified'), el('th', {}, 'Actions'), ), @@ -401,15 +575,30 @@ export async function renderSftpView( if (listing.parentPath) { const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)'); upBtn.addEventListener('click', () => goPath(listing!.parentPath!)); - tbody.append(el('tr', {}, el('td', { colspan: 6 }, upBtn))); + tbody.append(el('tr', {}, el('td', { colspan: 7 }, upBtn))); } for (const entry of listing.entries) { + const selChk = el('input', { type: 'checkbox', 'aria-label': `Select ${entry.name}` }) as HTMLInputElement; + selChk.addEventListener('change', () => { + if (selChk.checked) selectedPaths.add(entry.path); + else selectedPaths.delete(entry.path); + updateBulkBtn(); + }); + const nameCell = el('td', {}); if (entry.type === 'dir') { const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`); openBtn.addEventListener('click', () => goPath(entry.path)); nameCell.append(openBtn); + } else if (entry.type === 'symlink') { + nameCell.append( + el('span', { class: 'badge' }, 'LNK'), + el('span', { class: 'mono', style: 'margin-left:6px' }, entry.name), + entry.symlinkTarget + ? el('div', { class: 'mono muted' }, `-> ${entry.symlinkTarget}`) + : '', + ); } else { nameCell.append(el('span', { class: 'mono' }, entry.name)); } @@ -466,6 +655,32 @@ export async function renderSftpView( await renderSftpView(root, state); }); + const chownBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Chown'); + chownBtn.addEventListener('click', async () => { + const curOwner = `${entry.uid ?? 0}:${entry.gid ?? 0}`; + const rawOwner = window.prompt('Owner UID:GID (numeric, e.g. 1000:1000):', curOwner); + if (!rawOwner) return; + const parts = rawOwner.trim().split(':'); + const uid = Number(parts[0]); + const gid = Number(parts[1] ?? parts[0]); + if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) { + showToast('Invalid UID:GID numbers.', 'err'); + return; + } + const useSudo = window.confirm('Use sudo chown (requires step-up)? Cancel = normal chown.'); + try { + await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/chown`, { + method: 'POST', + body: { path: entry.path, uid, gid, sudo: useSudo }, + }); + showToast(`Changed owner of ${entry.name} to ${uid}:${gid}`, 'ok'); + await renderSftpView(root, state); + } catch (err) { + statusMsg.className = 'form-msg err-text'; + statusMsg.textContent = extractErrorMessage(err); + } + }); + const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); delBtn.addEventListener('click', async () => { const ok = await confirmDialog( @@ -482,16 +697,20 @@ export async function renderSftpView( await renderSftpView(root, state); }); - actionsRow.append(renBtn, chmodBtn, delBtn); + actionsRow.append(renBtn, chmodBtn, chownBtn, delBtn); + + const ownerText = + entry.uid !== undefined && entry.gid !== undefined ? ` (${entry.uid}:${entry.gid})` : ''; tbody.append( el( 'tr', {}, + el('td', {}, selChk), nameCell, el('td', { class: 'mono' }, entry.type), el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)), - el('td', { class: 'mono' }, entry.permissionsOctal), + el('td', { class: 'mono' }, `${entry.permissionsOctal}${ownerText}`), el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)), el('td', {}, actionsRow), ), @@ -500,7 +719,7 @@ export async function renderSftpView( tbl.append(tbody); dropPanel.append( - el('div', { class: 'muted', style: 'margin-bottom:6px' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), + el('div', { class: 'row-between', style: 'margin-bottom:6px' }, el('span', { class: 'muted' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), bulkDelBtn), el('div', { class: 'table-wrap' }, tbl), ); root.append(dropPanel); diff --git a/src/client/ts/views/tunnels-panel.ts b/src/client/ts/views/tunnels-panel.ts index c748242..4c4a40a 100644 --- a/src/client/ts/views/tunnels-panel.ts +++ b/src/client/ts/views/tunnels-panel.ts @@ -1,6 +1,13 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; -import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js'; +import { + el, + extractErrorMessage, + fmtTime, + registerViewCleanup, + type ServerEntry, +} from '../state.js'; +import { showToast } from '../toast.js'; export interface TunnelViewEntry { key: string; @@ -8,11 +15,15 @@ export interface TunnelViewEntry { tunnel: { id: string; name: string; - mode: 'http-proxy' | 'local-tcp' | 'remote-tcp'; + mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; bindHost?: string; bindPort?: number; targetHost: string; targetPort: number; + targetProtocol?: 'http' | 'https'; + tlsRejectUnauthorized?: boolean; + tlsServerName?: string; + ttlSec?: number; autoStart: boolean; }; active: boolean; @@ -20,6 +31,7 @@ export interface TunnelViewEntry { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; + expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -28,6 +40,13 @@ export interface TunnelViewEntry { lastError?: string; } +function fmtRemainingSec(sec: number): string { + const s = Math.max(0, Math.floor(sec)); + const m = Math.floor(s / 60); + const rem = s % 60; + return m > 0 ? `${m}m ${rem}s` : `${rem}s`; +} + function fmtBytes(bytes: number): string { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (bytes < 1024) return `${bytes} B`; @@ -90,24 +109,71 @@ export async function renderTunnelsPanel( ), ); const tbody = el('tbody'); + const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = []; for (const item of tunnels) { - const bindInfo = item.proxyPath - ? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath) - : item.tunnel.mode === 'remote-tcp' - ? el( - 'span', - { class: 'mono' }, - item.active && item.remoteBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, - ) - : el( - 'span', - { class: 'mono' }, - item.active && item.localBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + let bindInfo: HTMLElement; + if (item.tunnel.mode === 'http-proxy' && item.active) { + const launchBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-primary' }, + 'Open Isolated Proxy', + ); + launchBtn.addEventListener('click', async () => { + launchBtn.disabled = true; + try { + const ticketRes = await apiFetch<{ + launchUrl: string; + mode: 'subdomain' | 'port' | 'same-origin'; + expiresInSec: number; + }>( + `/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/proxy-ticket`, + { method: 'POST', body: {} }, ); + if (ticketRes.mode === 'same-origin') { + showToast( + 'Launched via same-origin fallback proxy (isolated subdomain/port offers stronger cookie isolation).', + 'warn', + ); + } + window.open(ticketRes.launchUrl, '_blank', 'noopener,noreferrer'); + } catch (err) { + const msg = extractErrorMessage(err); + statusMsg.className = 'form-msg err-text'; + statusMsg.textContent = msg; + showToast(msg, 'err'); + } finally { + launchBtn.disabled = false; + } + }); + bindInfo = el( + 'div', + { class: 'stack' }, + launchBtn, + el( + 'span', + { class: 'mono muted' }, + `${item.tunnel.targetProtocol ?? 'http'}:// via ticket`, + ), + ); + } else if (item.tunnel.mode === 'http-proxy') { + bindInfo = el('span', { class: 'muted mono' }, 'proxy (inactive)'); + } else if (item.tunnel.mode === 'remote-tcp') { + bindInfo = el( + 'span', + { class: 'mono' }, + item.active && item.remoteBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + ); + } else { + bindInfo = el( + 'span', + { class: 'mono' }, + item.active && item.localBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + ); + } const toggleBtn = el( 'button', @@ -154,6 +220,15 @@ export async function renderTunnelsPanel( } }); + let ttlBadge: HTMLElement | string = ''; + if (item.active && item.expiresAt) { + const b = el('div', { class: 'badge badge-warn' }, `TTL: ${fmtRemainingSec((item.expiresAt - Date.now()) / 1000)}`); + countdownEls.push({ el: b, expiresAt: item.expiresAt }); + ttlBadge = b; + } else if (item.tunnel.ttlSec) { + ttlBadge = el('div', { class: 'muted' }, `TTL: ${item.tunnel.ttlSec}s`); + } + tbody.append( el( 'tr', @@ -169,9 +244,16 @@ export async function renderTunnelsPanel( {}, el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()), item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '', + ttlBadge, ), el('td', {}, bindInfo), - el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`), + el( + 'td', + { class: 'mono' }, + item.tunnel.mode === 'socks5' + ? 'Dynamic SOCKS5' + : `${item.tunnel.targetProtocol ? `${item.tunnel.targetProtocol}://` : ''}${item.tunnel.targetHost}:${item.tunnel.targetPort}`, + ), el( 'td', { class: 'mono' }, @@ -185,6 +267,17 @@ export async function renderTunnelsPanel( } tbl.append(tbody); listPanel.append(el('div', { class: 'table-wrap' }, tbl)); + + if (countdownEls.length > 0) { + const ttlTimer = window.setInterval(() => { + const now = Date.now(); + for (const row of countdownEls) { + const remSec = Math.max(0, Math.floor((row.expiresAt - now) / 1000)); + row.el.textContent = `TTL: ${fmtRemainingSec(remSec)}`; + } + }, 1000); + registerViewCleanup(() => window.clearInterval(ttlTimer)); + } } // Add Tunnel Form @@ -194,7 +287,7 @@ export async function renderTunnelsPanel( el( 'p', { class: 'muted' }, - 'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy//.', + 'http-proxy serves via short-lived proxy tickets in isolated origin mode (subdomain/port) or same-origin fallback when enabled. socks5 provides dynamic local forwarding without targetPort.', ), ); @@ -213,31 +306,67 @@ export async function renderTunnelsPanel( const modeSel = el( 'select', { name: 'mode' }, - el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy//)'), + el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'), el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'), el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'), - ); - const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }); + el('option', { value: 'socks5' }, 'socks5 (Dynamic Local SOCKS5 Proxy)'), + ) as HTMLSelectElement; + const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement; const targetPortInput = el('input', { name: 'targetPort', type: 'number', - min: 1, + min: 0, max: 65535, value: '3000', required: true, - }); - const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' }); + }) as HTMLInputElement; + const protoSel = el( + 'select', + { name: 'targetProtocol' }, + el('option', { value: 'http' }, 'http'), + el('option', { value: 'https' }, 'https'), + ) as HTMLSelectElement; + const tlsVerifyChk = el('input', { type: 'checkbox', name: 'tlsRejectUnauthorized', checked: true }) as HTMLInputElement; + const tlsSniInput = el('input', { name: 'tlsServerName', placeholder: 'optional TLS SNI host' }) as HTMLInputElement; + const ttlSecInput = el('input', { + name: 'ttlSec', + type: 'number', + min: 60, + max: 86400, + placeholder: 'optional auto-expire (60-86400s)', + }) as HTMLInputElement; + const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp/socks5)' }) as HTMLInputElement; const bindPortInput = el('input', { name: 'bindPort', type: 'number', min: 1, max: 65535, - placeholder: 'auto (tcp modes)', - }); - const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }); - const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }); + placeholder: 'auto (tcp/socks5)', + }) as HTMLInputElement; + const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement; + const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement; const formMsg = el('p', { class: 'form-msg' }); + const targetPortWrap = el('div', {}, el('label', {}, 'Target Port'), targetPortInput); + const httpTlsWrap = el( + 'div', + { class: 'grid-3' }, + el('div', {}, el('label', {}, 'Upstream Protocol'), protoSel), + el('div', {}, el('label', {}, 'TLS SNI ServerName (HTTPS)'), tlsSniInput), + el('div', { style: 'padding-top:22px' }, el('label', { class: 'chk-row' }, tlsVerifyChk, 'Verify upstream TLS cert')), + ); + + const syncModeFields = () => { + const m = modeSel.value; + targetPortWrap.hidden = m === 'socks5'; + targetPortInput.required = m !== 'socks5'; + if (m === 'socks5') targetPortInput.value = '0'; + else if (targetPortInput.value === '0') targetPortInput.value = '3000'; + httpTlsWrap.hidden = m !== 'http-proxy'; + }; + modeSel.addEventListener('change', syncModeFields); + syncModeFields(); + form.append( el( 'div', @@ -247,10 +376,12 @@ export async function renderTunnelsPanel( el('div', {}, el('label', {}, 'Display Name'), nameInput), el('div', {}, el('label', {}, 'Mode'), modeSel), el('div', {}, el('label', {}, 'Target Host'), targetHostInput), - el('div', {}, el('label', {}, 'Target Port'), targetPortInput), - el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput), - el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput), + targetPortWrap, + el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput), + el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput), + el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput), ), + httpTlsWrap, el( 'div', { class: 'row' }, @@ -271,10 +402,12 @@ export async function renderTunnelsPanel( return; } - const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp'; + const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; const bindHost = bindHostInput.value.trim() || undefined; const bindPortVal = bindPortInput.value.trim(); const bindPort = bindPortVal ? Number(bindPortVal) : undefined; + const ttlVal = ttlSecInput.value.trim(); + const ttlSec = ttlVal ? Number(ttlVal) : undefined; try { const res = await apiFetch<{ startError?: string }>('/api/tunnels', { @@ -286,7 +419,13 @@ export async function renderTunnelsPanel( name: nameInput.value.trim(), mode, targetHost: targetHostInput.value.trim() || '127.0.0.1', - targetPort: Number(targetPortInput.value), + targetPort: mode === 'socks5' ? 0 : Number(targetPortInput.value), + targetProtocol: mode === 'http-proxy' ? protoSel.value : 'http', + tlsRejectUnauthorized: mode === 'http-proxy' ? tlsVerifyChk.checked : true, + ...(mode === 'http-proxy' && tlsSniInput.value.trim() + ? { tlsServerName: tlsSniInput.value.trim() } + : {}), + ...(ttlSec !== undefined ? { ttlSec } : {}), bindHost: mode === 'http-proxy' ? undefined : bindHost, bindPort: mode === 'http-proxy' ? undefined : bindPort, autoStart: autoStartChk.checked, @@ -297,6 +436,8 @@ export async function renderTunnelsPanel( if (res.startError) { statusMsg.className = 'form-msg warn-text'; statusMsg.textContent = `Saved, but start failed: ${res.startError}`; + } else { + showToast('Tunnel saved.', 'ok'); } await renderTunnelsPanel(root, fixedServerId); } catch (err) { From f45d128c4fd16a8d94a337d76d699ac9eda3eea7 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:23:31 +0000 Subject: [PATCH 17/19] feat(client): upgrade Systems, Workflows, Alerts, Vault, Config, Auth & Settings views for v1.1 --- src/client/ts/state.ts | 4 + src/client/ts/views/alerts-view.ts | 29 +- src/client/ts/views/auth-view.ts | 35 ++- src/client/ts/views/config-view.ts | 54 +++- src/client/ts/views/settings-ops-panel.ts | 360 ++++++++++++++++++++++ src/client/ts/views/settings-view.ts | 98 +++--- src/client/ts/views/systems-view.ts | 151 +++++++-- src/client/ts/views/vault-view.ts | 70 ++++- src/client/ts/views/workflows-view.ts | 226 ++++++++++++-- 9 files changed, 895 insertions(+), 132 deletions(-) create mode 100644 src/client/ts/views/settings-ops-panel.ts diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index 48c2183..b8455d4 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -79,6 +79,10 @@ export interface ClientSecuritySettings { elevateOnLogin: boolean; keepElevationOnSafeMode: boolean; enableEmergencySecretsBackup: boolean; + allowSameOriginProxy?: boolean; + egressAllowedCidrs?: string[]; + sessionTtlHours?: number; + sessionIdleTimeoutMin?: number; } export interface ClientAuthRequirements { diff --git a/src/client/ts/views/alerts-view.ts b/src/client/ts/views/alerts-view.ts index 9014748..240bca9 100644 --- a/src/client/ts/views/alerts-view.ts +++ b/src/client/ts/views/alerts-view.ts @@ -23,7 +23,7 @@ interface AlertChannelItem { interface AlertRuleItem { id: string; name: string; - kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system'; + kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event'; severity: 'warn' | 'critical'; target: { serverId?: string; tags?: string[]; all?: boolean }; forConsecutivePolls: number; @@ -40,6 +40,7 @@ interface AlertRuleItem { probeId?: string; systemId?: string; item?: string; + events?: string[]; } interface MaintenanceWindowItem { @@ -330,11 +331,12 @@ export async function renderAlertsView( 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) { + const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret'); + for (const cr of webhookCreds) { 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)')); + if (webhookCreds.length === 0) { + chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)')); } const chForm = el( 'form', @@ -385,7 +387,9 @@ export async function renderAlertsView( ? `offline >= ${r.offlineSec}s` : r.kind === 'probe' ? `probe ${r.probeId ?? '*'}` - : `system ${r.systemId}/${r.item ?? '*'}`; + : r.kind === 'security-event' + ? `security-event [${r.events?.join(', ') ?? ''}]` + : `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({ @@ -404,9 +408,9 @@ export async function renderAlertsView( 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 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'), el('option', { value: 'security-event' }, 'security-event')); 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 ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system or events csv (auth.lockout,ssh.host_key_mismatch,vault.panic_lock)' }); 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)' }); @@ -443,6 +447,17 @@ export async function renderAlertsView( 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 if (ruleKind.value === 'security-event') { + const events = ruleParam1.value + .split(',') + .map((e) => e.trim()) + .filter(Boolean); + nextRule = { + ...base, + kind: 'security-event', + forConsecutivePolls: 1, + events: events.length > 0 ? events : ['auth.lockout', 'ssh.host_key_mismatch', 'vault.panic_lock'], + }; } else { nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) }; } diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index 6dab298..fd1c305 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -87,16 +87,36 @@ export async function renderAuthView( placeholder: '6-digit code from authenticator', required: true, }); + const bootTokInput = el('input', { + id: 'boot-token', + name: 'bootstrapToken', + type: 'password', + autocomplete: 'off', + placeholder: 'GCOORD_BOOTSTRAP_TOKEN (auto-filled unless operator-only)', + }) as HTMLInputElement; let secretBase32 = ''; - let bootstrapToken = ''; try { const data = await apiFetch('/api/auth/bootstrap'); secretBase32 = data.secretBase32; - bootstrapToken = data.bootstrapToken ?? ''; - const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); - if (doc.documentElement.nodeName === 'svg') { - qrContainer.append(document.importNode(doc.documentElement, true)); + bootTokInput.value = data.bootstrapToken ?? ''; + if ( + typeof data.qrDataUri === 'string' && + /^data:image\/(?:png|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(data.qrDataUri) + ) { + const img = el('img', { + src: data.qrDataUri, + alt: 'TOTP Enrollment QR Code', + width: 200, + height: 200, + style: 'background:#fff;padding:6px;display:block', + }); + qrContainer.append(img); + } else { + const doc = new DOMParser().parseFromString(data.qrSvg, 'image/svg+xml'); + if (doc.documentElement.nodeName === 'svg') { + qrContainer.append(document.importNode(doc.documentElement, true)); + } } secretLine.textContent = `Secret: ${data.secretBase32}`; } catch (err) { @@ -119,6 +139,8 @@ export async function renderAuthView( el('div', { class: 'stack' }, el('label', {}, 'Scan TOTP QR Code'), qrContainer, secretLine), el('label', { for: 'boot-totp' }, 'Verify 6-Digit TOTP Code'), codeInput, + el('label', { for: 'boot-token' }, 'Bootstrap Token (if GCOORD_BOOTSTRAP_TOKEN is enforced)'), + bootTokInput, statusMsg, submitBtn, ); @@ -128,6 +150,7 @@ export async function renderAuthView( statusMsg.textContent = ''; submitBtn.disabled = true; try { + const tok = bootTokInput.value.trim(); const res = await apiFetch<{ csrfToken: string; recoveryCodes: string[]; @@ -138,7 +161,7 @@ export async function renderAuthView( password: passInput.value, totpCode: codeInput.value.trim(), secretBase32, - ...(bootstrapToken ? { bootstrapToken } : {}), + ...(tok ? { bootstrapToken: tok } : {}), initialSafeMode, securityPreset: presetSelect.value, }, diff --git a/src/client/ts/views/config-view.ts b/src/client/ts/views/config-view.ts index 6bc070f..2f440df 100644 --- a/src/client/ts/views/config-view.ts +++ b/src/client/ts/views/config-view.ts @@ -1,3 +1,4 @@ +import { collapseDiffHunks, computeLineDiff, type CollapsedDiffEntry } from '../../../shared/diff.js'; import { apiFetch, type ApiError } from '../api.js'; import { confirmDialog, openDiffModal } from '../dialogs.js'; import { @@ -5,9 +6,11 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ConfigOverview, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; interface FileDetails { @@ -236,18 +239,14 @@ export async function renderConfigView( } }); - const saveBtn = el( - 'button', - { type: 'button', class: 'btn btn-primary mutating-action' }, - 'Save Config', - ); - saveBtn.addEventListener('click', async () => { + const saveFile = async () => { msgEl.replaceChildren(); try { await apiFetch('/api/config/file', { method: 'PUT', body: { path: details.filePath, content: editor.value }, }); + showToast(`Saved ${details.filePath}.`, 'ok'); await onReloadOverview(); } catch (err) { const apiErr = err as ApiError; @@ -256,9 +255,44 @@ export async function renderConfigView( msgEl.append(el('div', { class: 'mono err-text' }, ` ${issue.path}: ${issue.message}`)); } } + }; + + const previewBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Preview Changes'); + previewBtn.addEventListener('click', () => { + const diff = computeLineDiff(details.rawContent, editor.value, 'saved', 'draft'); + const hunks = diff.collapsedLines ?? collapseDiffHunks(diff.lines); + msgEl.replaceChildren( + el('div', { class: 'mono muted' }, `+${diff.additions} / -${diff.deletions}`), + el( + 'pre', + { class: 'diff-body mono', style: 'max-height:220px' }, + ...hunks.map((entry) => + entry.type === 'hunk' + ? el('div', { class: 'diff-hunk-sep' }, entry.text) + : el( + 'div', + { class: entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '' }, + `${entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' '} ${entry.text}`, + ), + ), + ), + ); }); - const actionRow = el('div', { class: 'row' }, fmtBtn, saveBtn); + const saveBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary mutating-action' }, + 'Save Config', + ); + saveBtn.addEventListener('click', () => void saveFile()); + + const onCtrlS = () => { + if (editor.isConnected && !state.safeMode) void saveFile(); + }; + window.addEventListener('gcoord:save', onCtrlS); + registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS)); + + const actionRow = el('div', { class: 'row' }, fmtBtn, previewBtn, saveBtn); if (isAiEnabled(state)) { const aiBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Assist]'); aiBtn.addEventListener('click', async () => { @@ -336,7 +370,10 @@ export async function renderConfigView( diffBtn.addEventListener('click', async () => { const res = await apiFetch<{ revision: { id: number; filePath: string; source: string; createdAt: number }; - diff: { lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }> }; + diff: { + lines: Array<{ type: 'equal' | 'add' | 'del'; text: string }>; + collapsedLines?: CollapsedDiffEntry[]; + }; }>(`/api/config/revisions/${rev.id}/diff`); openDiffModal({ revisionId: res.revision.id, @@ -344,6 +381,7 @@ export async function renderConfigView( source: res.revision.source, createdAt: res.revision.createdAt, lines: res.diff.lines, + collapsedLines: res.diff.collapsedLines, onRollback: async () => { await apiFetch(`/api/config/revisions/${rev.id}/rollback`, { method: 'POST' }); await onReloadOverview(); diff --git a/src/client/ts/views/settings-ops-panel.ts b/src/client/ts/views/settings-ops-panel.ts new file mode 100644 index 0000000..34af14b --- /dev/null +++ b/src/client/ts/views/settings-ops-panel.ts @@ -0,0 +1,360 @@ +import { apiFetch } from '../api.js'; +import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { showToast } from '../toast.js'; + +interface AuditRow { + id: number; + ts: number; + action: string; + actor_ip: string; + target: string | null; + status: string; + details: string | null; +} + +interface BackupScheduleStatus { + enabled: boolean; + cron: string; + timezone: string; + destination: 'local' | 'sftp'; + running: boolean; + lastRunAt: number | null; + lastStatus: 'never' | 'ok' | 'error' | 'skipped'; + lastFilename: string | null; + lastError: string | null; + nextRunAt: number | null; + localFiles: Array<{ name: string; sizeBytes: number; mtimeMs: number }>; +} + +export async function renderSettingsOpsPanels( + host: HTMLElement, + state: ClientState, + creds: Array<{ id: string; name: string; type: string }>, + onReloadState: () => Promise, +): Promise { + const settingsObj = (state.overview?.settings ?? {}) as Record; + const runtimeCfg = (settingsObj.runtime ?? {}) as { throttleMode?: string }; + const metricsCfg = (settingsObj.metrics ?? {}) as { + prometheusEnabled?: boolean; + prometheusSecretRef?: string; + prometheusTokenHash?: string; + }; + const schedCfg = (settingsObj.scheduledBackup ?? {}) as { + enabled?: boolean; + cron?: string; + timezone?: string; + destination?: 'local' | 'sftp'; + localDir?: string; + remoteServerId?: string; + remotePath?: string; + retentionCount?: number; + passphraseSecretRef?: string; + }; + + // 1. Runtime Resource Profile & Prometheus /metrics + const opsGrid = el('div', { class: 'grid-2' }); + + const rtPanel = el('section', { class: 'panel panel-region' }); + rtPanel.append( + el('h2', {}, 'Runtime Throttle Profile'), + el( + 'p', + { class: 'muted' }, + 'Tune polling, log caps, and worker concurrency for constrained 1 vCPU / 1 GB RAM VPS vs larger servers.', + ), + ); + const modeSel = el( + 'select', + {}, + el('option', { value: 'low-resource', selected: (runtimeCfg.throttleMode ?? 'low-resource') === 'low-resource' }, 'low-resource (1 vCPU / 1 GB RAM — bounded polls & caches)'), + el('option', { value: 'balanced', selected: runtimeCfg.throttleMode === 'balanced' }, 'balanced (moderate parallelism & buffer caps)'), + el('option', { value: 'unthrottled', selected: runtimeCfg.throttleMode === 'unthrottled' }, 'unthrottled (high parallelism for multi-core hosts)'), + ) as HTMLSelectElement; + const rtMsg = el('p', { class: 'form-msg' }); + const saveRtBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Save Runtime Mode'); + saveRtBtn.addEventListener('click', async () => { + rtMsg.textContent = ''; + try { + const nextSettings = { + ...settingsObj, + runtime: { throttleMode: modeSel.value }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `runtime.throttleMode -> ${modeSel.value}`, + }, + }); + showToast(`Runtime profile set to ${modeSel.value}.`, 'ok'); + await onReloadState(); + } catch (err) { + rtMsg.className = 'form-msg err-text'; + rtMsg.textContent = extractErrorMessage(err); + } + }); + rtPanel.append(el('label', {}, 'Throttle Mode'), modeSel, el('div', { class: 'row', style: 'margin-top:8px' }, saveRtBtn), rtMsg); + + const promPanel = el('section', { class: 'panel panel-region' }); + promPanel.append( + el('h2', {}, 'Prometheus /metrics Endpoint'), + el( + 'p', + { class: 'muted' }, + 'Exposes fleet gauges on GET /metrics with Bearer token auth (either rotated token hash or Vault secret).', + ), + ); + const promChk = el('input', { type: 'checkbox', checked: metricsCfg.prometheusEnabled ? true : undefined }) as HTMLInputElement; + const promMsg = el('p', { class: 'form-msg' }); + const tokenBox = el('pre', { class: 'mono warn-text', hidden: true }); + const copyPromBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: true }, 'Copy Bearer Token'); + copyPromBtn.addEventListener('click', () => { + void navigator.clipboard?.writeText(tokenBox.textContent ?? ''); + copyPromBtn.textContent = 'Copied!'; + }); + + const savePromBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Metrics Setting'); + savePromBtn.addEventListener('click', async () => { + try { + const nextSettings = { + ...settingsObj, + metrics: { ...metricsCfg, prometheusEnabled: promChk.checked }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: `metrics.prometheusEnabled -> ${String(promChk.checked)}`, + }, + }); + showToast(`Prometheus /metrics ${promChk.checked ? 'enabled' : 'disabled'}.`, 'ok'); + await onReloadState(); + } catch (err) { + promMsg.className = 'form-msg err-text'; + promMsg.textContent = extractErrorMessage(err); + } + }); + + const rotPromBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Rotate Bearer Token'); + rotPromBtn.addEventListener('click', async () => { + try { + const r = await apiFetch<{ token: string; prometheusEnabled: boolean }>('/api/config/prometheus-token', { + method: 'POST', + body: { enable: true }, + }); + promChk.checked = r.prometheusEnabled; + tokenBox.hidden = false; + tokenBox.textContent = r.token; + copyPromBtn.hidden = false; + promMsg.className = 'form-msg ok-text'; + promMsg.textContent = 'New Bearer token generated (copy now — shown once):'; + showToast('Rotated Prometheus Bearer token.', 'ok'); + } catch (err) { + promMsg.className = 'form-msg err-text'; + promMsg.textContent = extractErrorMessage(err); + } + }); + + promPanel.append( + el('label', { class: 'chk-row' }, promChk, 'Enable GET /metrics endpoint'), + el( + 'div', + { class: 'mono muted', style: 'margin-top:4px' }, + metricsCfg.prometheusTokenHash + ? 'Auth status: Bearer token hash configured' + : metricsCfg.prometheusSecretRef + ? `Auth status: Vault ref ${metricsCfg.prometheusSecretRef}` + : 'Auth status: Rotate Bearer Token to enable authenticated scrapes', + ), + el('div', { class: 'row', style: 'margin-top:8px' }, savePromBtn, rotPromBtn), + promMsg, + tokenBox, + copyPromBtn, + ); + + opsGrid.append(rtPanel, promPanel); + host.append(opsGrid); + + // 2. Scheduled Encrypted Backups + const schedPanel = el('section', { class: 'panel panel-region' }); + const schedStatusRes = await apiFetch<{ schedule: BackupScheduleStatus }>('/api/backup/schedule').catch(() => null); + const st = schedStatusRes?.schedule; + schedPanel.append( + el('h2', {}, 'Scheduled .gcoord.enc Backups'), + el( + 'p', + { class: 'muted mono' }, + st + ? `Status: ${st.lastStatus.toUpperCase()} | Running: ${String(st.running)} | Local bundles: ${st.localFiles.length} | Next: ${fmtTime(st.nextRunAt)}${st.lastError ? ` | Err: ${st.lastError}` : ''}` + : 'Backup scheduler unavailable.', + ), + ); + + const sbEnChk = el('input', { type: 'checkbox', checked: schedCfg.enabled ? true : undefined }) as HTMLInputElement; + const sbCronInp = el('input', { value: schedCfg.cron ?? '0 3 * * *', placeholder: '0 3 * * *' }) as HTMLInputElement; + const sbTzInp = el('input', { value: schedCfg.timezone ?? 'UTC', placeholder: 'UTC' }) as HTMLInputElement; + const sbDestSel = el( + 'select', + {}, + el('option', { value: 'local', selected: (schedCfg.destination ?? 'local') === 'local' }, 'local'), + el('option', { value: 'sftp', selected: schedCfg.destination === 'sftp' }, 'sftp'), + ) as HTMLSelectElement; + const sbLocalDirInp = el('input', { value: schedCfg.localDir ?? 'backups', placeholder: 'backups' }) as HTMLInputElement; + const sbRetInp = el('input', { type: 'number', min: 1, max: 100, value: String(schedCfg.retentionCount ?? 7) }) as HTMLInputElement; + const sbSrvInp = el('input', { value: schedCfg.remoteServerId ?? '', placeholder: 'Remote Server ID (sftp)' }) as HTMLInputElement; + const sbPathInp = el('input', { value: schedCfg.remotePath ?? '', placeholder: '/var/backups/gcoord (sftp)' }) as HTMLInputElement; + const sbRefSel = el( + 'select', + {}, + el('option', { value: '' }, '(Use Vault Master Key)'), + ...creds.map((c) => el('option', { value: c.id, selected: schedCfg.passphraseSecretRef === c.id }, `${c.id} (${c.type})`)), + ) as HTMLSelectElement; + + const sbMsg = el('p', { class: 'form-msg' }); + const saveSbBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Save Schedule'); + saveSbBtn.addEventListener('click', async () => { + sbMsg.textContent = ''; + try { + const nextSettings = { + ...settingsObj, + scheduledBackup: { + enabled: sbEnChk.checked, + cron: sbCronInp.value.trim() || '0 3 * * *', + timezone: sbTzInp.value.trim() || 'UTC', + destination: sbDestSel.value as 'local' | 'sftp', + localDir: sbLocalDirInp.value.trim() || 'backups', + retentionCount: Number(sbRetInp.value || 7), + ...(sbSrvInp.value.trim() ? { remoteServerId: sbSrvInp.value.trim() } : {}), + ...(sbPathInp.value.trim() ? { remotePath: sbPathInp.value.trim() } : {}), + ...(sbRefSel.value ? { passphraseSecretRef: sbRefSel.value } : {}), + }, + }; + await apiFetch('/api/config/file', { + method: 'PUT', + body: { + path: 'settings.json', + content: `${JSON.stringify(nextSettings, null, 2)}\n`, + summary: 'Update scheduled backup configuration', + }, + }); + showToast('Scheduled backup config saved.', 'ok'); + await onReloadState(); + } catch (err) { + sbMsg.className = 'form-msg err-text'; + sbMsg.textContent = extractErrorMessage(err); + } + }); + + const runSbBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Run Backup Now'); + runSbBtn.addEventListener('click', async () => { + sbMsg.className = 'form-msg muted'; + sbMsg.textContent = 'Running scheduled backup...'; + try { + const r = await apiFetch<{ ok: boolean; filename?: string; error?: string }>('/api/backup/schedule/run', { + method: 'POST', + body: {}, + }); + sbMsg.className = r.ok ? 'form-msg ok-text' : 'form-msg err-text'; + sbMsg.textContent = r.ok ? `Backup created: ${r.filename ?? 'ok'}` : (r.error ?? 'Backup failed'); + showToast(sbMsg.textContent, r.ok ? 'ok' : 'err'); + } catch (err) { + sbMsg.className = 'form-msg err-text'; + sbMsg.textContent = extractErrorMessage(err); + } + }); + + schedPanel.append( + el('label', { class: 'chk-row' }, sbEnChk, 'Enable scheduled encrypted backups'), + el( + 'div', + { class: 'grid-3', style: 'margin-top:8px' }, + el('div', {}, el('label', {}, 'Cron'), sbCronInp), + el('div', {}, el('label', {}, 'Timezone'), sbTzInp), + el('div', {}, el('label', {}, 'Destination'), sbDestSel), + el('div', {}, el('label', {}, 'Local Dir (under data/)'), sbLocalDirInp), + el('div', {}, el('label', {}, 'Retention Count'), sbRetInp), + el('div', {}, el('label', {}, 'Passphrase Secret'), sbRefSel), + el('div', {}, el('label', {}, 'Remote Server (SFTP)'), sbSrvInp), + el('div', {}, el('label', {}, 'Remote Path (SFTP)'), sbPathInp), + ), + el('div', { class: 'row', style: 'margin-top:8px' }, saveSbBtn, runSbBtn), + sbMsg, + ); + host.append(schedPanel); + + // 3. Filterable & Exportable Audit Log + const auditPanel = el('section', { class: 'panel panel-region' }); + const initialAudit = await apiFetch<{ total: number; items: AuditRow[]; actions?: string[] }>('/api/audit?limit=40'); + + const actSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: '' }, 'All Actions'), + ...(initialAudit.actions ?? []).map((a) => el('option', { value: a }, a)), + ) as HTMLSelectElement; + const stSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: '' }, 'All Statuses'), + el('option', { value: 'ok' }, 'ok'), + el('option', { value: 'denied' }, 'denied'), + el('option', { value: 'error' }, 'error'), + ) as HTMLSelectElement; + const qInput = el('input', { type: 'search', class: 'input-sm', placeholder: 'Filter target/IP/details...' }) as HTMLInputElement; + const applyBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary' }, 'Filter'); + const exportCsvLink = el('a', { href: '/api/audit/export?format=csv', class: 'btn btn-sm', download: '' }, 'Export CSV'); + const exportNdLink = el('a', { href: '/api/audit/export?format=ndjson', class: 'btn btn-sm', download: '' }, 'Export NDJSON'); + const titleEl = el('h2', {}, `Security & Action Audit Log (${initialAudit.total} entries)`); + const aBody = el('tbody'); + + const buildAuditQuery = () => { + const p = new URLSearchParams(); + p.set('limit', '60'); + if (actSel.value) p.set('action', actSel.value); + if (stSel.value) p.set('status', stSel.value); + if (qInput.value.trim()) p.set('q', qInput.value.trim()); + return p.toString(); + }; + + const renderRows = (rows: AuditRow[], total: number) => { + titleEl.textContent = `Security & Action Audit Log (${total} matching)`; + const qStr = buildAuditQuery(); + exportCsvLink.setAttribute('href', `/api/audit/export?format=csv&${qStr}`); + exportNdLink.setAttribute('href', `/api/audit/export?format=ndjson&${qStr}`); + aBody.replaceChildren(); + for (const row of rows) { + aBody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, fmtTime(row.ts)), + el('td', { class: 'mono' }, row.action), + el('td', {}, el('span', { class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` }, row.status)), + el('td', { class: 'mono' }, row.target ?? '—'), + el('td', { class: 'mono' }, row.actor_ip), + el('td', { class: 'mono muted' }, row.details ?? '—'), + ), + ); + } + }; + renderRows(initialAudit.items, initialAudit.total); + + applyBtn.addEventListener('click', async () => { + const res = await apiFetch<{ total: number; items: AuditRow[] }>(`/api/audit?${buildAuditQuery()}`); + renderRows(res.items, res.total); + }); + + const aTable = el('table'); + aTable.append( + el('thead', {}, el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details'))), + aBody, + ); + auditPanel.append( + el('div', { class: 'row-between' }, titleEl, el('div', { class: 'row' }, exportCsvLink, exportNdLink)), + el('div', { class: 'row', style: 'margin:8px 0' }, actSel, stSel, qInput, applyBtn), + el('div', { class: 'table-wrap' }, aTable), + ); + host.append(auditPanel); +} diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index 2524ecc..55c942e 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -20,16 +20,6 @@ interface SessionRow { current: boolean; } -interface AuditRow { - id: number; - ts: number; - action: string; - actor_ip: string; - target: string | null; - status: string; - details: string | null; -} - interface FactorsData { passwords: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>; @@ -55,9 +45,8 @@ export async function renderSettingsView( ): Promise { root.replaceChildren(); - const [sessRes, auditRes, factorsRes, credsRes] = await Promise.all([ + const [sessRes, 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', @@ -198,12 +187,33 @@ export async function renderSettingsView( 'select', {}, el('option', { value: 'off', selected: sec.stepUpPolicy === 'off' ? true : undefined }, 'Off (never re-prompt)'), - el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session (7d)'), + el('option', { value: 'session', selected: sec.stepUpPolicy === 'session' ? true : undefined }, 'Once per login session'), el('option', { value: '24h', selected: sec.stepUpPolicy === '24h' ? true : undefined }, '24 hours'), - el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour (default)'), + el('option', { value: '1h', selected: sec.stepUpPolicy === '1h' ? true : undefined }, '1 hour'), + el('option', { value: '15m', selected: sec.stepUpPolicy === '15m' ? true : undefined }, '15 minutes (v1.1 default)'), el('option', { value: '5m', selected: sec.stepUpPolicy === '5m' ? true : undefined }, '5 minutes'), el('option', { value: 'every-action', selected: sec.stepUpPolicy === 'every-action' ? true : undefined }, 'Every sensitive action'), ); + const allowSameOriginProxyChk = el('input', { + type: 'checkbox', + checked: sec.allowSameOriginProxy ? true : undefined, + }) as HTMLInputElement; + const egressCidrsInput = el('input', { + value: (sec.egressAllowedCidrs ?? []).join(', '), + placeholder: 'e.g. 10.20.0.0/24 (blank = block all private IPs)', + }) as HTMLInputElement; + const sessTtlInput = el('input', { + type: 'number', + min: 1, + max: 720, + value: String(sec.sessionTtlHours ?? 168), + }) as HTMLInputElement; + const sessIdleInput = el('input', { + type: 'number', + min: 0, + max: 10080, + value: String(sec.sessionIdleTimeoutMin ?? 60), + }) as HTMLInputElement; const methodSel = el( 'select', {}, @@ -270,6 +280,7 @@ export async function renderSettingsView( policyMsg.textContent = ''; try { const nextSecurity: ClientSecuritySettings = { + ...sec, requireTotpOnLogin: reqTotpChk.checked, passwordMode: pwModeSel.value as 'any' | 'all', totpMode: totpModeSel.value as 'any' | 'all', @@ -278,6 +289,13 @@ export async function renderSettingsView( elevateOnLogin: elevateLoginChk.checked, keepElevationOnSafeMode: keepSafeChk.checked, enableEmergencySecretsBackup: backupChk.checked, + allowSameOriginProxy: allowSameOriginProxyChk.checked, + egressAllowedCidrs: egressCidrsInput.value + .split(',') + .map((s) => s.trim()) + .filter(Boolean), + sessionTtlHours: Number(sessTtlInput.value || 168), + sessionIdleTimeoutMin: Number(sessIdleInput.value || 0), }; const nextSettings = { ...(state.overview?.settings ?? {}), @@ -307,14 +325,18 @@ export async function renderSettingsView( el('div', {}, el('label', {}, 'TOTP Matching Mode'), totpModeSel), el('div', {}, el('label', {}, 'Step-Up Re-Auth Window'), policySel), el('div', {}, el('label', {}, 'Step-Up Method'), methodSel), + el('div', {}, el('label', {}, 'Session Max Lifetime (hours)'), sessTtlInput), + el('div', {}, el('label', {}, 'Session Idle Timeout (min, 0=off)'), sessIdleInput), ), + el('div', { style: 'margin-top:8px' }, el('label', {}, 'Egress Allowed CIDRs / IPs (CSV)'), egressCidrsInput), el( 'div', { class: 'stack', style: 'margin-top:8px' }, el('label', { class: 'chk-row' }, reqTotpChk, 'Require TOTP code during Login'), el('label', { class: 'chk-row' }, elevateLoginChk, 'Auto-elevate session on Login (skips immediate Step-Up)'), el('label', { class: 'chk-row' }, keepSafeChk, 'Keep Step-Up elevation when toggling Safe Mode ON'), - el('label', { class: 'chk-row' }, backupChk, 'Maintain automatic chmod 0600 secrets backup in data/recovery/'), + el('label', { class: 'chk-row' }, allowSameOriginProxyChk, 'Allow same-origin HTTP proxy fallback (less strict cookie isolation than isolated origin)'), + el('label', { class: 'chk-row' }, backupChk, 'Maintain passwordless emergency secrets backup in data/recovery/ (master key + vault creds only; login passwords never stored)'), ), el('div', { class: 'row', style: 'margin-top:8px' }, savePolicyBtn), policyMsg, @@ -730,7 +752,7 @@ export async function renderSettingsView( 'p', { class: 'muted' }, isWebAuthnSupported() - ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification.' + ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification. Reverse-proxy overrides: GCOORD_WEBAUTHN_RP_ID and GCOORD_WEBAUTHN_ORIGINS.' : 'Passkeys require HTTPS (e.g. Cloudflare Tunnel) or http://localhost — plain HTTP or raw IP URLs block navigator.credentials.', ), ); @@ -817,7 +839,7 @@ export async function renderSettingsView( el( 'p', { class: 'muted mono' }, - `Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, + `Passwordless bundle (login passwords are never written) — Path: ${rb.filePath} (chmod 0600) | Exists: ${rb.exists ? 'YES' : 'NO'} | MasterKeySaved: ${rb.hasMasterKey ? 'YES' : 'NO'} | VaultCreds: ${rb.credentialCount} | Snapshots: ${rb.snapshotCount}`, ), ); const bMsg = el('p', { class: 'form-msg' }); @@ -947,41 +969,9 @@ export async function renderSettingsView( sessPanel.append(el('div', { class: 'table-wrap' }, sTable)); root.append(sessPanel); - // 6. Audit Log - const auditPanel = el('section', { class: 'panel panel-region' }); - auditPanel.append(el('h2', {}, `Security & Action Audit Log (${auditRes.total} entries)`)); - const aTable = el('table'); - aTable.append( - el( - 'thead', - {}, - el('tr', {}, el('th', {}, 'Timestamp'), el('th', {}, 'Action'), el('th', {}, 'Status'), el('th', {}, 'Target'), el('th', {}, 'IP'), el('th', {}, 'Details')), - ), - ); - const aBody = el('tbody'); - for (const row of auditRes.items) { - aBody.append( - el( - 'tr', - {}, - el('td', { class: 'mono' }, fmtTime(row.ts)), - el('td', { class: 'mono' }, row.action), - el( - 'td', - {}, - el( - 'span', - { class: `badge ${row.status === 'ok' ? 'badge-ok' : 'badge-err'}` }, - row.status, - ), - ), - el('td', { class: 'mono' }, row.target ?? '—'), - el('td', { class: 'mono' }, row.actor_ip), - el('td', { class: 'mono muted' }, row.details ?? '—'), - ), - ); - } - aTable.append(aBody); - auditPanel.append(el('div', { class: 'table-wrap' }, aTable)); - root.append(auditPanel); + // 6. Runtime Profile, Prometheus /metrics, Scheduled Backups & Filterable Audit Log (lazy chunk) + const opsHost = el('div', { class: 'stack' }); + root.append(opsHost); + const { renderSettingsOpsPanels } = await import('./settings-ops-panel.js'); + await renderSettingsOpsPanels(opsHost, state, credsRes.credentials, onReloadState); } diff --git a/src/client/ts/views/systems-view.ts b/src/client/ts/views/systems-view.ts index a24300b..752682b 100644 --- a/src/client/ts/views/systems-view.ts +++ b/src/client/ts/views/systems-view.ts @@ -7,11 +7,23 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; +interface SystemActionInputDef { + name: string; + type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; + label?: string; + description?: string; + required?: boolean; + default?: unknown; + options?: string[]; +} + interface SystemActionDef { id: string; label: string; @@ -19,6 +31,7 @@ interface SystemActionDef { mode: 'oneshot' | 'stream' | 'interactive'; sudo: boolean; confirm: boolean; + inputs?: SystemActionInputDef[]; } interface SystemParamDef { @@ -65,6 +78,88 @@ interface ServerSnapshotView { } let unsubStreamListener: (() => void) | null = null; +let unsubStreamChannel: (() => void) | null = null; + +function releaseSystemStream(): void { + if (unsubStreamChannel) { + unsubStreamChannel(); + unsubStreamChannel = null; + } + if (unsubStreamListener) { + unsubStreamListener(); + unsubStreamListener = null; + } +} + +async function promptActionInputs( + actionLabel: string, + defs: SystemActionInputDef[], +): Promise | null> { + if (!defs || defs.length === 0) return {}; + return new Promise((resolve) => { + const dialog = document.createElement('dialog'); + dialog.className = 'dialog-wide'; + const closeBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Cancel'); + const ctrls = new Map(); + const fieldsBox = el('div', { class: 'stack' }); + for (const def of defs) { + let node: HTMLInputElement | HTMLSelectElement; + if (def.type === 'select' && def.options) { + const sel = el('select', { required: def.required !== false }); + for (const opt of def.options) { + sel.append(el('option', { value: opt, selected: def.default === opt }, opt)); + } + node = sel; + } else if (def.type === 'boolean') { + node = el('input', { type: 'checkbox', checked: Boolean(def.default) }) as HTMLInputElement; + } else { + node = el('input', { + type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', + value: def.default !== undefined ? String(def.default) : '', + required: def.required !== false, + placeholder: def.description ?? def.name, + }) as HTMLInputElement; + } + ctrls.set(def.name, { def, node }); + fieldsBox.append(el('label', {}, `${def.label ?? def.name} (${def.type})`), node); + } + + const form = el( + 'form', + { class: 'stack' }, + fieldsBox, + el('div', { class: 'dialog-actions' }, closeBtn, el('button', { type: 'submit', class: 'btn btn-primary mutating-action' }, 'Run')), + ); + + let settled = false; + const finish = (val: Record | null) => { + if (settled) return; + settled = 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 out: Record = {}; + for (const [k, { def, node }] of ctrls.entries()) { + out[k] = + def.type === 'boolean' + ? (node as HTMLInputElement).checked + : def.type === 'number' + ? Number(node.value) + : node.value; + } + finish(out); + }); + + dialog.append(el('h1', {}, `Action Inputs: ${actionLabel}`), form); + document.body.append(dialog); + dialog.showModal(); + }); +} function healthBadgeClass(h: string): string { if (h === 'ok') return 'badge badge-ok'; @@ -175,6 +270,12 @@ async function runSystemAction(opts: { onFinished: () => Promise; }): Promise { const { action } = opts; + let actionInputs: Record | undefined; + if (action.inputs && action.inputs.length > 0) { + const prompted = await promptActionInputs(action.label, action.inputs); + if (!prompted) return; + actionInputs = prompted; + } if (action.confirm) { const target = opts.subItemName ?? opts.itemName ?? opts.serverId; const ok = await confirmDialog( @@ -186,20 +287,28 @@ async function runSystemAction(opts: { opts.outputHost.replaceChildren(el('p', { class: 'muted mono' }, `Running ${action.label}...`)); - const res = await apiFetch< + let res: | { mode: 'oneshot'; exitCode: number | null; stdout: string; stderr: string; durationMs: number } | { mode: 'stream'; jobId: string } - | { mode: 'interactive'; session: { sessionId: string } } - >( - `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, - { - method: 'POST', - body: { - itemName: opts.itemName, - subItemName: opts.subItemName, + | { mode: 'interactive'; session: { sessionId: string } }; + try { + res = await apiFetch( + `/api/systems/${encodeURIComponent(opts.systemId)}/servers/${encodeURIComponent(opts.serverId)}/actions/${encodeURIComponent(action.id)}`, + { + method: 'POST', + body: { + itemName: opts.itemName, + subItemName: opts.subItemName, + ...(actionInputs ? { inputs: actionInputs } : {}), + }, }, - }, - ); + ); + } catch (err) { + const msg = extractErrorMessage(err); + opts.outputHost.replaceChildren(el('p', { class: 'err-text mono' }, msg)); + showToast(msg, 'err'); + return; + } if (res.mode === 'interactive') { window.location.hash = `#terminal?session=${encodeURIComponent(res.session.sessionId)}`; @@ -242,16 +351,14 @@ async function runSystemAction(opts: { } // Stream mode - if (unsubStreamListener) { - unsubStreamListener(); - unsubStreamListener = null; - } + releaseSystemStream(); const logPre = el('pre', { class: 'stream-log mono' }); - const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Stop Stream'); + const stopBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Stream'); stopBtn.addEventListener('click', async () => { await apiFetch(`/api/systems/streams/${encodeURIComponent(res.jobId)}/cancel`, { method: 'POST' }); stopBtn.disabled = true; + showToast(`Stream ${res.jobId} cancelled.`, 'warn'); }); const streamAiBtn = isAiEnabled(opts.state) ? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Debug Output]') @@ -303,7 +410,7 @@ async function runSystemAction(opts: { logPre.scrollTop = logPre.scrollHeight; }); - opts.wsClient.subscribe([`stream:${res.jobId}`]); + unsubStreamChannel = opts.wsClient.subscribe([`stream:${res.jobId}`]); } export async function renderSystemsView( @@ -311,10 +418,8 @@ export async function renderSystemsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - if (unsubStreamListener) { - unsubStreamListener(); - unsubStreamListener = null; - } + releaseSystemStream(); + registerViewCleanup(releaseSystemStream); root.replaceChildren(); const segs = state.routeSegments ?? []; const forceRefresh = state.routeQuery?.refresh === '1'; @@ -567,14 +672,16 @@ export async function renderSystemsView( // Quick Editable Files via SFTP inline diff editor if (item.editableFiles.length > 0) { + const needsSudo = system.actions.some((a) => a.sudo); const editRow = el('div', { class: 'chip-list' }); for (const fPath of item.editableFiles) { editRow.append( el( 'a', { - href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}`, + href: `#sftp?server=${encodeURIComponent(targetServerId)}&edit=${encodeURIComponent(fPath)}${needsSudo ? '&sudo=1' : ''}`, class: 'btn btn-sm', + title: fPath, }, `Edit ${fPath.split('/').pop()}`, ), diff --git a/src/client/ts/views/vault-view.ts b/src/client/ts/views/vault-view.ts index 1789733..02359ed 100644 --- a/src/client/ts/views/vault-view.ts +++ b/src/client/ts/views/vault-view.ts @@ -1,6 +1,7 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, fmtTime, type ClientState } from '../state.js'; +import { showToast } from '../toast.js'; interface VaultCredMeta { id: string; @@ -123,19 +124,44 @@ export async function renderVaultView( onPanicLock: () => Promise, ): Promise { root.replaceChildren(); - const vaultData = await apiFetch<{ - state: 'uninitialized' | 'locked' | 'unlocked'; - runtimeReady?: boolean; - isPanicLocked?: boolean; - credentials: VaultCredMeta[]; - }>('/api/vault/credentials'); - const runtimeReady = Boolean(vaultData.runtimeReady ?? vaultData.state === 'unlocked'); - state.vaultState = vaultData.state; + const [vaultData, statusRes] = await Promise.all([ + apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + runtimeReady?: boolean; + sealState?: string; + isPanicLocked?: boolean; + credentials: VaultCredMeta[]; + }>('/api/vault/credentials'), + apiFetch<{ + state: 'uninitialized' | 'locked' | 'unlocked'; + runtimeReady: boolean; + sealState: string; + isPanicLocked: boolean; + }>('/api/vault/status').catch(() => null), + ]); + const runtimeReady = Boolean(statusRes?.runtimeReady ?? vaultData.runtimeReady ?? vaultData.state === 'unlocked'); + const sealState = statusRes?.sealState ?? vaultData.sealState ?? (runtimeReady ? 'unsealed' : 'sealed'); + state.vaultState = statusRes?.state ?? vaultData.state; state.vaultRuntimeReady = runtimeReady; - if (vaultData.isPanicLocked !== undefined) { - state.isPanicLocked = vaultData.isPanicLocked; + if (statusRes?.isPanicLocked !== undefined || vaultData.isPanicLocked !== undefined) { + state.isPanicLocked = Boolean(statusRes?.isPanicLocked ?? vaultData.isPanicLocked); } + const doSealVault = async () => { + const ok = await confirmDialog( + 'dialog-confirm', + 'Seal the Vault now? This wipes the in-memory master key (collectors/SSH will pause until unsealed with the 32-byte key), without revoking your admin login session.', + ); + if (!ok) return; + try { + await apiFetch('/api/vault/seal', { method: 'POST', body: {} }); + showToast('Vault sealed and runtime master key cleared from memory.', 'warn'); + await onStateChanged(); + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }; + const statusPanel = el('section', { class: 'panel' }); if (vaultData.state === 'uninitialized') { @@ -283,13 +309,23 @@ export async function renderVaultView( }); statusPanel.append( - el('h1', {}, 'Encrypted Vault — [LOCKED]'), + el('h1', {}, `Encrypted Vault — [${vaultData.state.toUpperCase()} / ${sealState.toUpperCase()}]`), el( 'p', { class: 'muted' }, - 'Established secrets remain active in the background for stat collectors, SSH, SFTP, Terminal, Systems, and Tunnels. Unlock the Vault to add, update, delete, rotate, or reveal secrets.', + 'Established secrets remain active in memory while unsealed (chmod 0600 data/vault.key or GCOORD_MASTER_KEY env). Unlock to edit, or Seal to zeroize keys from RAM without dropping sessions.', + ), + el( + 'div', + { class: 'row' }, + unlockBtn, + (() => { + const sealBtn = el('button', { type: 'button', class: 'btn mutating-action' }, 'Seal Vault'); + sealBtn.addEventListener('click', () => void doSealVault()); + return sealBtn; + })(), + panicBtn, ), - el('div', { class: 'row' }, unlockBtn, panicBtn), lockMsg, credTableWrap, revealBox, @@ -308,9 +344,15 @@ export async function renderVaultView( await apiFetch('/api/vault/lock', { method: 'POST' }); await onStateChanged(); }); + const sealUnlockedBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Seal Vault', + ); + sealUnlockedBtn.addEventListener('click', () => void doSealVault()); statusPanel.append( - el('div', { class: 'row-between' }, el('h1', {}, 'Encrypted Vault — [UNLOCKED]'), lockBtn), + el('div', { class: 'row-between' }, el('h1', {}, `Encrypted Vault — [UNLOCKED / ${sealState.toUpperCase()}]`), el('div', { class: 'row' }, lockBtn, sealUnlockedBtn)), credTableWrap, revealBox, ); diff --git a/src/client/ts/views/workflows-view.ts b/src/client/ts/views/workflows-view.ts index 83a4b30..4d0bb20 100644 --- a/src/client/ts/views/workflows-view.ts +++ b/src/client/ts/views/workflows-view.ts @@ -7,16 +7,18 @@ import { extractErrorMessage, fmtTime, isAiEnabled, + registerViewCleanup, type ClientState, type ServerEntry, } from '../state.js'; +import { showToast } from '../toast.js'; import type { MultiplexWsClient } from '../ws-client.js'; type WfSubTab = 'workflows' | 'broadcast' | 'snippets'; interface WorkflowInputDef { name: string; - type: 'string' | 'number' | 'boolean' | 'server' | 'select'; + type: 'string' | 'number' | 'boolean' | 'server' | 'select' | 'secret'; label?: string; description?: string; required?: boolean; @@ -26,7 +28,7 @@ interface WorkflowInputDef { interface WorkflowStepDef { id: string; - type: 'exec' | 'read-file' | 'system-action' | 'transfer'; + type: 'exec' | 'read-file' | 'system-action' | 'transfer' | 'http' | 'notify'; dependsOn?: Array; target?: { serverId?: string; tags?: string[]; all?: boolean }; command?: string; @@ -39,7 +41,19 @@ interface WorkflowStepDef { mode?: 'hub-relayed' | 'direct'; source?: { serverId: string; path: string }; destination?: { serverId: string; path: string }; + url?: string; + method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'; + body?: string; + secretRef?: string; + expectedStatus?: number; + channelIds?: string[]; + title?: string; + message?: string; + severity?: 'warn' | 'critical'; timeoutSec?: number; + retries?: number; + retryBackoffSec?: number; + when?: string; sudo?: boolean; captureAs?: string; onFailure?: string | { action: string; channelId?: string; workflowId?: string }; @@ -108,6 +122,18 @@ let activeSubTab: WfSubTab = 'workflows'; let selectedRunDetailId: string | null = null; let broadcastPresetSnippetId: string | null = null; let unsubWfWs: (() => void) | null = null; +let unsubWfChannel: (() => void) | null = null; + +function releaseWfWs(): void { + if (unsubWfChannel) { + unsubWfChannel(); + unsubWfChannel = null; + } + if (unsubWfWs) { + unsubWfWs(); + unsubWfWs = null; + } +} function statusBadgeClass(status: string): string { if (status === 'succeeded' || status === 'ok') return 'badge badge-ok'; @@ -251,10 +277,10 @@ async function promptWorkflowInputs( 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) : '', + type: def.type === 'secret' ? 'password' : def.type === 'number' ? 'number' : 'text', + value: def.type === 'secret' ? '' : def.default !== undefined ? String(def.default) : '', required: def.required, - placeholder: def.description ?? def.name, + placeholder: def.type === 'secret' ? '(secret input — masked in logs)' : (def.description ?? def.name), }); } fields.set(def.name, ctrl); @@ -419,7 +445,7 @@ function openWorkflowEditorDialog( const sType = el( 'select', { class: 'input-sm' }, - ...(['exec', 'read-file', 'system-action', 'transfer'] as const).map((t) => + ...(['exec', 'read-file', 'system-action', 'transfer', 'http', 'notify'] as const).map((t) => el('option', { value: t, selected: step.type === t }, t), ), ); @@ -429,6 +455,14 @@ function openWorkflowEditorDialog( 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' }; + } else if (step.type === 'http' && !step.url) { + step.method = 'POST'; + step.url = 'https://example.invalid/webhook'; + } else if (step.type === 'notify' && !step.channelIds) { + step.channelIds = ['ops-webhook']; + step.title = 'Workflow Notification'; + step.message = 'Step reached'; + step.severity = 'warn'; } redrawSteps(); }); @@ -462,6 +496,26 @@ function openWorkflowEditorDialog( redrawSteps(); }); + const sRetries = el('input', { + class: 'input-sm', + type: 'number', + min: 0, + max: 5, + value: String(step.retries ?? 0), + placeholder: 'retries (0-5)', + }) as HTMLInputElement; + sRetries.addEventListener('input', () => { + step.retries = Number(sRetries.value || 0); + }); + const sWhen = el('input', { + class: 'input-sm', + value: step.when ?? '', + placeholder: 'when expr (e.g. inputs.env == "prod")', + }) as HTMLInputElement; + sWhen.addEventListener('input', () => { + step.when = sWhen.value.trim() || undefined; + }); + card.append( el( 'div', @@ -469,10 +523,57 @@ function openWorkflowEditorDialog( el('strong', {}, `Step #${idx + 1}`), el('div', { class: 'row' }, sId, sType, rmBtn), ), - sDeps, + el('div', { class: 'grid-3', style: 'margin-top:6px' }, sDeps, sRetries, sWhen), ); - if (step.type === 'transfer') { + if (step.type === 'http') { + const mSel = el( + 'select', + { class: 'input-sm' }, + ...(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const).map((m) => + el('option', { value: m, selected: (step.method ?? 'POST') === m }, m), + ), + ) as HTMLSelectElement; + const uIn = el('input', { class: 'input-sm', value: step.url ?? '', placeholder: 'https://...' }) as HTMLInputElement; + const secIn = el('input', { class: 'input-sm', value: step.secretRef ?? '', placeholder: 'secretRef (api-token/webhook-secret)' }) as HTMLInputElement; + const expIn = el('input', { class: 'input-sm', type: 'number', value: step.expectedStatus ? String(step.expectedStatus) : '', placeholder: 'expectedStatus' }) as HTMLInputElement; + const bArea = el('textarea', { rows: 2, placeholder: 'Optional HTTP JSON body' }, step.body ?? '') as HTMLTextAreaElement; + bArea.value = step.body ?? ''; + const syncHttp = () => { + step.method = mSel.value as WorkflowStepDef['method']; + step.url = uIn.value.trim(); + step.secretRef = secIn.value.trim() || undefined; + step.expectedStatus = expIn.value.trim() ? Number(expIn.value) : undefined; + step.body = bArea.value || undefined; + }; + [mSel, uIn, secIn, expIn, bArea].forEach((n) => n.addEventListener('input', syncHttp)); + card.append( + el('div', { class: 'grid-2', style: 'margin-top:6px' }, mSel, uIn, secIn, expIn), + bArea, + ); + } else if (step.type === 'notify') { + const chIn = el('input', { class: 'input-sm', value: (step.channelIds ?? []).join(', '), placeholder: 'channelIds (comma-sep)' }) as HTMLInputElement; + const tIn = el('input', { class: 'input-sm', value: step.title ?? '', placeholder: 'Notification title' }) as HTMLInputElement; + const sevSel = el( + 'select', + { class: 'input-sm' }, + el('option', { value: 'warn', selected: (step.severity ?? 'warn') === 'warn' }, 'warn'), + el('option', { value: 'critical', selected: step.severity === 'critical' }, 'critical'), + ) as HTMLSelectElement; + const mArea = el('textarea', { rows: 2, placeholder: 'Notification message' }, step.message ?? '') as HTMLTextAreaElement; + mArea.value = step.message ?? ''; + const syncNotify = () => { + step.channelIds = chIn.value.split(',').map((s) => s.trim()).filter(Boolean); + step.title = tIn.value; + step.severity = sevSel.value as 'warn' | 'critical'; + step.message = mArea.value; + }; + [chIn, tIn, sevSel, mArea].forEach((n) => n.addEventListener('input', syncNotify)); + card.append( + el('div', { class: 'grid-3', style: 'margin-top:6px' }, chIn, tIn, sevSel), + mArea, + ); + } else if (step.type === 'transfer') { const modeSel = el( 'select', { class: 'input-sm' }, @@ -675,11 +776,12 @@ export async function renderWorkflowsView( state: ClientState, wsClient: MultiplexWsClient, ): Promise { - if (unsubWfWs) { - unsubWfWs(); - unsubWfWs = null; - } - wsClient.subscribe(['workflows']); + releaseWfWs(); + const unsubBase = wsClient.subscribe(['workflows']); + registerViewCleanup(() => { + releaseWfWs(); + unsubBase(); + }); root.replaceChildren(); const tabBar = el( @@ -761,17 +863,18 @@ export async function renderWorkflowsView( 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'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel Run'); cancelBtn.addEventListener('click', async () => { cancelBtn.disabled = true; await apiFetch(`/api/workflows/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }); + showToast(`Cancellation requested for run ${runId}.`, 'warn'); }); streamPanel.replaceChildren( el('div', { class: 'row-between' }, el('strong', {}, `Live Run Stream: ${wfId} (${runId})`), cancelBtn), logPre, ); - if (unsubWfWs) unsubWfWs(); + releaseWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type === 'stream:chunk' && frame.jobId === `wf:${runId}`) { if (frame.stream !== 'meta') { @@ -791,7 +894,7 @@ export async function renderWorkflowsView( } } }); - wsClient.subscribe([`stream:wf:${runId}`]); + unsubWfChannel = wsClient.subscribe([`stream:wf:${runId}`]); }; const loadRunDetail = async (runId: string) => { @@ -802,6 +905,29 @@ export async function renderWorkflowsView( }>(`/api/workflows/runs/${encodeURIComponent(runId)}`); detailPanel.hidden = false; renderStructuredOutput(detailPanel, res.workflow, res.run, res.stepLogs); + const uniqueSteps = [...new Set(res.stepLogs.map((l) => l.stepId))]; + if (uniqueSteps.length > 0) { + const lazyPre = el('pre', { class: 'stream-log mono', hidden: true }); + const stepRow = el('div', { class: 'row', style: 'margin-top:8px' }, el('span', { class: 'muted' }, 'Inspect step:')); + for (const sid of uniqueSteps) { + const b = el('button', { type: 'button', class: 'btn btn-sm' }, sid); + b.addEventListener('click', async () => { + try { + const sLogs = await apiFetch<{ logs: WorkflowStepLogItem[] }>( + `/api/workflows/runs/${encodeURIComponent(runId)}/steps/${encodeURIComponent(sid)}/logs`, + ); + lazyPre.hidden = false; + lazyPre.textContent = sLogs.logs + .map((l) => `[${l.serverId}] exit=${String(l.exitCode)}\n${l.stdout}${l.stderr ? `\nSTDERR:\n${l.stderr}` : ''}`) + .join('\n---\n') || '(empty)'; + } catch (err) { + showToast(extractErrorMessage(err), 'err'); + } + }); + stepRow.append(b); + } + detailPanel.append(stepRow, lazyPre); + } if (isAiEnabled(state)) { const diagBtn = el( 'button', @@ -944,9 +1070,10 @@ export async function renderWorkflowsView( }); 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'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger' }, 'Cancel'); cancelBtn.addEventListener('click', async () => { await apiFetch(`/api/workflows/runs/${encodeURIComponent(r.runId)}/cancel`, { method: 'POST' }); + showToast(`Cancelled run ${r.runId}.`, 'warn'); await renderWorkflowsView(root, state, wsClient); }); actRow.append(cancelBtn); @@ -1034,7 +1161,7 @@ export async function renderWorkflowsView( 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'); + const cancelBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger', hidden: true }, 'Cancel Broadcast'); let activeJobId: string | null = null; cancelBtn.addEventListener('click', async () => { if (!activeJobId) return; @@ -1099,7 +1226,7 @@ export async function renderWorkflowsView( ); } - if (unsubWfWs) unsubWfWs(); + releaseWfWs(); unsubWfWs = wsClient.onFrame((frame: ServerWsFrame) => { if (frame.type !== 'stream:chunk' || frame.jobId !== activeJobId || frame.stream !== 'meta') return; try { @@ -1134,20 +1261,77 @@ export async function renderWorkflowsView( cancelBtn.hidden = true; msgEl.className = 'form-msg ok-text'; msgEl.textContent = `Broadcast finished: ${String(m.okCount)}/${String(m.total)} succeeded.`; + void loadBroadcastHistory(); } } catch { // Ignore meta parse error } }); - wsClient.subscribe([`stream:${activeJobId}`]); + unsubWfChannel = wsClient.subscribe([`stream:${activeJobId}`]); } catch (err) { msgEl.className = 'form-msg err-text'; msgEl.textContent = extractErrorMessage(err); } }); + const histPanel = el('section', { class: 'panel panel-region' }); + const loadBroadcastHistory = async () => { + histPanel.replaceChildren(el('h2', {}, 'Broadcast History')); + try { + const hRes = await apiFetch<{ + jobs: Array<{ + jobId: string; + snippetId?: string; + command: string; + createdAt: number; + finishedAt: number | null; + done: boolean; + cancelled: boolean; + targets: Array<{ status: string }>; + }>; + }>('/api/workflows/broadcast/history?limit=25'); + if (hRes.jobs.length === 0) { + histPanel.append(el('p', { class: 'muted' }, 'No past fleet broadcasts recorded yet.')); + return; + } + const tbl = el('table'); + tbl.append( + el('thead', {}, el('tr', {}, el('th', {}, 'Job ID'), el('th', {}, 'Command / Snippet'), el('th', {}, 'Result'), el('th', {}, 'Started'), el('th', {}, 'Export'))), + ); + const tbody = el('tbody'); + for (const j of hRes.jobs) { + const okCount = j.targets.filter((t) => t.status === 'ok').length; + tbody.append( + el( + 'tr', + {}, + el('td', { class: 'mono' }, j.jobId), + el('td', { class: 'mono' }, j.snippetId ? `[${j.snippetId}] ${j.command.slice(0, 50)}` : j.command.slice(0, 60)), + el('td', { class: 'mono' }, `${okCount}/${j.targets.length} ok${j.cancelled ? ' (cancelled)' : ''}`), + el('td', { class: 'mono' }, fmtTime(j.createdAt)), + el( + 'td', + {}, + el( + 'div', + { class: 'row' }, + el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=json`, class: 'btn btn-sm', download: '' }, 'JSON'), + el('a', { href: `/api/workflows/broadcast/${encodeURIComponent(j.jobId)}/export?format=csv`, class: 'btn btn-sm', download: '' }, 'CSV'), + ), + ), + ), + ); + } + tbl.append(tbody); + histPanel.append(el('div', { class: 'table-wrap' }, tbl)); + } catch (err) { + histPanel.append(el('p', { class: 'err-text' }, extractErrorMessage(err))); + } + }; + panel.append(el('h2', {}, 'Ad-Hoc Fleet Broadcast'), form); - root.append(panel, cardsGrid); + root.append(panel, cardsGrid, histPanel); + void loadBroadcastHistory(); return; } From a5a937850e38e53d05be8c2cc86fda5fb7f68925 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:31:16 +0000 Subject: [PATCH 18/19] test: add comprehensive v1.1 security, proxy/SFTP, automation/CLI & bundle tests --- tests/mobile-and-themes.test.ts | 31 +- tests/v11-automation-monitoring-cli.test.ts | 451 ++++++++++++++++++++ tests/v11-security-hardening.test.ts | 388 +++++++++++++++++ tests/v11-ssh-proxy-sftp.test.ts | 361 ++++++++++++++++ 4 files changed, 1228 insertions(+), 3 deletions(-) create mode 100644 tests/v11-automation-monitoring-cli.test.ts create mode 100644 tests/v11-security-hardening.test.ts create mode 100644 tests/v11-ssh-proxy-sftp.test.ts diff --git a/tests/mobile-and-themes.test.ts b/tests/mobile-and-themes.test.ts index 9195ab7..17f3e83 100644 --- a/tests/mobile-and-themes.test.ts +++ b/tests/mobile-and-themes.test.ts @@ -26,9 +26,29 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op } }); - it('meets <50KB core gzipped bundle, splits lazy chunks, preserves PWA & mobile CSS, and caps DOM streams', () => { + it('meets <50KB core gzipped bundle (including static sync chunks), 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']; + + // Recursively follow static ESM imports from main.js to measure true eager core bundle + const visitedJs = new Set(['main.js']); + const queue = ['main.js']; + while (queue.length > 0) { + const rel = queue.shift()!; + const abs = path.join(publicDir, rel); + if (!fs.existsSync(abs)) continue; + const code = fs.readFileSync(abs, 'utf8'); + const importRe = /\bfrom\s*["']\.\/(chunks\/[^"']+\.js)["']|\bimport\s*["']\.\/(chunks\/[^"']+\.js)["']/g; + let m: RegExpExecArray | null; + while ((m = importRe.exec(code)) !== null) { + const target = m[1] ?? m[2]!; + if (!visitedJs.has(target)) { + visitedJs.add(target); + queue.push(target); + } + } + } + + const coreFiles = ['index.html', 'themes.css', 'base.css', ...visitedJs]; let totalCoreGzip = 0; for (const f of coreFiles) { @@ -37,13 +57,18 @@ describe('Phase 5: 8 Theme Presets, Code-Splitting Budgets & Galaxy J7 Mobile Op } expect(totalCoreGzip).toBeLessThan(50 * 1024); - // Heavy/optional UI stays code-split out of main.js + // Heavy/optional views & overlays stay 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'); + expect(mainJs).not.toContain('Fleet Monitor'); 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('command-palette-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('dashboard-view-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('settings-view-') && c.endsWith('.js'))).toBe(true); + expect(chunks.some((c) => c.startsWith('settings-ops-panel-') && 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); diff --git a/tests/v11-automation-monitoring-cli.test.ts b/tests/v11-automation-monitoring-cli.test.ts new file mode 100644 index 0000000..8566613 --- /dev/null +++ b/tests/v11-automation-monitoring-cli.test.ts @@ -0,0 +1,451 @@ +import { execFile } from 'node:child_process'; +import fs from 'node:fs'; +import http from 'node:http'; +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 { interpolateShellCommandSafe } from '../src/server/automation/template.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('v1.1 Monitoring, Prometheus /metrics, Systems, Workflows, Broadcast History & CLI Tools', () => { + it('covers template Go preservation, Prometheus /metrics, rollup/probe history, systems inputs/cancel, http/notify workflows, broadcast export, and CLI tools', async () => { + // 1. Go template preservation vs safe shell quoting + const goCmd = interpolateShellCommandSafe( + "docker ps --format '{{.Names}}' --filter name={{inputs.filter}}", + { inputs: { filter: "web'; rm -rf /; #" } }, + ); + expect(goCmd).toContain('{{.Names}}'); + expect(goCmd).toContain("'web'\\''; rm -rf /; #'"); + + let httpStepHit: Record | null = null; + const targetHttp = http.createServer((req, res) => { + if (req.url === '/probe') { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('probe-healthy-ok'); + return; + } + if (req.url === '/wf-hook' && req.method === 'POST') { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + httpStepHit = { + auth: req.headers.authorization, + body: Buffer.concat(chunks).toString('utf8'), + }; + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ accepted: true })); + }); + return; + } + res.writeHead(404).end(); + }); + await new Promise((r) => targetHttp.listen(0, '127.0.0.1', () => r())); + cleanups.push(() => new Promise((r) => targetHttp.close(() => r()))); + const httpPort = (targetHttp.address() as { port: number }).port; + + let lastActionCmd = ''; + const mock = new MockSshServer({ + username: 'ops', + os: 'Linux', + onExec: (cmd) => { + lastActionCmd = cmd; + if (cmd.includes('SYSTEMD_DISCOVER')) { + return { stdout: 'demo.service\n', exitCode: 0 }; + } + if (cmd.includes('SYSTEMD_SHOW')) { + return { + stdout: JSON.stringify({ + Id: 'demo.service', + ActiveState: 'active', + SubState: 'running', + FragmentPath: '/etc/systemd/system/demo.service', + DropInPaths: '/etc/systemd/system/demo.service.d/override.conf', + }), + exitCode: 0, + }; + } + if (cmd.includes('echo-secret-action')) { + return { stdout: 'action-ok\n', exitCode: 0 }; + } + return null; + }, + }); + await mock.start(); + cleanups.push(() => mock.close()); + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-auto-')); + const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-cli-work-')); + const server = await createGCoordinatorServer({ + dataDir, + port: 0, + host: '127.0.0.1', + publicDir: path.resolve('dist/public'), + watchConfig: false, + }); + let closedServer = false; + cleanups.push(async () => { + if (!closedServer) 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; raw?: boolean; 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); + if (opts.raw) { + return { status: res.status, text: await res.text(), data: {} as Record }; + } + const data = (await res.json().catch(() => ({}))) as Record; + return { status: res.status, data, text: '' }; + }; + + const bootInfo = await api('/api/auth/bootstrap'); + const totp = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), + }); + const bootRes = await api('/api/auth/bootstrap', { + method: 'POST', + body: { + username: 'admin', + password: 'automation-v11-password!', + totpCode: totp.generate(), + securityPreset: 'relaxed', + }, + }); + csrfToken = String(bootRes.data.csrfToken); + + await api('/api/vault/init', { method: 'POST', body: {} }); + const kp = await api('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'main-key', name: 'Main Key' }, + }); + mock.authorizedKeys.push(String((kp.data.credential as { publicKey: string }).publicKey)); + await api('/api/vault/credentials', { + method: 'POST', + body: { id: 'wf-api-tok', name: 'WF API', type: 'api-token', token: 'Bearer wf-tok-secret' }, + }); + + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'] }, + }); + + // Prometheus /metrics disabled initially -> 404; rotate-token enables & secures it + expect((await fetch(`${baseUrl}/metrics`)).status).toBe(404); + const promRot = await api('/api/config/prometheus-token', { + method: 'POST', + body: { enable: true }, + }); + expect(promRot.status).toBe(200); + const promToken = String(promRot.data.token); + expect(promToken.length).toBeGreaterThan(20); + expect((await fetch(`${baseUrl}/metrics`)).status).toBe(401); + const promOk = await fetch(`${baseUrl}/metrics`, { + headers: { Authorization: `Bearer ${promToken}` }, + }); + expect(promOk.status).toBe(200); + const promText = await promOk.text(); + expect(promText).toContain('gcoordinator_tunnels_active'); + expect(promText).toContain('gcoordinator_process_resident_memory_bytes'); + + // Register server with hub HTTP probe + await api('/api/servers', { + method: 'POST', + body: { + id: 'srv-1', + name: 'Server 1', + host: '127.0.0.1', + port: mock.port, + username: 'ops', + credentialId: 'main-key', + pollIntervalSec: 120, + probes: [ + { + id: 'web-hp', + type: 'http', + url: `http://127.0.0.1:${httpPort}/probe`, + from: 'hub', + expectedStatus: 200, + bodyIncludes: 'probe-healthy-ok', + enabled: true, + }, + ], + }, + }); + await api('/api/servers/srv-1/reconnect', { method: 'POST' }); + await api('/api/servers/srv-1/tofu/approve', { + method: 'POST', + body: { fingerprint: mock.hostFingerprint }, + }); + + // On-demand probe run + probe history query + const runProbe = await api('/api/servers/srv-1/probes/web-hp/run', { method: 'POST', body: {} }); + expect(runProbe.status).toBe(200); + expect((runProbe.data.sample as { ok: boolean }).ok).toBe(true); + const probeHist = await api('/api/servers/srv-1/probes/history?range=1h'); + expect(probeHist.status).toBe(200); + expect((probeHist.data.samples as unknown[]).length).toBeGreaterThanOrEqual(1); + + // Rollup partial-bucket upsert check: seed older bucket raw rows across two flushes + const oldBucketTs = Math.floor((Date.now() - 2 * 3600_000) / 3600_000) * 3600_000; + server.db + .prepare( + `INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec) + VALUES (?, 'srv-1', 20, 500, 1000, 1000, 2000, 0.5, 100)`, + ) + .run(oldBucketTs + 10_000); + server.db + .prepare( + `INSERT INTO metrics_disks (ts, server_id, mount_point, fs_type, used_mb, total_mb, used_pct) + VALUES (?, 'srv-1', '/', 'ext4', 4000, 10000, 40)`, + ) + .run(oldBucketTs + 10_000); + server.monitoringService.runMaintenance(); + + server.db + .prepare( + `INSERT INTO metrics_raw (ts, server_id, cpu_pct, mem_used_mb, mem_total_mb, net_rx_bps, net_tx_bps, load_1m, uptime_sec) + VALUES (?, 'srv-1', 80, 700, 1000, 3000, 4000, 1.5, 200)`, + ) + .run(oldBucketTs + 20_000); + server.monitoringService.runMaintenance(); + + const rollupRow = server.db + .prepare( + `SELECT cpu_min, cpu_max, net_rx_avg_bps, disk_max_pct FROM metrics_rollup + WHERE server_id = 'srv-1' AND granularity = '1h' AND bucket_ts = ?`, + ) + .get(oldBucketTs) as { + cpu_min: number; + cpu_max: number; + net_rx_avg_bps: number; + disk_max_pct: number; + }; + expect(rollupRow.cpu_min).toBe(20); + expect(rollupRow.cpu_max).toBe(80); + expect(rollupRow.disk_max_pct).toBe(40); + expect(rollupRow.net_rx_avg_bps).toBe(2000); + + // Custom System with systemd editableFiles + action inputs[] secret redaction + Safe-Mode stream cancel + await api('/api/config/file', { + method: 'PUT', + body: { + path: 'systems/sys-v11.json', + content: JSON.stringify({ + id: 'sys-v11', + name: 'System v1.1 Test', + cacheTtlSec: 30, + params: [], + discovery: { type: 'command', command: 'echo SYSTEMD_DISCOVER', parser: 'lines' }, + status: { command: 'echo SYSTEMD_SHOW', parser: 'json' }, + actions: [ + { + id: 'secret-act', + label: 'Secret Action', + scope: 'item', + mode: 'oneshot', + inputs: [{ name: 'apiSecret', type: 'secret', required: true }], + command: 'echo echo-secret-action "$GCOORD_INPUT_APISECRET"', + }, + ], + editableFiles: [], + }), + }, + }); + await api('/api/systems/sys-v11/servers/srv-1/attach', { method: 'PUT', body: { params: {} } }); + const sysSnap = await api('/api/systems/sys-v11?refresh=1&serverId=srv-1'); + const items = (sysSnap.data.snapshots as Array<{ items: Array<{ editableFiles: string[] }> }>)[0]!.items; + expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service'); + expect(items[0]!.editableFiles).toContain('/etc/systemd/system/demo.service.d/override.conf'); + + const actRun = await api('/api/systems/sys-v11/servers/srv-1/actions/secret-act', { + method: 'POST', + body: { itemName: 'demo.service', inputs: { apiSecret: 'super-secret-input-val' } }, + }); + expect(actRun.status).toBe(200); + expect(lastActionCmd).toContain('echo-secret-action'); + const sysAudit = await api('/api/audit?action=system.action&limit=5'); + expect(JSON.stringify(sysAudit.data.items)).not.toContain('super-secret-input-val'); + + // Safe Mode stream cancel exemption works even cleanly + const safeCancel = await api('/api/systems/streams/nonexistent-job/cancel', { + method: 'POST', + safeMode: true, + }); + expect(safeCancel.status).toBe(200); + + // Workflow with http step + secret input masking + lazy step logs + await api('/api/workflows', { + method: 'POST', + body: { + id: 'wf-v11-http', + name: 'Workflow v1.1', + enabled: true, + trigger: { type: 'manual' }, + overlapPolicy: 'skip', + display: { mode: 'log' }, + inputs: [{ name: 'secretTok', type: 'secret', required: true }], + steps: [ + { + id: 'exec-mask', + type: 'exec', + target: { serverId: 'srv-1' }, + command: 'echo got={{inputs.secretTok}}', + }, + { + id: 'call-http', + type: 'http', + dependsOn: ['exec-mask'], + url: `http://127.0.0.1:${httpPort}/wf-hook`, + method: 'POST', + secretRef: 'wf-api-tok', + body: '{"event":"done"}', + expectedStatus: 200, + }, + ], + }, + }); + const wfRun = await api('/api/workflows/wf-v11-http/run', { + method: 'POST', + body: { inputs: { secretTok: 'MY-TOP-SECRET-VALUE-77' } }, + }); + expect(wfRun.status).toBe(202); + const runId = String(wfRun.data.runId); + + for (let i = 0; i < 30; i++) { + const st = await api(`/api/workflows/runs/${runId}`); + if ((st.data.run as { status: string }).status !== 'running' && (st.data.run as { status: string }).status !== 'queued') { + expect((st.data.run as { status: string }).status).toBe('succeeded'); + break; + } + await new Promise((r) => setTimeout(r, 80)); + } + expect(httpStepHit).not.toBeNull(); + const stepLogRes = await api(`/api/workflows/runs/${runId}/steps/exec-mask/logs`); + expect(stepLogRes.status).toBe(200); + expect(JSON.stringify(stepLogRes.data)).not.toContain('MY-TOP-SECRET-VALUE-77'); + + // Broadcast history + JSON/CSV export + const bcastRes = await api('/api/workflows/broadcast', { + method: 'POST', + body: { command: 'echo broadcast-v11', target: { serverIds: ['srv-1'] } }, + }); + expect(bcastRes.status).toBe(202); + const jobId = String((bcastRes.data.job as { jobId: string }).jobId); + for (let i = 0; i < 20; i++) { + const pollB = await api(`/api/workflows/broadcast/${jobId}`); + if ((pollB.data.job as { done: boolean }).done) break; + await new Promise((r) => setTimeout(r, 60)); + } + const histRes = await api('/api/workflows/broadcast/history?limit=10'); + expect(histRes.status).toBe(200); + expect((histRes.data.jobs as Array<{ jobId: string }>).some((j) => j.jobId === jobId)).toBe(true); + const bCsv = await api(`/api/workflows/broadcast/${jobId}/export?format=csv`, { raw: true }); + expect(bCsv.status).toBe(200); + expect(bCsv.text).toContain('srv-1'); + + // Scheduled Backup runNow + const schedRun = await api('/api/backup/schedule/run', { method: 'POST', body: {} }); + expect(schedRun.status).toBe(200); + expect(schedRun.data.ok).toBe(true); + + // Close server before offline CLI tests + await server.close(); + closedServer = true; + + const statusOut = await execFileAsync(process.execPath, [ + CLI_PATH, + 'status', + '--data-dir', + dataDir, + '--json', + ]); + const stJson = JSON.parse(statusOut.stdout) as { bootstrapped: boolean; auditLogRows: number }; + expect(stJson.bootstrapped).toBe(true); + expect(stJson.auditLogRows).toBeGreaterThan(0); + + const newPwFile = path.join(workDir, 'newpw.txt'); + fs.writeFileSync(newPwFile, 'offline-reset-password-2026!', { mode: 0o600 }); + const resetPwOut = await execFileAsync(process.execPath, [ + CLI_PATH, + 'reset-password', + '--data-dir', + dataDir, + '--password-file', + newPwFile, + ]); + expect(resetPwOut.stdout).toContain('reset cleanly'); + + const reset2faOut = await execFileAsync(process.execPath, [ + CLI_PATH, + 'reset-2fa', + '--data-dir', + dataDir, + '--json', + ]); + expect((JSON.parse(reset2faOut.stdout) as { reset: boolean }).reset).toBe(true); + + const panicOut = await execFileAsync(process.execPath, [ + CLI_PATH, + 'panic-lock', + '--data-dir', + dataDir, + ]); + expect(panicOut.stdout).toContain('Panic Lock engaged cleanly'); + expect(fs.existsSync(path.join(dataDir, 'vault.enc.panic-locked'))).toBe(true); + }); +}); diff --git a/tests/v11-security-hardening.test.ts b/tests/v11-security-hardening.test.ts new file mode 100644 index 0000000..ef0840a --- /dev/null +++ b/tests/v11-security-hardening.test.ts @@ -0,0 +1,388 @@ +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 { redactSecrets } from '../src/server/ai/redactor.js'; +import { createGCoordinatorServer } from '../src/server/app.js'; +import { resolveRuntimeLimits } from '../src/server/config/runtime-limits.js'; +import { openDatabase } from '../src/server/db/database.js'; +import { AuditService } from '../src/server/security/audit.js'; +import { + EgressBlockedError, + assertEgressUrlAllowed, + fetchWithEgressGuard, +} from '../src/server/security/egress-guard.js'; +import { RateLimiter } from '../src/server/security/guards.js'; +import { EmergencyRecoveryService } from '../src/server/security/recovery-store.js'; +import { VaultService } from '../src/server/security/vault.js'; +import { AlertChannelSchema } from '../src/shared/schemas/alerts.schema.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('v1.1 Security Hardening Suite', () => { + it('enforces Zero-Trust Egress Guard, CIDR allowlist, and redirect blocking', async () => { + await expect(assertEgressUrlAllowed('http://127.0.0.1:8080/api')).rejects.toBeInstanceOf( + EgressBlockedError, + ); + await expect( + assertEgressUrlAllowed('http://169.254.169.254/latest/meta-data/'), + ).rejects.toBeInstanceOf(EgressBlockedError); + await expect(assertEgressUrlAllowed('http://10.0.0.5/hook')).rejects.toBeInstanceOf( + EgressBlockedError, + ); + + let internalRedirectFollowed = false; + const srv = http.createServer((req, res) => { + if (req.url === '/ok') { + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('hello-egress'); + return; + } + if (req.url === '/redir') { + res.writeHead(302, { Location: `http://127.0.0.1:${port}/never-hit` }); + res.end(); + return; + } + if (req.url === '/never-hit') { + internalRedirectFollowed = true; + res.writeHead(200).end('leaked'); + return; + } + res.writeHead(404).end(); + }); + await new Promise((r) => srv.listen(0, '127.0.0.1', () => r())); + cleanups.push(() => new Promise((r) => srv.close(() => r()))); + const port = (srv.address() as { port: number }).port; + + const okRes = await fetchWithEgressGuard( + `http://127.0.0.1:${port}/ok`, + { method: 'GET' }, + { allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 }, + ); + expect(okRes.status).toBe(200); + expect(await okRes.text()).toBe('hello-egress'); + + await expect( + fetchWithEgressGuard( + `http://127.0.0.1:${port}/redir`, + { method: 'GET' }, + { allowedCidrs: ['127.0.0.1/32'], timeoutMs: 3000 }, + ), + ).rejects.toThrow(); + expect(internalRedirectFollowed).toBe(false); + }); + + it('persists SQLite RateLimiter lockouts across instances and removes legacy recovery passwords', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-rl-')); + cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true })); + const dbPath = path.join(dir, 'gcoord.db'); + const db1 = openDatabase(dbPath); + const rl1 = new RateLimiter({ db: db1 }); + for (let i = 0; i < 6; i++) { + rl1.recordFailure('login', '198.51.100.77'); + } + expect(rl1.check('login', '198.51.100.77').allowed).toBe(false); + db1.close(); + + const db2 = openDatabase(dbPath); + const rl2 = new RateLimiter({ db: db2 }); + expect(rl2.check('login', '198.51.100.77').allowed).toBe(false); + db2.close(); + + // Passwordless emergency recovery + chmod 0600 Vault keyfile + seal() + const vault = new VaultService(path.join(dir, 'vault.enc'), { + keyFilePath: path.join(dir, 'vault.key'), + allowLocalKeyFile: true, + }); + vault.initRuntime({ autoCreateIfMissing: true }); + const keyMode = fs.statSync(path.join(dir, 'vault.key')).mode & 0o777; + expect(keyMode).toBe(0o600); + vault.unlockForModifications(); + + vault.upsertCredential({ + id: 'wh-1', + name: 'Webhook Sec', + type: 'webhook-secret', + secret: 'super-secret-wh-value', + }); + + const recovery = new EmergencyRecoveryService(dir); + const bundle = recovery.syncState({ + enabled: true, + vault, + username: 'admin', + passwordMetaList: [{ id: 'pw-1', label: 'Primary', createdAt: Date.now() }], + }); + expect(bundle).not.toBeNull(); + const recMode = fs.statSync(recovery.filePath).mode & 0o777; + expect(recMode).toBe(0o600); + const serialized = fs.readFileSync(recovery.filePath, 'utf8'); + expect(serialized).not.toContain('passwordHash'); + expect(serialized).not.toContain('plaintext'); + + let panicTriggered = false; + vault.onPanicLock(() => { + panicTriggered = true; + }); + vault.seal(); + expect(vault.sealState).toBe('sealed'); + expect(vault.isRuntimeReady).toBe(false); + expect(panicTriggered).toBe(false); + + const keyHex = fs.readFileSync(path.join(dir, 'vault.key'), 'utf8').trim(); + vault.unlock(keyHex); + expect(vault.sealState).toBe('unlocked'); + expect(vault.isRuntimeReady).toBe(true); + }); + + it('scales AI redactor linearly O(n) on huge malformed inputs and strips truncated PEM & Vault secrets', () => { + const bigPem = `-----BEGIN RSA PRIVATE KEY-----\n${'MIIEowIBAAKCAQEA'.repeat(8000)}\n`; + const sampleJson = `{"password":"my-db-pass-123","api_key":"sk-live-secret-999","token":"tok-abc"}`; + const payload = `${bigPem}\n${sampleJson}\nAuthorization: Bearer topsecretbearer\n`; + + const started = Date.now(); + const res = redactSecrets(payload, ['topsecretbearer', 'xy99']); + const elapsed = Date.now() - started; + + expect(elapsed).toBeLessThan(1000); + expect(res.text).toContain('[REDACTED_PRIVATE_KEY]'); + expect(res.text).not.toContain('my-db-pass-123'); + expect(res.text).not.toContain('sk-live-secret-999'); + expect(res.text).not.toContain('topsecretbearer'); + expect(res.redactedCount).toBeGreaterThanOrEqual(3); + }); + + it('enforces idle timeout, real-time WS revocation, audit CSV formula neutralization, alert security events & throttle presets', async () => { + const low = resolveRuntimeLimits('low-resource'); + const bal = resolveRuntimeLimits('balanced'); + const unth = resolveRuntimeLimits('unthrottled'); + expect(low.maxConcurrentMetricPolls).toBeLessThan(bal.maxConcurrentMetricPolls); + expect(unth.maxConcurrentMetricPolls).toBe(0); // 0 = unthrottled unlimited polls + expect(low.maxConcurrentWorkflows).toBeLessThan(bal.maxConcurrentWorkflows); + expect(bal.maxConcurrentWorkflows).toBeLessThan(unth.maxConcurrentWorkflows); + expect(low.argon2Concurrency).toBe(1); + + // Non-webhook-secret creds are rejected by alerts test or config runtime check cleanly; schema parses valid channel + expect(() => + AlertChannelSchema.parse({ + id: 'ch1', + name: 'Ch', + type: 'generic', + url: 'https://hooks.example.com/1', + secretRef: 'wh-sec', + }), + ).not.toThrow(); + + let receivedWebhook: Record | null = null; + const whSrv = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on('data', (c: Buffer) => chunks.push(c)); + req.on('end', () => { + try { + receivedWebhook = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record; + } catch { + receivedWebhook = { raw: Buffer.concat(chunks).toString('utf8') }; + } + res.writeHead(200).end('ok'); + }); + }); + await new Promise((r) => whSrv.listen(0, '127.0.0.1', () => r())); + cleanups.push(() => new Promise((r) => whSrv.close(() => r()))); + const whPort = (whSrv.address() as { port: number }).port; + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-sec-e2e-')); + 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 jar = new CookieJar(); + let csrfToken = ''; + const api = async ( + pathname: string, + opts: { method?: string; body?: unknown; raw?: 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; + const res = await fetch(`${baseUrl}${pathname}`, { + method: opts.method ?? 'GET', + headers, + body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, + }); + jar.updateFrom(res); + if (opts.raw) { + return { status: res.status, text: await res.text(), data: {} as Record }; + } + const data = (await res.json().catch(() => ({}))) as Record; + return { status: res.status, data, text: '' }; + }; + + const bootInfo = await api('/api/auth/bootstrap'); + const totp = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), + }); + const bootRes = await api('/api/auth/bootstrap', { + method: 'POST', + body: { + username: 'admin', + password: 'v11-hardening-password!', + totpCode: totp.generate(), + securityPreset: 'relaxed', + }, + }); + expect(bootRes.status).toBe(201); + csrfToken = String(bootRes.data.csrfToken); + + // Initialize Vault + allow localhost egress for webhook test + await api('/api/vault/init', { method: 'POST', body: {} }); + await api('/api/vault/credentials', { + method: 'POST', + body: { id: 'tok-not-wh', name: 'API Token', type: 'api-token', token: 'bearer-xyz' }, + }); + await api('/api/vault/credentials', { + method: 'POST', + body: { id: 'wh-valid', name: 'Webhook', type: 'webhook-secret', secret: 'wh-tok-1' }, + }); + await api('/api/auth/security-policy', { + method: 'PUT', + body: { egressAllowedCidrs: ['127.0.0.1/32'], sessionIdleTimeoutMin: 60 }, + }); + + // Reject referencing non-webhook-secret credential in channel test + await api('/api/alerts/config', { + method: 'PUT', + body: { + channels: [ + { + id: 'bad-ch', + name: 'Bad Channel', + type: 'generic', + url: `http://127.0.0.1:${whPort}/hook`, + secretRef: 'tok-not-wh', + enabled: true, + }, + { + id: 'good-ch', + name: 'Good Channel', + type: 'generic', + url: `http://127.0.0.1:${whPort}/hook`, + secretRef: 'wh-valid', + enabled: true, + }, + ], + rules: [ + { + id: 'sec-lockout', + name: 'Auth Lockout Event', + kind: 'security-event', + events: ['auth.lockout'], + severity: 'critical', + forConsecutivePolls: 1, + cooldownSec: 0, + channelIds: ['good-ch'], + enabled: true, + }, + ], + }, + }); + const badTest = await api('/api/alerts/channels/bad-ch/test', { method: 'POST' }); + expect(badTest.status === 400 || badTest.data.ok === false).toBe(true); + + // Trigger security-event alert -> webhook receives notification + await server.alertEngine.emitSecurityEvent('auth.lockout', { + message: 'Repeated login failure from 203.0.113.9', + }); + expect(receivedWebhook).not.toBeNull(); + + // Audit formula-injection neutralization + filtering + CSV/NDJSON export + server.auditService.log({ + action: 'custom.formula', + actorIp: '127.0.0.1', + target: '=CMD|calc', + status: 'denied', + details: 'formula-needle', + }); + const filteredAudit = await api('/api/audit?action=custom.formula&status=denied&q=formula-needle'); + expect(filteredAudit.status).toBe(200); + expect(filteredAudit.data.total).toBe(1); + + const csvRes = await api('/api/audit/export?format=csv&action=custom.formula', { raw: true }); + expect(csvRes.status).toBe(200); + expect(csvRes.text).toContain('"\'=CMD|calc"'); + + const ndjsonRes = await api('/api/audit/export?format=ndjson&action=custom.formula', { raw: true }); + expect(ndjsonRes.status).toBe(200); + const firstRow = JSON.parse(ndjsonRes.text.trim().split('\n')[0]!) as { action: string }; + expect(firstRow.action).toBe('custom.formula'); + + // Real-time WS close with 4001 on logout/revocation + const wsCloseCode = await new Promise((resolve, reject) => { + const ws = new WebSocket(`ws://127.0.0.1:${server.port}/ws`, { + headers: { Cookie: jar.header() }, + }); + ws.once('open', () => { + void api('/api/auth/logout', { method: 'POST' }); + }); + ws.once('close', (code) => resolve(code)); + ws.once('error', reject); + }); + expect(wsCloseCode).toBe(4001); + + // Log back in and verify sliding sessionIdleTimeoutMin invalidates idle session + await new Promise((r) => setTimeout(r, 20)); + const reLogin = await api('/api/auth/login', { + method: 'POST', + body: { username: 'admin', passwords: ['v11-hardening-password!'], codes: [] }, + }); + expect(reLogin.status).toBe(200); + server.db.prepare('UPDATE sessions SET last_seen_at = ?').run(Date.now() - 120 * 60_000); + const afterIdle = await api('/api/auth/status'); + expect(afterIdle.status).toBe(200); + expect(afterIdle.data.authenticated).toBe(false); + }); +}); diff --git a/tests/v11-ssh-proxy-sftp.test.ts b/tests/v11-ssh-proxy-sftp.test.ts new file mode 100644 index 0000000..5768e1e --- /dev/null +++ b/tests/v11-ssh-proxy-sftp.test.ts @@ -0,0 +1,361 @@ +import fs from 'node:fs'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import * as OTPAuth from 'otpauth'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createGCoordinatorServer } from '../src/server/app.js'; +import { formatRemoteCd } from '../src/server/ssh/pty-manager.js'; +import { parseOpenSshConfig } from '../src/server/ssh/ssh-config-import.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('; '); + } +} + +afterEach(async () => { + while (cleanups.length > 0) { + await cleanups.pop()!(); + } +}); + +describe('v1.1 SSH Import, Multi-Algo known_hosts, PTY Security/.cast, SFTP v1.1 & Isolated Proxy / SOCKS5', () => { + it('parses & imports OpenSSH config, manages multi-algo known_hosts, enforces PTY/SFTP v1.1 ops, and validates proxy/SOCKS5/TTL', async () => { + const seenExecs: string[] = []; + const mock = new MockSshServer({ + username: 'ops', + os: 'Linux', + allowTcpForward: true, + onExec: (cmd) => { + seenExecs.push(cmd); + if (cmd.startsWith('chown ')) { + return { stdout: '', exitCode: 0 }; + } + if (cmd.startsWith('find ') && cmd.includes('needle')) { + return { stdout: '/sub/needle.conf\n', exitCode: 0 }; + } + return null; + }, + }); + await mock.start(); + cleanups.push(() => mock.close()); + + // Populate mock sftp root files + fs.writeFileSync(path.join(mock.sftpRootDir, 'alpha.log'), 'hello-alpha\n'); + fs.mkdirSync(path.join(mock.sftpRootDir, 'sub'), { recursive: true }); + fs.writeFileSync(path.join(mock.sftpRootDir, 'sub', 'needle.conf'), 'port=8080\n'); + const outsideSecret = path.join(os.tmpdir(), `outside-secret-${Date.now()}.txt`); + fs.writeFileSync(outsideSecret, 'TOP_SECRET'); + cleanups.push(() => fs.rmSync(outsideSecret, { force: true })); + fs.symlinkSync(outsideSecret, path.join(mock.sftpRootDir, 'escape-link')); + + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gcoord-v11-ssh-')); + // First start WITHOUT proxyPort to test strict PROXY_ORIGIN_ISOLATION_REQUIRED enforcement + const serverNoIso = await createGCoordinatorServer({ + dataDir, + port: 0, + host: '127.0.0.1', + publicDir: path.resolve('dist/public'), + watchConfig: false, + }); + + const baseUrl = `http://127.0.0.1:${serverNoIso.port}`; + const jar = new CookieJar(); + let csrfToken = ''; + const api = async ( + pathname: string, + opts: { method?: string; body?: unknown; raw?: 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; + const res = await fetch(`${baseUrl}${pathname}`, { + method: opts.method ?? 'GET', + headers, + body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined, + }); + jar.updateFrom(res); + if (opts.raw) { + return { status: res.status, text: await res.text(), data: {} as Record }; + } + const data = (await res.json().catch(() => ({}))) as Record; + return { status: res.status, data, text: '' }; + }; + + try { + const bootInfo = await api('/api/auth/bootstrap'); + const totp = new OTPAuth.TOTP({ + issuer: 'GCoordinator', + label: 'admin', + algorithm: 'SHA1', + digits: 6, + period: 30, + secret: OTPAuth.Secret.fromBase32(String(bootInfo.data.secretBase32)), + }); + const bootRes = await api('/api/auth/bootstrap', { + method: 'POST', + body: { + username: 'admin', + password: 'ssh-proxy-v11-password!', + totpCode: totp.generate(), + securityPreset: 'relaxed', + }, + }); + expect(bootRes.status).toBe(201); + csrfToken = String(bootRes.data.csrfToken); + + await api('/api/vault/init', { method: 'POST', body: {} }); + const genKey = await api('/api/vault/generate-ed25519', { + method: 'POST', + body: { id: 'ssh-main', name: 'Main Key' }, + }); + mock.authorizedKeys.push( + String((genKey.data.credential as { publicKey: string }).publicKey), + ); + + // OpenSSH parser + /api/servers/import-ssh-config preview & apply + const sshConfigText = [ + 'Host *', + ' User ignored', + 'Host bastion', + ' HostName 127.0.0.1', + ` Port ${mock.port}`, + ' User ops', + 'Host app-behind-bastion', + ' HostName 127.0.0.1', + ` Port ${mock.port}`, + ' User ops', + ' ProxyJump bastion', + ].join('\n'); + const parsed = parseOpenSshConfig(sshConfigText); + expect(parsed.entries.map((e) => e.alias)).toEqual(['bastion', 'app-behind-bastion']); + + const prevRes = await api('/api/servers/import-ssh-config', { + method: 'POST', + body: { configText: sshConfigText, apply: false }, + }); + expect(prevRes.status).toBe(200); + expect((prevRes.data.createdIds as string[]).length).toBe(0); + + const applyRes = await api('/api/servers/import-ssh-config', { + method: 'POST', + body: { configText: sshConfigText, defaultCredentialId: 'ssh-main', apply: true }, + }); + expect(applyRes.status).toBe(201); + expect(applyRes.data.createdIds).toEqual(['bastion', 'app-behind-bastion']); + + // Reconnect + approve TOFU on bastion + await api('/api/servers/bastion/reconnect', { method: 'POST' }); + const approve = await api('/api/servers/bastion/tofu/approve', { + method: 'POST', + body: { fingerprint: mock.hostFingerprint }, + }); + expect(approve.status).toBe(200); + + // Multi-algorithm known_hosts CRUD + const curKnown = serverNoIso.knownHosts.listKnownHosts(); + serverNoIso.knownHosts.replaceAllKnownHosts([ + ...curKnown, + { + hostPort: `127.0.0.1:${mock.port}`, + algorithm: 'ssh-rsa', + fingerprint: 'SHA256:fakeRsaFp', + }, + ]); + const khList = await api('/api/servers/known-hosts'); + expect(khList.status).toBe(200); + const matching = (khList.data.knownHosts as Array<{ hostPort: string; algorithm: string }>).filter( + (x) => x.hostPort === `127.0.0.1:${mock.port}`, + ); + expect(matching.length).toBeGreaterThanOrEqual(2); + + const delRsa = await api( + `/api/servers/known-hosts?hostPort=${encodeURIComponent(`127.0.0.1:${mock.port}`)}&algorithm=ssh-rsa`, + { method: 'DELETE' }, + ); + expect(delRsa.status).toBe(200); + + // PTY cwd injection defense (control chars blocked 400 + single-quoted shell cwd) + .cast export + reconnect + expect(formatRemoteCd("/tmp'; rm -rf /")).toBe("cd -- '/tmp'\\''; rm -rf /'"); + expect(formatRemoteCd('~/My Dir')).toBe('cd -- "$HOME/"\'My Dir\''); + + const badCtrlPty = await api('/api/terminal/sessions', { + method: 'POST', + body: { serverId: 'bastion', cwd: '/tmp\nbad', cols: 80, rows: 24 }, + }); + expect(badCtrlPty.status).toBe(400); + + const quotedCwdPty = await api('/api/terminal/sessions', { + method: 'POST', + body: { serverId: 'bastion', cwd: '/tmp; rm -rf /', cols: 80, rows: 24 }, + }); + expect(quotedCwdPty.status).toBe(201); + const qPtyId = String((quotedCwdPty.data.session as { sessionId: string }).sessionId); + await new Promise((r) => setTimeout(r, 80)); + const qExport = await api(`/api/terminal/sessions/${qPtyId}/export?format=plain`, { raw: true }); + expect(qExport.text).toContain("cd -- '/tmp; rm -rf /'"); + await api(`/api/terminal/sessions/${qPtyId}`, { method: 'DELETE' }); + + const ptyRes = await api('/api/terminal/sessions', { + method: 'POST', + body: { serverId: 'bastion', cwd: '/tmp', cols: 80, rows: 24 }, + }); + expect(ptyRes.status).toBe(201); + const ptyId = String((ptyRes.data.session as { sessionId: string }).sessionId); + await new Promise((r) => setTimeout(r, 150)); + + const castRes = await api(`/api/terminal/sessions/${ptyId}/export?format=cast`, { raw: true }); + expect(castRes.status).toBe(200); + const header = JSON.parse(castRes.text.trim().split('\n')[0]!) as { version: number; width: number }; + expect(header.version).toBe(2); + expect(header.width).toBe(80); + + const reconPty = await api(`/api/terminal/sessions/${ptyId}/reconnect`, { + method: 'POST', + body: {}, + }); + expect(reconPty.status).toBe(200); + expect((reconPty.data.session as { exited: boolean }).exited).toBe(false); + await api(`/api/terminal/sessions/${ptyId}`, { method: 'DELETE' }); + + // SFTP v1.1: touch, chown (sudo via MockSshServer), search, bulk-delete, symlink escape refusal + const touchRes = await api('/api/servers/bastion/sftp/touch', { + method: 'POST', + body: { path: '/touched.txt' }, + }); + expect(touchRes.status).toBe(201); + expect(fs.existsSync(path.join(mock.sftpRootDir, 'touched.txt'))).toBe(true); + + const chownRes = await api('/api/servers/bastion/sftp/chown', { + method: 'POST', + body: { path: '/touched.txt', uid: 1000, gid: 1000, sudo: true }, + }); + expect(chownRes.status).toBe(200); + expect(seenExecs.some((c) => c.includes('chown 1000:1000'))).toBe(true); + + const searchRes = await api('/api/servers/bastion/sftp/search?path=/&q=needle'); + expect(searchRes.status).toBe(200); + expect(searchRes.data.matches).toContain('/sub/needle.conf'); + expect(seenExecs.some((c) => c.startsWith("find '/' -maxdepth 5 -iname '*needle*'"))).toBe( + true, + ); + + const bulkDel = await api('/api/servers/bastion/sftp/bulk-delete', { + method: 'POST', + body: { paths: ['/touched.txt', '/alpha.log'], recursive: false }, + }); + expect(bulkDel.status).toBe(200); + expect((bulkDel.data.deleted as string[]).length).toBe(2); + + // Symlink inspection + safe symlink deletion (lstat unlinks symlink without touching target dir) + const targetDir = path.join(mock.sftpRootDir, 'keep-dir'); + fs.mkdirSync(targetDir, { recursive: true }); + fs.writeFileSync(path.join(targetDir, 'precious.txt'), 'do-not-delete'); + fs.symlinkSync(targetDir, path.join(mock.sftpRootDir, 'link-to-dir')); + + const symStat = await api('/api/servers/bastion/sftp/stat?path=/escape-link'); + expect(symStat.status).toBe(200); + expect((symStat.data.entry as { type: string }).type).toBe('symlink'); + + const delLink = await api( + '/api/servers/bastion/sftp/entry?path=/link-to-dir&recursive=1', + { method: 'DELETE' }, + ); + expect(delLink.status).toBe(200); + expect(fs.existsSync(path.join(targetDir, 'precious.txt'))).toBe(true); + expect(fs.existsSync(path.join(mock.sftpRootDir, 'link-to-dir'))).toBe(false); + + const nullPath = await api('/api/servers/bastion/sftp/text?path=/bad%00path'); + expect(nullPath.status).toBeGreaterThanOrEqual(400); + + // SOCKS5 tunnel without targetPort + TTL countdown metadata + const socksCreate = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'bastion', + tunnel: { + id: 'socks-tun', + name: 'SOCKS5 Local', + mode: 'socks5', + targetHost: '127.0.0.1', + targetPort: 0, + ttlSec: 120, + autoStart: false, + }, + start: true, + }, + }); + expect(socksCreate.status).toBe(201); + const tList = await api('/api/tunnels'); + const socksItem = (tList.data.tunnels as Array<{ + tunnel: { id: string; mode: string; ttlSec?: number }; + active: boolean; + localBoundPort?: number; + expiresAt?: number; + }>).find((t) => t.tunnel.id === 'socks-tun'); + expect(socksItem?.active).toBe(true); + expect(socksItem?.expiresAt).toBeGreaterThan(Date.now()); + + // SOCKS5 method negotiation (0x05 0x01 0x00 -> 0x05 0x00) + const socksReply = await new Promise((resolve, reject) => { + const sock = net.connect(socksItem!.localBoundPort!, '127.0.0.1', () => { + sock.write(Buffer.from([0x05, 0x01, 0x00])); + }); + sock.once('data', (d) => { + sock.destroy(); + resolve(d); + }); + sock.once('error', reject); + }); + expect(socksReply[0]).toBe(0x05); + expect(socksReply[1]).toBe(0x00); + + // Without isolated proxyPort/subdomain & allowSameOriginProxy=false -> 403 PROXY_ORIGIN_ISOLATION_REQUIRED + const proxyCreate = await api('/api/tunnels', { + method: 'POST', + body: { + serverId: 'bastion', + tunnel: { + id: 'web-noiso', + name: 'NoIso Web', + mode: 'http-proxy', + targetHost: '127.0.0.1', + targetPort: 9999, + autoStart: false, + }, + start: true, + }, + }); + expect(proxyCreate.status).toBe(201); + const noIsoTicket = await api('/api/tunnels/bastion/web-noiso/proxy-ticket', { + method: 'POST', + body: {}, + }); + expect(noIsoTicket.status).toBe(403); + expect(noIsoTicket.data.error).toBe('PROXY_ISOLATION_NOT_CONFIGURED'); + } finally { + await serverNoIso.close(); + fs.rmSync(dataDir, { recursive: true, force: true }); + } + }); +}); From 5701e7778098db0ae00897934204b5f4478a08ad Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:32:50 +0000 Subject: [PATCH 19/19] chore(release): bump version to 1.1.0 and update AGENTS.md --- How/AGENTS.md | 177 +++++++++++++++++++++++++++------------------- package-lock.json | 4 +- package.json | 2 +- 3 files changed, 108 insertions(+), 75 deletions(-) diff --git a/How/AGENTS.md b/How/AGENTS.md index 21137d6..d6e7f91 100644 --- a/How/AGENTS.md +++ b/How/AGENTS.md @@ -12,9 +12,9 @@ - Centralized `AES-256-GCM` credential storage (`vault.enc`), Ed25519 key lifecycle + zero-lockout atomic key rotation, Argon2id + multi-factor TOTP + optional WebAuthn Passkeys, configurable re-auth strictness, Safe Mode, and Emergency Panic Lock. - Agentless Linux/BSD/macOS metric polling, multi-mount disk tracking, on-demand Server Inspector, HTTP/TCP probes, declarative `systems/*.json` discovery/status/actions, Full-DAG `workflows/*.json`, fleet broadcast, cross-server transfers, webhook alerting, portable `.gcoord.enc` backups, and an opt-in BYO-API OpenAI-compatible AI assistant. -All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.md) plus post-Phase-2 and post-Phase-3 enhancements are implemented and verified (`18/18` Vitest suites, `35/35` tests passing). +All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.md) plus **v1.1.0** security hardening, lightweight low-resource runtime throttling, and operational enhancements are implemented and verified (`21/21` Vitest suites, `41/41` tests passing). Key v1.1 additions include configurable `runtime.throttleMode` (`low-resource` | `balanced` | `unthrottled`) tuned for 1 vCPU / 1 GB RAM + 2 GB Swap servers, Zero-Trust Egress Guard, Vault `seal()` + passwordless emergency recovery, encrypted TOTP + SQLite rate limiting + CIDR-gated proxy IP trust + real-time WS revocation, dual-mode isolated proxy origins + SOCKS5/TTL tunnels + OpenSSH config import, Prometheus `/metrics`, Security Event Alerting, scheduled `.gcoord.enc` backups, offline CLI admin tools (`status`, `panic-lock`, `reset-2fa`, `reset-password`), and full dynamic client code-splitting. -**Precedence rule:** [How/Plan.md](./Plan.md) is the original Phase 1–5 design blueprint (its directory-tree diagram still references root `Plan.md`, which now lives at `How/Plan.md`). Several core behaviors evolved during implementation—including write-only Vault locking vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, the `data/recovery/` emergency backup store, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget, and `xterm.js` mobile IME composition fixes. **Wherever `How/AGENTS.md` differs from `How/Plan.md`, `How/AGENTS.md` reflects the live codebase and takes precedence.** +**Precedence rule:** [How/Plan.md](./Plan.md) is the original Phase 1–5 design blueprint (its directory-tree diagram still references root `Plan.md`, which now lives at `How/Plan.md`). Several core behaviors evolved across v1.0 and v1.1—including write-only Vault locking + explicit `seal()` vs. always-on runtime secrets, multi-password/multi-TOTP & configurable strictness, WebAuthn Passkeys, passwordless `data/recovery/` emergency secret backups, Zero-Trust egress & dual-mode isolated proxy origins, configurable `runtime.throttleMode`, 8 UI/terminal themes, a strict `< 20 KB` lazy-chunk budget across all code-split views, and `xterm.js` mobile IME composition fixes. **Wherever `How/AGENTS.md` differs from `How/Plan.md`, `How/AGENTS.md` reflects the live codebase and takes precedence.** --- @@ -29,19 +29,23 @@ All 5 phases of [Plan.md](file:///home/devuser/workspace/GCoordinator/How/Plan.m ### NPM Scripts (`package.json`) - `npm run typecheck` — `tsc --noEmit` (strict TypeScript with `noUncheckedIndexedAccess: true` and `noImplicitOverride: true`). -- `npm run build:client` — `tsx src/client/build.ts` (bundles ES2020 client modules + CSS into `dist/public/` and enforces gzip budgets). +- `npm run build:client` — `tsx src/client/build.ts` (bundles ES2020 client modules + CSS into `dist/public/` and enforces gzip budgets recursively across `main.js` static imports and lazy chunks). - `npm run build:server` — `esbuild` bundles `dist/server/index.js` and `dist/cli/gcoord.js` (`--platform=node --target=node22 --format=esm --packages=external`). - `npm run build` — runs `typecheck && build:client && build:server`. -- `npm test` — `vitest run` (runs all 18 unit/E2E suites in ~5s using in-process HTTP servers and `MockSshServer`). +- `npm test` — `vitest run` (runs all 21 unit/E2E suites, 41 tests using in-process HTTP servers and `MockSshServer`). - `npx vitest run tests/.test.ts` — run a targeted Vitest file. - `npm run dev` — `tsx watch src/server/index.ts`. - `npm start` — `node dist/server/index.js` (requires `npm run build` first so `dist/public/` and `dist/server/` exist). ### CLI (`src/cli/gcoord.ts` -> `dist/cli/gcoord.js`) ```bash +node dist/cli/gcoord.js status [--data-dir ] [--json] +node dist/cli/gcoord.js panic-lock [--data-dir ] +node dist/cli/gcoord.js reset-2fa [--data-dir ] [--disable] [--json] +node dist/cli/gcoord.js reset-password [--data-dir ] [--password-file ] node dist/cli/gcoord.js rotate-key [--data-dir ] [--current-key-file ] [--new-key-out ] node dist/cli/gcoord.js backup --out [--data-dir ] [--key-file ] [--passphrase-file ] -node dist/cli/gcoord.js verify-backup [--bundle ] [--key-file ] [--passphrase-file ] [--vault-key-file ] [--json] +node dist/cli/gcoord.js verify-backup [--bundle ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] [--json] node dist/cli/gcoord.js restore [--bundle ] [--data-dir ] [--key-file ] [--passphrase-file ] [--vault-key-file ] ``` @@ -51,8 +55,18 @@ node dist/cli/gcoord.js restore [--bundle ] [--data-dir - `HOST` — bind address (default: `0.0.0.0`). - `GCOORD_MASTER_KEY` — 32-byte Vault master key (hex or base64). - `GCOORD_MASTER_KEY_FILE` — master key file path (default: `/run/secrets/gcoord_master_key`). +- `GCOORD_DB_KEY` — 32-byte key encrypting TOTP secrets at rest in SQLite (otherwise auto-created `0600` at `data/db.key`). +- `GCOORD_AUTO_KEYFILE` — set `'true'` to mirror an env/secret Vault key into local `data/vault.key` (`0600`). - `GCOORD_BACKUP_PASSPHRASE` — optional passphrase for `.gcoord.enc` CLI operations. -- `TRUST_CLOUDFLARE` — set `'true'` to enable `app.set('trust proxy', 1)` and honor `CF-Connecting-IP` in rate limiting. +- `TRUST_CLOUDFLARE` — set `'true'` to trust proxy headers from `TRUSTED_PROXY_CIDRS` / loopback and honor `CF-Connecting-IP` in rate limiting. +- `TRUSTED_PROXY_CIDRS` — comma-separated CIDR allowlist of trusted reverse proxies (`trust proxy` & client IP resolution). +- `GCOORD_ALLOW_LAN_TUNNELS` — set `'true'` to permit LAN-bound tunnel listeners where applicable. +- `GCOORD_PROXY_PORT` — optional dedicated local port for origin-isolated reverse-proxy tunnel traffic. +- `GCOORD_PROXY_BASE_DOMAIN` — optional wildcard subdomain base host (e.g. `proxy.example.com`) for origin-isolated tunnel proxying. +- `GCOORD_WEBAUTHN_RP_ID` — optional explicit WebAuthn Relying Party ID override. +- `GCOORD_WEBAUTHN_ORIGINS` — optional comma-separated allowed WebAuthn origins. +- `GCOORD_METRICS_TOKEN` — optional Bearer token override for Prometheus `GET /metrics`. +- `GCOORD_THROTTLE_MODE` — runtime throttle profile override: `'low-resource'` | `'balanced'` | `'unthrottled'` (overrides `settings.runtime.throttleMode`). --- @@ -69,7 +83,7 @@ GCoordinator/ │ └── docker-compose.lan.yml ├── src/ │ ├── cli/ -│ │ └── gcoord.ts # rotate-key, backup, verify-backup, restore CLI +│ │ └── gcoord.ts # status, panic-lock, reset-2fa, reset-password, rotate-key, backup, verify-backup, restore │ ├── shared/ │ │ ├── diff.ts # Pure TS unified LCS line diff utility │ │ ├── ws-protocol.ts # Multiplexed /ws frame schemas & WS_CHANNELS helpers @@ -85,76 +99,84 @@ GCoordinator/ │ │ └── vault.schema.ts │ ├── server/ │ │ ├── index.ts # Process bootstrap & SIGINT/SIGTERM graceful shutdown -│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock +│ │ ├── app.ts # createGCoordinatorServer() wiring, middleware order, Panic Lock, /metrics │ │ ├── db/ -│ │ │ ├── database.ts # SQLite WAL connection & ordered migration runner -│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts +│ │ │ ├── database.ts # SQLite WAL connection, throttle PRAGMAs & ordered migration runner +│ │ │ └── migrations/ # 001_initial.ts, 002_multi_auth.ts, 003_phase4_meta.ts, 004_v1_1.ts │ │ ├── security/ -│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, Ed25519) -│ │ │ ├── auth.ts # AuthService (Argon2id, multi-password, multi-TOTP, recovery codes, WebAuthn) -│ │ │ ├── guards.ts # RateLimiter, attachClientIp, CSRF, Safe Mode, createStepUpGuard -│ │ │ ├── audit.ts # Append-only AuditService -│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (data/recovery/emergency-secrets.json) -│ │ │ └── backup.ts # Portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore +│ │ │ ├── vault.ts # VaultService (AES-256-GCM, runtime-ready vs write-locked, seal(), Ed25519) +│ │ │ ├── auth.ts # AuthService (Argon2id queue, multi-password, encrypted TOTP, idle TTL, WebAuthn) +│ │ │ ├── guards.ts # SQLite RateLimiter, attachClientIp (CIDR trust), CSRF, Safe Mode, Step-Up +│ │ │ ├── egress-guard.ts # Zero-Trust SSRF/DNS/CIDR guard & redirect: 'error' fetch wrapper +│ │ │ ├── audit.ts # Append-only AuditService (filtered query, CSV formula guard, NDJSON) +│ │ │ ├── recovery-store.ts # EmergencyRecoveryService (passwordless data/recovery/emergency-secrets.json) +│ │ │ ├── backup.ts # Async portable AES-256-GCM .gcoord.enc (GCOORD_BACKUP_V1) export/verify/restore +│ │ │ └── backup-scheduler.ts # Scheduled .gcoord.enc backups (local & SFTP) with retention pruning │ │ ├── config/ -│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions) +│ │ │ ├── config-manager.ts # ConfigManager (atomic writes, chokidar hot-reload, revisions, symlink guard) +│ │ │ ├── runtime-limits.ts # Throttle profile presets (low-resource | balanced | unthrottled) │ │ │ ├── presets.ts # Default docker-compose, systemd, os-packages seeds │ │ │ └── diff.ts │ │ ├── ssh/ │ │ │ ├── ssh-pool.ts # SSHPool (coalesced connections, ProxyJump, execStream, openShell, openSftp) -│ │ │ ├── known-hosts.ts # KnownHostsService (strict TOFU, MITM guard, replaceAllKnownHosts) +│ │ │ ├── ssh-config-import.ts # Safe OpenSSH config parser for /api/servers/import-ssh-config +│ │ │ ├── known-hosts.ts # KnownHostsService (strict multi-algo TOFU, MITM guard, replaceAllKnownHosts) │ │ │ ├── key-manager.ts # KeyManager (authorized_keys deploy/revoke, zero-lockout rotation) -│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper & Buffer zeroization -│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, export, reaper) -│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, atomic inline edit, tar archives) -│ │ │ └── tunnel-manager.ts # TunnelManager (http-proxy, local-tcp, remote-tcp) +│ │ │ ├── sudo.ts # POSIX-quoted sudo wrapper, askpass-free pipe & Buffer zeroization +│ │ │ ├── pty-manager.ts # PTYManager (UTF-8 framing, scrollback ring, .cast v2 export, reaper) +│ │ │ ├── sftp-service.ts # SftpService (stream upload/download, touch/chown/search, symlink-safe ops) +│ │ │ └── tunnel-manager.ts # TunnelManager (dual-mode isolated HTTP/WS proxy, SOCKS5, local/remote TCP, TTL) │ │ ├── monitoring/ -│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector +│ │ │ ├── collectors.ts # OS-aware LinuxCollector, BSDCollector, MacOSCollector (+ net/disk I/O) │ │ │ ├── inspector.ts # On-demand ServerInspector (processes, ports, sensors) -│ │ │ ├── probes.ts # ProbeRunner (hub or target forwardOutStream HTTP/TCP probes) -│ │ │ └── monitoring-service.ts # MonitoringService (always-on polling, SQLite rollups, retention) +│ │ │ ├── probes.ts # ProbeRunner (hub egress-guarded HTTP + TLS expiry, target forwardOutStream) +│ │ │ ├── monitoring-service.ts # MonitoringService (staggered/capped polling, SQLite rollups, retention) +│ │ │ └── prometheus.ts # Opt-in Bearer-authenticated Prometheus GET /metrics exporter │ │ ├── systems/ │ │ │ ├── parsers.ts # Output parsers for declarative system discovery/status -│ │ │ └── systems-engine.ts # CustomSystemsEngine (TTL cache, overlays, 3x3 scoped/moded actions) +│ │ │ └── systems-engine.ts # CustomSystemsEngine (bounded TTL cache, overlays, editableFiles, action inputs) │ │ ├── automation/ │ │ │ ├── template.ts # Safe env-var & POSIX single-quoted interpolation + target filtering -│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (128 KB circular WS replay ring) +│ │ │ ├── stream-buffer.ts # BufferedStreamEmitter (capped circular WS replay ring) │ │ │ ├── transfer-engine.ts # TransferEngine (hub-relayed SFTP or direct rsync) -│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG scheduler, croner, event triggers, dry-run) -│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet command execution) +│ │ │ ├── workflow-engine.ts # WorkflowEngine (Kahn DAG, retries, http/notify steps, croner, secret inputs) +│ │ │ └── broadcast-service.ts # BroadcastService (parallel fleet execution + SQLite history & CSV) │ │ ├── alerts/ -│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system rules, silences, webhooks) +│ │ │ └── alert-engine.ts # AlertEngine (metric/disk/offline/probe/system/security-event, egress-guarded webhooks) │ │ ├── ai/ -│ │ │ ├── redactor.ts # collectVaultSecretStrings & redactSecrets +│ │ │ ├── redactor.ts # Linear O(n) collectVaultSecretStrings & redactSecrets │ │ │ ├── guides.ts # AiSurfaceSchema & buildSurfaceGuideAndInventory -│ │ │ └── ai-service.ts # AiService (opt-in /v1/chat/completions, WS streaming, Zod draft check) +│ │ │ └── ai-service.ts # AiService (opt-in egress-guarded /v1/chat/completions, WS streaming, Zod draft check) │ │ └── api/ -│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, replay) +│ │ ├── ws-hub.ts # Multiplexed WebSocket hub (/ws, origin & ticket/session checks, real-time close 4001) │ │ └── routes/ # auth, vault, config, audit, servers, terminal, sftp, tunnels, systems, workflows, snippets, alerts, backup, ai │ └── client/ -│ ├── build.ts # esbuild client/CSS bundler + gzip budget assertions +│ ├── build.ts # esbuild client/CSS bundler + recursive sync-core & lazy-chunk gzip assertions │ ├── index.html # SPA shell + PWA manifest + dynamic theme-color meta │ ├── manifest.json │ ├── icon.svg │ ├── css/ │ │ ├── themes.css # 8 CSS custom-property terminal themes -│ │ └── base.css # Flat sharp styles, dialog/drawer styles, mobile <768px rules +│ │ └── base.css # Flat sharp styles, dialog/drawer/toast/palette styles, mobile <768px rules │ └── ts/ -│ ├── main.ts # Router, nav, topbar indicators, Panic Lock, global state sync -│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText +│ ├── main.ts # Router, nav, view cleanup lifecycle, topbar indicators, Panic Lock, global state sync +│ ├── state.ts # Client store, CLIENT_THEME_IDS, applyTheme, appendBoundedStreamText, registerViewCleanup │ ├── api.ts # Fetch wrapper (CSRF header + auto Vault unlock prompt on 423 VAULT_LOCKED) -│ ├── ws-client.ts # Reconnecting /ws client -│ ├── dialogs.ts # Native modals (multi-factor step-up, confirm, prompts) -│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points) +│ ├── ws-client.ts # Reconnecting /ws client with ref-counted subscribe()/unsubscribe +│ ├── dialogs.ts # Native modals (multi-factor step-up, confirm, collapsible hunk diffs) +│ ├── charts.ts # Flat SVG sparklines & metric charts (viewport-capped points, multi-series overlay) +│ ├── toast.ts # Live toast notification bus (lazy/core feedback helpers) │ ├── webauthn.ts # navigator.credentials base64url helper -│ └── views/ -│ ├── auth-view.ts # Core static views +│ ├── command-palette.ts # Code-split Ctrl/Cmd+K quick switcher & action palette +│ └── views/ # All views dynamically code-split via import(...) +│ ├── auth-view.ts │ ├── dashboard-view.ts │ ├── server-detail-view.ts │ ├── vault-view.ts │ ├── config-view.ts │ ├── settings-view.ts -│ ├── terminal-view.ts # Code-split lazy views (keep dynamically imported!) +│ ├── settings-ops-panel.ts +│ ├── terminal-view.ts │ ├── xterm-runtime.ts │ ├── sftp-view.ts │ ├── tunnels-panel.ts @@ -164,56 +186,67 @@ GCoordinator/ │ └── ai-drawer.ts └── tests/ ├── helpers/mock-ssh-server.ts # In-process ssh2.Server fixture (PTY, SFTP, forwardOut, forwardIn, sudo) - └── *.test.ts # 18 Vitest integration & unit suites + └── *.test.ts # 21 Vitest integration & unit suites ``` --- ## 4. Critical Architectural Invariants (Must Preserve) -### 1. Runtime-Ready Secrets vs. Write-Only Vault Lock (`vault.ts`) +### 1. Runtime-Ready Secrets, `seal()` & Panic Lock (`vault.ts`) - `vaultService.isRuntimeReady` is decoupled from `vaultService.state === 'unlocked'`. -- At server startup (`initRuntime` in `src/server/app.ts`), established secrets are decrypted into memory using `secretFilePath`, `GCOORD_MASTER_KEY`, `data/vault.key` (`0600`), or `data/recovery/emergency-secrets.json`, while `state` begins `'locked'` (write-locked). -- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `/api/backup/export`) **must** check `isRuntimeReady` and read credentials via `getRuntimeSecret(id)` so polling, crons, SFTP, and webhooks work unattended before login and while write-locked. -- Only Vault mutations (adding/editing/deleting credentials), Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`. When write-locked, these endpoints must fail with `HTTP 423 VAULT_LOCKED` (which `src/client/ts/api.ts` intercepts to prompt Vault unlock and retry automatically). -- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`) is the **only** state that zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI sessions, revokes sessions (`WS 4001`), and refuses silent disk/env auto-unlock across restarts until a user manually unlocks with the master key. +- At server startup (`initRuntime` in `src/server/app.ts`), established secrets are decrypted into memory using `secretFilePath`, `GCOORD_MASTER_KEY`, `data/vault.key` (`0600`), or `data/recovery/emergency-secrets.json`, while `state` begins `'locked'` (write-locked). `data/vault.key` is only written for locally generated keys (never mirroring `GCOORD_MASTER_KEY` or Docker secrets unless `GCOORD_AUTO_KEYFILE=true`). +- Background and established-secret consumers (`SSHPool`, `MonitoringService`, `TunnelManager`, `CustomSystemsEngine`, `WorkflowEngine`, `AlertEngine`, `AiService`, `BackupScheduler`, `/api/backup/export`) **must** check `isRuntimeReady` and read credentials via `getRuntimeSecret(id)` so polling, crons, SFTP, and webhooks work unattended before login and while write-locked. +- Only Vault mutations, Ed25519 key generation, raw secret reveals, master-key rotation, and fleet key rotation require `state === 'unlocked'`; write-locked mutations must fail with `HTTP 423 VAULT_LOCKED` (intercepted by `src/client/ts/api.ts`). +- **Explicit Seal (`POST /api/vault/seal` -> `vaultService.seal()`)**: clears runtime secret buffers and pauses active background SSH/monitoring/workflow/tunnel operations **without** revoking admin HTTP/WS sessions. +- **Emergency Panic Lock** (`panicLock()`, persisted via `${vaultFilePath}.panic-locked`): zeroes runtime secret buffers (`isRuntimeReady = false`), tears down active SSH/PTY/tunnel/AI/scheduler sessions, revokes sessions immediately (`WS 4001`), emits a `vault.panic_lock` security event, and refuses silent disk/env auto-unlock across restarts until manually unlocked with the master key. ### 2. Auth, Multi-Factor Strictness, Safe Mode & Passkeys (`auth.ts`, `guards.ts`) -- Supports multiple admin passwords (`admin_passwords`) and multiple TOTPs (`admin_totps`) evaluated in `any` or `all` mode, single-use recovery codes, and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; accessing WebAuthn endpoints over raw IP literals returns `WEBAUTHN_RPID_INVALID`). -- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 1h | 24h | session`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard` rather than hardcoding 5-minute TOTP assumptions. -- All mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token` header, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE` when `session.safeMode` is true; mobile viewports `< 768px` default to Safe Mode ON). Only **Panic Lock** and **`/api/backup/verify`** are Safe-Mode exempt. +- Supports multiple admin passwords (`admin_passwords`), multiple TOTPs (`admin_totps` encrypted at rest with `data/db.key` / `GCOORD_DB_KEY` using `AES-256-GCM`, plus single-use TOTP replay tracking) evaluated in `any` or `all` mode, single-use recovery codes, rate-limited bootstrap (`15m` token TTL), and `@simplewebauthn/server` Passkeys (`webauthn_credentials`; raw IP literals return `WEBAUTHN_RPID_INVALID`). +- Sessions enforce both absolute `sessionTtlHours` and sliding `sessionIdleTimeoutMin`; revoking sessions via logout, password reset, key/2FA reset, or Panic Lock broadcasts real-time `WS 4001` disconnects through `WsHub`. +- `RateLimiter` is SQLite-backed (`rate_limits` table) to persist lockouts across restarts, and `attachClientIp` / Express `trust proxy` only honor forwarding headers when the socket peer matches `TRUSTED_PROXY_CIDRS` (plus loopback when `TRUST_CLOUDFLARE=true`). +- `SecuritySettingsSchema` (`src/shared/schemas/settings.schema.ts`) configures `requireTotpOnLogin`, `stepUpPolicy` (`off | every-action | 5m | 15m | 1h | 24h | session`, default `15m`), `stepUpMethod` (`totp | password | both | passkey`), `elevateOnLogin`, and `keepElevationOnSafeMode`. Always gate elevated endpoints with `createStepUpGuard`. +- Mutating HTTP routes require an authenticated session cookie, matching `X-CSRF-Token`, and Safe Mode enforcement (`HTTP 423 SAFE_MODE_ACTIVE`; mobile `< 768px` defaults to Safe Mode ON). Safe-Mode exemptions are limited to `/api/auth/logout`, `/api/auth/safe-mode`, Panic Lock (`/api/security/panic-lock`), `/api/backup/verify`, read-only AI draft/chat endpoints (all except `/api/ai/save-draft`), `/api/workflows/:id/dry-run`, and live cancellation endpoints (`/api/systems/streams/:jobId/cancel`, `/api/workflows/runs/:runId/cancel`, `/api/workflows/broadcast/:jobId/cancel`). -### 3. Dual Backup Subsystems (`recovery-store.ts` vs. `backup.ts`) -- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains `data/recovery/emergency-secrets.json` (`chmod 0600`) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations. -- **Portable Encrypted Bundles (`backup.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) containing gzipped `config/**` JSONs (including `servers/*.json` `systems[].itemOverrides` / `activeFiles[]`), `vault.enc`, and SQLite `known_hosts` + `alert_silences`. -- **Linux `inotify` Rule on Config Restore**: Whenever swapping or replacing `data/config/` while the server is running (e.g., `/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward; otherwise `chokidar` retains stale directory inodes and stops firing hot-reload events. +### 3. Dual Backup Subsystems (`recovery-store.ts`, `backup.ts`, `backup-scheduler.ts`) +- **Local Emergency Secrets Store (`recovery-store.ts`)**: When `settings.security.enableEmergencySecretsBackup` is enabled, `EmergencyRecoveryService` maintains a **passwordless** `data/recovery/emergency-secrets.json` (`chmod 0600`, Vault/key/TOTP recovery data only—never stores plaintext admin login passwords) plus up to 10 snapshots under `data/recovery/snapshots/`. Keep `syncRecovery()` wired after auth/vault mutations. +- **Portable Encrypted Bundles (`backup.ts` & `backup-scheduler.ts`)**: Creates, verifies, and restores `GCOORD_BACKUP_V1` `.gcoord.enc` bundles encrypted with `AES-256-GCM` (`raw-master-key` or `scrypt` passphrase KDF) via non-blocking async workers (`createBackupBundleAsync`) bounded by `runtimeLimits`, plus scheduled local/SFTP backups with retention pruning. +- **Linux `inotify` Rule on Config Restore**: Whenever replacing `data/config/` while running (`/api/backup/restore`), **always** call `configManager.pauseWatcher()` before replacing the directory and `reloadAllFromDisk()` + `await configManager.resumeWatcher()` afterward so `chokidar` re-attaches cleanly to new directory inodes. -### 4. Config Hot-Reload & SQLite Migrations (`config-manager.ts`, `database.ts`) -- Every config write must be atomic (`tmp -> fsync -> rename`), validated against Zod schemas, and recorded in SQLite `config_revisions` for diff/rollback. Hand-edited invalid config files must remain isolated without crashing the hub or clobbering valid files. -- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`) destructively; add new schema changes as `004_*.ts` and register them in `src/server/db/database.ts`. +### 4. Runtime Throttle Profile & Lightweight Footprint (`runtime-limits.ts`, `settings.schema.ts`) +- `settings.runtime.throttleMode` defaults to `'low-resource'` (sized for single-core 1 vCPU / 1 GB RAM + 2 GB Swap deployments) and supports `'balanced'` and `'unthrottled'` (overrideable via `GCOORD_THROTTLE_MODE`). +- `resolveRuntimeLimits()` governs Argon2id memory/concurrency/queueing (`piscina`/mutex semaphore), `scrypt` concurrency, backup unzip/body limits, SQLite PRAGMAs (`cache_size`, `mmap_size`, `temp_store`), max active/retained PTYs & default scrollback bytes, staggered & concurrency-capped metric polling, parallel systems inspection & cache size, workflow concurrency/targets/queue/log bytes, WS replay buffer sizes, AI stream concurrency, and tunnel socket caps. Always consume limits via `getRuntimeLimits()` rather than hardcoding unbounded concurrency. -### 5. SSH, Shell Quoting, Crypto & Tunnel Proxy Rules -- **No Shell Injection**: Never interpolate user inputs, workflow variables, or parameters directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`src/server/automation/template.ts`) / POSIX single-quoting in `src/server/ssh/sudo.ts` (and zeroize `sudo` password `Buffer`s right after writing to stdin). -- **`ssh2` Ed25519 Keygen Bug**: Always generate Ed25519 keys through `generateValidEd25519KeyPair()` in `src/server/security/vault.ts` (retries around `ssh2`'s ASN.1 leading-`0x00` BitString parser issue). -- **Direct `rsync` Channel Drain**: In `TransferEngine` (`src/server/automation/transfer-engine.ts`), always drain/consume SSH channel `stdout` and `stderr` streams so `close` never deadlocks on full flow-control windows. -- **Reverse Proxy Isolation**: In `src/server/app.ts`, keep `/proxy` mounted **before** `express.json()` and exempt `/proxy/*` from the hub SPA Content-Security-Policy. `TunnelManager` (`src/server/ssh/tunnel-manager.ts`) must keep stripping `gcoord_sid` and `gcoord_csrf` cookies from forwarded headers and rewriting relative `Location` redirects. +### 5. Config Hot-Reload, Symlink Safety & SQLite Migrations (`config-manager.ts`, `database.ts`) +- Every config write uses atomic staging (`tmp -> fsync -> rename`), rejects symlinks across config/backup/CLI file operations, validates against Zod schemas, and records `config_revisions`. Invalid hand-edited config files stay isolated without crashing the hub. +- Never mutate existing migration files (`001_initial.ts`, `002_multi_auth.ts`, `003_phase4_meta.ts`, `004_v1_1.ts`) destructively; add new schema changes as `005_*.ts` and register them in `src/server/db/database.ts`. -### 6. Optional BYO-API AI Assistant (`src/server/ai/`) -- Strictly opt-in: return `403 AI_DISABLED` whenever `settings.ai.enabled === false` and hide `[AI ...]` triggers in the UI unless `isAiEnabled(state)` is true. -- Sanitize all outbound AI prompts and context previews through `redactSecrets()` (`redactor.ts`) seeded with `collectVaultSecretStrings()`. -- Never auto-execute AI-suggested shell commands or auto-save AI-generated JSON/system/workflow drafts—require server Zod `validateDraft`, line diff preview, and explicit user confirmation in `ai-drawer.ts`. +### 6. SSH, Shell Quoting, Egress Guard & Dual-Mode Isolated Proxy (`egress-guard.ts`, `tunnel-manager.ts`) +- **Zero-Trust Egress Guard (`egress-guard.ts`)**: All outbound hub HTTP calls (HTTP probes, webhook deliveries, BYO AI requests, workflow `http` steps) must go through `fetchWithEgressGuard()` / `assertSafeEgressUrl()`, which default-denies loopback, private, link-local, carrier-grade NAT, and cloud-metadata IPs/DNS resolutions, disables automatic redirects (`redirect: 'error'`), and honors explicit `settings.security.egressAllowedCidrs` opt-ins. +- **No Shell Injection**: Never interpolate user inputs, workflow variables, or PTY `cwd` directly into shell strings. Pass inputs via `GCOORD_*` environment variables (`buildWorkflowEnv`, `GCOORD_PARAM_*`) or sanitize explicitly with `interpolateShellCommandSafe()` (`template.ts`), `formatRemoteCd()` (`pty-manager.ts`), and POSIX single-quoting (`sudo.ts`, zeroizing password `Buffer`s immediately after writing). +- **Direct `rsync` & `ssh2` Invariants**: Generate Ed25519 keys via `generateValidEd25519KeyPair()` (`vault.ts`), validate all host-key algorithms in `known-hosts.ts`, drain SSH channel `stdout`/`stderr` streams in `TransferEngine`, and enforce symlink-safe `lstat` checks in `sftp-service.ts`. +- **Dual-Mode Isolated Reverse Proxy (`tunnel-manager.ts`, `app.ts`)**: + - Prefer origin-isolated proxying via `GCOORD_PROXY_PORT` (dedicated local port) or `GCOORD_PROXY_BASE_DOMAIN` (wildcard subdomain), bridged via single-use `/proxy-ticket` redemption into a proxy-scoped `gcoord_proxy_sid` session so proxied target apps cannot share hub origin cookies or storage. + - Same-origin `/proxy` requests are rejected with `HTTP 403 PROXY_ISOLATION_NOT_CONFIGURED` unless `settings.security.allowSameOriginProxy: true` is explicitly enabled. + - Keep `/proxy` mounted before `express.json()`, exempt `/proxy/*` from the hub CSP, strip `gcoord_sid` / `gcoord_csrf` / `gcoord_proxy_sid` cookies upstream, rewrite relative `Location` redirects, and support HTTPS upstream, SOCKS5 (`mode: 'socks5'`), and TTL auto-expiry. + +### 7. Alerts, Prometheus `/metrics` & BYO-API AI (`alerts/`, `prometheus.ts`, `ai/`) +- Alert channels strictly allow only `webhook-secret` Vault credential IDs (preventing arbitrary Vault credential exfiltration in webhook headers/bodies) and dispatch `security-event` alerts emitted by Auth, KnownHosts, and Vault Panic Lock. +- Prometheus `GET /metrics` (`prometheus.ts`) is opt-in (`settings.metrics.prometheusEnabled`) and Bearer-authenticated against `GCOORD_METRICS_TOKEN`, the rotated SHA-256 token hash from `POST /api/config/prometheus-token`, or a Vault `api-token`/`webhook-secret` ref (`404` when disabled, `401` when unauthenticated). +- AI Assistant (`src/server/ai/`): opt-in (`403 AI_DISABLED` when disabled), linear-time `O(n)` secret redaction (`redactor.ts`), and mandatory server Zod `validateDraft` + diff review before saving/running anything. --- ## 5. Frontend, Bundle Budget & Mobile Rules ### Hard Gzip Budgets (`src/client/build.ts` — throws and fails build if exceeded) -- **Core bundle** (`index.html` + `themes.css` + `base.css` + `main.js`): strictly **`< 50.00 KB` gzipped** (currently `25.46 KB`). +- **Core bundle** (`index.html` + `themes.css` + `base.css` + `main.js` + all recursive static ESM imports of `main.js`): strictly **`< 50.00 KB` gzipped** (currently `15.80 KB`). - **Every non-terminal lazy chunk** (`dist/public/chunks/*.js` except `terminal-view-*`): strictly **`< 20.00 KB` gzipped**. -### CRITICAL: Zero Runtime `zod` in Client Code -- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Importing Zod into client TypeScript drags Zod into `main.js` or lazy chunks and breaks the gzip budgets. -- Use `import type { ... } from '../../shared/...'` exclusively, mirror minimal constants cleanly in `src/client/ts/state.ts` (such as `CLIENT_THEME_IDS`), and keep heavy secondary views (`terminal-view`, `sftp-view`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`, `tunnels-panel`) code-split via dynamic `import(...)`. +### CRITICAL: Zero Runtime `zod` & View Lifecycle in Client Code +- **NEVER** import runtime schemas or runtime values from `src/shared/schemas/*` or `zod` anywhere inside `src/client/ts/**`. Use `import type` exclusively and mirror minimal constants cleanly in `src/client/ts/state.ts`. +- Keep **all** views (`auth-view`, `dashboard-view`, `server-detail-view`, `vault-view`, `config-view`, `settings-view`, `settings-ops-panel`, `terminal-view`, `sftp-view`, `tunnels-panel`, `systems-view`, `workflows-view`, `alerts-view`, `ai-drawer`) plus `command-palette.ts` dynamically imported (`import(...)`) so initial core JS stays minimal. +- Every view/panel with timers, DOM window listeners, xterm instances, or dynamic WS channels **must** register teardown via `registerViewCleanup()` (`state.ts`, flushed on navigation by `main.ts`) and use ref-counted `wsClient.subscribe()` cleanup callbacks (which send `{ type: 'unsub' }` when refcount hits 0). ### Flat Sharp Aesthetic & 8 Themes - Maintain the zero-overhead aesthetic: `border-radius: 0`, `1px` crisp borders, zero `box-shadow`, zero gradients, zero `backdrop-filter`. diff --git a/package-lock.json b/package-lock.json index 010f476..d020f50 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "dependencies": { "@simplewebauthn/server": "^13.1.1", "@xterm/addon-fit": "^0.11.0", diff --git a/package.json b/package.json index 24db5a4..ac93c5f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gcoordinator", - "version": "0.1.0", + "version": "1.1.0", "description": "Self-hosted, security-first central sysadmin hub for multiplexed SSH access, monitoring, custom systems, workflows, and alerting.", "type": "module", "engines": {