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

View file

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

View file

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

View file

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

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