// API test: node apitest.js . Never runs a real kill / restart / cleanup / reboot on Linux. const http = require('http'), fs = require('fs'), path = require('path'); const [port, cfgRoot, os] = process.argv.slice(2), dir = path.join(cfgRoot, 'ServerMonitorWeb'), t0 = Date.now(), win = os === 'Windows'; let failed = 0; const check = (name, ok, info = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${info ? ' — ' + info : ''}`); if (!ok) ++failed; }; const sleep = ms => new Promise(r => setTimeout(r, ms)); function req(method, p, body, headers = {}) { // raw request so that any header (Host, Origin) can be forged return new Promise((resolve, reject) => { const data = body === undefined ? null : typeof body === 'string' ? body : JSON.stringify(body); const r = http.request({ host: '127.0.0.1', port, method, path: p, headers: { ...(data != null && { 'Content-Type': 'application/json', 'X-SM': '1' }), ...headers } }, res => { let s = ''; res.setEncoding('utf8').on('data', d => s += d).on('end', () => { let json; try { json = JSON.parse(s); } catch {} resolve({ status: res.statusCode, headers: res.headers, text: s, json }); }); }); r.on('error', reject); r.end(data); }); } const post = async (p, body) => { const r = await req('POST', '/api/' + p, body); if (r.status !== 200) throw new Error(`${p}: ${r.status} ${r.text}`); return r.json; }; const state = async () => (await req('GET', '/api/state')).json; function sse(p, ms) { // collect events for a while return new Promise(resolve => { const events = [], r = http.get({ host: '127.0.0.1', port, path: p }, res => { let buf = ''; res.setEncoding('utf8').on('data', d => { buf += d; for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) { const [e, data] = buf.slice(0, i).split('\n'); events.push([e.slice(7), JSON.parse(data.slice(6))]); } }); setTimeout(() => { r.destroy(); resolve({ events, type: res.headers['content-type'], headers: res.headers }); }, ms); }); }); } (async () => { // --- state + security --- let s = await state(); check('GET /api/state', s.plat.name === os && s.servers.length === 2, `${s.plat.name}, ${s.servers.map(x => x.cfg.name + '=' + x.status).join(', ')}`); const local = s.servers[0].cfg.id, dead = s.servers[1].cfg.id; check('no password field is sent, only hasPassword', s.servers.every(x => !('password' in x.cfg) && 'hasPassword' in x.cfg)); const page = await req('GET', '/'); check('GET / serves the page with security headers', page.status === 200 && /app\.js/.test(page.text) && page.headers['content-security-policy'].includes("default-src 'self'") && page.headers['x-content-type-options'] === 'nosniff'); for (const f of ['/app.js', '/shared.js', '/style.css', '/icon.svg']) { const r = await req('GET', f); check('GET ' + f, r.status === 200 && r.text.length > 300, r.headers['content-type']); } check('GET /../server.js is not served', (await req('GET', '/../server.js')).status === 404 && (await req('GET', '/%2e%2e/server.js')).status === 404); let r = await req('GET', '/api/state', undefined, { Host: 'evil.example:' + port }); check('wrong Host header is rejected (DNS rebinding)', r.status === 403, `${r.status} ${r.text}`); r = await req('GET', '/api/state', undefined, { Host: '127.0.0.1:1' }); check('right host with wrong port is rejected', r.status === 403); r = await req('GET', '/api/state', undefined, { Host: 'localhost:' + port }); check('Host localhost: is accepted', r.status === 200); r = await req('POST', '/api/alerts/clear', '{}', { 'X-SM': '' }); check('POST without the X-SM header is rejected', r.status === 403, `${r.status} ${r.text}`); r = await req('POST', '/api/alerts/clear', '{}', { 'Content-Type': 'text/plain' }); check('POST with a non-JSON content type is rejected', r.status === 403); r = await req('POST', '/api/exec', { id: local, cmd: 'echo should-not-run' }, { Origin: 'http://evil.example' }); check('POST from a foreign Origin is rejected', r.status === 403, `${r.status} ${r.text}`); r = await req('GET', '/api/alerts/clear'); check('state-changing route does not answer GET', r.status === 404); r = await req('OPTIONS', '/api/exec', undefined, { Origin: 'http://evil.example', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'x-sm,content-type' }); check('CORS preflight gets no permission', r.status >= 400 && !Object.keys(r.headers).some(h => h.startsWith('access-control')), `status ${r.status}`); check('no CORS headers on normal replies', !Object.keys(page.headers).some(h => h.startsWith('access-control'))); r = await req('POST', '/api/exec', '{broken'); check('invalid JSON body -> 400', r.status === 400, r.text); r = await req('POST', '/api/exec', { id: 'nope', cmd: 'echo x' }); check('unknown server -> 404', r.status === 404, r.text); // --- live streams --- const [g, d] = await Promise.all([sse('/api/events', 7000), sse('/api/events?id=' + local, 7000)]); const count = (x, name) => x.events.filter(e => e[0] === name).length; check('SSE /api/events: hello + state updates', g.type === 'text/event-stream' && count(g, 'hello') === 1 && count(g, 'state') >= 2, g.events.map(e => e[0]).join(' ')); check('SSE /api/events?id=: live + samples', count(d, 'live') === 1 && count(d, 'sample') >= 2, d.events.map(e => e[0]).join(' ')); const m = d.events.findLast(e => e[0] === 'sample')[1].m; check('sample carries full metrics', m.valid && m.cpuCount >= 1 && m.memTotal > 1e9 && m.procs.length > 3 && m.mounts.length >= 1 && m.nets.length >= 1, `${m.hostname} | ${m.os} | ${m.cpuCount} cores | cpu ${m.cpuUsage.toFixed(1)}% | mem ${m.memPct.toFixed(1)}% | ${m.procs.length} procs | ${m.services.length} services | load ${m.load1.toFixed(2)} | net rx ${Math.round(m.netRxBps)} B/s`); if (win) { const eth = m.nets.find(n => n.name === 'Ethernet'); check('Windows parser: Hyper-V NIC "Ethernet" is physical and counted in the totals', eth && !eth.virt && m.netRxBps > 0 && m.netRxBps === eth.rxBps, `rx ${Math.round(m.netRxBps)} B/s tx ${Math.round(m.netTxBps)} B/s; virtual: ${m.nets.filter(n => n.virt).map(n => n.name).join(', ')}`); check('Windows parser: services / tcp / disks / load', m.servicesFailed === 1 && m.servicesRunning === 4 && m.tcp.ESTABLISHED === 42 && m.tcp.LISTEN === 27 && m.socketsUsed === 73 && m.disks.length === 2 && m.mounts[0].mount === 'C:\\' && m.load1 > 0 && m.temps.length === 1, `failed ${m.servicesFailed}, running ${m.servicesRunning}, tcp ${JSON.stringify(m.tcp)}, fullest ${m.fullestMount} ${m.maxDiskPct.toFixed(1)}%, load ${m.load1.toFixed(2)}/${m.load5.toFixed(2)}/${m.load15.toFixed(2)}, temp ${m.maxTemp}`); const sql = m.procs.find(p => p.name === 'sqlservr.exe'); check('Windows parser: processes', m.procs.length === 7 && !m.procs.some(p => p.pid === 0) && sql.user === 'NT AUTHORITY\\SYSTEM' && sql.nice === 8 && sql.age > 86400, `top: ${m.procs[0].name} ${m.procs[0].cpu.toFixed(1)}% (${m.procs[0].user})`); } s = await state(); check('offline host is detected', s.servers[1].status === 'Offline' && !s.servers[1].online && /Unreachable/.test(s.servers[1].alerts[0]), s.servers[1].alerts[0]); check('an "unreachable" alert was raised', s.alerts.some(a => a.severity === 'critical' && a.serverName === s.servers[1].cfg.name && /unreachable/.test(a.message))); // --- console + platform commands --- r = await post('exec', { id: local, cmd: 'echo hello-$((6*7))' }); check('console echo', win ? r.code === 0 && /would run/.test(r.out) && /echo hello/.test(r.out) : r.code === 0 && r.out === 'hello-42\n', JSON.stringify(r)); r = await post('exec', { id: dead, cmd: 'echo x' }); check('console on an offline server', r.code === -1 && r.out === 'server is not connected', JSON.stringify(r)); if (!win) { r = await post('exec', { id: local, cmd: 'echo out; echo err >&2; exit 3' }); check('console merges stderr and reports the exit code', r.code === 3 && /out/.test(r.out) && /err/.test(r.out), JSON.stringify(r)); r = await post('run', { id: local, list: 'procActions', i: 0, arg: '4999999' }); // a pid above pid_max: nothing can be hit check('process action builds the platform command (non-existent pid)', r.cmd === 'kill -TERM 4999999' && r.code !== 0, JSON.stringify(r)); r = await post('logs', { id: local, unit: "no'such.service", lines: 60 }); check('service logs (read-only, quoted unit name)', /journal/.test(r.out), JSON.stringify(r.out.slice(0, 120))); } else { r = await post('run', { id: local, list: 'procActions', i: 2, arg: '1200' }); check('process action builds the platform command', r.cmd === 'taskkill /F /T /PID 1200' && r.code === 0 && r.out.includes(r.cmd), JSON.stringify(r)); r = await post('run', { id: local, list: 'serviceActions', i: 2, arg: "Bro'ken" }); check('service action quotes the name', r.cmd === "Restart-Service -Name 'Bro''ken' -Force", r.cmd); r = await post('run', { id: local, list: 'priorities', i: 0, arg: '1200' }); check('priority action', r.cmd === "(Get-Process -Id 1200).PriorityClass = 'Idle'", r.cmd); r = await post('logs', { id: local, unit: 'Spooler', lines: 100 }); check('service logs command', /Select-Object -First 100/.test(r.out), JSON.stringify(r.out.slice(-160))); r = await post('power', { id: local, reboot: true }); check('power command (stand-in powershell only echoes)', r.code === 0 && /shutdown \/r \/t 5/.test(r.out), JSON.stringify(r.out)); await post('server/analyze', { id: local }); const f = (await sse('/api/events?id=' + local, 1500)).events.find(e => e[0] === 'live')[1].an.findings.find(x => x.action === 'restart_service'); r = f && await post('finding', { id: local, key: f.key }); check('manual fix of a finding (echo only)', r && r.code === 0 && /Restart-Service -Name 'BrokenSvc' -Force/.test(r.out), f && f.title); } r = await req('POST', '/api/run', { id: local, list: 'ui', i: 0, arg: '1' }); check('unknown command list -> 400', r.status === 400, r.text); r = await req('POST', '/api/finding', { id: local, key: 'nope' }); check('unknown finding -> 404', r.status === 404, r.text); // --- servers: test connection, add, edit, reorder, password handling, remove --- r = await post('server/test', { name: 't', transport: 0 }); check('test connection (local, two frames)', r.ok && /Connected in \d+ ms/.test(r.text), r.text); r = await post('server/test', { name: 't', transport: 1, host: '127.0.0.1', port: 1, user: 'nobody' }); check('test connection (unreachable)', !r.ok && r.text.startsWith('✗'), r.text); r = await req('POST', '/api/server/add', { name: '', transport: 1, host: '' }); check('add without name/address -> 400', r.status === 400, r.text); r = await req('POST', '/api/server/add', { name: 'x', transport: 1, host: '-oProxyCommand=id' }); check('add with an option-like host -> 400', r.status === 400, r.text); const added = (await post('server/add', { name: ' second local ', group: 'Test', transport: 0, interval: 1, autopilot: { dryRun: true } })).id; const ssh = (await post('server/add', { name: 'with password', group: 'Test', transport: 1, host: '127.0.0.1', port: 1, user: 'nobody', password: 'p@ss "w" ö', enabled: false, autopilot: { dryRun: true } })).id; s = await state(); const a = s.servers.find(x => x.cfg.id === added), b = s.servers.find(x => x.cfg.id === ssh); check('add server', a && a.cfg.name === 'second local' && a.cfg.interval === 1 && a.cfg.rules.length === 7 && a.cfg.autopilot.dryRun && a.cfg.autopilot.maxRestartsPerHour === 3, `${s.servers.length} servers`); check('added disabled SSH server: Disabled, hasPassword', b && b.status === 'Disabled' && b.cfg.hasPassword === true && !('password' in b.cfg)); const stored = () => JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'), 'utf8')); const unxor = p => Buffer.from(p, 'base64').map((c, i) => c ^ Buffer.from('ServerMonitor/obfuscation/v1')[i % 28]).toString(); check('servers.json: version 1, password XOR+base64, mode 600', stored().version === 1 && unxor(stored().servers.find(x => x.id === ssh).password) === 'p@ss "w" ö' && (fs.statSync(path.join(dir, 'servers.json')).mode & 0o777) === 0o600, stored().servers.find(x => x.id === ssh).password); await post('server/update', { id: ssh, name: 'renamed', password: '', notes: 'n' }); check('edit with an empty password keeps the stored one', unxor(stored().servers.find(x => x.id === ssh).password) === 'p@ss "w" ö' && stored().servers.find(x => x.id === ssh).name === 'renamed'); await post('server/update', { id: ssh, clearPassword: true }); check('"remove stored" clears the password', stored().servers.find(x => x.id === ssh).password === '' && !(await state()).servers.find(x => x.cfg.id === ssh).cfg.hasPassword); await post('server/move', { id: ssh, delta: -1 }); s = await state(); check('reorder', s.servers.map(x => x.cfg.id).join() === [local, dead, ssh, added].join() && stored().servers[2].id === ssh); await sleep(3500); s = await state(); check('added local server comes online', s.servers.find(x => x.cfg.id === added).online); // --- rules + autopilot --- const rules = s.servers[0].cfg.rules; await post('server/update', { id: local, rules: [...rules, { metric: 'procs', op: '>', value: 1, duration: 0, severity: 'info', action: 'notify', cooldown: 30 }] }); s = await state(); const mine = s.servers[0].cfg.rules.at(-1); check('add rule', s.servers[0].cfg.rules.length === rules.length + 1 && mine.id.length === 12 && mine.metric === 'procs' && mine.enabled === true && stored().servers[0].rules.length === rules.length + 1); await sleep(2600); s = await state(); check('new rule fires (notify only)', s.servers[0].alerts.includes('Process count > 1') && s.alerts.some(x => x.severity === 'info' && x.message.startsWith('Process count > 1 (now')), s.alerts.find(x => x.severity === 'info')?.message); await post('server/update', { id: local, rules: s.servers[0].cfg.rules.filter(x => x.id !== mine.id) }); s = await state(); check('delete rule', s.servers[0].cfg.rules.length === rules.length && !s.servers[0].cfg.rules.some(x => x.id === mine.id)); await post('server/update', { id: local, autopilot: { ...s.servers[0].cfg.autopilot, runawayMinutes: 25, anomalyZ: 4.5, leakMode: 'none', dryRun: true } }); s = await state(); const ap = stored().servers[0].autopilot; check('autopilot save', s.servers[0].cfg.autopilot.runawayMinutes === 25 && ap.anomalyZ === 4.5 && ap.leakMode === 'none' && ap.dryRun === true && ap.enabled === true, JSON.stringify(ap).slice(0, 150)); // --- pause / reconnect / analyze / history / events --- await post('server/pause', { id: local, paused: true }); check('pause', (await state()).servers[0].paused === true); await post('server/pause', { id: local, paused: false }); await post('server/analyze', { id: local }); const an = (await sse('/api/events?id=' + local, 1200)).events.find(e => e[0] === 'live')[1].an; // review: the id stream now starts with hello, then live check('analysis', an.when > 0 && an.health >= 0 && an.grade.length === 1 && an.heat.length === 2 && an.up.length === 3, `health ${an.health} ${an.grade}; findings: ${an.findings.map(f => `[${f.severity}] ${f.title}`).join('; ') || 'none'}`); await post('server/reconnect', { id: local }); check('reconnect -> Connecting', (await state()).servers[0].status === 'Connecting'); await sleep(Math.max(6000, 72000 - (Date.now() - t0))); // let the server run for more than 70 s (a minute bucket closes) s = await state(); check('online again after reconnect', s.servers[0].online); for (const range of [3600, 86400, 0]) { const h = (await req('GET', `/api/history?id=${local}&range=${range}`)).json; check(`history range ${range || 'all'}`, h.points >= 1 && h.t.length >= h.points && h.v.cpu.length === h.t.length && h.stats.length === 15 && h.stats[0].count >= 1, `${h.tier}, ${h.points} points, availability ${h.availability?.toFixed(2)}%, cpu avg ${h.stats[0].avg?.toFixed(1)} p95 ${h.stats[0].p95?.toFixed(1)} max ${h.stats[0].max?.toFixed(1)}, stored ${h.bytes} B`); } r = await req('GET', `/api/history.csv?id=${local}&range=3600`); const lines = r.text.split('\n'); check('CSV export', r.status === 200 && lines[0].startsWith('time,samples,online_pct,cpu_avg,cpu_max,iowait_avg') && lines[0].split(',').length === 33 && lines.length > 10 && /^\d{4}-\d\d-\d\dT[\d:]{8},1,100,/.test(lines[1]) && /attachment/.test(r.headers['content-disposition']), `${lines.length - 1} rows; ${lines[1].slice(0, 60)}`); r = await req('GET', '/api/alerts.log'); check('alerts.log download = file on disk', r.status === 200 && r.text === fs.readFileSync(path.join(dir, 'alerts.log'), 'utf8') && /^\d{4}-\d\d-\d\dT[\d:]{8}\t(critical|warning|info|resolved|action)\t[^\t]+\t./.test(r.text), `${r.text.split('\n').length - 1} lines`); const hd = path.join(dir, 'history', local), files = fs.readdirSync(hd); check('history files: SMH1 header + 136-byte records', files.includes('raw.bin') && files.includes('minute.bin') && files.every(f => { const b = fs.readFileSync(path.join(hd, f)); return b.subarray(0, 8).equals(Buffer.from([0x53, 0x4d, 0x48, 0x31, 15, 0, 136, 0])) && (b.length - 8) % 136 === 0 && b.length > 8; }), files.map(f => `${f} ${fs.statSync(path.join(hd, f)).size} B`).join(', ')); check('offline host: downtime recorded for availability', fs.statSync(path.join(dir, 'history', dead, 'raw.bin')).size > 8 && (await req('GET', `/api/history?id=${dead}&range=3600`)).json.availability === 0); await post('alerts/clear', {}); check('clear events', (await state()).alerts.length === 0); // --- remove --- await post('server/remove', { id: added, deleteHistory: true }); await post('server/remove', { id: ssh, deleteHistory: false }); s = await state(); check('remove servers (delete history / keep history files)', s.servers.length === 2 && !fs.existsSync(path.join(dir, 'history', added)) && fs.existsSync(path.join(dir, 'history', ssh)) && stored().servers.length === 2); console.log(`\n${failed ? failed + ' check(s) FAILED' : 'all checks passed'} — server ran ${(Math.round((Date.now() - t0) / 1000))} s during the test`); process.exit(failed ? 1 : 0); })().catch(e => { console.error('TEST ERROR', e); process.exit(2); });