'use strict'; const { validateWebhookUrl, applyParams, evalCondition, calculateNextRun } = require('../lib/utils'); // ── validateWebhookUrl ────────────────────────────────────────────────────── describe('validateWebhookUrl', () => { test('null/empty returns ok with null url', () => { expect(validateWebhookUrl(null)).toEqual({ ok: true, url: null }); expect(validateWebhookUrl('')).toEqual({ ok: true, url: null }); }); test('valid public https URL is accepted', () => { const result = validateWebhookUrl('https://hooks.example.com/notify'); expect(result.ok).toBe(true); expect(result.url).toBeInstanceOf(URL); }); test('valid public http URL is accepted', () => { const result = validateWebhookUrl('http://webhook.example.com/event'); expect(result.ok).toBe(true); }); test('invalid URL format is rejected', () => { expect(validateWebhookUrl('not a url')).toMatchObject({ ok: false, reason: expect.stringContaining('Invalid URL') }); }); test('non-http protocol is rejected', () => { expect(validateWebhookUrl('ftp://example.com/hook')).toMatchObject({ ok: false, reason: expect.stringContaining('http') }); }); test('localhost is rejected', () => { expect(validateWebhookUrl('http://localhost/hook')).toMatchObject({ ok: false }); }); test('10.x.x.x private range is rejected', () => { expect(validateWebhookUrl('http://10.0.0.1/hook')).toMatchObject({ ok: false }); expect(validateWebhookUrl('http://10.10.10.45/hook')).toMatchObject({ ok: false }); }); test('192.168.x.x private range is rejected', () => { expect(validateWebhookUrl('http://192.168.1.1/hook')).toMatchObject({ ok: false }); }); test('127.0.0.1 loopback is rejected', () => { expect(validateWebhookUrl('http://127.0.0.1/hook')).toMatchObject({ ok: false }); }); test('172.16.x.x to 172.31.x.x private range is rejected', () => { expect(validateWebhookUrl('http://172.16.0.1/hook')).toMatchObject({ ok: false }); expect(validateWebhookUrl('http://172.31.255.255/hook')).toMatchObject({ ok: false }); }); test('172.32.x.x (outside private range) is accepted', () => { const result = validateWebhookUrl('http://172.32.0.1/hook'); expect(result.ok).toBe(true); }); }); // ── applyParams ───────────────────────────────────────────────────────────── describe('applyParams', () => { test('replaces a single placeholder', () => { expect(applyParams('echo {{msg}}', { msg: 'hello' })).toBe('echo hello'); }); test('replaces multiple placeholders', () => { expect(applyParams('cp {{src}} {{dst}}', { src: 'a.txt', dst: 'b.txt' })).toBe('cp a.txt b.txt'); }); test('leaves unknown placeholders unchanged', () => { expect(applyParams('echo {{unknown}}', {})).toBe('echo {{unknown}}'); }); test('throws on unsafe param value with spaces', () => { expect(() => applyParams('echo {{x}}', { x: 'rm -rf /' })).toThrow('Unsafe value'); }); test('throws on unsafe param value with semicolons', () => { expect(() => applyParams('echo {{x}}', { x: 'a;b' })).toThrow('Unsafe value'); }); test('allows safe characters: dots, dashes, slashes, colons, @', () => { expect(applyParams('ssh {{host}}', { host: 'user@10.0.0.1:22' })).toBe('ssh user@10.0.0.1:22'); expect(applyParams('cat {{path}}', { path: '/etc/hosts' })).toBe('cat /etc/hosts'); }); test('trims whitespace from param values', () => { expect(applyParams('echo {{x}}', { x: ' hello ' })).toBe('echo hello'); }); }); // ── evalCondition ─────────────────────────────────────────────────────────── describe('evalCondition', () => { test('evaluates truthy expression', () => { expect(evalCondition('1 === 1', {}, {})).toBe(true); }); test('evaluates falsy expression', () => { expect(evalCondition('1 === 2', {}, {})).toBe(false); }); test('accesses state variables', () => { expect(evalCondition('state.count > 5', { count: 10 }, {})).toBe(true); expect(evalCondition('state.count > 5', { count: 3 }, {})).toBe(false); }); test('accesses params', () => { expect(evalCondition('params.env === "prod"', {}, { env: 'prod' })).toBe(true); }); test('returns false on syntax error (does not throw)', () => { expect(evalCondition('this is not valid js !!!', {}, {})).toBe(false); }); test('returns false on timeout / infinite loop', () => { expect(evalCondition('while(true){}', {}, {})).toBe(false); }); }); // ── calculateNextRun ──────────────────────────────────────────────────────── describe('calculateNextRun', () => { test('interval: returns a date ~N minutes in the future', () => { // Bounded by the clock before and after the call: its first use loads cron-parser, // which took 30 s once on a loaded CI runner and broke a fixed 1 s tolerance. const before = Date.now(); const result = calculateNextRun('interval', '30'); const after = Date.now(); expect(result.getTime()).toBeGreaterThanOrEqual(before + 30 * 60000); expect(result.getTime()).toBeLessThanOrEqual(after + 30 * 60000); }); test('interval: throws on non-positive value', () => { expect(() => calculateNextRun('interval', '0')).toThrow(); expect(() => calculateNextRun('interval', '-5')).toThrow(); expect(() => calculateNextRun('interval', 'abc')).toThrow(); }); test('hourly: returns a date ~N hours in the future', () => { const before = Date.now(); const result = calculateNextRun('hourly', '2'); expect(result.getTime()).toBeGreaterThanOrEqual(before + 2 * 3600000 - 100); }); test('daily: returns a Date object', () => { const result = calculateNextRun('daily', '06:00'); expect(result).toBeInstanceOf(Date); expect(result.getTime()).toBeGreaterThan(Date.now()); }); test('daily: throws on invalid time format', () => { expect(() => calculateNextRun('daily', 'noon')).toThrow(); }); test('cron: returns next occurrence after now', () => { const result = calculateNextRun('cron', '0 6 * * 1'); expect(result).toBeInstanceOf(Date); expect(result.getTime()).toBeGreaterThan(Date.now()); }); test('unknown type throws', () => { expect(() => calculateNextRun('weekly', '1')).toThrow('Unknown schedule type'); }); }); describe('resolveParams (#23)', () => { const { resolveParams } = require('../lib/utils'); const defs = [ { name: 'host', label: 'Host', required: true }, { name: 'count', type: 'number', min: 1, max: 10, default: '3' }, { name: 'mode', type: 'select', options: ['fast', 'safe'], default: 'safe' }, { name: 'force', type: 'boolean' }, { name: 'node', type: 'worker' }, ]; test('fills defaults and normalises values', () => { expect(resolveParams(defs, { host: ' web-01 ', force: true })).toEqual({ params: { host: 'web-01', count: '3', mode: 'safe', force: 'true' }, errors: [], }); }); test('reports every problem before the run starts', () => { const { errors } = resolveParams(defs, { count: '99', mode: 'yolo', force: 'maybe', node: 'a b' }); expect(errors).toEqual([ 'Host is required', 'count must be at most 10', 'mode must be one of: fast, safe', 'force must be true or false', 'node may only contain letters, digits and . _ : @ / -', ]); }); test('text values with spaces or shell characters are refused', () => { expect(resolveParams(defs, { host: 'web-01; rm -rf /' }).errors).toEqual(['Host may only contain letters, digits and . _ : @ / -']); }); test('numbers must be numbers', () => { for (const bad of ['abc', '1e3', '--1', 'Infinity']) { expect(resolveParams([{ name: 'n', type: 'number' }], { n: bad }).errors).toEqual(['n must be a number']); } expect(resolveParams([{ name: 'n', type: 'number' }], { n: '-2.5' }).params).toEqual({ n: '-2.5' }); }); test('undeclared keys (e.g. an old re-run) must still be safe', () => { expect(resolveParams([], { extra: 'ok' }).params).toEqual({ extra: 'ok' }); expect(resolveParams([], { extra: '$(id)' }).errors).toHaveLength(1); }); }); describe('definitionErrors (#11)', () => { const { definitionErrors } = require('../lib/utils'); const msgs = def => definitionErrors(def).map(p => `${p.where || 'step ' + p.step}: ${p.error}`); test('a good definition has no problems', () => { expect(definitionErrors({ params: [{ name: 'host', required: true }, { name: 'mode', type: 'select', options: ['a', 'b'], default: 'a' }], steps: [ { id: 'run', type: 'execute', command: 'echo {{host}}', targets: ['all'] }, { id: 'p', type: 'parse' }, { id: 'r', type: 'route', conditions: [{ if: 'state.x === "1"', goto: 'end' }, { default: true, goto: 'ask' }] }, { id: 'ask', type: 'prompt', message: 'Go?', options: ['Yes', 'No'], routes: { No: 'end' } }, { id: 'w', type: 'wait', duration: 2 }, ], })).toEqual([]); }); test('catches the typos the issue lists', () => { expect(msgs({ steps: [ { id: 'a', type: 'exec', command: 'x' }, { id: 'b', type: 'prompt', message: 'Go?' }, { id: 'a', type: 'execute' }, { type: 'wait', duration: 'soon' }, { id: 'r', type: 'route', conditions: [] }, { id: 'q', type: 'prompt', message: 'Go?', options: ['Yes'], routes: { No: 'end' } }, ] })).toEqual([ 'step a: unknown type "exec" (use execute, prompt, wait, parse, route)', 'step b: "options" must be a non-empty list of strings', 'step a: id "a" is used more than once', 'step a: "command" is required', 'step 4: "duration" must be a number of seconds', 'step r: "conditions" must be a non-empty list', 'step q: route for "No", which is not one of the options', ]); }); test('steps must be a non-empty list', () => { expect(msgs({ steps: {} })).toEqual(['definition: "steps" must be a non-empty list']); expect(msgs([])).toEqual(['definition: must be a JSON object']); }); test('checks parameter definitions', () => { expect(msgs({ steps: [{ type: 'parse' }], params: [ { name: 'bad name' }, { name: 'x', type: 'colour' }, { name: 's', type: 'select' }, { name: 'n', type: 'number', default: 'many' }, { name: 'n' }, { name: 'o', type: 'select', options: ['ok', 'not ok'] }, ] })).toEqual([ 'param "bad name": "name" must be letters, digits or _', 'param "x": unknown type "colour" (use text, number, select, boolean, worker)', 'param "s": "options" must be a non-empty list for a select', 'param "n": default must be a number', 'param "n": is declared more than once', 'param "o": options may only contain letters, digits and . _ : @ / -: not ok', ]); }); });