Files
pulse/lib/utils.js
T
jaredandClaude Opus 5.5 a6d693c13e
CI / Test (jest) (pull_request) Successful in 26s
CI / Lint (eslint) (pull_request) Successful in 29s
CI / Security (npm audit) (pull_request) Successful in 13s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 1m36s
CI / Integration (api) (pull_request) Successful in 2m26s
CI / UI (playwright) (pull_request) Successful in 2m25s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
CI / UI screenshots (before/after) (pull_request) Successful in 2m3s
Workflow parameters: types, defaults, checked before a run (#23, #11)
#23
- Parameters can be text (default), number (min, max), select
  (options), boolean, or worker, with a default. The Run dialog shows a
  matching field, the allowed characters for text, and the range for
  numbers; worker parameters choose from the connected workers.
- Values are checked before anything starts: in the dialog, naming the
  characters that are not allowed, and by the server (resolveParams),
  which answers 400 "Invalid parameters: ..." and creates no execution.
  A bad value used to fail mid-run as "Unsafe value for workflow
  parameter". Server errors now show in the dialog instead of a toast.

#11
- Saving a workflow checks its shape (definitionErrors): known step
  types and their required fields, unique ids, prompt routes that match
  options, route conditions, and parameter definitions. Unknown step
  types were silently skipped at run time.
- README documents the parameter types and the checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:11:49 -05:00

303 lines
12 KiB
JavaScript

'use strict';
const { evaluateCondition, checkCondition } = require('./condition');
/**
* Validate a webhook URL.
* Returns { ok: true, url } or { ok: false, reason }.
*/
function validateWebhookUrl(raw) {
if (!raw) return { ok: true, url: null };
let url;
try { url = new URL(raw); } catch { return { ok: false, reason: 'Invalid URL format' }; }
if (!['http:', 'https:'].includes(url.protocol)) {
return { ok: false, reason: 'Webhook URL must use http or https' };
}
const host = url.hostname.toLowerCase();
if (
host === 'localhost' ||
host === '::1' ||
/^127\./.test(host) ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[01])\./.test(host) ||
/^169\.254\./.test(host) ||
/^fe80:/i.test(host)
) {
return { ok: false, reason: 'Webhook URL must not point to a private/internal address' };
}
return { ok: true, url };
}
/**
* Replace {{param}} placeholders in a command string.
* Throws if a substituted value contains unsafe characters.
*/
// What a parameter value may contain once it is substituted into a command.
const PARAM_VALUE_RE = /^[a-zA-Z0-9._:@/-]+$/;
const PARAM_RULE = 'letters, digits and . _ : @ / -';
const PARAM_TYPES = ['text', 'number', 'select', 'boolean', 'worker'];
const STEP_TYPES = ['execute', 'prompt', 'wait', 'parse', 'route'];
function applyParams(command, params) {
return command.replace(/\{\{(\w+)\}\}/g, (match, key) => {
if (!(key in params)) return match;
const val = String(params[key]).trim();
if (!PARAM_VALUE_RE.test(val)) {
throw new Error(`Unsafe value for workflow parameter "${key}"`);
}
return val;
});
}
/**
* Evaluate a workflow condition with the safe interpreter in lib/condition.js (no vm,
* no JavaScript engine). Returns a boolean; a condition that can't be parsed or
* evaluated counts as false.
*/
function evalCondition(condition, state, params) {
try {
return evaluateCondition(condition, state, params);
} catch (e) {
console.warn(`[Workflow] evalCondition error (treated as false): ${e.message} (condition: ${condition})`);
return false;
}
}
/**
* Every condition in a workflow definition that doesn't parse, as
* [{ step, condition, error }]. Used to reject bad definitions when they are saved.
*/
function conditionErrors(definition) {
const problems = [];
let def = definition;
if (typeof def === 'string') {
try { def = JSON.parse(def); } catch { return problems; } // JSON errors are reported elsewhere
}
const steps = (def && Array.isArray(def.steps)) ? def.steps : [];
steps.forEach((step, i) => {
const label = (step && (step.id || step.name)) || `step ${i + 1}`;
const exprs = [];
if (step && step.condition) exprs.push(step.condition);
for (const c of (step && Array.isArray(step.conditions) ? step.conditions : [])) {
if (c && !c.default && c.if) exprs.push(c.if);
}
for (const expr of exprs) {
try { checkCondition(expr); } catch (e) { problems.push({ step: label, condition: expr, error: e.message }); }
}
});
return problems;
}
/**
* Every jump in a workflow definition to a step id that doesn't exist (#20), as
* [{ step, goto, error }]. 'end' and '__end__' finish the workflow and are always valid.
*/
function gotoErrors(definition) {
let def = definition;
if (typeof def === 'string') {
try { def = JSON.parse(def); } catch { return []; }
}
const steps = (def && Array.isArray(def.steps)) ? def.steps : [];
const ids = new Set(steps.map(st => st && st.id).filter(Boolean));
const ok = target => target === 'end' || target === '__end__' || ids.has(target);
const problems = [];
steps.forEach((step, i) => {
if (!step) return;
const label = step.id || step.name || `step ${i + 1}`;
const targets = [];
if (step.goto) targets.push(step.goto);
for (const c of (Array.isArray(step.conditions) ? step.conditions : [])) if (c && c.goto) targets.push(c.goto);
if (step.routes && typeof step.routes === 'object') targets.push(...Object.values(step.routes));
for (const t of targets) {
if (typeof t !== 'string' || !ok(t)) problems.push({ step: label, goto: t, error: `no step with id ${JSON.stringify(t)}` });
}
});
return problems;
}
/**
* Check one parameter value against its definition (#23).
* Returns { value } (normalised to a string) or { error }.
*/
function checkParamValue(pd, raw) {
const type = pd.type || 'text';
if (type === 'boolean') {
const v = String(raw).trim().toLowerCase();
if (['true', '1', 'yes', 'on'].includes(v)) return { value: 'true' };
if (['false', '0', 'no', 'off'].includes(v)) return { value: 'false' };
return { error: 'must be true or false' };
}
const v = String(raw).trim();
if (type === 'number') {
const n = Number(v);
if (v === '' || !Number.isFinite(n) || !/^[-0-9.]+$/.test(v)) return { error: 'must be a number' };
if (typeof pd.min === 'number' && n < pd.min) return { error: `must be at least ${pd.min}` };
if (typeof pd.max === 'number' && n > pd.max) return { error: `must be at most ${pd.max}` };
return { value: v };
}
if (type === 'select') {
const options = Array.isArray(pd.options) ? pd.options.map(String) : [];
if (!options.includes(v)) return { error: `must be one of: ${options.join(', ')}` };
return { value: v };
}
if (!PARAM_VALUE_RE.test(v)) return { error: `may only contain ${PARAM_RULE}` };
return { value: v };
}
/**
* The parameters a run will use (#23): each declared one from the request or its
* default, checked against its type; extra keys must still be safe to substitute.
* Returns { params, errors } with errors as readable strings.
*/
function resolveParams(paramDefs, input) {
const defs = Array.isArray(paramDefs) ? paramDefs : [];
const given = (input && typeof input === 'object') ? input : {};
const params = {};
const errors = [];
const declared = new Set();
for (const pd of defs) {
if (!pd || !pd.name) continue;
declared.add(pd.name);
const label = pd.label || pd.name;
let raw = given[pd.name];
if (raw === undefined || raw === null || String(raw).trim() === '') raw = pd.default;
if (raw === undefined || raw === null || String(raw).trim() === '') {
if (pd.required) errors.push(`${label} is required`);
continue;
}
const r = checkParamValue(pd, raw);
if (r.error) errors.push(`${label} ${r.error}`); else params[pd.name] = r.value;
}
for (const [key, raw] of Object.entries(given)) {
if (declared.has(key) || raw === undefined || raw === null || String(raw).trim() === '') continue;
const r = checkParamValue({ type: 'text' }, raw);
if (r.error) errors.push(`${key} ${r.error}`); else params[key] = r.value;
}
return { params, errors };
}
/**
* Structural problems in a workflow definition (#11): step types and their required
* fields, unique ids, and parameter definitions. As [{ step, error }] like the other
* checks; parameter problems use { where: 'param "name"', error }.
*/
function definitionErrors(definition) {
let def = definition;
if (typeof def === 'string') {
try { def = JSON.parse(def); } catch { return []; } // JSON errors are reported elsewhere
}
if (!def || typeof def !== 'object' || Array.isArray(def)) return [{ where: 'definition', error: 'must be a JSON object' }];
const problems = [];
const isStr = v => typeof v === 'string' && v.trim() !== '';
const isStrList = v => Array.isArray(v) && v.length > 0 && v.every(isStr);
if (!Array.isArray(def.steps) || def.steps.length === 0) {
problems.push({ where: 'definition', error: '"steps" must be a non-empty list' });
} else {
const seen = new Set();
def.steps.forEach((step, i) => {
if (!step || typeof step !== 'object' || Array.isArray(step)) {
problems.push({ step: `${i + 1}`, error: 'must be an object' });
return;
}
const label = step.id || step.name || `${i + 1}`;
const bad = error => problems.push({ step: label, error });
if (step.id !== undefined) {
if (!isStr(step.id)) bad('"id" must be a non-empty string');
else if (seen.has(step.id)) bad(`id ${JSON.stringify(step.id)} is used more than once`);
else seen.add(step.id);
}
if (!STEP_TYPES.includes(step.type)) {
bad(step.type === undefined ? `"type" is required (${STEP_TYPES.join(', ')})`
: `unknown type ${JSON.stringify(step.type)} (use ${STEP_TYPES.join(', ')})`);
return;
}
if (step.type === 'execute') {
if (!isStr(step.command)) bad('"command" is required');
if (step.targets !== undefined && !isStrList(step.targets)) bad('"targets" must be a list of worker names or ["all"]');
} else if (step.type === 'prompt') {
if (!isStr(step.message)) bad('"message" is required');
if (!isStrList(step.options)) bad('"options" must be a non-empty list of strings');
else if (step.routes && typeof step.routes === 'object') {
for (const answer of Object.keys(step.routes)) {
if (!step.options.includes(answer)) bad(`route for ${JSON.stringify(answer)}, which is not one of the options`);
}
}
} else if (step.type === 'wait') {
if (step.duration !== undefined && !(Number(step.duration) >= 0)) bad('"duration" must be a number of seconds');
} else if (step.type === 'route') {
if (!Array.isArray(step.conditions) || step.conditions.length === 0) bad('"conditions" must be a non-empty list');
else {
step.conditions.forEach((c, j) => {
if (!c || typeof c !== 'object') bad(`condition ${j + 1} must be an object`);
else if (!c.default && !isStr(c.if)) bad(`condition ${j + 1} needs "if" (or "default": true)`);
});
}
}
});
}
if (def.params !== undefined) {
if (!Array.isArray(def.params)) {
problems.push({ where: 'definition', error: '"params" must be a list' });
} else {
const names = new Set();
def.params.forEach((pd, i) => {
const where = `param ${pd && pd.name ? JSON.stringify(String(pd.name)) : i + 1}`;
const bad = error => problems.push({ where, error });
if (!pd || typeof pd !== 'object') { bad('must be an object'); return; }
if (typeof pd.name !== 'string' || !/^\w+$/.test(pd.name)) { bad('"name" must be letters, digits or _'); return; }
if (names.has(pd.name)) bad('is declared more than once');
names.add(pd.name);
const type = pd.type || 'text';
if (!PARAM_TYPES.includes(type)) { bad(`unknown type ${JSON.stringify(pd.type)} (use ${PARAM_TYPES.join(', ')})`); return; }
if (type === 'select') {
if (!isStrList(pd.options)) { bad('"options" must be a non-empty list for a select'); return; }
const unsafe = pd.options.filter(o => !PARAM_VALUE_RE.test(o));
if (unsafe.length) bad(`options may only contain ${PARAM_RULE}: ${unsafe.join(', ')}`);
}
if (pd.default !== undefined && pd.default !== null && pd.default !== '') {
const r = checkParamValue(pd, pd.default);
if (r.error) bad(`default ${r.error}`);
}
});
}
}
return problems;
}
/**
* Calculate the next run date for a scheduled command.
*/
function calculateNextRun(scheduleType, scheduleValue) {
const cronParser = require('cron-parser');
const now = new Date();
if (scheduleType === 'interval') {
const minutes = parseInt(scheduleValue);
if (isNaN(minutes) || minutes <= 0) throw new Error(`Invalid interval value: ${scheduleValue}`);
return new Date(now.getTime() + minutes * 60000);
} else if (scheduleType === 'daily') {
const [hours, minutes] = scheduleValue.split(':').map(Number);
if (isNaN(hours) || isNaN(minutes)) throw new Error(`Invalid daily time format: ${scheduleValue}`);
const next = new Date(now);
next.setHours(hours, minutes, 0, 0);
if (next <= now) next.setDate(next.getDate() + 1);
return next;
} else if (scheduleType === 'hourly') {
const hours = parseInt(scheduleValue);
if (isNaN(hours) || hours <= 0) throw new Error(`Invalid hourly value: ${scheduleValue}`);
return new Date(now.getTime() + hours * 3600000);
} else if (scheduleType === 'cron') {
const interval = cronParser.CronExpressionParser.parse(scheduleValue, { currentDate: now });
return interval.next().toDate();
}
throw new Error(`Unknown schedule type: ${scheduleType}`);
}
module.exports = {
validateWebhookUrl, applyParams, evalCondition, conditionErrors, gotoErrors, calculateNextRun,
definitionErrors, resolveParams, checkParamValue, PARAM_RULE, PARAM_TYPES, STEP_TYPES,
};