'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { EventEmitter } = require('node:events');
const { Duplex } = require('node:stream');
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const express = require('express');
const WebSocket = require('ws');
const { config } = require('../lib/config');
const { createApplication, createServer, attachLogConnection, handleHttpError, MAX_WS_PAYLOAD, MAX_WS_BUFFER } = require('../server');
class FakeSocket extends EventEmitter {
constructor() {
super();
this.readyState = WebSocket.OPEN;
this.bufferedAmount = 0;
this.sent = [];
this.closeCalls = [];
this.terminations = 0;
this.pings = 0;
}
send(text, callback) {
assert.equal(this.readyState, WebSocket.OPEN, 'Never send after a socket is closed.');
if (this.sendFailure) throw new Error('NOT_A_REAL_SEND_SECRET');
this.sent.push(JSON.parse(text));
callback?.(this.sendCallbackFailure ? new Error('NOT_A_REAL_CALLBACK_SECRET') : undefined);
}
close(code, reason) {
this.closeCalls.push({ code, reason });
this.readyState = WebSocket.CLOSED;
this.emit('close');
}
terminate() {
this.terminations++;
this.readyState = WebSocket.CLOSED;
this.emit('close');
}
ping() { this.pings++; }
}
function childProcess() {
const child = new EventEmitter();
child.stdout = new EventEmitter();
child.stderr = new EventEmitter();
child.killCalls = 0;
child.kill = () => { child.killCalls++; return true; };
return child;
}
function logFixture(resolveWorker = async name => ({ name, pm_id: '0' })) {
const socket = new FakeSocket();
const children = [];
const calls = [];
const connection = attachLogConnection(socket, {
settings: config,
resolveWorker,
spawnProcess: (...args) => {
calls.push(args);
const child = childProcess();
children.push(child);
return child;
},
});
return { socket, children, calls, connection };
}
const settle = () => new Promise(resolve => setImmediate(resolve));
async function message(socket, payload) {
socket.emit('message', Buffer.from(JSON.stringify(payload)), false);
await settle();
}
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
test('log subscriptions resolve a registered worker and invoke its numeric PM2 ID', async () => {
const names = [];
const fixture = logFixture(async name => { names.push(name); return { name, pm_id: '0' }; });
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
assert.deepEqual(names, ['proxer-worker-1']);
assert.deepEqual(fixture.calls[0], ['pm2', ['logs', '0', '--raw', '--lines', '200'], {
cwd: config.projectRoot,
stdio: ['ignore', 'pipe', 'pipe'],
}]);
fixture.connection.dispose();
});
test('log requests reject missing names, all, and option-like names without resolving or spawning', async () => {
let lookups = 0;
const fixture = logFixture(async () => { lookups++; return null; });
for (const name of [undefined, null, '', 'all', 'ALL', '--help', '-worker']) {
await message(fixture.socket, { type: 'logs', name });
}
assert.equal(lookups, 0);
assert.equal(fixture.calls.length, 0);
assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7);
});
test('unknown workers and invalid resolved IDs cannot start log processes', async () => {
for (const worker of [null, { pm_id: '-1' }, { pm_id: 'all' }, { pm_id: '9007199254740993' }]) {
const fixture = logFixture(async () => worker);
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
assert.equal(fixture.calls.length, 0);
assert.match(fixture.socket.sent.at(-1).error, /not found/);
}
});
test('null, arrays, primitives, malformed JSON, and binary requests are handled safely', async () => {
const fixture = logFixture();
for (const payload of [null, [], 'logs', 1, true]) await message(fixture.socket, payload);
fixture.socket.emit('message', Buffer.from('{'), false);
fixture.socket.emit('message', Buffer.from('{}'), true);
await settle();
assert.equal(fixture.calls.length, 0);
assert.equal(fixture.socket.sent.filter(item => item.type === 'error').length, 7);
});
test('oversized log requests close the connection with a bounded message', async () => {
const fixture = logFixture();
fixture.socket.emit('message', Buffer.from('x'.repeat(MAX_WS_PAYLOAD + 1)), false);
await settle();
assert.equal(fixture.socket.closeCalls[0].code, 1009);
assert.equal(fixture.calls.length, 0);
assert.ok(JSON.stringify(fixture.socket.sent).length < 1000);
});
test('log streams redact split-chunk URLs and credential lines and bound oversized lines', async () => {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
const child = fixture.children[0];
child.stdout.emit('data', Buffer.from('Resolved https://stream.inv'));
child.stdout.emit('data', Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE\n'));
child.stderr.emit('data', Buffer.from('Token=NOT_A_REAL_'));
child.stderr.emit('data', Buffer.from('TOKEN\n'));
child.stdout.emit('data', Buffer.from('x'.repeat(100_000) + '\n'));
child.stdout.emit('data', Buffer.from('Completed a fixture'));
child.emit('close', 0);
const output = fixture.socket.sent.filter(item => ['stdout', 'stderr'].includes(item.type));
assert.doesNotMatch(JSON.stringify(output), /NOT_A_REAL_|https:\/\/|stream\.invalid/);
assert.match(JSON.stringify(output), /redacted URL/);
assert.match(JSON.stringify(output), /oversized log line omitted/);
assert.match(JSON.stringify(output), /Completed a fixture/);
assert.ok(JSON.stringify(output).length < 1000);
});
test('stop-logs kills the subscription and suppresses later child output', async () => {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
const child = fixture.children[0];
await message(fixture.socket, { type: 'stop-logs' });
const count = fixture.socket.sent.length;
child.stdout.emit('data', Buffer.from('stale output\n'));
child.emit('close', 0);
assert.equal(child.killCalls, 1);
assert.equal(fixture.socket.sent.length, count);
});
test('disconnect and socket errors clean up children without sending on a closed connection', async () => {
for (const event of ['close', 'error']) {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
fixture.socket.readyState = WebSocket.CLOSED;
fixture.socket.emit(event, new Error('NOT_A_REAL_SOCKET_SECRET'));
const count = fixture.socket.sent.length;
fixture.children[0].stderr.emit('data', Buffer.from('late output\n'));
fixture.children[0].emit('error', new Error('NOT_A_REAL_LATE_SECRET'));
assert.equal(fixture.children[0].killCalls, 1);
assert.equal(fixture.socket.sent.length, count);
}
});
test('stop and disconnect invalidate a pending worker lookup before it can spawn', async () => {
for (const action of ['stop', 'disconnect']) {
const pending = deferred();
const fixture = logFixture(() => pending.promise);
await message(fixture.socket, { type: 'logs', name: 'proxer-worker-1' });
if (action === 'stop') await message(fixture.socket, { type: 'stop-logs' });
else fixture.socket.close(1000, 'fixture finished');
pending.resolve({ pm_id: '0' });
await settle();
assert.equal(fixture.calls.length, 0, action);
}
});
test('a newer selection wins when an older worker lookup resolves later', async () => {
const old = deferred();
const fixture = logFixture(name => name === 'worker-old' ? old.promise : Promise.resolve({ pm_id: '2' }));
await message(fixture.socket, { type: 'logs', name: 'worker-old' });
await message(fixture.socket, { type: 'logs', name: 'worker-new' });
old.resolve({ pm_id: '1' });
await settle();
assert.equal(fixture.calls.length, 1);
assert.equal(fixture.calls[0][1][1], '2');
fixture.connection.dispose();
});
test('late close events from an old log process cannot clear a new subscription', async () => {
const fixture = logFixture(async name => ({ pm_id: name === 'worker-old' ? '1' : '2' }));
await message(fixture.socket, { type: 'logs', name: 'worker-old' });
await message(fixture.socket, { type: 'logs', name: 'worker-new' });
const old = fixture.children[0];
const current = fixture.children[1];
assert.equal(old.killCalls, 1);
old.emit('close', 0);
current.stdout.emit('data', Buffer.from('new subscription is active\n'));
assert.match(fixture.socket.sent.at(-1).data, /new subscription is active/);
assert.equal(fixture.socket.sent.some(item => item.type === 'close'), false);
fixture.connection.dispose();
assert.equal(current.killCalls, 1);
});
test('lookup and spawn errors return generic messages without raw details', async () => {
const fixture = logFixture(async () => { throw new Error('NOT_A_REAL_LOOKUP_SECRET'); });
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/);
const socket = new FakeSocket();
attachLogConnection(socket, {
resolveWorker: async () => ({ pm_id: '0' }),
spawnProcess: () => { throw new Error('NOT_A_REAL_SPAWN_SECRET'); },
});
await message(socket, { type: 'logs', name: 'worker-one' });
assert.equal(socket.sent.at(-1).type, 'error');
assert.doesNotMatch(JSON.stringify(socket.sent), /NOT_A_REAL_/);
});
test('asynchronous child and pipe errors are handled and cleaned up', async () => {
for (const source of ['child', 'stdout', 'stderr']) {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
const child = fixture.children[0];
(source === 'child' ? child : child[source]).emit('error', new Error('NOT_A_REAL_PIPE_SECRET'));
assert.equal(child.killCalls, 1);
assert.equal(fixture.socket.sent.at(-1).type, 'error');
assert.doesNotMatch(JSON.stringify(fixture.socket.sent), /NOT_A_REAL_/);
}
});
test('a slow WebSocket consumer is disconnected and its log child is stopped', async () => {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
fixture.socket.bufferedAmount = MAX_WS_BUFFER;
fixture.children[0].stdout.emit('data', Buffer.from('next bounded line\n'));
assert.equal(fixture.socket.closeCalls.at(-1).code, 1013);
assert.equal(fixture.children[0].killCalls, 1);
});
test('WebSocket send failures clean up the active subscription', async () => {
for (const property of ['sendFailure', 'sendCallbackFailure']) {
const fixture = logFixture();
await message(fixture.socket, { type: 'logs', name: 'worker-one' });
fixture.socket[property] = true;
fixture.children[0].stdout.emit('data', Buffer.from('next line\n'));
assert.equal(fixture.children[0].killCalls, 1);
assert.equal(fixture.socket.closeCalls.at(-1).code, 1011);
}
});
test('HTTP error rendering and JSON responses exclude raw errors and stacks', () => {
function response() {
return {
status(code) { this.statusCode = code; return this; },
json(body) { this.body = body; return this; },
render(view, body) { this.view = view; this.body = body; return this; },
};
}
for (const api of [false, true]) {
const res = response();
handleHttpError(new Error('NOT_A_REAL_DATABASE_SECRET'), { path: api ? '/pm2/list-json' : '/', is: () => false }, res, () => assert.fail('Unexpected next().'));
assert.equal(res.statusCode, 500);
assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stack|Error:/);
if (!api) assert.equal(res.view, 'error');
}
let forwarded;
handleHttpError(new Error('NOT_A_REAL_SECRET'), {}, { headersSent: true }, error => { forwarded = error; });
assert.doesNotMatch(forwarded.message, /NOT_A_REAL_/);
});
// Exercise Express body parsing using real HTTP message objects and no listening socket.
function offlineRequest(app, body, contentType = 'application/json') {
return new Promise((resolve, reject) => {
const socket = new Duplex({ read() {}, write(chunk, encoding, callback) { callback(); } });
const request = new http.IncomingMessage(socket);
const bytes = Buffer.from(body);
request.method = 'POST';
request.url = '/pm2/fixture';
request.headers = { 'content-type': contentType, 'content-length': String(bytes.length) };
const response = new http.ServerResponse(request);
const timeout = setTimeout(() => reject(new Error('Offline HTTP fixture did not complete.')), 2000);
response.end = data => {
clearTimeout(timeout);
resolve({ status: response.statusCode, text: String(data ?? '') });
socket.destroy();
return response;
};
app.handle(request, response, error => {
clearTimeout(timeout);
socket.destroy();
reject(error || new Error('Offline HTTP fixture was not handled.'));
});
request.push(bytes);
request.push(null);
});
}
test('application factory has safe shared locals and enforces32KiB JSON/form limits without listening', async () => {
const router = express.Router();
router.post('/pm2/fixture', (req, res) => res.json({ received: req.body }));
const app = createApplication({ router });
assert.deepEqual(app.locals.global, { captcha_blocked: false });
const valid = await offlineRequest(app, JSON.stringify({ title: 'Fixture' }));
assert.equal(valid.status, 200);
assert.deepEqual(JSON.parse(valid.text), { received: { title: 'Fixture' } });
const invalid = await offlineRequest(app, '{NOT_A_REAL_PARSE_SECRET');
assert.equal(invalid.status, 400);
assert.doesNotMatch(invalid.text, /NOT_A_REAL_/);
const largeJson = await offlineRequest(app, JSON.stringify({ text: 'x'.repeat(33 * 1024) }));
assert.equal(largeJson.status, 413);
const largeForm = await offlineRequest(app, 'text=' + 'x'.repeat(33 * 1024), 'application/x-www-form-urlencoded');
assert.equal(largeForm.status, 413);
});
test('server construction does not listen and heartbeat/server close clean up log children and timer', async () => {
const server = new EventEmitter();
server.listening = false;
server.listen = () => assert.fail('createServer must not listen automatically.');
class FakeWebSocketServer extends EventEmitter {
constructor(options) { super(); this.options = options; this.clients = new Set(); this.closed = false; }
close() { if (!this.closed) { this.closed = true; this.emit('close'); } }
}
let tick;
let cleared = 0;
const interval = { unref() {} };
const child = childProcess();
const runtime = createServer({
router: express.Router(),
createHttpServer: () => server,
WebSocketServer: FakeWebSocketServer,
scheduleInterval: (callback, period) => { tick = callback; assert.equal(period, 30_000); return interval; },
cancelInterval: actual => { assert.equal(actual, interval); cleared++; },
resolveWorker: async () => ({ pm_id: '0' }),
spawnProcess: () => child,
});
assert.equal(runtime.wss.options.maxPayload, 16 * 1024);
const socket = new FakeSocket();
runtime.wss.clients.add(socket);
runtime.wss.emit('connection', socket);
await message(socket, { type: 'logs', name: 'worker-one' });
tick();
assert.equal(socket.pings, 1);
socket.emit('pong');
tick();
assert.equal(socket.pings, 2);
tick();
assert.equal(socket.terminations, 1);
assert.equal(child.killCalls, 1);
server.emit('close');
assert.equal(cleared, 1);
assert.equal(runtime.wss.closed, true);
await runtime.close();
assert.equal(cleared, 1);
});
test('worker view escapes process fields and exposes accessible scoped controls', async () => {
const filename = path.join(config.projectRoot, 'views/pm2.ejs');
const template = fs.readFileSync(filename, 'utf8');
const attack = '
';
const rendered = await require('ejs').renderFile(filename, {
processes: [{ name: attack, pm_id: '0', pid: '12', status: attack, execPath: attack,
cpu: '1.2%', memoryMB: '40 MB', uptime: '1m' }],
});
assert.equal(template.includes('id="btn-save"'), false);
assert.equal(template.includes('/home/pm2/'), false);
assert.ok(template.indexOf('id="control-output"') < template.indexOf('id="control-centre"'));
assert.match(template, /