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