feat(systems): harden CustomSystemsEngine/presets, add systemd editableFiles, parallel inspection & action inputs

This commit is contained in:
tyuXX 2026-11-28 05:02:09 +00:00
parent dbf7144c5d
commit d5822c9eca
5 changed files with 468 additions and 115 deletions

View file

@ -1,4 +1,4 @@
import { Router } from 'express'; import { Router, type RequestHandler } from 'express';
import { z } from 'zod'; import { z } from 'zod';
import type { AuditService } from '../../security/audit.js'; import type { AuditService } from '../../security/audit.js';
import type { AuthService } from '../../security/auth.js'; import type { AuthService } from '../../security/auth.js';
@ -6,6 +6,7 @@ import {
enforceSafeMode, enforceSafeMode,
requireAuth, requireAuth,
requireCsrf, requireCsrf,
requireStepUp,
} from '../../security/guards.js'; } from '../../security/guards.js';
import type { CustomSystemsEngine } from '../../systems/systems-engine.js'; import type { CustomSystemsEngine } from '../../systems/systems-engine.js';
@ -13,11 +14,12 @@ export interface SystemsRouterDeps {
authService: AuthService; authService: AuthService;
auditService: AuditService; auditService: AuditService;
systemsEngine: CustomSystemsEngine; systemsEngine: CustomSystemsEngine;
stepUpGuard?: RequestHandler;
} }
export function createSystemsRouter(deps: SystemsRouterDeps): Router { export function createSystemsRouter(deps: SystemsRouterDeps): Router {
const router = Router(); const router = Router();
const { authService, auditService, systemsEngine } = deps; const { authService, auditService, systemsEngine, stepUpGuard = requireStepUp } = deps;
router.get('/', requireAuth(authService), (_req, res) => { router.get('/', requireAuth(authService), (_req, res) => {
res.json({ systems: systemsEngine.listSystemsOverview() }); res.json({ systems: systemsEngine.listSystemsOverview() });
@ -153,7 +155,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode, enforceSafeMode,
async (req, res) => { (req, res) => {
const systemId = String(req.params.systemId ?? ''); const systemId = String(req.params.systemId ?? '');
const serverId = String(req.params.serverId ?? ''); const serverId = String(req.params.serverId ?? '');
const actionId = String(req.params.actionId ?? ''); const actionId = String(req.params.actionId ?? '');
@ -161,6 +163,7 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
.object({ .object({
itemName: z.string().min(1).optional(), itemName: z.string().min(1).optional(),
subItemName: z.string().min(1).optional(), subItemName: z.string().min(1).optional(),
inputs: z.record(z.unknown()).optional(),
cols: z.number().int().min(10).max(500).optional(), cols: z.number().int().min(10).max(500).optional(),
rows: z.number().int().min(4).max(200).optional(), rows: z.number().int().min(4).max(200).optional(),
}) })
@ -170,43 +173,75 @@ export function createSystemsRouter(deps: SystemsRouterDeps): Router {
return; return;
} }
try { const actionMeta = systemsEngine.getActionMeta(systemId, actionId);
const result = await systemsEngine.executeAction({ const execute = async () => {
serverId, try {
systemId, const result = await systemsEngine.executeAction({
actionId, serverId,
...parsed.data, systemId,
}); actionId,
auditService.log({ ...parsed.data,
action: 'system.action', });
actorIp: req.clientIp ?? 'unknown', const secretInputKeys = new Set(
sessionIdHash: req.authSession!.idHash, (actionMeta?.inputs ?? []).filter((i) => i.type === 'secret').map((i) => i.name),
target: `${serverId}:${systemId}:${actionId}`, );
status: 'ok', const sanitizedInputs = parsed.data.inputs
details: { ? Object.fromEntries(
itemName: parsed.data.itemName, Object.entries(parsed.data.inputs).map(([k, v]) => [
subItemName: parsed.data.subItemName, k,
mode: result.mode, secretInputKeys.has(k) ? '[REDACTED]' : v,
}, ]),
}); )
res.json(result); : undefined;
} catch (err) { auditService.log({
res.status(400).json({ action: 'system.action',
error: 'SYSTEM_ACTION_FAILED', actorIp: req.clientIp ?? 'unknown',
message: err instanceof Error ? err.message : 'Unable to execute system action', sessionIdHash: req.authSession!.idHash,
target: `${serverId}:${systemId}:${actionId}`,
status: 'ok',
details: {
itemName: parsed.data.itemName,
subItemName: parsed.data.subItemName,
inputs: sanitizedInputs,
mode: result.mode,
},
});
res.json(result);
} catch (err) {
res.status(400).json({
error: 'SYSTEM_ACTION_FAILED',
message: err instanceof Error ? err.message : 'Unable to execute system action',
});
}
};
if (actionMeta?.confirm || actionMeta?.sudo) {
stepUpGuard(req, res, () => {
void execute();
}); });
return;
} }
void execute();
}, },
); );
// Cancelling a running stream must work even if Safe Mode was just toggled on
router.post( router.post(
'/streams/:jobId/cancel', '/streams/:jobId/cancel',
requireAuth(authService), requireAuth(authService),
requireCsrf, requireCsrf,
enforceSafeMode,
(req, res) => { (req, res) => {
const jobId = String(req.params.jobId ?? ''); const jobId = String(req.params.jobId ?? '');
res.json({ cancelled: systemsEngine.cancelStream(jobId) }); const cancelled = systemsEngine.cancelStream(jobId);
auditService.log({
action: 'system.stream_cancel',
actorIp: req.clientIp ?? 'unknown',
sessionIdHash: req.authSession!.idHash,
target: jobId,
status: 'ok',
details: { cancelled },
});
res.json({ cancelled });
}, },
); );

View file

@ -194,6 +194,7 @@ export async function createGCoordinatorServer(
vaultService, vaultService,
ptyManager, ptyManager,
wsHub, wsHub,
getRuntimeLimits,
); );
const serverInspector = new ServerInspector(sshPool, configManager); const serverInspector = new ServerInspector(sshPool, configManager);
const probeRunner = new ProbeRunner(sshPool, configManager); const probeRunner = new ProbeRunner(sshPool, configManager);
@ -566,7 +567,12 @@ export async function createGCoordinatorServer(
); );
app.use( app.use(
'/api/systems', '/api/systems',
createSystemsRouter({ authService, auditService, systemsEngine: customSystemsEngine }), createSystemsRouter({
authService,
auditService,
systemsEngine: customSystemsEngine,
stepUpGuard,
}),
); );
app.use( app.use(
'/api/workflows', '/api/workflows',

View file

@ -138,12 +138,12 @@ export const PRESET_SYSTEMS: SystemConfig[] = [
discovery: { discovery: {
type: 'command', type: 'command',
command: command:
'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'{print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }', 'systemctl list-units --type=service --all --no-pager --no-legend --plain | awk \'NF && $1 !~ /^UNIT$/ {print $1}\' | { if [ -n "$GCOORD_PARAM_UNITFILTER" ]; then grep -E -- "$GCOORD_PARAM_UNITFILTER" || true; else cat; fi; }',
parser: 'lines', parser: 'lines',
}, },
status: { status: {
command: command:
'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {gsub(/"/,"\\\\\"",$2); printf "\\"%s\\":\\"%s\\"",$1,$2} END{printf "}\\n"}\'', 'systemctl show "$GCOORD_ITEM_NAME" --property=Id,LoadState,ActiveState,SubState,MainPID,FragmentPath,DropInPaths --no-pager | awk -F= \'BEGIN{printf "{"} NR>1{printf ","} {key=$1; sub(/^[^=]*=/,""); gsub(/\\\\/,"\\\\\\\\"); gsub(/"/,"\\\\\""); gsub(/\\t/," "); printf "\\"%s\\":\\"%s\\"",key,$0} END{printf "}\\n"}\'',
parser: 'json', parser: 'json',
health: { health: {
field: 'ActiveState', field: 'ActiveState',

View file

@ -17,6 +17,7 @@ export interface ParsedStatusResult {
subItems: ParsedSubItem[]; subItems: ParsedSubItem[];
rawSummary: string; rawSummary: string;
exitCode: number | null; exitCode: number | null;
raw?: Record<string, unknown>;
} }
export interface ScannedFolderMatch { export interface ScannedFolderMatch {
@ -25,10 +26,11 @@ export interface ScannedFolderMatch {
} }
export function globToRegExp(pattern: string): RegExp { export function globToRegExp(pattern: string): RegExp {
const escaped = pattern const collapsed = pattern.slice(0, 128).replace(/\*+/g, '*');
const escaped = collapsed
.replace(/[.+^${}()|[\]\\]/g, '\\$&') .replace(/[.+^${}()|[\]\\]/g, '\\$&')
.replace(/\*/g, '.*') .replace(/\*/g, '[^/]*')
.replace(/\?/g, '.'); .replace(/\?/g, '[^/]');
return new RegExp(`^${escaped}$`); return new RegExp(`^${escaped}$`);
} }
@ -314,6 +316,7 @@ export function parseStatusOutput(
subItems: [], subItems: [],
rawSummary: summarizeRecord(rec), rawSummary: summarizeRecord(rec),
exitCode, exitCode,
raw: rec,
}; };
} }
} catch { } catch {
@ -327,15 +330,16 @@ export function parseStatusOutput(
} }
if (statusCfg.parser === 'regex') { if (statusCfg.parser === 'regex') {
const bounded = trimmed.length > 262_144 ? trimmed.slice(0, 262_144) : trimmed;
const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null; const re = statusCfg.regexPattern ? new RegExp(statusCfg.regexPattern, 'm') : null;
const matched = re ? re.test(trimmed) : trimmed.length > 0; const matched = re ? re.test(bounded) : bounded.length > 0;
const exitOk = statusCfg.health?.healthyExitCodes const exitOk = statusCfg.health?.healthyExitCodes
? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode) ? exitCode !== null && statusCfg.health.healthyExitCodes.includes(exitCode)
: exitCode === null || exitCode === 0; : exitCode === null || exitCode === 0;
return { return {
health: exitOk && matched ? 'ok' : 'down', health: exitOk && matched ? 'ok' : 'down',
subItems: [], subItems: [],
rawSummary: trimmed.split(/\r?\n/).slice(0, 4).join(' | '), rawSummary: bounded.split(/\r?\n/).slice(0, 4).join(' | '),
exitCode, exitCode,
}; };
} }

View file

@ -5,6 +5,7 @@ import type { SystemAction, SystemConfig } from '../../shared/schemas/system.sch
import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js'; import { WS_CHANNELS, type ServerWsFrame } from '../../shared/ws-protocol.js';
import type { WsHub } from '../api/ws-hub.js'; import type { WsHub } from '../api/ws-hub.js';
import type { ConfigManager } from '../config/config-manager.js'; import type { ConfigManager } from '../config/config-manager.js';
import type { RuntimeLimits } from '../config/runtime-limits.js';
import type { VaultService } from '../security/vault.js'; import type { VaultService } from '../security/vault.js';
import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js'; import type { PTYManager, PtySessionInfo } from '../ssh/pty-manager.js';
import type { SSHPool } from '../ssh/ssh-pool.js'; import type { SSHPool } from '../ssh/ssh-pool.js';
@ -64,19 +65,65 @@ interface ActiveStreamJob {
bufferBytes: number; bufferBytes: number;
done: boolean; done: boolean;
abort: () => void; abort: () => void;
timeoutTimer?: NodeJS.Timeout;
idleTimer?: NodeJS.Timeout;
} }
const MAX_STREAM_REPLAY_BYTES = 128 * 1024;
const MAX_RETAINED_DONE_STREAMS = 25; const MAX_RETAINED_DONE_STREAMS = 25;
const MAX_DISCOVERED_ITEMS = 500;
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const SUBITEM_SAFE_RE = /^[A-Za-z0-9._][A-Za-z0-9._:@/-]{0,127}$/;
export function isValidRelativeOverlayFile(fileName: string): boolean { export function isValidRelativeOverlayFile(fileName: string): boolean {
const clean = fileName.trim(); const clean = fileName.trim();
if (!clean) return false; if (!clean || clean.length > 255) return false;
if (clean.includes('/') || clean.includes('\\') || clean.includes('..')) return false; if (FORBIDDEN_KEYS.has(clean)) return false;
if (/[\s'"$;|&<>()`]/.test(clean)) return false; if (clean.startsWith('-') || clean.includes('/') || clean.includes('\\') || clean.includes('..')) {
return false;
}
if (/[\x00-\x1f\x7f\s'"$;|&<>()`{}!*?[\]]/.test(clean)) return false;
return /^[A-Za-z0-9._][A-Za-z0-9._+-]*$/.test(clean);
}
function isValidSubItemName(subItem: string): boolean {
const clean = subItem.trim();
if (!clean || clean.startsWith('-') || clean.includes('..')) return false;
if (/[\x00-\x1f\x7f]/.test(clean)) return false;
return SUBITEM_SAFE_RE.test(clean);
}
function isValidAbsolutePath(p: string): boolean {
if (!p.startsWith('/') || p.includes('..')) return false;
if (/[\x00-\x1f\x7f]/.test(p)) return false;
return true; return true;
} }
function assertSafeKey(key: string, label = 'key'): void {
if (!key || FORBIDDEN_KEYS.has(key) || /[\x00-\x1f\x7f]/.test(key)) {
throw new Error(`Unsafe ${label}: "${key}"`);
}
}
async function runPool<T, R>(
items: T[],
concurrency: number,
worker: (item: T) => Promise<R>,
): Promise<R[]> {
if (items.length === 0) return [];
const cap = Math.max(1, Math.min(items.length, concurrency));
const results = new Array<R>(items.length);
let cursor = 0;
const runners = Array.from({ length: cap }, async () => {
while (cursor < items.length) {
const idx = cursor++;
results[idx] = await worker(items[idx]!);
}
});
await Promise.all(runners);
return results;
}
function expandShellRoot(root: string): string { function expandShellRoot(root: string): string {
const trimmed = root.trim(); const trimmed = root.trim();
if (trimmed === '~' || trimmed === '~/') return '"$HOME"'; if (trimmed === '~' || trimmed === '~/') return '"$HOME"';
@ -85,20 +132,27 @@ function expandShellRoot(root: string): string {
} }
function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string { function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: string[]): string {
const safeDepth = Math.max(1, Math.min(5, Math.floor(maxDepth)));
const rootArgs = roots.map(expandShellRoot).join(' '); const rootArgs = roots.map(expandShellRoot).join(' ');
const casePatterns = matchFiles const casePatterns =
.map((p) => p.replace(/[^A-Za-z0-9._*?[\]-]/g, '')) matchFiles
.filter(Boolean) .map((p) => p.replace(/[^A-Za-z0-9._*?-]/g, ''))
.join('|') || '*'; .filter((p) => p && !p.startsWith('-'))
.slice(0, 32)
.join('|') || '*';
return [ return [
`TAB=$(printf '\\t'); CR=$(printf '\\r')`,
`for r in ${rootArgs}; do`, `for r in ${rootArgs}; do`,
` case "$r" in -*) r="./$r" ;; esac`,
` [ -d "$r" ] || continue`, ` [ -d "$r" ] || continue`,
` find "$r" -maxdepth ${maxDepth} -type d 2>/dev/null | while IFS= read -r d; do`, ` find "$r" -maxdepth ${safeDepth} -type d 2>/dev/null | while IFS= read -r d; do`,
` case "$d" in *"$TAB"*|*"$CR"*) continue ;; esac`,
` matched=0`, ` matched=0`,
` for f in "$d"/* "$d"/.*; do`, ` for f in "$d"/* "$d"/.*; do`,
` [ -f "$f" ] || continue`, ` [ -f "$f" ] || continue`,
` b=\${f##*/}`, ` b=\${f##*/}`,
` [ "$b" = "." ] || [ "$b" = ".." ] && continue`,
` case "$b" in`, ` case "$b" in`,
` ${casePatterns}) matched=1; break ;;`, ` ${casePatterns}) matched=1; break ;;`,
` esac`, ` esac`,
@ -116,6 +170,16 @@ function buildFolderScanScript(roots: string[], maxDepth: number, matchFiles: st
].join('\n'); ].join('\n');
} }
function substituteActionInputs(
command: string,
inputs: Record<string, string>,
): string {
return command.replace(/\{\{\s*input\.([a-zA-Z0-9._-]+)\s*\}\}/g, (_match, key: string) => {
assertSafeKey(key, 'input name');
return posixSingleQuote(inputs[key] ?? '');
});
}
export class CustomSystemsEngine { export class CustomSystemsEngine {
private readonly cache = new Map<string, ServerSystemSnapshot>(); private readonly cache = new Map<string, ServerSystemSnapshot>();
private readonly streamJobs = new Map<string, ActiveStreamJob>(); private readonly streamJobs = new Map<string, ActiveStreamJob>();
@ -128,6 +192,7 @@ export class CustomSystemsEngine {
private readonly vaultService: VaultService, private readonly vaultService: VaultService,
private readonly ptyManager: PTYManager, private readonly ptyManager: PTYManager,
private readonly wsHub: WsHub, private readonly wsHub: WsHub,
private readonly getRuntimeLimits?: () => RuntimeLimits,
) {} ) {}
onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void { onHealthSnapshot(listener: (snapshot: ServerSystemSnapshot) => void): () => void {
@ -137,6 +202,11 @@ export class CustomSystemsEngine {
}; };
} }
getActionMeta(systemId: string, actionId: string): SystemAction | undefined {
const sys = this.configManager.getSystem(systemId);
return sys?.actions.find((a) => a.id === actionId);
}
getStreamReplayFrames(jobId: string): ServerWsFrame[] { getStreamReplayFrames(jobId: string): ServerWsFrame[] {
const job = this.streamJobs.get(jobId); const job = this.streamJobs.get(jobId);
return job ? [...job.frames] : []; return job ? [...job.frames] : [];
@ -199,10 +269,12 @@ export class CustomSystemsEngine {
.filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId)) .filter((s) => s.enabled && s.systems.some((a) => a.systemId === systemId))
.filter((s) => !opts.serverId || s.id === opts.serverId); .filter((s) => !opts.serverId || s.id === opts.serverId);
const snapshots = await Promise.all( const concurrency = Math.max(
targets.map((srv) => 1,
this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }), this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2,
), );
const snapshots = await runPool(targets, concurrency, (srv) =>
this.getServerSystem(srv.id, systemId, { forceRefresh: opts.forceRefresh }),
); );
return { system, snapshots }; return { system, snapshots };
@ -247,7 +319,7 @@ export class CustomSystemsEngine {
'ok', 'ok',
), ),
}; };
this.cache.set(cacheKey, snapshot); this.setCacheBounded(cacheKey, snapshot);
this.emitHealth(snapshot); this.emitHealth(snapshot);
return snapshot; return snapshot;
} catch (err) { } catch (err) {
@ -261,16 +333,68 @@ export class CustomSystemsEngine {
items: [], items: [],
systemHealth: 'down', systemHealth: 'down',
}; };
this.emitHealth(snapshot);
return snapshot; return snapshot;
} }
} }
private resolveActionInputs(
action: SystemAction,
suppliedInputs?: Record<string, unknown>,
): { resolved: Record<string, string>; secretNames: Set<string> } {
const supplied = suppliedInputs ?? {};
for (const k of Object.keys(supplied)) {
assertSafeKey(k, 'input parameter');
}
const resolved: Record<string, string> = {};
const secretNames = new Set<string>();
for (const def of action.inputs ?? []) {
assertSafeKey(def.name, 'input definition');
if (def.type === 'secret') secretNames.add(def.name);
let rawVal = Object.hasOwn(supplied, def.name) ? supplied[def.name] : def.default;
if (rawVal === undefined || rawVal === null || rawVal === '') {
if (def.required) {
throw new Error(`Missing required input "${def.name}" for action "${action.id}"`);
}
continue;
}
if (def.type === 'number') {
const n = Number(rawVal);
if (!Number.isFinite(n)) {
throw new Error(`Input "${def.name}" must be a finite number`);
}
rawVal = String(n);
} else if (def.type === 'boolean') {
rawVal = rawVal === true || rawVal === 'true' ? 'true' : 'false';
} else {
const str = String(rawVal);
if (/[\x00]/.test(str)) {
throw new Error(`Input "${def.name}" contains NUL bytes`);
}
if (def.type === 'select' && def.options && def.options.length > 0) {
if (!def.options.includes(str)) {
throw new Error(`Input "${def.name}" value is not in allowed options`);
}
}
rawVal = str;
}
resolved[def.name] = String(rawVal);
}
return { resolved, secretNames };
}
private resolveActionContext(params: { private resolveActionContext(params: {
serverId: string; serverId: string;
systemId: string; systemId: string;
actionId: string; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
}) { }) {
return (async () => { return (async () => {
const system = this.configManager.getSystem(params.systemId); const system = this.configManager.getSystem(params.systemId);
@ -287,7 +411,13 @@ export class CustomSystemsEngine {
throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`); throw new Error(`Action "${params.actionId}" not found in system "${system.id}"`);
} }
if (params.itemName) assertSafeKey(params.itemName, 'itemName');
if (params.subItemName && !isValidSubItemName(params.subItemName)) {
throw new Error(`Invalid subItemName "${params.subItemName}"`);
}
const resolvedParams = this.resolveParams(system, attachment.params); const resolvedParams = this.resolveParams(system, attachment.params);
const { resolved: actionInputs } = this.resolveActionInputs(action, params.inputs);
let item: DiscoveredSystemItem | undefined; let item: DiscoveredSystemItem | undefined;
if (action.scope === 'item' || action.scope === 'subitem') { if (action.scope === 'item' || action.scope === 'subitem') {
@ -299,8 +429,18 @@ export class CustomSystemsEngine {
if (!item) { if (!item) {
throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`); throw new Error(`Item "${params.itemName}" not found under ${server.id}/${system.id}`);
} }
if (action.scope === 'subitem' && !params.subItemName) { if (action.scope === 'subitem') {
throw new Error(`Action "${action.id}" requires subItemName`); if (!params.subItemName) {
throw new Error(`Action "${action.id}" requires subItemName`);
}
if (
item.status.subItems.length > 0 &&
!item.status.subItems.some((s) => s.name === params.subItemName)
) {
throw new Error(
`Sub-item "${params.subItemName}" was not discovered under "${item.name}"`,
);
}
} }
} }
@ -310,13 +450,15 @@ export class CustomSystemsEngine {
resolvedParams, resolvedParams,
item, item,
params.subItemName, params.subItemName,
actionInputs,
); );
const substitutedCmd = substituteActionInputs(action.command, actionInputs);
const execCmd = item?.dir const execCmd = item?.dir
? `cd -- ${posixSingleQuote(item.dir)} && ${action.command}` ? `cd -- ${posixSingleQuote(item.dir)} && ${substitutedCmd}`
: action.command; : substitutedCmd;
return { system, server, action, item, env, execCmd }; return { system, server, action, item, env, execCmd, substitutedCmd };
})(); })();
} }
@ -326,6 +468,7 @@ export class CustomSystemsEngine {
actionId: string; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
timeoutMs?: number; timeoutMs?: number;
signal?: AbortSignal; signal?: AbortSignal;
onChunk?: (stream: 'stdout' | 'stderr', text: string) => void; onChunk?: (stream: 'stdout' | 'stderr', text: string) => void;
@ -344,7 +487,7 @@ export class CustomSystemsEngine {
throw new Error('Interactive PTY actions cannot run unattended in workflows'); throw new Error('Interactive PTY actions cannot run unattended in workflows');
} }
const timeoutMs = params.timeoutMs ?? 300_000; const timeoutMs = params.timeoutMs ?? (action.timeoutSec ?? 300) * 1000;
const started = Date.now(); const started = Date.now();
const handle = await this.sshPool.execStream(server.id, execCmd, { const handle = await this.sshPool.execStream(server.id, execCmd, {
env, env,
@ -434,17 +577,18 @@ export class CustomSystemsEngine {
actionId: string; actionId: string;
itemName?: string; itemName?: string;
subItemName?: string; subItemName?: string;
inputs?: Record<string, unknown>;
cols?: number; cols?: number;
rows?: number; rows?: number;
}): Promise<ActionExecutionResult> { }): Promise<ActionExecutionResult> {
const { system, server, action, item, env, execCmd } = const { system, server, action, item, env, execCmd, substitutedCmd } =
await this.resolveActionContext(params); await this.resolveActionContext(params);
if (action.mode === 'oneshot') { if (action.mode === 'oneshot') {
const res = await this.sshPool.exec(server.id, execCmd, { const res = await this.sshPool.exec(server.id, execCmd, {
env, env,
sudo: action.sudo, sudo: action.sudo,
timeoutMs: 120_000, timeoutMs: (action.timeoutSec ?? 120) * 1000,
}); });
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
return { return {
@ -460,7 +604,7 @@ export class CustomSystemsEngine {
const session = await this.ptyManager.openSession({ const session = await this.ptyManager.openSession({
serverId: server.id, serverId: server.id,
cwd: item?.dir, cwd: item?.dir,
command: action.command, command: substitutedCmd,
env, env,
sudo: action.sudo, sudo: action.sudo,
cols: params.cols, cols: params.cols,
@ -471,13 +615,14 @@ export class CustomSystemsEngine {
return { mode: 'interactive', session }; return { mode: 'interactive', session };
} }
// Stream mode // Stream mode with timeout & idle reaper
const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`; const jobId = `stream-${crypto.randomBytes(6).toString('hex')}`;
const handle = await this.sshPool.execStream(server.id, execCmd, { const handle = await this.sshPool.execStream(server.id, execCmd, {
env, env,
sudo: action.sudo, sudo: action.sudo,
}); });
const maxReplayBytes = this.getRuntimeLimits?.().streamReplayBytes ?? 128 * 1024;
const job: ActiveStreamJob = { const job: ActiveStreamJob = {
jobId, jobId,
serverId: server.id, serverId: server.id,
@ -489,12 +634,23 @@ export class CustomSystemsEngine {
}; };
this.streamJobs.set(jobId, job); this.streamJobs.set(jobId, job);
const clearJobTimers = () => {
if (job.timeoutTimer) {
clearTimeout(job.timeoutTimer);
job.timeoutTimer = undefined;
}
if (job.idleTimer) {
clearTimeout(job.idleTimer);
job.idleTimer = undefined;
}
};
const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => { const pushFrame = (stream: 'stdout' | 'stderr' | 'meta', data: string) => {
const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data }; const frame: ServerWsFrame = { type: 'stream:chunk', jobId, stream, data };
const bytes = Buffer.byteLength(data, 'utf8'); const bytes = Buffer.byteLength(data, 'utf8');
job.frames.push(frame); job.frames.push(frame);
job.bufferBytes += bytes; job.bufferBytes += bytes;
while (job.bufferBytes > MAX_STREAM_REPLAY_BYTES && job.frames.length > 0) { while (job.bufferBytes > maxReplayBytes && job.frames.length > 0) {
const dropped = job.frames.shift()!; const dropped = job.frames.shift()!;
if (dropped.type === 'stream:chunk') { if (dropped.type === 'stream:chunk') {
job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8'); job.bufferBytes -= Buffer.byteLength(dropped.data, 'utf8');
@ -503,6 +659,28 @@ export class CustomSystemsEngine {
this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame); this.wsHub.broadcastChannel(WS_CHANNELS.stream(jobId), frame);
}; };
const maxStreamMs = (action.timeoutSec ?? 600) * 1000;
job.timeoutTimer = setTimeout(() => {
if (job.done) return;
pushFrame(
'meta',
JSON.stringify({ event: 'timeout', message: `Stream exceeded ${maxStreamMs}ms limit` }),
);
handle.abort();
}, maxStreamMs);
job.timeoutTimer.unref();
const bumpIdleTimer = () => {
if (job.idleTimer) clearTimeout(job.idleTimer);
job.idleTimer = setTimeout(() => {
if (job.done) return;
pushFrame('meta', JSON.stringify({ event: 'timeout', message: 'Stream idle timeout' }));
handle.abort();
}, Math.min(maxStreamMs, 300_000));
job.idleTimer.unref();
};
bumpIdleTimer();
pushFrame( pushFrame(
'meta', 'meta',
JSON.stringify({ JSON.stringify({
@ -516,21 +694,25 @@ export class CustomSystemsEngine {
); );
handle.channel.on('data', (chunk: Buffer) => { handle.channel.on('data', (chunk: Buffer) => {
bumpIdleTimer();
pushFrame('stdout', chunk.toString('utf8')); pushFrame('stdout', chunk.toString('utf8'));
}); });
handle.channel.stderr?.on('data', (chunk: Buffer) => { handle.channel.stderr?.on('data', (chunk: Buffer) => {
bumpIdleTimer();
pushFrame('stderr', chunk.toString('utf8')); pushFrame('stderr', chunk.toString('utf8'));
}); });
void handle.done void handle.done
.then(({ exitCode, signal }) => { .then(({ exitCode, signal }) => {
job.done = true; job.done = true;
clearJobTimers();
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal })); pushFrame('meta', JSON.stringify({ event: 'exit', exitCode, signal }));
this.pruneStreamJobs(); this.pruneStreamJobs();
}) })
.catch((err) => { .catch((err) => {
job.done = true; job.done = true;
clearJobTimers();
this.invalidateCache(server.id, system.id); this.invalidateCache(server.id, system.id);
pushFrame( pushFrame(
'meta', 'meta',
@ -556,10 +738,11 @@ export class CustomSystemsEngine {
throw new Error(`Unknown server "${serverId}" or system "${systemId}"`); throw new Error(`Unknown server "${serverId}" or system "${systemId}"`);
} }
const validatedParams = this.validateAndResolveParamsStrict(system, params);
const existing = server.systems.find((a) => a.systemId === systemId); const existing = server.systems.find((a) => a.systemId === systemId);
const nextSystems = existing const nextSystems = existing
? server.systems.map((a) => (a.systemId === systemId ? { ...a, params } : a)) ? server.systems.map((a) => (a.systemId === systemId ? { ...a, params: validatedParams } : a))
: [...server.systems, { systemId, params, itemOverrides: {} }]; : [...server.systems, { systemId, params: validatedParams, itemOverrides: {} }];
const updated: ServerConfig = { ...server, systems: nextSystems }; const updated: ServerConfig = { ...server, systems: nextSystems };
this.configManager.saveConfigText( this.configManager.saveConfigText(
@ -599,18 +782,38 @@ export class CustomSystemsEngine {
itemName: string, itemName: string,
activeFiles: string[], activeFiles: string[],
): ServerConfig { ): ServerConfig {
assertSafeKey(itemName, 'itemName');
const system = this.configManager.getSystem(systemId);
const server = this.configManager.getServer(serverId); const server = this.configManager.getServer(serverId);
if (!server) { if (!system || !server) {
throw new Error(`Unknown server "${serverId}"`); throw new Error(`Unknown server "${serverId}" or system "${systemId}"`);
} }
const cleanFiles = activeFiles.map((f) => f.trim()).filter(Boolean); const cleanFiles = [...new Set(activeFiles.map((f) => f.trim()).filter(Boolean))];
if (cleanFiles.length === 0) { if (cleanFiles.length === 0) {
throw new Error('At least one active file must be selected'); throw new Error('At least one active file must be selected');
} }
const cachedItem = this.cache
.get(`${serverId}:${systemId}`)
?.items.find((i) => i.name === itemName);
const selectableRegexes =
system.discovery.type === 'folder-scan'
? (system.discovery.selectableFiles ?? system.discovery.matchFiles).map(globToRegExp)
: [];
for (const file of cleanFiles) { for (const file of cleanFiles) {
if (!isValidRelativeOverlayFile(file)) { if (!isValidRelativeOverlayFile(file)) {
throw new Error(`Invalid overlay filename: "${file}"`); throw new Error(`Invalid overlay filename: "${file}"`);
} }
if (cachedItem && cachedItem.selectableFiles.length > 0) {
if (!cachedItem.selectableFiles.includes(file)) {
throw new Error(`Overlay file "${file}" was not discovered for item "${itemName}"`);
}
} else if (selectableRegexes.length > 0) {
if (!selectableRegexes.some((re) => re.test(file))) {
throw new Error(`Overlay file "${file}" does not match selectableFiles patterns`);
}
}
} }
const hasAtt = server.systems.some((a) => a.systemId === systemId); const hasAtt = server.systems.some((a) => a.systemId === systemId);
@ -620,20 +823,20 @@ export class CustomSystemsEngine {
const updated: ServerConfig = { const updated: ServerConfig = {
...server, ...server,
systems: server.systems.map((att) => systems: server.systems.map((att) => {
att.systemId === systemId if (att.systemId !== systemId) return att;
? { const safeOverrides: Record<string, { activeFiles?: string[]; [k: string]: unknown }> =
...att, Object.create(null);
itemOverrides: { for (const [k, v] of Object.entries(att.itemOverrides ?? {})) {
...att.itemOverrides, if (FORBIDDEN_KEYS.has(k)) continue;
[itemName]: { safeOverrides[k] = v;
...(att.itemOverrides[itemName] ?? {}), }
activeFiles: cleanFiles, safeOverrides[itemName] = {
}, ...(Object.hasOwn(att.itemOverrides, itemName) ? att.itemOverrides[itemName] : {}),
}, activeFiles: cleanFiles,
} };
: att, return { ...att, itemOverrides: safeOverrides };
), }),
}; };
this.configManager.saveConfigText( this.configManager.saveConfigText(
@ -679,6 +882,8 @@ export class CustomSystemsEngine {
for (const job of this.streamJobs.values()) { for (const job of this.streamJobs.values()) {
if (!job.done) { if (!job.done) {
job.done = true; job.done = true;
if (job.timeoutTimer) clearTimeout(job.timeoutTimer);
if (job.idleTimer) clearTimeout(job.idleTimer);
job.abort(); job.abort();
} }
} }
@ -690,6 +895,17 @@ export class CustomSystemsEngine {
this.cache.clear(); this.cache.clear();
} }
private setCacheBounded(key: string, snapshot: ServerSystemSnapshot): void {
const maxEntries = Math.max(8, this.getRuntimeLimits?.().maxSystemCacheEntries ?? 64);
if (this.cache.has(key)) this.cache.delete(key);
this.cache.set(key, snapshot);
while (this.cache.size > maxEntries) {
const oldestKey = this.cache.keys().next().value;
if (!oldestKey) break;
this.cache.delete(oldestKey);
}
}
private async discoverAndInspectItems( private async discoverAndInspectItems(
server: ServerConfig, server: ServerConfig,
system: SystemConfig, system: SystemConfig,
@ -697,6 +913,10 @@ export class CustomSystemsEngine {
params: Record<string, unknown>, params: Record<string, unknown>,
): Promise<DiscoveredSystemItem[]> { ): Promise<DiscoveredSystemItem[]> {
const baseEnv = this.buildExecutionEnv(server.id, system.id, params); const baseEnv = this.buildExecutionEnv(server.id, system.id, params);
const concurrency = Math.max(
1,
this.getRuntimeLimits?.().maxParallelSystemInspect ?? 2,
);
if (system.discovery.type === 'folder-scan') { if (system.discovery.type === 'folder-scan') {
const rawRoots = params[system.discovery.rootsParam]; const rawRoots = params[system.discovery.rootsParam];
@ -713,7 +933,7 @@ export class CustomSystemsEngine {
system.discovery.matchFiles, system.discovery.matchFiles,
); );
const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv }); const scanRes = await this.sshPool.exec(server.id, script, { env: baseEnv });
const rawMatches = parseFolderScanOutput(scanRes.stdout); const rawMatches = parseFolderScanOutput(scanRes.stdout).slice(0, MAX_DISCOVERED_ITEMS);
const matchRegexes = system.discovery.matchFiles.map(globToRegExp); const matchRegexes = system.discovery.matchFiles.map(globToRegExp);
const selectableRegexes = ( const selectableRegexes = (
@ -724,33 +944,45 @@ export class CustomSystemsEngine {
.map(globToRegExp); .map(globToRegExp);
const usedNames = new Map<string, number>(); const usedNames = new Map<string, number>();
const items: DiscoveredSystemItem[] = []; const draftItems: DiscoveredSystemItem[] = [];
for (const m of rawMatches) { for (const m of rawMatches) {
const matchedFiles = m.files.filter((f) => matchRegexes.some((re) => re.test(f))); if (/[\x00-\x1f\x7f]/.test(m.dir)) continue;
const safeFiles = m.files.filter(
(f) => !/[\x00-\x1f\x7f]/.test(f) && !f.startsWith('-'),
);
const matchedFiles = safeFiles.filter((f) => matchRegexes.some((re) => re.test(f)));
if (matchedFiles.length === 0) continue; if (matchedFiles.length === 0) continue;
let baseName = path.posix.basename(m.dir) || 'root'; let baseName = path.posix.basename(m.dir) || 'root';
if (FORBIDDEN_KEYS.has(baseName)) baseName = `item-${baseName}`;
const seenCount = (usedNames.get(baseName) ?? 0) + 1; const seenCount = (usedNames.get(baseName) ?? 0) + 1;
usedNames.set(baseName, seenCount); usedNames.set(baseName, seenCount);
if (seenCount > 1) { if (seenCount > 1) {
baseName = `${baseName}-${seenCount}`; baseName = `${baseName}-${seenCount}`;
} }
const selectableFiles = m.files.filter((f) => selectableRegexes.some((re) => re.test(f))); const selectableFiles = safeFiles.filter(
const editableFiles = m.files (f) => isValidRelativeOverlayFile(f) && selectableRegexes.some((re) => re.test(f)),
);
const editableFiles = safeFiles
.filter((f) => editableRegexes.some((re) => re.test(f))) .filter((f) => editableRegexes.some((re) => re.test(f)))
.map((f) => path.posix.join(m.dir, f)); .map((f) => path.posix.join(m.dir, f));
const overrideFiles = attachment.itemOverrides[baseName]?.activeFiles?.filter((f) => const overrideRaw = Object.hasOwn(attachment.itemOverrides, baseName)
isValidRelativeOverlayFile(f), ? attachment.itemOverrides[baseName]?.activeFiles
: undefined;
const overrideFiles = overrideRaw?.filter(
(f) =>
isValidRelativeOverlayFile(f) &&
(selectableFiles.length === 0 || selectableFiles.includes(f)),
); );
const activeFiles = const activeFiles =
overrideFiles && overrideFiles.length > 0 overrideFiles && overrideFiles.length > 0
? overrideFiles ? overrideFiles
: [matchedFiles[0]!]; : [matchedFiles[0]!];
const draftItem: DiscoveredSystemItem = { draftItems.push({
name: baseName, name: baseName,
dir: m.dir, dir: m.dir,
activeFiles, activeFiles,
@ -762,12 +994,14 @@ export class CustomSystemsEngine {
rawSummary: '', rawSummary: '',
exitCode: null, exitCode: null,
}, },
}; });
}
await runPool(draftItems, concurrency, async (draftItem) => {
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
const statusRes = await this.sshPool.exec( const statusRes = await this.sshPool.exec(
server.id, server.id,
`cd -- ${posixSingleQuote(m.dir)} && ${system.status.command}`, `cd -- ${posixSingleQuote(draftItem.dir!)} && ${system.status.command}`,
{ env: itemEnv }, { env: itemEnv },
); );
draftItem.status = parseStatusOutput( draftItem.status = parseStatusOutput(
@ -776,32 +1010,33 @@ export class CustomSystemsEngine {
statusRes.exitCode, statusRes.exitCode,
system.status, system.status,
); );
items.push(draftItem); });
}
return items; return draftItems;
} }
// command discovery // command discovery
const discRes = await this.sshPool.exec(server.id, system.discovery.command, { const discRes = await this.sshPool.exec(server.id, system.discovery.command, {
env: baseEnv, env: baseEnv,
}); });
const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser); const names = parseDiscoveryOutput(discRes.stdout, system.discovery.parser)
const items: DiscoveredSystemItem[] = []; .filter((n) => !FORBIDDEN_KEYS.has(n) && !/[\x00-\x1f\x7f]/.test(n))
.slice(0, MAX_DISCOVERED_ITEMS);
for (const itemName of names) { const draftItems: DiscoveredSystemItem[] = names.map((itemName) => ({
const draftItem: DiscoveredSystemItem = { name: itemName,
name: itemName, activeFiles: [],
activeFiles: [], selectableFiles: [],
selectableFiles: [], editableFiles: [],
editableFiles: [], status: {
status: { health: 'unknown',
health: 'unknown', subItems: [],
subItems: [], rawSummary: '',
rawSummary: '', exitCode: null,
exitCode: null, },
}, }));
};
await runPool(draftItems, concurrency, async (draftItem) => {
const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem); const itemEnv = this.buildExecutionEnv(server.id, system.id, params, draftItem);
const statusRes = await this.sshPool.exec(server.id, system.status.command, { const statusRes = await this.sshPool.exec(server.id, system.status.command, {
env: itemEnv, env: itemEnv,
@ -812,25 +1047,88 @@ export class CustomSystemsEngine {
statusRes.exitCode, statusRes.exitCode,
system.status, system.status,
); );
items.push(draftItem);
}
return items; // Populate editableFiles dynamically from systemd FragmentPath / DropInPaths when present
const raw = draftItem.status.raw;
if (raw) {
const dynamicPaths: string[] = [];
if (typeof raw.FragmentPath === 'string' && isValidAbsolutePath(raw.FragmentPath.trim())) {
dynamicPaths.push(raw.FragmentPath.trim());
}
if (typeof raw.DropInPaths === 'string') {
for (const dp of raw.DropInPaths.trim().split(/\s+/)) {
if (dp && isValidAbsolutePath(dp)) dynamicPaths.push(dp);
}
}
if (dynamicPaths.length > 0) {
draftItem.editableFiles = [...new Set(dynamicPaths)];
}
}
});
return draftItems;
}
private validateAndResolveParamsStrict(
system: SystemConfig,
supplied: Record<string, unknown>,
): Record<string, unknown> {
for (const k of Object.keys(supplied)) {
assertSafeKey(k, 'param name');
}
const out: Record<string, unknown> = Object.create(null);
for (const def of system.params) {
assertSafeKey(def.name, 'param definition');
const hasVal = Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined;
const val = hasVal ? supplied[def.name] : def.default;
if (val === undefined) {
if (def.required) {
throw new Error(`Missing required system param "${def.name}"`);
}
continue;
}
if (def.type === 'string') {
if (typeof val !== 'string' || /[\x00]/.test(val)) {
throw new Error(`Param "${def.name}" must be a valid string`);
}
out[def.name] = val;
} else if (def.type === 'number') {
const num = typeof val === 'number' ? val : Number(val);
if (!Number.isFinite(num)) {
throw new Error(`Param "${def.name}" must be a finite number`);
}
out[def.name] = num;
} else if (def.type === 'boolean') {
if (typeof val !== 'boolean') {
throw new Error(`Param "${def.name}" must be a boolean`);
}
out[def.name] = val;
} else if (def.type === 'string[]') {
if (!Array.isArray(val) || !val.every((x) => typeof x === 'string' && !/[\x00]/.test(x))) {
throw new Error(`Param "${def.name}" must be an array of strings`);
}
out[def.name] = [...val];
}
}
return { ...out };
} }
private resolveParams( private resolveParams(
system: SystemConfig, system: SystemConfig,
supplied: Record<string, unknown>, supplied: Record<string, unknown>,
): Record<string, unknown> { ): Record<string, unknown> {
const out: Record<string, unknown> = {}; const out: Record<string, unknown> = Object.create(null);
for (const def of system.params) { for (const def of system.params) {
if (supplied[def.name] !== undefined) { if (FORBIDDEN_KEYS.has(def.name)) continue;
if (Object.hasOwn(supplied, def.name) && supplied[def.name] !== undefined) {
out[def.name] = supplied[def.name]; out[def.name] = supplied[def.name];
} else if (def.default !== undefined) { } else if (def.default !== undefined) {
out[def.name] = structuredClone(def.default); out[def.name] = structuredClone(def.default);
} }
} }
return out; return { ...out };
} }
private buildExecutionEnv( private buildExecutionEnv(
@ -839,6 +1137,7 @@ export class CustomSystemsEngine {
params: Record<string, unknown>, params: Record<string, unknown>,
item?: DiscoveredSystemItem, item?: DiscoveredSystemItem,
subItem?: string, subItem?: string,
actionInputs?: Record<string, string>,
): Record<string, string> { ): Record<string, string> {
const env: Record<string, string> = { const env: Record<string, string> = {
GCOORD_SERVER_ID: serverId, GCOORD_SERVER_ID: serverId,
@ -846,10 +1145,19 @@ export class CustomSystemsEngine {
}; };
for (const [k, v] of Object.entries(params)) { for (const [k, v] of Object.entries(params)) {
if (FORBIDDEN_KEYS.has(k)) continue;
const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`; const envKey = `GCOORD_PARAM_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`;
env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? ''); env[envKey] = Array.isArray(v) ? v.map((x) => String(x)).join('\n') : String(v ?? '');
} }
if (actionInputs) {
for (const [k, v] of Object.entries(actionInputs)) {
if (FORBIDDEN_KEYS.has(k)) continue;
const envKey = `GCOORD_INPUT_${k.replace(/[^A-Za-z0-9]/g, '_').toUpperCase()}`;
env[envKey] = v;
}
}
if (item) { if (item) {
env.GCOORD_ITEM_NAME = item.name; env.GCOORD_ITEM_NAME = item.name;
if (item.dir) { if (item.dir) {