GCoordinator/src/server/automation/template.ts

385 lines
12 KiB
TypeScript

import type { InputDef } from '../../shared/schemas/common.js';
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import { posixSingleQuote } from '../ssh/sudo.js';
export interface StepOutputSummary {
stdout: string;
exitCode: number | null;
}
export interface TemplateContext {
workflowId?: string;
runId?: string;
triggerSource?: string;
serverId?: string;
serverMeta?: { id: string; name: string; host: string; port: number };
inputs: Record<string, string>;
stepOutputs?: Map<string, StepOutputSummary>;
captures?: Map<string, string>;
eventMeta?: Record<string, string>;
}
const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
export function toEnvIdent(raw: string): string {
return raw.replace(/[^A-Za-z0-9]/g, '_').toUpperCase();
}
export function validateAndResolveInputs(
defs: InputDef[],
supplied: Record<string, unknown> = {},
): Record<string, string> {
const out: Record<string, string> = {};
for (const k of Object.keys(supplied)) {
if (FORBIDDEN_KEYS.has(k)) {
throw new Error(`Unsafe input parameter name "${k}"`);
}
}
for (const def of defs) {
if (FORBIDDEN_KEYS.has(def.name)) continue;
const raw = Object.hasOwn(supplied, def.name) ? supplied[def.name] : undefined;
const hasSupplied = raw !== undefined && raw !== null && raw !== '';
const candidate = hasSupplied ? raw : def.default;
if (candidate === undefined || candidate === null || candidate === '') {
if (def.required) {
throw new Error(`Missing required input "${def.label ?? def.name}"`);
}
continue;
}
if (def.type === 'number') {
const n = Number(candidate);
if (!Number.isFinite(n)) {
throw new Error(`Input "${def.name}" must be a valid number`);
}
out[def.name] = String(n);
continue;
}
if (def.type === 'boolean') {
if (typeof candidate === 'boolean') {
out[def.name] = candidate ? 'true' : 'false';
} else {
const lower = String(candidate).trim().toLowerCase();
if (lower === 'true' || lower === '1' || lower === 'yes') out[def.name] = 'true';
else if (lower === 'false' || lower === '0' || lower === 'no') out[def.name] = 'false';
else throw new Error(`Input "${def.name}" must be true or false`);
}
continue;
}
const strVal = String(candidate);
if (/[\x00]/.test(strVal)) {
throw new Error(`Input "${def.name}" contains NUL bytes`);
}
if (def.type === 'select' && def.options && def.options.length > 0) {
if (!def.options.includes(strVal)) {
throw new Error(
`Input "${def.name}" must be one of: ${def.options.join(', ')}`,
);
}
}
out[def.name] = strVal;
}
for (const [k, v] of Object.entries(supplied)) {
if (FORBIDDEN_KEYS.has(k)) continue;
if (!Object.hasOwn(out, k) && v !== undefined && v !== null) {
const s = String(v);
if (/[\x00]/.test(s)) {
throw new Error(`Input "${k}" contains NUL bytes`);
}
out[k] = s;
}
}
return out;
}
export function maskSecretInputsForStorage(
defs: InputDef[],
resolved: Record<string, string>,
): { masked: Record<string, string>; secretValues: string[] } {
const secretKeys = new Set(defs.filter((d) => d.type === 'secret').map((d) => d.name));
const masked: Record<string, string> = {};
const secretValues: string[] = [];
for (const [k, v] of Object.entries(resolved)) {
if (secretKeys.has(k) && v.length > 0) {
masked[k] = '***REDACTED***';
secretValues.push(v);
} else {
masked[k] = v;
}
}
return { masked, secretValues };
}
export function redactWorkflowSecrets(text: string, secretValues: string[]): string {
if (!text || secretValues.length === 0) return text;
let out = text;
for (const sec of secretValues) {
if (sec.length >= 2 && out.includes(sec)) {
out = out.split(sec).join('***REDACTED***');
}
}
return out;
}
export function buildWorkflowEnv(ctx: TemplateContext): Record<string, string> {
const env: Record<string, string> = {};
if (ctx.workflowId) env.GCOORD_WORKFLOW_ID = ctx.workflowId;
if (ctx.runId) env.GCOORD_RUN_ID = ctx.runId;
if (ctx.serverId) env.GCOORD_SERVER_ID = ctx.serverId;
for (const [k, v] of Object.entries(ctx.inputs)) {
if (FORBIDDEN_KEYS.has(k)) continue;
env[`GCOORD_INPUT_${toEnvIdent(k)}`] = v;
}
if (ctx.stepOutputs) {
for (const [stepId, res] of ctx.stepOutputs.entries()) {
const keyBase = `GCOORD_STEP_${toEnvIdent(stepId)}`;
env[`${keyBase}_STDOUT`] = res.stdout.slice(0, 32 * 1024);
env[`${keyBase}_EXIT`] = res.exitCode === null ? '' : String(res.exitCode);
}
}
if (ctx.captures) {
for (const [alias, val] of ctx.captures.entries()) {
env[`GCOORD_CAPTURE_${toEnvIdent(alias)}`] = val.slice(0, 32 * 1024);
}
}
if (ctx.eventMeta) {
for (const [k, v] of Object.entries(ctx.eventMeta)) {
if (FORBIDDEN_KEYS.has(k)) continue;
env[`GCOORD_EVENT_${toEnvIdent(k)}`] = v;
}
}
return env;
}
/**
* Resolve ONLY recognized GCoordinator template namespaces so Go/Docker format
* templates like `{{.Names}}` or `{{json .}}` are left completely untouched.
*/
export function resolveTemplateToken(
rawExpr: string,
ctx: TemplateContext,
): { matched: boolean; value: string } {
const expr = rawExpr.trim();
if (!expr || expr.startsWith('.')) return { matched: false, value: '' };
const parts = expr.split('.');
if (parts.some((p) => FORBIDDEN_KEYS.has(p))) {
return { matched: false, value: '' };
}
if (expr.startsWith('inputs.') || expr.startsWith('input.')) {
const key = expr.slice(expr.indexOf('.') + 1);
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(key)) return { matched: false, value: '' };
return {
matched: true,
value: Object.hasOwn(ctx.inputs, key) ? ctx.inputs[key]! : '',
};
}
if (expr.startsWith('steps.') || expr.startsWith('step.')) {
const rest = expr.slice(expr.indexOf('.') + 1);
const dot = rest.lastIndexOf('.');
if (dot > 0) {
const stepId = rest.slice(0, dot);
const field = rest.slice(dot + 1);
const out = ctx.stepOutputs?.get(stepId);
if (field === 'stdout') return { matched: true, value: out ? out.stdout.trim() : '' };
if (field === 'exitCode') {
return {
matched: true,
value: out && out.exitCode !== null ? String(out.exitCode) : '',
};
}
}
return { matched: false, value: '' };
}
if (expr.startsWith('captures.') || expr.startsWith('capture.')) {
const key = expr.slice(expr.indexOf('.') + 1);
return { matched: true, value: (ctx.captures?.get(key) ?? '').trim() };
}
if (expr.startsWith('event.')) {
const key = expr.slice('event.'.length);
return {
matched: true,
value: ctx.eventMeta && Object.hasOwn(ctx.eventMeta, key) ? ctx.eventMeta[key]! : '',
};
}
if (expr.startsWith('server.')) {
const field = expr.slice('server.'.length);
if (field === 'id') return { matched: true, value: ctx.serverMeta?.id ?? ctx.serverId ?? '' };
if (field === 'name') return { matched: true, value: ctx.serverMeta?.name ?? '' };
if (field === 'host') return { matched: true, value: ctx.serverMeta?.host ?? '' };
if (field === 'port') {
return {
matched: true,
value: ctx.serverMeta ? String(ctx.serverMeta.port) : '',
};
}
return { matched: false, value: '' };
}
if (expr === 'run.id') return { matched: true, value: ctx.runId ?? '' };
if (expr === 'run.workflowId') return { matched: true, value: ctx.workflowId ?? '' };
if (expr === 'trigger.source') return { matched: true, value: ctx.triggerSource ?? '' };
if (expr.startsWith('env.')) {
const key = expr.slice('env.'.length);
const env = buildWorkflowEnv(ctx);
return { matched: true, value: Object.hasOwn(env, key) ? env[key]! : '' };
}
if (/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(expr)) {
if (ctx.captures?.has(expr)) {
return { matched: true, value: (ctx.captures.get(expr) ?? '').trim() };
}
if (Object.hasOwn(ctx.inputs, expr)) {
return { matched: true, value: ctx.inputs[expr]! };
}
}
return { matched: false, value: '' };
}
export function interpolateValuePlain(template: string, ctx: TemplateContext): string {
return template.replace(/\{\{([^{}]+)\}\}/g, (full, expr: string) => {
const res = resolveTemplateToken(expr, ctx);
return res.matched ? res.value : full;
});
}
function escapeDoubleQuotedShell(val: string): string {
return val.replace(/([\\"$`])/g, '\\$1');
}
function escapeInsideSingleQuotedShell(val: string): string {
return val.replace(/'/g, "'\\''");
}
/**
* Quote-aware shell template substitution:
* - Unquoted `{{token}}`: wrapped in `posixSingleQuote(...)`
* - Inside `'...'`: safely single-quote escaped without outer quotes
* - Inside `"..."`: escaped for `$`, `"`, `\`, `` ` ``
* - Unrecognized `{{.Names}}` Go templates remain byte-for-byte untouched
*/
export function interpolateShellCommandSafe(template: string, ctx: TemplateContext): string {
let out = '';
let quote: 'none' | 'single' | 'double' = 'none';
let i = 0;
while (i < template.length) {
const ch = template[i]!;
if (quote === 'none') {
if (ch === '\\' && i + 1 < template.length) {
out += template.slice(i, i + 2);
i += 2;
continue;
}
if (ch === "'") {
quote = 'single';
out += ch;
i += 1;
continue;
}
if (ch === '"') {
quote = 'double';
out += ch;
i += 1;
continue;
}
} else if (quote === 'single') {
if (ch === "'") {
quote = 'none';
out += ch;
i += 1;
continue;
}
} else if (quote === 'double') {
if (ch === '\\' && i + 1 < template.length) {
out += template.slice(i, i + 2);
i += 2;
continue;
}
if (ch === '"') {
quote = 'none';
out += ch;
i += 1;
continue;
}
}
if (ch === '{' && template[i + 1] === '{') {
const closeIdx = template.indexOf('}}', i + 2);
if (closeIdx > i + 1) {
const expr = template.slice(i + 2, closeIdx);
const resolved = resolveTemplateToken(expr, ctx);
if (!resolved.matched) {
out += template.slice(i, closeIdx + 2);
} else if (quote === 'single') {
out += escapeInsideSingleQuotedShell(resolved.value);
} else if (quote === 'double') {
out += escapeDoubleQuotedShell(resolved.value);
} else {
out += posixSingleQuote(resolved.value);
}
i = closeIdx + 2;
continue;
}
}
out += ch;
i += 1;
}
return out;
}
export function resolveTargetServers(
target: { serverId?: string; tags?: string[]; all?: boolean },
servers: ServerConfig[],
ctx: TemplateContext,
): ServerConfig[] {
const enabled = servers.filter((s) => s.enabled);
if (target.all) {
return enabled;
}
const out: ServerConfig[] = [];
const seen = new Set<string>();
if (target.serverId) {
const resolvedId = interpolateValuePlain(target.serverId, ctx).trim();
const match = enabled.find((s) => s.id === resolvedId);
if (match) {
seen.add(match.id);
out.push(match);
}
}
if (target.tags && target.tags.length > 0) {
const wanted = new Set(target.tags);
for (const s of enabled) {
if (seen.has(s.id)) continue;
if (s.tags.some((t) => wanted.has(t))) {
seen.add(s.id);
out.push(s);
}
}
}
return out;
}