'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const path = require('node:path'); const { createConfig } = require('../lib/config'); const { createDbProvider } = require('../lib/mongo'); const { LOG_LIMIT, sanitizeLog, createLineSanitizer } = require('../lib/logging'); const { createPm2Controller, normalizeProcess } = require('../controllers/pm2Controller'); const settings = createConfig({ MONGO_URI: 'mongodb://fixture-user:NOT_A_REAL_PASSWORD@database.invalid/fixture', MONGO_DB: 'phase1_fixture', }); function response() { return { statusCode: 200, status(code) { this.statusCode = code; return this; }, json(value) { this.body = value; return this; }, render(view, value) { this.view = view; this.body = value; return this; }, }; } function pm2Process(overrides = {}) { return { name: 'proxer-worker-1', pid: 1234, pm_id: 0, monit: { cpu: 2.5, memory: 8 * 1024 * 1024 }, pm2_env: { name: 'proxer-worker-1', pm_id: 0, status: 'online', pm_uptime: Date.now() - 60_000, pm_exec_path: settings.workerScript, MONGO_URI: settings.mongoUri, TOKEN: 'NOT_A_REAL_PM2_TOKEN', env: { PASSWORD: 'NOT_A_REAL_PM2_PASSWORD' }, }, ...overrides, }; } function supervisor(processes = [], commandResult = {}) { const calls = []; const controller = createPm2Controller({ settings, run: async args => { calls.push([...args]); if (args[0] === 'jlist') return { code: 0, stdout: JSON.stringify(processes), stderr: '' }; return { code: 0, stdout: 'NOT_A_REAL_STDOUT_SECRET', stderr: 'NOT_A_REAL_STDERR_SECRET', ...commandResult }; }, }); return { controller, calls }; } test('configuration defaults describe a portable home-directory installation', () => { const config = createConfig({}); assert.equal(config.mongoDb, 'downloads'); assert.equal(config.outputDir, '/mnt/media/WIP'); assert.equal(config.pythonPath, 'python3'); assert.equal(config.maxSeriesEpisodes, 500); assert.equal(config.port, 3000); assert.equal(config.mongoUri, ''); assert.equal(config.tokenPrefix, ''); assert.equal(config.workerScript, path.join(config.projectRoot, 'queue_worker.js')); assert.equal(config.videoScript, path.join(config.projectRoot, 'scripts/proxer-dl-video.py')); assert.equal(Object.isFrozen(config), true); }); test('web and worker configuration share explicit database and path overrides', () => { const config = createConfig({ MONGO_URI: settings.mongoUri, MONGO_DB: 'private_download_queue', OUTPUT_DIR: '/mnt/media/fixture-output', VENV_PYTHON: '/home/fixture-download/Proxer-Downloader/.venv/bin/python', TOKEN_PREFIX: 'FIXTURE_COOKIE=', MAX_SERIES_EPISODES: '120', PORT: '3033', HOST: '127.0.0.1', }); assert.equal(config.mongoUri, settings.mongoUri); assert.equal(config.mongoDb, 'private_download_queue'); assert.equal(config.outputDir, '/mnt/media/fixture-output'); assert.equal(config.pythonPath, '/home/fixture-download/Proxer-Downloader/.venv/bin/python'); assert.equal(config.tokenPrefix, 'FIXTURE_COOKIE='); assert.equal(config.maxSeriesEpisodes, 120); assert.equal(config.port, 3033); assert.equal(config.host, '127.0.0.1'); }); test('configuration rejects malformed, unsafe, and out-of-range positive integers', () => { for (const value of ['0', '-1', '1.5', 'Infinity', '12x', ' 12 ', '9007199254740993']) { assert.throws(() => createConfig({ PORT: value }), /PORT/); assert.throws(() => createConfig({ MAX_SERIES_EPISODES: value }), /MAX_SERIES_EPISODES/); } assert.throws(() => createConfig({ PORT: '65536' }), /PORT/); assert.throws(() => createConfig({ MAX_SERIES_EPISODES: '10001' }), /MAX_SERIES_EPISODES/); assert.equal(createConfig({ PORT: '', MAX_SERIES_EPISODES: '' }).port, 3000); }); test('concurrent database callers share one connection and the configured database', async () => { let instances = 0; let connections = 0; let closes = 0; const selectedNames = []; const selectedDb = { fixture: true }; let release; const connected = new Promise(resolve => { release = resolve; }); class FakeMongoClient { constructor(uri) { instances++; assert.equal(uri, settings.mongoUri); } async connect() { connections++; await connected; } db(name) { selectedNames.push(name); return selectedDb; } async close() { closes++; } } const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); const resultsPromise = Promise.all([provider.getDb(), provider.getDb(), provider.getDb()]); await Promise.resolve(); release(); const results = await resultsPromise; assert.equal(instances, 1); assert.equal(connections, 1); assert.deepEqual(selectedNames, ['phase1_fixture']); assert.equal(results.every(value => value === selectedDb), true); assert.equal(await provider.getDb(), selectedDb); await provider.closeDb(); assert.equal(closes, 1); }); test('a failed database connection is sanitized, closed, and retryable', async () => { let instances = 0; let closes = 0; const selectedDb = { recovered: true }; class FakeMongoClient { constructor() { this.attempt = ++instances; } async connect() { if (this.attempt === 1) throw new Error(`connect failed: ${settings.mongoUri}`); } db() { return selectedDb; } async close() { closes++; } } const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); await assert.rejects(provider.getDb(), error => { assert.match(error.message, /Database connection failed/); assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); assert.equal(error.message.includes('mongodb://'), false); return true; }); assert.equal(closes, 1); assert.equal(await provider.getDb(), selectedDb); assert.equal(instances, 2); await provider.closeDb(); }); test('database client construction errors cannot reveal the connection URI', async () => { class ConstructorFailure { constructor() { throw new Error(`Invalid URI: ${settings.mongoUri}`); } } const provider = createDbProvider({ settings, MongoClientClass: ConstructorFailure }); await assert.rejects(provider.getDb(), error => { assert.match(error.message, /Database connection failed/); assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); return true; }); await provider.closeDb(); }); test('database selection errors are sanitized and do not poison later attempts', async () => { let instances = 0; let closes = 0; const selectedDb = { recovered: true }; class SelectionFailure { constructor() { this.attempt = ++instances; } async connect() {} db() { if (this.attempt === 1) throw new Error(`database selection failed: ${settings.mongoUri}`); return selectedDb; } async close() { closes++; } } const provider = createDbProvider({ settings, MongoClientClass: SelectionFailure }); await assert.rejects(provider.getDb(), error => { assert.match(error.message, /Database connection failed/); assert.equal(error.message.includes('NOT_A_REAL_PASSWORD'), false); return true; }); assert.equal(closes, 1); assert.equal(await provider.getDb(), selectedDb); assert.equal(instances, 2); await provider.closeDb(); }); test('missing database configuration fails before constructing any client', async () => { class UnexpectedClient { constructor() { assert.fail('A client must not be created without MONGO_URI.'); } } const provider = createDbProvider({ settings: createConfig({}), MongoClientClass: UnexpectedClient }); await assert.rejects(provider.getDb(), /MONGO_URI must be configured/); await provider.closeDb(); }); test('database close is idempotent, waits for a pending connection, and allows reopening', async () => { let instances = 0; let closes = 0; let release; const connected = new Promise(resolve => { release = resolve; }); class FakeMongoClient { constructor() { this.attempt = ++instances; } async connect() { if (this.attempt === 1) await connected; } db() { return { attempt: this.attempt }; } async close() { closes++; } } const provider = createDbProvider({ settings, MongoClientClass: FakeMongoClient }); const pending = provider.getDb(); const closing = provider.closeDb(); release(); await Promise.all([pending, closing]); assert.equal(closes, 1); await provider.closeDb(); assert.equal(closes, 1); assert.deepEqual(await provider.getDb(), { attempt: 2 }); await provider.closeDb(); assert.equal(closes, 2); }); test('logs redact URLs, credential fields, explicit secrets, and terminal control characters', () => { const raw = [ 'Resolved https://stream.invalid/video.mp4?signature=NOT_A_REAL_SIGNATURE', 'Database mongodb+srv://fixture:NOT_A_REAL_PASSWORD@database.invalid/', 'Authorization: Bearer NOT_A_REAL_BEARER', 'Cookie=FIXTURE_COOKIE=NOT_A_REAL_COOKIE', 'Raw known value KNOWN_FIXTURE_SECRET==', '\x1b[31mReadable status\x1b[0m\x00', ].join('\n'); const sanitized = sanitizeLog(raw, ['KNOWN_FIXTURE_SECRET==']); assert.doesNotMatch(sanitized, /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|https:\/\/|mongodb\+srv:\/\/|\x1b|\x00/); assert.match(sanitized, /Readable status/); assert.match(sanitized, /\[redacted URL\]/); }); test('streamed log redaction handles URLs and secrets split across pipe chunks', () => { const lines = []; const sanitizer = createLineSanitizer(line => lines.push(line), { secrets: ['KNOWN_FIXTURE_SECRET=='] }); sanitizer.write(Buffer.from('Resolving https://stream.inv')); sanitizer.write(Buffer.from('alid/video?signature=NOT_A_REAL_SIGNATURE and KNOWN_FIX')); assert.deepEqual(lines, []); sanitizer.write(Buffer.from('TURE_SECRET==\n')); sanitizer.end(); assert.equal(lines.length, 1); assert.doesNotMatch(lines.join(''), /NOT_A_REAL_|KNOWN_FIXTURE_SECRET|stream\.invalid|https:/); assert.match(lines.join(''), /\[redacted URL\]/); assert.match(lines.join(''), /\[redacted\]/); }); test('streamed log decoding preserves UTF-8 and sanitizes the unterminated final line', () => { const lines = []; const sanitizer = createLineSanitizer(line => lines.push(line)); const input = Buffer.from('Grüße — fertig\nToken=NOT_A_REAL_TOKEN'); const split = input.indexOf(Buffer.from('ü')) + 1; sanitizer.write(input.subarray(0, split)); sanitizer.write(input.subarray(split)); sanitizer.end(); assert.equal(lines[0], 'Grüße — fertig\n'); assert.doesNotMatch(lines.join(''), /NOT_A_REAL_TOKEN|�/); }); test('oversized streamed lines are discarded whole and subsequent lines recover', () => { const lines = []; const sanitizer = createLineSanitizer(line => lines.push(line), { maxLineLength: 32 }); sanitizer.write('x'.repeat(100_000)); sanitizer.write('NOT_A_REAL_TRAILING_SECRET\nNormal status\n'); sanitizer.end(); assert.deepEqual(lines, ['[oversized log line omitted]\n', 'Normal status\n']); }); test('large stored logs remain bounded after redaction', () => { const sanitized = sanitizeLog('x'.repeat(LOG_LIMIT * 4) + '\nToken=NOT_A_REAL_TOKEN'); assert.ok(sanitized.length <= LOG_LIMIT + 64); assert.match(sanitized, /^\[earlier log output omitted\]/); assert.doesNotMatch(sanitized, /NOT_A_REAL_TOKEN/); }); test('normalized PM2 data retains process ID zero and excludes raw environments', () => { const normalized = normalizeProcess(pm2Process()); assert.equal(normalized.pm_id, '0'); assert.equal(normalized.cpu, '2.5%'); assert.equal(normalized.memoryMB, '8 MB'); assert.deepEqual(Object.keys(normalized).sort(), ['name', 'pid', 'pm_id', 'status', 'cpu', 'memoryMB', 'uptime', 'execPath'].sort()); assert.doesNotMatch(JSON.stringify(normalized), /NOT_A_REAL_|MONGO_URI|pm2_env|"raw"/); }); test('worker lists and management pages include only the configured worker executable', async () => { const { controller, calls } = supervisor([ pm2Process(), pm2Process({ name: 'unrelated-app', pm_id: 3, pm2_env: { pm_exec_path: '/srv/unrelated/queue_worker.js', status: 'online' } }), pm2Process({ name: 'same-prefix', pm_id: 4, pm2_env: { pm_exec_path: settings.workerScript + '.unrelated' } }), ]); const json = response(); await controller.listJson({}, json); assert.equal(json.statusCode, 200); assert.equal(json.body.processes.length, 1); assert.equal(json.body.processes[0].name, 'proxer-worker-1'); assert.doesNotMatch(JSON.stringify(json.body), /NOT_A_REAL_|unrelated-app|same-prefix|pm2_env/); const page = response(); await controller.getManage({}, page, error => { throw error; }); assert.equal(page.view, 'pm2'); assert.equal(page.body.processes.length, 1); assert.deepEqual(calls, [['jlist'], ['jlist']]); }); test('PM2 management rejects all and leading-option names before calling the supervisor', async () => { const { controller, calls } = supervisor([pm2Process()]); for (const name of ['all', 'ALL', '--help', '-worker']) { const res = response(); await controller.postCommand({ body: { cmd: 'stop', name } }, res); assert.equal(res.statusCode, 400, name); assert.equal(res.body.ok, false); assert.equal(await controller.resolveManagedProcess(name), null); } assert.deepEqual(calls, []); }); test('worker creation rejects arbitrary script paths before invoking PM2', async () => { const { controller, calls } = supervisor([]); const res = response(); await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2', scriptPath: '/tmp/unrelated-script.js' } }, res); assert.equal(res.statusCode, 400); assert.deepEqual(calls, []); }); test('worker creation uses server-owned executable and cwd without returning PM2 output', async () => { const { controller, calls } = supervisor([]); const res = response(); await controller.postCommand({ body: { cmd: 'create', name: 'proxer-worker-2' } }, res); assert.equal(res.statusCode, 200); assert.equal(res.body.ok, true); assert.deepEqual(calls[0], ['jlist']); const create = calls[1]; assert.deepEqual(create.slice(0, 4), ['start', settings.workerScript, '--name', 'proxer-worker-2']); assert.equal(create[create.indexOf('--cwd') + 1], settings.projectRoot); assert.equal(create[create.indexOf('--interpreter') + 1], process.execPath); assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr|pm2_env/); }); test('worker creation cannot reuse an unrelated PM2 process name', async () => { const unrelated = pm2Process({ name: 'existing-service', pm2_env: { pm_exec_path: '/srv/existing-service.js' } }); const { controller, calls } = supervisor([unrelated]); const res = response(); await controller.postCommand({ body: { cmd: 'create', name: 'existing-service' } }, res); assert.equal(res.statusCode, 409); assert.deepEqual(calls, [['jlist']]); }); test('worker commands target the resolved numeric PM2 ID, including zero', async () => { for (const cmd of ['start', 'stop', 'restart', 'delete']) { const { controller, calls } = supervisor([pm2Process()]); const res = response(); await controller.postCommand({ body: { cmd, name: 'proxer-worker-1' } }, res); assert.equal(res.statusCode, 200, cmd); assert.deepEqual(calls, [['jlist'], [cmd, '0']]); assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/); } }); test('commands cannot target unrelated, ambiguous, or invalid-ID PM2 processes', async () => { const cases = [ [pm2Process({ pm2_env: { pm_exec_path: '/srv/unrelated.js' } })], [pm2Process(), pm2Process({ pm_id: 1 })], [pm2Process({ pm_id: -1 })], [pm2Process({ pm_id: '0' })], ]; for (const processes of cases) { const { controller, calls } = supervisor(processes); const res = response(); await controller.postCommand({ body: { cmd: 'stop', name: 'proxer-worker-1' } }, res); assert.equal(res.statusCode, 404); assert.deepEqual(calls, [['jlist']]); } }); test('PM2 command failures return a useful status without raw stderr', async () => { const { controller } = supervisor([pm2Process()], { code: 1 }); const res = response(); await controller.postCommand({ body: { cmd: 'restart', name: 'proxer-worker-1' } }, res); assert.equal(res.statusCode, 502); assert.equal(res.body.ok, false); assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_|stdout|stderr/); }); test('PM2 availability and malformed-list errors are sanitized', async () => { for (const run of [ async () => { throw new Error('NOT_A_REAL_SUPERVISOR_SECRET'); }, async () => ({ code: 0, stdout: 'NOT_A_REAL_INVALID_JSON', stderr: '' }), async () => ({ code: 0, stdout: '{}', stderr: '' }), async () => ({ code: 2, stdout: '[]', stderr: 'NOT_A_REAL_STDERR_SECRET' }), ]) { const controller = createPm2Controller({ settings, run }); const res = response(); await controller.listJson({}, res); assert.equal(res.statusCode, 503); assert.doesNotMatch(JSON.stringify(res.body), /NOT_A_REAL_/); } }); test('host-wide PM2 save returns409 without running a supervisor command', async () => { const { controller, calls } = supervisor([pm2Process()]); const res = response(); await controller.postCommand({ body: { cmd: 'save' } }, res); assert.equal(res.statusCode, 409); assert.equal(res.body.ok, false); assert.deepEqual(calls, []); });