| 1 | 'use strict'; |
| 2 | |
| 3 | /** |
| 4 | * Unit tests for server/routes/admin.js — user CRUD and config management. |
| 5 | */ |
| 6 | |
| 7 | const express = require('express'); |
| 8 | const http = require('http'); |
| 9 | const { once } = require('events'); |
| 10 | const crypto = require('crypto'); |
| 11 | |
| 12 | // ── in-memory DB mock ─────────────────────────────────────────────────────── |
| 13 | jest.mock('../server/db', () => { |
| 14 | const { Database } = require('node-sqlite3-wasm'); |
| 15 | let db; |
| 16 | function getDb() { |
| 17 | if (!db) { |
| 18 | db = new Database(':memory:'); |
| 19 | db.exec(` |
| 20 | CREATE TABLE IF NOT EXISTS users ( |
| 21 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 22 | username TEXT UNIQUE NOT NULL, |
| 23 | password_hash TEXT NOT NULL, |
| 24 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 25 | permissions TEXT NOT NULL DEFAULT '{}' |
| 26 | ); |
| 27 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 28 | file_path TEXT PRIMARY KEY, |
| 29 | uploader TEXT NOT NULL DEFAULT '', |
| 30 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 31 | ); |
| 32 | `); |
| 33 | } |
| 34 | return db; |
| 35 | } |
| 36 | return { getDb, initDb: getDb }; |
| 37 | }); |
| 38 | |
| 39 | // ── config mock ───────────────────────────────────────────────────────────── |
| 40 | const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'] }; |
| 41 | jest.mock('../server/config', () => ({ |
| 42 | loadConfig: () => ({ ...mockConfig }), |
| 43 | saveConfig: (c) => Object.assign(mockConfig, c), |
| 44 | getEffectivePaths: (p) => p, |
| 45 | getAllowedRoot: () => null, |
| 46 | })); |
| 47 | |
| 48 | // ── auth mock — bypass JWT verification ───────────────────────────────────── |
| 49 | let mockUser = { id: 1, username: 'admin', isAdmin: true, permissions: {} }; |
| 50 | jest.mock('../server/auth', () => ({ |
| 51 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 52 | requireAdmin: (req, res, next) => { |
| 53 | if (!req.user.isAdmin) return res.status(403).json({ error: 'Admin required.' }); |
| 54 | next(); |
| 55 | }, |
| 56 | createToken: () => 'mock-token', |
| 57 | getClientIp: () => '127.0.0.1', |
| 58 | getRegion: () => 'US:CA', |
| 59 | })); |
| 60 | |
| 61 | const adminRoutes = require('../server/routes/admin'); |
| 62 | const { getDb } = require('../server/db'); |
| 63 | const bcrypt = require('bcrypt'); |
| 64 | |
| 65 | jest.setTimeout(30000); |
| 66 | |
| 67 | // ── seed a default admin before anything runs ──────────────────────────────── |
| 68 | beforeAll(() => { |
| 69 | const db = getDb(); |
| 70 | const hash = bcrypt.hashSync('admin1234', 4); // low rounds for speed |
| 71 | db.prepare('INSERT OR IGNORE INTO users (username, password_hash, is_admin, permissions) VALUES (?,?,1,?)') |
| 72 | .run(['admin', hash, '{}']); |
| 73 | }); |
| 74 | |
| 75 | // ── build minimal app ──────────────────────────────────────────────────────── |
| 76 | let server; |
| 77 | let baseUrl; |
| 78 | |
| 79 | beforeAll(async () => { |
| 80 | const app = express(); |
| 81 | app.use(express.json()); |
| 82 | app.use('/api/admin', adminRoutes); |
| 83 | app.use((err, req, res, next) => { |
| 84 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 85 | }); |
| 86 | server = http.createServer(app); |
| 87 | server.listen(0); |
| 88 | await once(server, 'listening'); |
| 89 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 90 | }); |
| 91 | |
| 92 | afterAll(() => server.close()); |
| 93 | |
| 94 | // ── helpers ────────────────────────────────────────────────────────────────── |
| 95 | function req(method, path, body) { |
| 96 | const payload = body ? JSON.stringify(body) : undefined; |
| 97 | return new Promise((resolve, reject) => { |
| 98 | const r = http.request(baseUrl + path, { |
| 99 | method, |
| 100 | headers: { |
| 101 | 'Content-Type': 'application/json', |
| 102 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 103 | }, |
| 104 | }, res => { |
| 105 | let data = ''; |
| 106 | res.on('data', d => data += d); |
| 107 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 108 | }); |
| 109 | r.on('error', reject); |
| 110 | if (payload) r.write(payload); |
| 111 | r.end(); |
| 112 | }); |
| 113 | } |
| 114 | |
| 115 | // ── tests ───────────────────────────────────────────────────────────────────── |
| 116 | |
| 117 | describe('GET /api/admin/users', () => { |
| 118 | test('returns the list of users', async () => { |
| 119 | const { status, body } = await req('GET', '/api/admin/users'); |
| 120 | expect(status).toBe(200); |
| 121 | expect(Array.isArray(body.users)).toBe(true); |
| 122 | expect(body.users[0]).toMatchObject({ username: 'admin', isAdmin: true }); |
| 123 | }); |
| 124 | }); |
| 125 | |
| 126 | describe('POST /api/admin/users', () => { |
| 127 | test('creates a new user', async () => { |
| 128 | const { status, body } = await req('POST', '/api/admin/users', { |
| 129 | username: 'bob', password: 'bobpass1', isAdmin: false, permissions: {}, |
| 130 | }); |
| 131 | expect(status).toBe(201); |
| 132 | expect(body.ok).toBe(true); |
| 133 | }); |
| 134 | |
| 135 | test('rejects duplicate username', async () => { |
| 136 | const { status } = await req('POST', '/api/admin/users', { |
| 137 | username: 'bob', password: 'bobpass2', isAdmin: false, permissions: {}, |
| 138 | }); |
| 139 | expect(status).toBe(409); |
| 140 | }); |
| 141 | |
| 142 | test('rejects short password', async () => { |
| 143 | const { status } = await req('POST', '/api/admin/users', { |
| 144 | username: 'carol', password: 'short', isAdmin: false, permissions: {}, |
| 145 | }); |
| 146 | expect(status).toBe(400); |
| 147 | }); |
| 148 | }); |
| 149 | |
| 150 | describe('PATCH /api/admin/users/:id', () => { |
| 151 | let bobId; |
| 152 | |
| 153 | beforeAll(async () => { |
| 154 | const { body } = await req('GET', '/api/admin/users'); |
| 155 | bobId = body.users.find(u => u.username === 'bob').id; |
| 156 | }); |
| 157 | |
| 158 | test('updates permissions', async () => { |
| 159 | const { status, body } = await req('PATCH', `/api/admin/users/${bobId}`, { |
| 160 | permissions: { data: { read: true, write: false } }, |
| 161 | }); |
| 162 | expect(status).toBe(200); |
| 163 | expect(body.ok).toBe(true); |
| 164 | }); |
| 165 | |
| 166 | test('returns 404 for unknown user', async () => { |
| 167 | const { status } = await req('PATCH', '/api/admin/users/99999', { isAdmin: false }); |
| 168 | expect(status).toBe(404); |
| 169 | }); |
| 170 | }); |
| 171 | |
| 172 | describe('DELETE /api/admin/users/:id', () => { |
| 173 | let bobId; |
| 174 | |
| 175 | beforeAll(async () => { |
| 176 | const { body } = await req('GET', '/api/admin/users'); |
| 177 | bobId = body.users.find(u => u.username === 'bob').id; |
| 178 | }); |
| 179 | |
| 180 | test('cannot delete own account', async () => { |
| 181 | // mock user id is 1 (admin); bob is a different id — but we test self-delete guard |
| 182 | const adminId = mockUser.id; |
| 183 | const { status } = await req('DELETE', `/api/admin/users/${adminId}`); |
| 184 | expect(status).toBe(400); |
| 185 | }); |
| 186 | |
| 187 | test('deletes another user', async () => { |
| 188 | const { status, body } = await req('DELETE', `/api/admin/users/${bobId}`); |
| 189 | expect(status).toBe(200); |
| 190 | expect(body.ok).toBe(true); |
| 191 | }); |
| 192 | |
| 193 | test('cannot delete the last admin', async () => { |
| 194 | // Only 'admin' left; try to delete them (switch mockUser to be different) |
| 195 | const { body: users } = await req('GET', '/api/admin/users'); |
| 196 | const adminUser = users.users.find(u => u.username === 'admin'); |
| 197 | const { status } = await req('DELETE', `/api/admin/users/${adminUser.id}`); |
| 198 | // Our mockUser.id === 1 === adminUser.id, so it should fail with "cannot delete own account" |
| 199 | expect([400]).toContain(status); |
| 200 | }); |
| 201 | }); |
| 202 | |
| 203 | describe('GET /api/admin/config', () => { |
| 204 | test('returns port and paths', async () => { |
| 205 | const { status, body } = await req('GET', '/api/admin/config'); |
| 206 | expect(status).toBe(200); |
| 207 | expect(body.port).toBe(3000); |
| 208 | expect(Array.isArray(body.paths)).toBe(true); |
| 209 | }); |
| 210 | }); |
| 211 | |
| 212 | describe('PUT /api/admin/config', () => { |
| 213 | test('saves new paths', async () => { |
| 214 | const { status, body } = await req('PUT', '/api/admin/config', { |
| 215 | paths: ['/mnt/newpath'], |
| 216 | }); |
| 217 | expect(status).toBe(200); |
| 218 | expect(body.ok).toBe(true); |
| 219 | }); |
| 220 | |
| 221 | test('rejects non-array paths', async () => { |
| 222 | const { status } = await req('PUT', '/api/admin/config', { paths: 'notanarray' }); |
| 223 | expect(status).toBe(400); |
| 224 | }); |
| 225 | |
| 226 | test('rejects invalid port', async () => { |
| 227 | const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 }); |
| 228 | expect(status).toBe(400); |
| 229 | }); |
| 230 | }); |