feat(db,schemas): add migration 004, runtime throttle profile, and v1.1 Zod schemas

This commit is contained in:
tyuXX 2026-11-27 22:15:50 +00:00
parent d7c3e11d7e
commit afc2d6358a
30 changed files with 792 additions and 118 deletions

View file

@ -74,7 +74,7 @@ export interface ClientSecuritySettings {
requireTotpOnLogin: boolean; requireTotpOnLogin: boolean;
passwordMode: 'any' | 'all'; passwordMode: 'any' | 'all';
totpMode: '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'; stepUpMethod: 'totp' | 'password' | 'both' | 'passkey';
elevateOnLogin: boolean; elevateOnLogin: boolean;
keepElevationOnSafeMode: boolean; keepElevationOnSafeMode: boolean;

View file

@ -771,9 +771,9 @@ export class AlertEngine {
ts: number; ts: number;
}, },
): Promise<{ ok: boolean; statusCode?: number; error?: string }> { ): 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) { if (!secret && !channel.url) {
return { ok: false, error: `Missing vault secret "${channel.secretRef}"` }; return { ok: false, error: `Missing vault secret "${channel.secretRef ?? ''}"` };
} }
try { try {

View file

@ -245,6 +245,13 @@ export class WorkflowEngine {
return next ? next.getTime() : null; return next ? next.getTime() : null;
} }
async triggerScheduledCron(workflowId: string): Promise<boolean> {
const job = this.cronJobs.get(workflowId);
if (!job) return false;
await job.trigger();
return true;
}
listWorkflowsWithSummary(): Array<{ listWorkflowsWithSummary(): Array<{
workflow: WorkflowConfig; workflow: WorkflowConfig;
nextRunAt: number | null; nextRunAt: number | null;
@ -632,6 +639,18 @@ export class WorkflowEngine {
continue; 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 matched = resolveTargetServers(step.target, allServers, baseCtx);
const plan: DryRunStepPlan = { const plan: DryRunStepPlan = {
stepId: step.id, 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()); const targets = resolveTargetServers(step.target, allServers, makeCtx());
if (targets.length === 0) { if (targets.length === 0) {
const msg = `No enabled target servers matched step "${step.id}"`; const msg = `No enabled target servers matched step "${step.id}"`;

View file

@ -351,7 +351,7 @@ export class ConfigManager {
const channelIds = new Set(this.alerts.channels.map((c) => c.id)); const channelIds = new Set(this.alerts.channels.map((c) => c.id));
if (this.vault && this.vault.isRuntimeReady) { if (this.vault && this.vault.isRuntimeReady) {
for (const ch of this.alerts.channels) { for (const ch of this.alerts.channels) {
if (!this.vault.hasCredential(ch.secretRef)) { if (ch.secretRef && !this.vault.hasCredential(ch.secretRef)) {
next.push({ next.push({
filePath: 'alerts.json', filePath: 'alerts.json',
code: 'MISSING_CHANNEL_SECRET', code: 'MISSING_CHANNEL_SECRET',

View file

@ -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<ThrottleMode, RuntimeLimits> = {
'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'];
}

View file

@ -1,26 +1,62 @@
import fs from 'node:fs'; import fs from 'node:fs';
import path from 'node:path'; import path from 'node:path';
import Database from 'better-sqlite3'; import Database from 'better-sqlite3';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import { migration001Initial, type Migration } from './migrations/001_initial.js'; import { migration001Initial, type Migration } from './migrations/001_initial.js';
import { migration002MultiAuth } from './migrations/002_multi_auth.js'; import { migration002MultiAuth } from './migrations/002_multi_auth.js';
import { migration003Phase4Meta } from './migrations/003_phase4_meta.js'; import { migration003Phase4Meta } from './migrations/003_phase4_meta.js';
import { migration004V11 } from './migrations/004_v1_1.js';
const MIGRATIONS: Migration[] = [ const MIGRATIONS: Migration[] = [
migration001Initial, migration001Initial,
migration002MultiAuth, migration002MultiAuth,
migration003Phase4Meta, 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<RuntimeLimits, 'sqliteCacheKb' | 'sqliteMmapBytes' | 'sqliteTempStore'>,
): 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 { 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); const db = new Database(dbPath);
db.pragma('journal_mode = WAL'); db.pragma('journal_mode = WAL');
db.pragma('synchronous = NORMAL'); db.pragma('synchronous = NORMAL');
db.pragma('foreign_keys = ON'); db.pragma('foreign_keys = ON');
db.pragma('busy_timeout = 5000'); 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); runMigrations(db);
chmodBestEffort(dbPath, 0o600);
chmodBestEffort(`${dbPath}-wal`, 0o600);
chmodBestEffort(`${dbPath}-shm`, 0o600);
return db; return db;
} }

View file

@ -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);
`);
},
};

View file

@ -179,6 +179,8 @@ function computeElevatedUntil(
return fromLogin ? null : nowMs + 60_000; return fromLogin ? null : nowMs + 60_000;
case '5m': case '5m':
return nowMs + 5 * 60 * 1000; return nowMs + 5 * 60 * 1000;
case '15m':
return nowMs + 15 * 60 * 1000;
case '1h': case '1h':
return nowMs + 60 * 60 * 1000; return nowMs + 60 * 60 * 1000;
case '24h': case '24h':

View file

@ -296,8 +296,7 @@ export class KnownHostsService {
.prepare( .prepare(
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at) `INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
ON CONFLICT(host_port) DO UPDATE SET ON CONFLICT(host_port, algorithm) DO UPDATE SET
algorithm = excluded.algorithm,
fingerprint = excluded.fingerprint, fingerprint = excluded.fingerprint,
updated_at = excluded.updated_at`, updated_at = excluded.updated_at`,
) )

View file

@ -1,15 +1,37 @@
import { z } from 'zod'; import { z } from 'zod';
import { CronExpressionSchema, EntityIdSchema } from './common.js'; import {
CronExpressionSchema,
EntityIdSchema,
HttpUrlSchema,
IanaTimezoneSchema,
} from './common.js';
export const AlertChannelSchema = z.object({ export const AlertChannelSchema = z
.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
type: z.enum(['discord', 'telegram', 'ntfy', 'generic']), type: z.enum(['discord', 'telegram', 'ntfy', 'generic']),
url: z.string().url().optional(), url: HttpUrlSchema.optional(),
secretRef: EntityIdSchema, secretRef: EntityIdSchema.optional(),
chatId: z.string().optional(), chatId: z.string().optional(),
topic: z.string().optional(), topic: z.string().optional(),
enabled: z.boolean().default(true), 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({ export const AlertRuleTargetSchema = z.object({
@ -30,6 +52,14 @@ const AlertRuleBase = {
enabled: z.boolean().default(true), 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', [ export const AlertRuleSchema = z.discriminatedUnion('kind', [
z.object({ z.object({
...AlertRuleBase, ...AlertRuleBase,
@ -60,26 +90,51 @@ export const AlertRuleSchema = z.discriminatedUnion('kind', [
systemId: EntityIdSchema, systemId: EntityIdSchema,
item: z.string().optional(), item: z.string().optional(),
}), }),
z.object({
...AlertRuleBase,
kind: z.literal('security-event'),
events: z.array(SecurityEventKindSchema).min(1),
}),
]); ]);
export const MaintenanceWindowSchema = z.object({ export const MaintenanceWindowSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
cron: CronExpressionSchema, cron: CronExpressionSchema,
timezone: z.string().min(1).default('UTC'), timezone: IanaTimezoneSchema.default('UTC'),
durationMinutes: z.number().int().min(1).max(1440), durationMinutes: z.number().int().min(1).max(1440),
target: AlertRuleTargetSchema.default({ all: true }), target: AlertRuleTargetSchema.default({ all: true }),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
}); });
export const AlertsFileSchema = z.object({ export const AlertsFileSchema = z
.object({
version: z.literal(1).default(1), version: z.literal(1).default(1),
channels: z.array(AlertChannelSchema).default([]), channels: z.array(AlertChannelSchema).default([]),
rules: z.array(AlertRuleSchema).default([]), rules: z.array(AlertRuleSchema).default([]),
maintenanceWindows: z.array(MaintenanceWindowSchema).default([]), maintenanceWindows: z.array(MaintenanceWindowSchema).default([]),
})
.superRefine((doc, ctx) => {
const checkDupes = (items: Array<{ id: string }>, arrPath: string) => {
const seen = new Set<string>();
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<typeof AlertChannelSchema>; export type AlertChannel = z.infer<typeof AlertChannelSchema>;
export type AlertRule = z.infer<typeof AlertRuleSchema>; export type AlertRule = z.infer<typeof AlertRuleSchema>;
export type SecurityEventKind = z.infer<typeof SecurityEventKindSchema>;
export type MaintenanceWindow = z.infer<typeof MaintenanceWindowSchema>; export type MaintenanceWindow = z.infer<typeof MaintenanceWindowSchema>;
export type AlertsFile = z.infer<typeof AlertsFileSchema>; export type AlertsFile = z.infer<typeof AlertsFileSchema>;

View file

@ -5,16 +5,44 @@ export const EntityIdSchema = z
.string() .string()
.min(1, 'ID must not be empty') .min(1, 'ID must not be empty')
.max(64, 'ID must be at most 64 characters') .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 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 export const CronExpressionSchema = z
.string() .string()
.min(1) .min(1)
.superRefine((expr, ctx) => { .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 { try {
new CronPattern(expr); new CronPattern(trimmed);
} catch (err) { } catch (err) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
@ -25,7 +53,7 @@ export const CronExpressionSchema = z
export const InputDefSchema = z.object({ export const InputDefSchema = z.object({
name: EntityIdSchema, 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(), label: z.string().min(1).optional(),
description: z.string().optional(), description: z.string().optional(),
required: z.boolean().default(false), required: z.boolean().default(false),

View file

@ -1,22 +1,42 @@
import { z } from 'zod'; 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({ export const HttpProbeSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
type: z.literal('http'), type: z.literal('http'),
url: z.string().url(), url: HttpUrlSchema,
from: z.enum(['hub', 'target']).default('target'), from: z.enum(['hub', 'target']).default('target'),
intervalSec: z.number().int().min(5).max(86400).default(30), intervalSec: z.number().int().min(5).max(86400).default(30),
timeoutMs: z.number().int().min(200).max(60000).default(5000), timeoutMs: z.number().int().min(200).max(60000).default(5000),
expectedStatus: z.number().int().min(100).max(599).default(200), expectedStatus: z.number().int().min(100).max(599).default(200),
bodyIncludes: z.string().optional(), bodyIncludes: z.string().optional(),
tlsRejectUnauthorized: z.boolean().default(true),
tlsCheckExpiryDays: z.number().int().min(1).max(365).optional(),
enabled: z.boolean().default(true), enabled: z.boolean().default(true),
}); });
export const TcpProbeSchema = z.object({ export const TcpProbeSchema = z.object({
id: EntityIdSchema, id: EntityIdSchema,
type: z.literal('tcp'), type: z.literal('tcp'),
host: z.string().min(1).default('127.0.0.1'), host: SafeHostSchema.default('127.0.0.1'),
port: PortSchema, port: PortSchema,
from: z.enum(['hub', 'target']).default('target'), from: z.enum(['hub', 'target']).default('target'),
intervalSec: z.number().int().min(5).max(86400).default(30), intervalSec: z.number().int().min(5).max(86400).default(30),
@ -40,23 +60,38 @@ export const ServerSystemAttachmentSchema = z.object({
.default({}), .default({}),
}); });
export const ServerTunnelSchema = z.object({ export const ServerTunnelSchema = z
.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp']), mode: z.enum(['http-proxy', 'local-tcp', 'remote-tcp', 'socks5']),
bindHost: z.string().min(1).optional(), bindHost: SafeHostSchema.optional(),
bindPort: PortSchema.optional(), bindPort: PortSchema.optional(),
targetHost: z.string().min(1).default('127.0.0.1'), targetHost: SafeHostSchema.default('127.0.0.1'),
targetPort: PortSchema, 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), 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({ export const ServerConfigSchema = z
.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
host: z.string().min(1), host: SafeHostSchema,
port: PortSchema.default(22), port: PortSchema.default(22),
username: z.string().min(1).max(64), username: SafeUsernameSchema,
credentialId: EntityIdSchema, credentialId: EntityIdSchema,
jumpHostId: EntityIdSchema.optional(), jumpHostId: EntityIdSchema.optional(),
sudoCredentialId: EntityIdSchema.optional(), sudoCredentialId: EntityIdSchema.optional(),
@ -69,6 +104,26 @@ export const ServerConfigSchema = z.object({
systems: z.array(ServerSystemAttachmentSchema).default([]), systems: z.array(ServerSystemAttachmentSchema).default([]),
tunnels: z.array(ServerTunnelSchema).default([]), tunnels: z.array(ServerTunnelSchema).default([]),
enabled: z.boolean().default(true), 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<string>();
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<typeof ServerProbeSchema>; export type ServerProbe = z.infer<typeof ServerProbeSchema>;

View file

@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema } from './common.js'; import { EntityIdSchema, HttpUrlSchema, IanaTimezoneSchema } from './common.js';
export const ThemeIdSchema = z.enum([ export const ThemeIdSchema = z.enum([
'phosphor-green', 'phosphor-green',
@ -14,10 +14,13 @@ export const ThemeIdSchema = z.enum([
export const THEME_IDS = ThemeIdSchema.options; export const THEME_IDS = ThemeIdSchema.options;
export const ThrottleModeSchema = z.enum(['low-resource', 'balanced', 'unthrottled']);
export const StepUpPolicySchema = z.enum([ export const StepUpPolicySchema = z.enum([
'off', 'off',
'every-action', 'every-action',
'5m', '5m',
'15m',
'1h', '1h',
'24h', '24h',
'session', 'session',
@ -29,11 +32,15 @@ export const SecuritySettingsSchema = z.object({
requireTotpOnLogin: z.boolean().default(true), requireTotpOnLogin: z.boolean().default(true),
passwordMode: z.enum(['any', 'all']).default('any'), passwordMode: z.enum(['any', 'all']).default('any'),
totpMode: 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'), stepUpMethod: StepUpMethodSchema.default('totp'),
elevateOnLogin: z.boolean().default(true), elevateOnLogin: z.boolean().default(false),
keepElevationOnSafeMode: z.boolean().default(true), 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({ export const SettingsSchema = z.object({
@ -42,29 +49,68 @@ export const SettingsSchema = z.object({
defaultMobileSafeMode: z.boolean().default(true), defaultMobileSafeMode: z.boolean().default(true),
rawRetentionHours: z.number().int().min(1).max(720).default(48), rawRetentionHours: z.number().int().min(1).max(720).default(48),
rollupRetentionDays: z.number().int().min(1).max(3650).default(30), 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), 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), ptyIdleTtlSec: z.number().int().min(60).max(604800).default(43200),
sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000), sshKeepaliveMs: z.number().int().min(5000).max(120000).default(15000),
sshReadyTimeoutMs: z.number().int().min(3000).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({}), security: SecuritySettingsSchema.default({}),
ai: z ai: z
.object({ .object({
enabled: z.boolean().default(false), 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'), model: z.string().min(1).default('qwen2.5-coder:7b'),
secretRef: EntityIdSchema.optional(), secretRef: EntityIdSchema.optional(),
maxContextChars: z.number().int().min(1000).max(128000).default(16000), 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({ .default({
enabled: false, enabled: false,
baseUrl: 'http://127.0.0.1:11434', baseUrl: 'http://127.0.0.1:11434',
model: 'qwen2.5-coder:7b', model: 'qwen2.5-coder:7b',
maxContextChars: 16000, maxContextChars: 16000,
timeoutSec: 90,
maxTokens: 2048,
}), }),
}); });
export type ThemeId = z.infer<typeof ThemeIdSchema>; export type ThemeId = z.infer<typeof ThemeIdSchema>;
export type ThrottleMode = z.infer<typeof ThrottleModeSchema>;
export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>; export type StepUpPolicy = z.infer<typeof StepUpPolicySchema>;
export type StepUpMethod = z.infer<typeof StepUpMethodSchema>; export type StepUpMethod = z.infer<typeof StepUpMethodSchema>;
export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>; export type SecuritySettings = z.infer<typeof SecuritySettingsSchema>;

View file

@ -7,6 +7,7 @@ export const SnippetSchema = z.object({
description: z.string().optional(), description: z.string().optional(),
command: z.string().min(1), command: z.string().min(1),
tags: z.array(z.string().min(1)).default([]), tags: z.array(z.string().min(1)).default([]),
osFilter: z.array(z.enum(['linux', 'bsd', 'macos'])).optional(),
inputs: z.array(InputDefSchema).default([]), inputs: z.array(InputDefSchema).default([]),
sudo: z.boolean().default(false), sudo: z.boolean().default(false),
confirm: z.boolean().default(false), confirm: z.boolean().default(false),

View file

@ -1,5 +1,5 @@
import { z } from 'zod'; import { z } from 'zod';
import { EntityIdSchema } from './common.js'; import { EntityIdSchema, InputDefSchema } from './common.js';
export const SystemParamDefSchema = z.object({ export const SystemParamDefSchema = z.object({
name: EntityIdSchema, name: EntityIdSchema,
@ -39,7 +39,19 @@ export const SystemStatusSchema = z.object({
command: z.string().min(1), command: z.string().min(1),
parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']), parser: z.enum(['json-lines', 'json', 'lines', 'regex', 'exit-code']),
subItemField: z.string().min(1).optional(), 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(), health: SystemHealthRuleSchema.optional(),
}); });
@ -49,11 +61,14 @@ export const SystemActionSchema = z.object({
scope: z.enum(['system', 'item', 'subitem']), scope: z.enum(['system', 'item', 'subitem']),
mode: z.enum(['oneshot', 'stream', 'interactive']), mode: z.enum(['oneshot', 'stream', 'interactive']),
command: z.string().min(1), command: z.string().min(1),
inputs: z.array(InputDefSchema).default([]),
timeoutSec: z.number().int().min(5).max(3600).optional(),
sudo: z.boolean().default(false), sudo: z.boolean().default(false),
confirm: z.boolean().default(false), confirm: z.boolean().default(false),
}); });
export const SystemConfigSchema = z.object({ export const SystemConfigSchema = z
.object({
id: EntityIdSchema, id: EntityIdSchema,
name: z.string().min(1).max(120), name: z.string().min(1).max(120),
description: z.string().optional(), description: z.string().optional(),
@ -64,6 +79,42 @@ export const SystemConfigSchema = z.object({
status: SystemStatusSchema, status: SystemStatusSchema,
actions: z.array(SystemActionSchema).default([]), actions: z.array(SystemActionSchema).default([]),
editableFiles: z.array(z.string().min(1)).default([]), editableFiles: z.array(z.string().min(1)).default([]),
})
.superRefine((sys, ctx) => {
const paramNames = new Set<string>();
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<string>();
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<typeof SystemParamDefSchema>; export type SystemParamDef = z.infer<typeof SystemParamDefSchema>;

View file

@ -1,5 +1,11 @@
import { z } from 'zod'; import { z } from 'zod';
import { CronExpressionSchema, EntityIdSchema, InputDefSchema } from './common.js'; import {
CronExpressionSchema,
EntityIdSchema,
HttpUrlSchema,
IanaTimezoneSchema,
InputDefSchema,
} from './common.js';
export const WorkflowTargetSchema = z export const WorkflowTargetSchema = z
.object({ .object({
@ -23,12 +29,13 @@ export const StepDependencySchema = z.union([
export const StepFailureActionSchema = z.union([ export const StepFailureActionSchema = z.union([
z.literal('abort'), z.literal('abort'),
z.literal('continue'), z.literal('continue'),
z.string().min(1), EntityIdSchema,
z.object({ z.discriminatedUnion('action', [
action: z.enum(['abort', 'continue', 'notify', 'run-workflow']), z.object({ action: z.literal('abort') }),
channelId: z.string().min(1).optional(), z.object({ action: z.literal('continue') }),
workflowId: EntityIdSchema.optional(), z.object({ action: z.literal('notify'), channelId: EntityIdSchema }),
}), z.object({ action: z.literal('run-workflow'), workflowId: EntityIdSchema }),
]),
]); ]);
const StepBaseFields = { const StepBaseFields = {
@ -36,6 +43,9 @@ const StepBaseFields = {
name: z.string().min(1).max(120).optional(), name: z.string().min(1).max(120).optional(),
dependsOn: z.array(StepDependencySchema).default([]), dependsOn: z.array(StepDependencySchema).default([]),
timeoutSec: z.number().int().min(1).max(86400).optional(), 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), sudo: z.boolean().default(false),
captureAs: z.string().min(1).max(64).optional(), captureAs: z.string().min(1).max(64).optional(),
onFailure: StepFailureActionSchema.optional(), onFailure: StepFailureActionSchema.optional(),
@ -80,6 +90,28 @@ export const TransferStepSchema = z.object({
serverId: z.string().min(1), serverId: z.string().min(1),
path: 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', [ export const WorkflowStepSchema = z.discriminatedUnion('type', [
@ -87,6 +119,8 @@ export const WorkflowStepSchema = z.discriminatedUnion('type', [
ReadFileStepSchema, ReadFileStepSchema,
SystemActionStepSchema, SystemActionStepSchema,
TransferStepSchema, TransferStepSchema,
HttpStepSchema,
NotifyStepSchema,
]); ]);
export const WorkflowTriggerSchema = z.discriminatedUnion('type', [ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
@ -94,7 +128,7 @@ export const WorkflowTriggerSchema = z.discriminatedUnion('type', [
z.object({ z.object({
type: z.literal('cron'), type: z.literal('cron'),
expression: CronExpressionSchema, expression: CronExpressionSchema,
timezone: z.string().min(1).default('UTC'), timezone: IanaTimezoneSchema.default('UTC'),
}), }),
z.object({ z.object({
type: z.literal('event'), type: z.literal('event'),

View file

@ -1,6 +1,7 @@
import { z } from 'zod'; import { z } from 'zod';
export type VaultState = 'uninitialized' | 'locked' | 'unlocked'; export type VaultState = 'uninitialized' | 'locked' | 'unlocked';
export type VaultSealState = 'uninitialized' | 'sealed' | 'write-locked' | 'unlocked';
export type ServerConnectionStatus = export type ServerConnectionStatus =
| 'disconnected' | 'disconnected'
@ -133,6 +134,7 @@ export type ServerWsFrame =
type: 'hello'; type: 'hello';
vaultState: VaultState; vaultState: VaultState;
vaultRuntimeReady?: boolean; vaultRuntimeReady?: boolean;
vaultSealState?: VaultSealState;
safeMode: boolean; safeMode: boolean;
elevatedUntil: number | null; elevatedUntil: number | null;
} }
@ -140,6 +142,7 @@ export type ServerWsFrame =
type: 'vault:state'; type: 'vault:state';
vaultState: VaultState; vaultState: VaultState;
vaultRuntimeReady: boolean; vaultRuntimeReady: boolean;
vaultSealState?: VaultSealState;
isPanicLocked: boolean; isPanicLocked: boolean;
} }
| { | {

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; 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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -225,7 +227,11 @@ describe('Phase 5: Optional BYO-API AI Assistant, Secret Redactor, Surface Guide
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
await api('/api/vault/credentials', { await api('/api/vault/credentials', {

View file

@ -3,7 +3,7 @@ import http from 'node:http';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -152,7 +154,11 @@ describe('Phase 4: AlertEngine, Webhooks, Silences & Maintenance Windows', () =>
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import zlib from 'node:zlib'; import zlib from 'node:zlib';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; 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); expect(health.status).toBe(200);
await expect(openWs(wsUrl, {})).rejects.toThrow('WS_HTTP_401'); 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'); const bootInfo = await api('/api/auth/bootstrap');
expect(bootInfo.status).toBe(200); expect(bootInfo.status).toBe(200);
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
@ -138,6 +140,7 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.setSystemTime(Date.now() + 31_000);
expect(bootDone.status).toBe(201); expect(bootDone.status).toBe(201);
csrfToken = String(bootDone.data.csrfToken); csrfToken = String(bootDone.data.csrfToken);
const recoveryCodes = bootDone.data.recoveryCodes as string[]; 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, (await api('/api/auth/safe-mode', { method: 'POST', body: { enabled: false } })).status,
).toBe(200); ).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: {} }); const vInit = await api('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201); expect(vInit.status).toBe(201);
const generatedMasterKey = String(vInit.data.generatedKeyHex); const generatedMasterKey = String(vInit.data.generatedKeyHex);
// Default balanced mode elevates on bootstrap/login; drop elevation to verify guard enforcement // v1.1 defaults elevateOnLogin=false; step up first, then verify drop-elevation clears it
const statusBeforeDrop = await api('/api/auth/status'); const statusInitial = await api('/api/auth/status');
expect(typeof statusBeforeDrop.data.elevatedUntil).toBe('number'); expect(statusInitial.data.elevatedUntil).toBeNull();
const dropped = await api('/api/auth/drop-elevation', { method: 'POST' });
expect(dropped.status).toBe(200);
expect(dropped.data.elevatedUntil).toBeNull();
const noStepUp = await api('/api/vault/generate-ed25519', { const noStepUp = await api('/api/vault/generate-ed25519', {
method: 'POST', method: 'POST',
@ -223,6 +223,23 @@ describe('Bundle size budget & full-stack Express + WS lifecycle', () => {
}); });
expect(stepUpRes.status).toBe(200); 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', { const genRes = await api('/api/vault/generate-ed25519', {
method: 'POST', method: 'POST',
body: { id: 'prod-key', name: 'Prod Key' }, body: { id: 'prod-key', name: 'Prod Key' },

View file

@ -164,7 +164,7 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
db.close(); 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'] }); vi.useFakeTimers({ toFake: ['Date'] });
const t0 = 1_700_000_010_000; const t0 = 1_700_000_010_000;
vi.setSystemTime(t0); vi.setSystemTime(t0);
@ -180,11 +180,18 @@ describe('AuthService, TOTP Replay, Step-Up, Safe Mode & Guards', () => {
userAgent: 'vitest', 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); const safeSession = auth.setSafeMode(boot.session.idHash, true);
expect(safeSession?.safeMode).toBe(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(); db.close();
}); });

View file

@ -4,7 +4,7 @@ import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { promisify } from 'node:util'; import { promisify } from 'node:util';
import * as OTPAuth from 'otpauth'; 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 { createGCoordinatorServer } from '../src/server/app.js';
import { openDatabase } from '../src/server/db/database.js'; import { openDatabase } from '../src/server/db/database.js';
import { VaultService } from '../src/server/security/vault.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 }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -104,7 +106,11 @@ describe('Phase 5: Portable .gcoord.enc Backup, Verify & Restore (API & gcoord C
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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<string, unknown> }; return { status: res.status, data: data as Record<string, unknown> };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -123,7 +125,11 @@ describe('Phase 3: CustomSystemsEngine (Presets, Overlays, TTL Cache, Actions &
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -192,7 +192,13 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
).status, ).status,
).toBe(201); ).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((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
expect( 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); expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf(); api.clearCsrf();
vi.setSystemTime(t0 + 31_000); vi.setSystemTime(t0 + 62_000);
const anyLogin = await api.call('/api/auth/login', { const anyLogin = await api.call('/api/auth/login', {
method: 'POST', method: 'POST',
body: { body: {
@ -275,7 +281,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
// Logout and test 'all' enforcement // Logout and test 'all' enforcement
expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200); expect((await api.call('/api/auth/logout', { method: 'POST' })).status).toBe(200);
api.clearCsrf(); api.clearCsrf();
vi.setSystemTime(t0 + 62_000); vi.setSystemTime(t0 + 93_000);
const partialPw = await api.call('/api/auth/login', { const partialPw = await api.call('/api/auth/login', {
method: 'POST', method: 'POST',
@ -288,7 +294,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
}); });
expect(partialPw.status).toBe(401); expect(partialPw.status).toBe(401);
vi.setSystemTime(t0 + 93_000); vi.setSystemTime(t0 + 124_000);
const partialTotp = await api.call('/api/auth/login', { const partialTotp = await api.call('/api/auth/login', {
method: 'POST', method: 'POST',
body: { body: {
@ -300,7 +306,7 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
}); });
expect(partialTotp.status).toBe(401); expect(partialTotp.status).toBe(401);
vi.setSystemTime(t0 + 124_000); vi.setSystemTime(t0 + 155_000);
const fullAllLogin = await api.call('/api/auth/login', { const fullAllLogin = await api.call('/api/auth/login', {
method: 'POST', method: 'POST',
body: { 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); let api = createApiClient(server);
const bootInfo = await api.call('/api/auth/bootstrap'); const bootInfo = await api.call('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); 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); expect(boot.status).toBe(201);
const recoveryCodes = boot.data.recoveryCodes as string[]; 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: {} }); const vInit = await api.call('/api/vault/init', { method: 'POST', body: {} });
expect(vInit.status).toBe(201); expect(vInit.status).toBe(201);
const masterKeyHex = String(vInit.data.generatedKeyHex); const masterKeyHex = String(vInit.data.generatedKeyHex);
@ -478,6 +507,11 @@ describe('Configurable Re-Auth Strictness, Multi-Auth Factors & Emergency Secret
).status, ).status,
).toBe(200); ).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', { const wipeRes = await api.call('/api/auth/recovery-backup?disable=1', {
method: 'DELETE', method: 'DELETE',
}); });

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 { createGCoordinatorServer } from '../src/server/app.js';
const cleanups: Array<() => Promise<void> | void> = []; const cleanups: Array<() => Promise<void> | void> = [];
@ -202,6 +202,8 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
return { status: res.status, data }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -226,6 +228,10 @@ describe('WebAuthn Passkey Registration, Login & Step-Up', () => {
}) })
).status, ).status,
).toBe(201); ).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/init', { method: 'POST', body: {} });
await api('/api/vault/generate-ed25519', { await api('/api/vault/generate-ed25519', {

View file

@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js'; import { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.js'; import { MockSshServer } from './helpers/mock-ssh-server.js';
@ -82,6 +82,8 @@ async function setupServerWithSsh() {
return { status: res.status, data: data as Record<string, unknown> }; return { status: res.status, data: data as Record<string, unknown> };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -102,7 +104,11 @@ async function setupServerWithSsh() {
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -2,7 +2,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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 // Bootstrap + Auth + Vault + Ed25519 Key
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -108,6 +110,7 @@ describe('Phase 2 E2E: /api/servers, TOFU, Live Metrics WS, Key Rotation & Panic
secretBase32, secretBase32,
}, },
}); });
vi.useRealTimers();
expect(bootRes.status).toBe(201); expect(bootRes.status).toBe(201);
csrfToken = String(bootRes.data.csrfToken); csrfToken = String(bootRes.data.csrfToken);

View file

@ -4,7 +4,7 @@ import net from 'node:net';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 WebSocket, { WebSocketServer } from 'ws';
import { createGCoordinatorServer } from '../src/server/app.js'; import { createGCoordinatorServer } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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<string, unknown> }; return { status: res.status, data: data as Record<string, unknown> };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -147,7 +149,11 @@ describe('Phase 3: TunnelManager, Authenticated /proxy HTTP+WS & Local/Remote TC
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { const keyRes = await api('/api/vault/generate-ed25519', {

View file

@ -2,7 +2,7 @@ import fs from 'node:fs';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import * as OTPAuth from 'otpauth'; 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 { createGCoordinatorServer, type GCoordinatorInstance } from '../src/server/app.js';
import { MockSshServer } from './helpers/mock-ssh-server.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); let api = createApiClient(activeServer);
const bootInfo = await api.call('/api/auth/bootstrap'); const bootInfo = await api.call('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); 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[]; const recoveryCodes = bootRes.data.recoveryCodes as string[];
expect(recoveryCodes.length).toBeGreaterThan(0); 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 // Explicitly initialize & add SSH key, register server, then lock Vault
expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201); expect((await api.call('/api/vault/init', { method: 'POST', body: {} })).status).toBe(201);
const keyRes = await api.call('/api/vault/generate-ed25519', { 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/inspect')).status).toBe(200);
expect((await api.call('/api/servers/srv-1/sftp/list?path=/')).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 // Modifications and secret reveals must still be blocked with 423 VAULT_LOCKED while locked
const addBlocked = await api.call('/api/vault/credentials', { const addBlocked = await api.call('/api/vault/credentials', {
method: 'POST', method: 'POST',

View file

@ -141,6 +141,8 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
return { status: res.status, data }; return { status: res.status, data };
}; };
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(Date.now() - 35_000);
const bootInfo = await api('/api/auth/bootstrap'); const bootInfo = await api('/api/auth/bootstrap');
const secretBase32 = String(bootInfo.data.secretBase32); const secretBase32 = String(bootInfo.data.secretBase32);
const totp = new OTPAuth.TOTP({ const totp = new OTPAuth.TOTP({
@ -161,7 +163,11 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
initialSafeMode: false, initialSafeMode: false,
}, },
}); });
vi.useRealTimers();
csrfToken = String(boot.data.csrfToken); 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/init', { method: 'POST', body: {} });
const keyRes = await api('/api/vault/generate-ed25519', { 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.status).toBe('cancelled');
expect(dCancelled.run.cancelledBy).toBe('admin'); expect(dCancelled.run.cancelledBy).toBe('admin');
// --- 5. Cron Workflow Scheduling --- // --- 5. Cron Workflow Scheduling (5-field enforced; 6-field rejected) ---
await api('/api/workflows', { 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', method: 'POST',
body: { body: {
id: 'wf-cron-sec', id: 'wf-cron-sec',
name: 'Every Second Cron', name: 'Every Minute Cron',
enabled: true, enabled: true,
trigger: { type: 'cron', expression: '* * * * * *', timezone: 'UTC' }, trigger: { type: 'cron', expression: '* * * * *', timezone: 'UTC' },
overlapPolicy: 'skip', overlapPolicy: 'skip',
display: { mode: 'log' }, display: { mode: 'log' },
inputs: [], inputs: [],
steps: [{ id: 'tick', type: 'exec', target: { serverId: 'srv-b' }, command: 'echo CRON_TICK' }], 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 listSummary = await api('/api/workflows');
const cronSummary = ( const cronSummary = (
@ -776,6 +798,7 @@ describe('Phase 4: Workflows, Snippets, Fleet Broadcast & Cross-Server Transfers
expect(typeof cronSummary?.nextRunAt).toBe('number'); expect(typeof cronSummary?.nextRunAt).toBe('number');
expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000); expect(cronSummary!.nextRunAt!).toBeGreaterThan(Date.now() - 2000);
expect(await server.workflowEngine.triggerScheduledCron('wf-cron-sec')).toBe(true);
const cronRun = await waitFor( const cronRun = await waitFor(
() => { () => {
const runs = server.workflowEngine.listRuns('wf-cron-sec'); const runs = server.workflowEngine.listRuns('wf-cron-sec');