Files
pulse/lib/condition.js
T
jaredandClaude Opus 5.5 040ad028c0
CI / UI screenshots (before/after) (push) Skipped
CI / Lint (eslint) (push) Successful in 25s
CI / Test (jest) (push) Successful in 25s
CI / Security (npm audit) (push) Successful in 21s
CI / Scan (secrets, workflows, shell) (push) Successful in 2m0s
CI / Integration (api) (push) Successful in 2m23s
CI / Lint (eslint) (pull_request) Successful in 24s
CI / Test (jest) (pull_request) Successful in 32s
CI / Security (npm audit) (pull_request) Successful in 39s
CI / UI (playwright) (push) Successful in 2m6s
CI / Deploy (push) Skipped
CI / Deploy worker (push) Skipped
CI / Notify (push) Skipped
CI / Integration (api) (pull_request) Successful in 2m13s
CI / Scan (secrets, workflows, shell) (pull_request) Successful in 2m46s
CI / UI screenshots (before/after) (pull_request) Successful in 27s
CI / UI (playwright) (pull_request) Successful in 3m5s
CI / Deploy (pull_request) Skipped
CI / Deploy worker (pull_request) Skipped
CI / Notify (pull_request) Skipped
Safer workflow conditions; Pulse is admin-only
- Workflow conditions (step.condition and route `if`) are now parsed and
  interpreted by lib/condition.js instead of being run with Node's vm
  module. The language covers what workflows use: state/params lookups,
  parseInt/parseFloat/Number/String/Boolean, a few string methods, the
  usual operators with JavaScript semantics. Conditions can only read the
  workflow's own data. Every condition in the production workflows gives
  the same result as before (differential test, 150 random states each).
- Creating and updating a workflow rejects conditions that don't parse
  (400 with the step and the error).
- Creating a workflow requires admin, like editing already did.
- Only the admin group may use Pulse (pages, API and live WebSocket);
  employees get 403. Gandalf and workers use API keys and are unaffected.
- The live-update UI test finds its execution's row by id instead of
  counting rows (the list is capped at 50).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 22:05:42 -05:00

246 lines
8.8 KiB
JavaScript

