'use strict'; /** * Unit tests for server/routes/admin.js — user CRUD and config management. */ const express = require('express'); const http = require('http'); const { once } = require('events'); const crypto = require('crypto'); const fs = require('fs'); const os = require('os'); const path = require('path'); let mockVideoStreamSnapshot = { streamRootDir: '/tmp/filemanager-video-streams', activeSessionCount: 0, activeLeaseCount: 0, activeStreams: [], orphanedOutputDirs: [], }; let mockSubtitleSnapshot = { eventCache: { entries: 0, bytes: 0, maxItems: 3, maxBytes: 0 }, frameCache: { entries: 0, bytes: 0, maxItems: 50, maxBytes: 0 }, byFile: {}, }; let mockRestartSchedulerSnapshot = { running: true, startedAt: Date.now(), lastTickAt: Date.now(), nextDueAt: Date.now() + 3600000, pendingSinceAt: null, lastShutdownAt: null, lastDecision: 'waiting-next-window', lastError: null, underSystemd: true, config: { enabled: false, cadence: 'daily', time: '04:00' }, intervalMs: 60000, }; // ── child_process mock — controlled per test ────────────────────────────────── let mockExecFileImpl = null; jest.mock('child_process', () => { const real = jest.requireActual('child_process'); return { ...real, execFile: jest.fn((...args) => { const cb = args[args.length - 1]; if (typeof mockExecFileImpl === 'function') { mockExecFileImpl(...args); return; } // Default: simulate git not available. cb(new Error('git not found')); }), }; }); // ── in-memory DB mock ─────────────────────────────────────────────────────── jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; function getDb () { if (!db) { db = new Database(':memory:'); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]' ); CREATE TABLE IF NOT EXISTS auth_sessions ( session_id TEXT PRIMARY KEY, username TEXT NOT NULL, ip TEXT NOT NULL, region TEXT NOT NULL, fp_hash TEXT NOT NULL, created_at INTEGER NOT NULL, last_seen_at INTEGER NOT NULL, revoked_at INTEGER ); CREATE TABLE IF NOT EXISTS share_tokens ( token TEXT PRIMARY KEY, file_path TEXT NOT NULL, is_dir INTEGER NOT NULL DEFAULT 0, created_by TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); `); } return db; } return { getDb, initDb: getDb }; }); jest.mock('../server/video-stream', () => ({ getVideoStreamDebugSnapshot: () => mockVideoStreamSnapshot, })); jest.mock('../server/image-subtitles', () => ({ getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot, })); jest.mock('../server/restart-scheduler', () => ({ getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot, })); // ── config mock ───────────────────────────────────────────────────────────── const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null, scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' }, }; jest.mock('../server/config', () => ({ loadConfig: () => ({ ...mockConfig }), saveConfig: (c) => Object.assign(mockConfig, c), getEffectivePaths: (p) => p, getAllowedRoot: () => null, })); // ── auth mock — bypass JWT verification ───────────────────────────────────── let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} }; jest.mock('../server/auth', () => ({ requireAuth: (req, res, next) => { req.user = mockUser; next(); }, requireAdmin: (req, res, next) => { if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' }); next(); }, createToken: () => 'mock-token', getClientIp: () => '127.0.0.1', getRegion: () => 'US:CA', clearAuthUserCache: () => {}, })); const adminRoutes = require('../server/routes/admin'); const { getDb } = require('../server/db'); const bcrypt = require('bcrypt'); jest.setTimeout(30000); // ── seed a default admin before anything runs ──────────────────────────────── beforeAll(() => { const db = getDb(); const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)') .run(['admin', hash, '{}']); }); // ── build minimal app ──────────────────────────────────────────────────────── let server; let baseUrl; let shutdownForRestartMock; beforeAll(async () => { const app = express(); shutdownForRestartMock = jest.fn(); app.set('shutdownForRestart', shutdownForRestartMock); app.use(express.json()); app.use('/api/admin', adminRoutes); app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: err.message || 'Internal error' }); }); server = http.createServer(app); server.listen(0); await once(server, 'listening'); baseUrl = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => server.close()); // ── helpers ────────────────────────────────────────────────────────────────── function req (method, path, body) { const payload = body ? JSON.stringify(body) : undefined; return new Promise((resolve, reject) => { const r = http.request(baseUrl + path, { method, headers: { 'Content-Type': 'application/json', ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), }, }, res => { let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); }); r.on('error', reject); if (payload) r.write(payload); r.end(); }); } // ── tests ───────────────────────────────────────────────────────────────────── describe('GET /api/admin/users', () => { test('returns the list of users', async () => { const { status, body } = await req('GET', '/api/admin/users'); expect(status).toBe(200); expect(Array.isArray(body.users)).toBe(true); expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true }); }); }); describe('POST /api/admin/users', () => { test('creates a new user', async () => { const { status, body } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {}, }); expect(status).toBe(201); expect(body.ok).toBe(true); }); test('rejects duplicate username', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {}, }); expect(status).toBe(409); }); test('rejects duplicate username with different case', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'BoB', password: 'bobpass3', isAdmin: false, permissions: {}, }); expect(status).toBe(409); }); test('rejects short password', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'carol', password: 'short', isAdmin: false, permissions: {}, }); expect(status).toBe(400); }); test('normalizes permissions so write implies read on create', async () => { const { status } = await req('POST', '/api/admin/users', { username: 'dora', password: 'dora-pass1', isAdmin: false, permissions: { data: { read: false, write: true } }, }); expect(status).toBe(201); const { body } = await req('GET', '/api/admin/users'); const dora = body.users.find(u => u.username === 'dora'); expect(dora.permissions).toMatchObject({ data: { read: true, write: true } }); }); }); describe('PATCH /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('updates permissions', async () => { const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, { permissions: { data: { read: true, write: false } }, }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('returns 404 for unknown user', async () => { const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false }); expect(status).toBe(404); }); test('normalizes permissions so write implies read on update', async () => { const { status } = await req('PATCH', `/api/admin/users/${bobId}`, { permissions: { data: { read: false, write: true } }, }); expect(status).toBe(200); const { body } = await req('GET', '/api/admin/users'); const bob = body.users.find(u => u.id === bobId); expect(bob.permissions).toMatchObject({ data: { read: true, write: true } }); }); test('rejects removing own admin privileges', async () => { const { status, body } = await req('PATCH', `/api/admin/users/${mockUser.id}`, { isAdmin: false, }); expect(status).toBe(400); expect(body.error).toMatch(/own admin privileges/i); const usersRes = await req('GET', '/api/admin/users'); const me = usersRes.body.users.find(u => String(u.id) === String(mockUser.id)); expect(me).toBeTruthy(); expect(me.isAdmin).toBe(true); }); }); describe('DELETE /api/admin/users/:id', () => { let bobId; beforeAll(async () => { const { body } = await req('GET', '/api/admin/users'); bobId = body.users.find(u => u.username === 'bob').id; }); test('cannot delete own account', async () => { // mock user id is 1 (admin); bob is a different id — but we test self-delete guard const adminId = mockUser.id; const { status } = await req('DELETE', `/api/admin/users/${adminId}`); expect(status).toBe(400); }); test('deletes another user', async () => { const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('cannot delete the last admin', async () => { // Only 'admin' left; try to delete them (switch mockUser to be different) const { body: users } = await req('GET', '/api/admin/users'); const adminUser = users.users.find(u => u.username === 'admin'); const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`); // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account" expect([400]).toContain(status); }); test('deletes an empty personal user folder when deleting that user account', async () => { const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-')); mockConfig.userPath = userFolderRoot; const db = getDb(); const hash = bcrypt.hashSync('freshpass1', 4); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['emptyfolderuser', hash, 0, '{}']); const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['emptyfolderuser']); const folderPath = path.join(userFolderRoot, 'emptyfolderuser'); fs.mkdirSync(folderPath, { recursive: true }); try { const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`); expect(status).toBe(200); expect(body.ok).toBe(true); expect(fs.existsSync(folderPath)).toBe(false); } finally { mockConfig.userPath = null; fs.rmSync(userFolderRoot, { recursive: true, force: true }); } }); test('keeps non-empty personal user folder when deleting that user account', async () => { const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-')); mockConfig.userPath = userFolderRoot; const db = getDb(); const hash = bcrypt.hashSync('freshpass2', 4); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['nonemptyuser', hash, 0, '{}']); const created = db.prepare('SELECT id FROM users WHERE username = ?').get(['nonemptyuser']); const folderPath = path.join(userFolderRoot, 'nonemptyuser'); fs.mkdirSync(folderPath, { recursive: true }); fs.writeFileSync(path.join(folderPath, 'keep.txt'), 'keep'); try { const { status, body } = await req('DELETE', `/api/admin/users/${created.id}`); expect(status).toBe(200); expect(body.ok).toBe(true); expect(fs.existsSync(folderPath)).toBe(true); } finally { mockConfig.userPath = null; fs.rmSync(userFolderRoot, { recursive: true, force: true }); } }); }); describe('GET /api/admin/orphan-userfolders', () => { test('returns only non-empty orphaned folders and deletes empty orphan folders', async () => { const userFolderRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-admin-userfolders-')); mockConfig.userPath = userFolderRoot; const linkedFolder = path.join(userFolderRoot, 'linkeduser'); const orphanFolder = path.join(userFolderRoot, 'ghostuser'); const emptyOrphanFolder = path.join(userFolderRoot, 'emptyghost'); fs.mkdirSync(linkedFolder, { recursive: true }); fs.mkdirSync(orphanFolder, { recursive: true }); fs.mkdirSync(emptyOrphanFolder, { recursive: true }); fs.writeFileSync(path.join(orphanFolder, 'file.txt'), 'hello'); const db = getDb(); const hash = bcrypt.hashSync('linked-pass1', 4); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['linkeduser', hash, 0, '{}']); try { const { status, body } = await req('GET', '/api/admin/orphan-userfolders'); expect(status).toBe(200); expect(Array.isArray(body.folders)).toBe(true); expect(body.folders).toEqual([ { folderName: 'ghostuser', path: orphanFolder, itemCount: 1, }, ]); expect(fs.existsSync(emptyOrphanFolder)).toBe(false); } finally { mockConfig.userPath = null; fs.rmSync(userFolderRoot, { recursive: true, force: true }); } }); }); describe('GET /api/admin/config', () => { test('returns port and paths', async () => { const { status, body } = await req('GET', '/api/admin/config'); expect(status).toBe(200); expect(body.port).toBe(3000); expect(Array.isArray(body.paths)).toBe(true); expect(body.scheduledRestart).toEqual(expect.objectContaining({ enabled: expect.any(Boolean), cadence: expect.any(String), time: expect.any(String), })); }); }); describe('GET /api/admin/debug/stream-stats', () => { test('includes active streams and cached-only video files with zero viewers', async () => { const now = Date.now(); mockVideoStreamSnapshot = { streamRootDir: '/tmp/filemanager-video-streams', activeSessionCount: 1, activeLeaseCount: 2, activeStreams: [ { sessionId: 'lease-live', sourcePath: '/videos/live.mkv', outputDir: '/tmp/filemanager-video-streams/live', viewers: 2, output: { totalFiles: 12, totalBytes: 12000000, segmentFiles: 10, segmentBytes: 11000000, }, }, ], orphanedOutputDirs: [], }; mockSubtitleSnapshot = { eventCache: { entries: 2, bytes: 4096, maxItems: 3, maxBytes: 52428800 }, frameCache: { entries: 4, bytes: 8192, maxItems: 50, maxBytes: 50331648 }, byFile: { '/videos/live.mkv': { filePath: '/videos/live.mkv', eventEntries: 1, eventBytes: 2048, eventCount: 30, eventImageBytes: 1500, frameEntries: 2, frameBytes: 4096, }, '/videos/cached-only.mkv': { filePath: '/videos/cached-only.mkv', eventEntries: 1, eventBytes: 2048, eventCount: 20, eventImageBytes: 1300, frameEntries: 2, frameBytes: 4096, }, }, }; const db = getDb(); db.prepare(`INSERT OR REPLACE INTO auth_sessions ( session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) .run(['sess-debug', 'admin', '127.0.0.1', 'EU', 'fp', now - 1000, now - 1000, null]); const { status, body } = await req('GET', '/api/admin/debug/stream-stats'); expect(status).toBe(200); expect(Array.isArray(body.videoFiles)).toBe(true); expect(body.maintenance).toEqual(expect.objectContaining({ uptimeMs: expect.any(Number), startedAt: expect.any(Number), rows: expect.objectContaining({ authSessionsTotal: expect.any(Number), shareTokensTotal: expect.any(Number), }), scheduledRestart: expect.objectContaining({ intervalMs: expect.any(Number), }), })); const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv'); expect(live).toBeTruthy(); expect(live.viewers).toBe(2); const cachedOnly = body.videoFiles.find((row) => row.filePath === '/videos/cached-only.mkv'); expect(cachedOnly).toBeTruthy(); expect(cachedOnly.viewers).toBe(0); expect(cachedOnly.subtitleCache.eventEntries).toBe(1); expect(body.subtitleDebugLog).toEqual(expect.objectContaining({ path: expect.stringContaining('filemanager-subtitle-debug-logs'), files: expect.any(Number), bytes: expect.any(Number), })); }); }); describe('PUT /api/admin/config', () => { test('saves new paths', async () => { const { status, body } = await req('PUT', '/api/admin/config', { paths: ['/mnt/newpath'], }); expect(status).toBe(200); expect(body.ok).toBe(true); }); test('rejects non-array paths', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' }); expect(status).toBe(400); }); test('rejects invalid port', async () => { const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 }); expect(status).toBe(400); }); test('saves scheduled restart config when running under systemd', async () => { const origInvocationId = process.env.INVOCATION_ID; process.env.INVOCATION_ID = 'test-invocation'; try { const { status, body } = await req('PUT', '/api/admin/config', { paths: ['/mnt/data'], scheduledRestart: { enabled: true, cadence: 'weekly', time: '03:45', }, }); expect(status).toBe(200); expect(body.ok).toBe(true); const readback = await req('GET', '/api/admin/config'); expect(readback.body.scheduledRestart).toEqual({ enabled: true, cadence: 'weekly', time: '03:45', }); } finally { if (origInvocationId === undefined) delete process.env.INVOCATION_ID; else process.env.INVOCATION_ID = origInvocationId; } }); test('rejects scheduled restart config when not running under systemd', async () => { const origInvocationId = process.env.INVOCATION_ID; delete process.env.INVOCATION_ID; try { const { status } = await req('PUT', '/api/admin/config', { paths: ['/mnt/data'], scheduledRestart: { enabled: true, cadence: 'daily', time: '02:15', }, }); expect(status).toBe(400); } finally { if (origInvocationId === undefined) delete process.env.INVOCATION_ID; else process.env.INVOCATION_ID = origInvocationId; } }); }); describe('POST /api/admin/shutdown', () => { test('responds ok and invokes shutdown callback', async () => { shutdownForRestartMock.mockClear(); const { status, body } = await req('POST', '/api/admin/shutdown'); expect(status).toBe(200); expect(body.ok).toBe(true); // Shutdown invocation is deferred via setImmediate(). await new Promise(resolve => setImmediate(resolve)); expect(shutdownForRestartMock).toHaveBeenCalledTimes(1); }); }); describe('GET /api/admin/update-status', () => { const origInvocationId = process.env.INVOCATION_ID; afterEach(() => { mockExecFileImpl = null; if (origInvocationId === undefined) delete process.env.INVOCATION_ID; else process.env.INVOCATION_ID = origInvocationId; }); test('returns underSystemd=false when INVOCATION_ID is not set', async () => { delete process.env.INVOCATION_ID; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(false); expect(body.commitsAhead).toEqual([]); }); test('returns underSystemd=true and commitsAhead when INVOCATION_ID is set and git reports commits', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; // git fetch succeeds, then git log returns two commits. let callCount = 0; let logArgs = null; mockExecFileImpl = (_cmd, _args, _opts, cb) => { callCount++; if (callCount === 1) cb(null, { stdout: '', stderr: '' }); // git fetch else { logArgs = _args; cb(null, { stdout: 'abc1234567890\x1fFix bug\x1fThis fixes an issue users were hitting.\x1e' + 'def5678901234\x1fAdd feature\x1fUsers can now do the new thing.\x1e', stderr: '', }); } }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(logArgs).toContain('--no-merges'); expect(body.commitsAhead).toEqual([ { hash: 'abc1234567890', subject: 'Fix bug', body: 'This fixes an issue users were hitting.', }, { hash: 'def5678901234', subject: 'Add feature', body: 'Users can now do the new thing.', }, ]); }); test('returns underSystemd=true and empty commitsAhead when git is up to date', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; let callCount = 0; mockExecFileImpl = (_cmd, _args, _opts, cb) => { callCount++; cb(null, { stdout: '', stderr: '' }); // fetch and log both return empty }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(body.commitsAhead).toEqual([]); }); test('returns underSystemd=true and empty commitsAhead when git fails', async () => { process.env.INVOCATION_ID = 'test-invocation-id'; mockExecFileImpl = (_cmd, _args, _opts, cb) => { cb(new Error('git: not found')); }; const { status, body } = await req('GET', '/api/admin/update-status'); expect(status).toBe(200); expect(body.underSystemd).toBe(true); expect(body.commitsAhead).toEqual([]); }); });