'use strict';
// Safe evaluator for workflow conditions (step.condition and route `if`).
//
// Conditions are written in a small JavaScript-like expression language:
// (state.carrier||'1') === '0' && parseInt(state.crc_errors||'0') > 10
// params.switch_ip && params.switch_ip.trim() !== ''
// They are parsed into a tree and interpreted here; nothing is ever handed to a
// JavaScript engine, so a condition can only read the workflow's own data. It can't
// reach globals, prototypes or the server process.
//
// Supported: string, number, boolean, null and undefined literals; the names state,
// params and promptResponse; member access by name (own data properties of plain
// objects only, never __proto__, constructor or prototype); the calls parseInt,
// parseFloat, Number, String and Boolean; the string methods trim, toLowerCase,
// toUpperCase, includes, startsWith and endsWith; and the operators
// || && ! === !== == != < <= > >= + - * / % with JavaScript semantics, plus parentheses.
const FUNCTIONS = {
parseInt: (v, radix) => parseInt(v, radix),
parseFloat: v => parseFloat(v),
Number: v => Number(v),
String: v => String(v),
Boolean: v => Boolean(v),
};
const STRING_METHODS = new Set(['trim', 'toLowerCase', 'toUpperCase', 'includes', 'startsWith', 'endsWith']);
const FORBIDDEN_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
const MAX_LENGTH = 2000;
const MAX_DEPTH = 50;
class ConditionError extends Error {}
function tokenize(src) {
const tokens = [];
let i = 0;
const two = ['===', '!==', '==', '!=', '<=', '>=', '&&', '||'];
while (i < src.length) {
const c = src[i];
if (/\s/.test(c)) { i++; continue; }
if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(src[i + 1] || ''))) {
const m = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/.exec(src.slice(i));
tokens.push({ t: 'num', v: Number(m[0]) });
i += m[0].length;
continue;
}
if (c === '\'' || c === '"') {
let j = i + 1;
let s = '';
while (j < src.length && src[j] !== c) {
if (src[j] === '\\') {
const n = src[j + 1];
s += n === 'n' ? '\n' : n === 't' ? '\t' : n;
j += 2;
} else {
s += src[j++];
}
}
if (j >= src.length) throw new ConditionError('unterminated string');
tokens.push({ t: 'str', v: s });
i = j + 1;
continue;
}
if (/[A-Za-z_$]/.test(c)) {
const m = /^[A-Za-z_$][A-Za-z0-9_$]*/.exec(src.slice(i));
tokens.push({ t: 'id', v: m[0] });
i += m[0].length;
continue;
}
const op = [...two].sort((a, b) => b.length - a.length).find(o => src.startsWith(o, i));
if (op) { tokens.push({ t: 'op', v: op }); i += op.length; continue; }
if ('!<>+-*/%().,'.includes(c)) { tokens.push({ t: 'op', v: c }); i++; continue; }
throw new ConditionError(`unexpected character ${JSON.stringify(c)}`);
}
tokens.push({ t: 'end' });
return tokens;
}
// Precedence climbing, lowest first.
const BINARY = [
['||'], ['&&'], ['===', '!==', '==', '!='], ['<', '<=', '>', '>='], ['+', '-'], ['*', '/', '%'],
];
function parse(src) {
if (typeof src !== 'string') throw new ConditionError('condition must be a string');
if (src.length > MAX_LENGTH) throw new ConditionError('condition is too long');
const tokens = tokenize(src);
let pos = 0;
const peek = () => tokens[pos];
const isOp = v => peek().t === 'op' && peek().v === v;
const expect = v => {
if (!isOp(v)) throw new ConditionError(`expected ${v}`);
pos++;
};
function binary(level, depth) {
if (depth > MAX_DEPTH) throw new ConditionError('condition is nested too deeply');
if (level === BINARY.length) return unary(depth);
let left = binary(level + 1, depth + 1);
while (peek().t === 'op' && BINARY[level].includes(peek().v)) {
const op = tokens[pos++].v;
left = { k: 'bin', op, left, right: binary(level + 1, depth + 1) };
}
return left;
}
function unary(depth) {
if (depth > MAX_DEPTH) throw new ConditionError('condition is nested too deeply');
if (isOp('!') || isOp('-') || isOp('+')) {
const op = tokens[pos++].v;
return { k: 'un', op, arg: unary(depth + 1) };
}
return postfix(depth);
}
function args(depth) {
expect('(');
const list = [];
if (!isOp(')')) {
list.push(binary(0, depth + 1));
while (isOp(',')) { pos++; list.push(binary(0, depth + 1)); }
}
expect(')');
return list;
}
function postfix(depth) {
let node = primary(depth);
for (;;) {
if (isOp('.')) {
pos++;
const name = peek();
if (name.t !== 'id') throw new ConditionError('expected a property name after "."');
pos++;
if (FORBIDDEN_NAMES.has(name.v)) throw new ConditionError(`"${name.v}" is not allowed`);
if (isOp('(')) {
if (!STRING_METHODS.has(name.v)) throw new ConditionError(`method "${name.v}" is not allowed`);
node = { k: 'method', obj: node, name: name.v, args: args(depth) };
} else {
node = { k: 'member', obj: node, name: name.v };
}
} else {
return node;
}
}
}
function primary(depth) {
const tok = peek();
if (tok.t === 'num' || tok.t === 'str') { pos++; return { k: 'lit', v: tok.v }; }
if (tok.t === 'op' && tok.v === '(') {
pos++;
const inner = binary(0, depth + 1);
expect(')');
return inner;
}
if (tok.t === 'id') {
pos++;
switch (tok.v) {
case 'true': return { k: 'lit', v: true };
case 'false': return { k: 'lit', v: false };
case 'null': return { k: 'lit', v: null };
case 'undefined': return { k: 'lit', v: undefined };
case 'state': case 'params': case 'promptResponse':
return { k: 'var', name: tok.v };
}
if (Object.prototype.hasOwnProperty.call(FUNCTIONS, tok.v) && isOp('(')) {
return { k: 'call', name: tok.v, args: args(depth) };
}
throw new ConditionError(`unknown name "${tok.v}"`);
}
throw new ConditionError(tok.t === 'end' ? 'unexpected end of condition' : `unexpected "${tok.v}"`);
}
const tree = binary(0, 0);
if (peek().t !== 'end') throw new ConditionError(`unexpected "${peek().v}"`);
return tree;
}
function isPlainObject(v) {
if (v === null || typeof v !== 'object') return false;
const proto = Object.getPrototypeOf(v);
return proto === Object.prototype || proto === null;
}
function evaluate(node, scope) {
switch (node.k) {
case 'lit': return node.v;
case 'var': return scope[node.name];
case 'member': {
const obj = evaluate(node.obj, scope);
// Only data the workflow put there: own properties of plain objects.
if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, node.name)) return obj[node.name];
if (typeof obj === 'string' && node.name === 'length') return obj.length;
return undefined;
}
case 'method': {
const obj = evaluate(node.obj, scope);
if (typeof obj !== 'string') throw new ConditionError(`.${node.name}() needs a string`);
const a = node.args.map(x => evaluate(x, scope));
return String.prototype[node.name].apply(obj, a);
}
case 'call': return FUNCTIONS[node.name](...node.args.map(x => evaluate(x, scope)));
case 'un': {
const v = evaluate(node.arg, scope);
return node.op === '!' ? !v : node.op === '-' ? -v : +v;
}
case 'bin': {
if (node.op === '||') return evaluate(node.left, scope) || evaluate(node.right, scope);
if (node.op === '&&') return evaluate(node.left, scope) && evaluate(node.right, scope);
const l = evaluate(node.left, scope);
const r = evaluate(node.right, scope);
switch (node.op) {
case '===': return l === r;
case '!==': return l !== r;
case '==': return l == r; // eslint-disable-line eqeqeq -- the language supports loose equality
case '!=': return l != r; // eslint-disable-line eqeqeq
case '<': return l < r;
case '<=': return l <= r;
case '>': return l > r;
case '>=': return l >= r;
case '+': return l + r;
case '-': return l - r;
case '*': return l * r;
case '/': return l / r;
case '%': return l % r;
}
}
}
throw new ConditionError('invalid condition');
}
// Throws ConditionError when the condition can't be parsed (used to validate on save).
function checkCondition(src) {
parse(src);
}
// Evaluates a condition to a boolean. Values in state and params are the workflow's
// own data; anything that isn't a plain object is treated as empty.
function evaluateCondition(src, state, params) {
const s = isPlainObject(state) ? state : {};
const p = isPlainObject(params) ? params : {};
return !!evaluate(parse(src), { state: s, params: p, promptResponse: s.promptResponse });
}
module.exports = { evaluateCondition, checkCondition, ConditionError };