| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const bcrypt = require('bcrypt'); |
| 5 | const path = require('path'); |
| 6 | const { execFile } = require('child_process'); |
| 7 | const { promisify } = require('util'); |
| 8 | const router = express.Router(); |
| 9 | |
| 10 | const execFileAsync = promisify(execFile); |
| 11 | const PROJECT_ROOT = path.resolve(__dirname, '../../'); |
| 12 | |
| 13 | const { getDb } = require('../db'); |
| 14 | const { requireAuth, requireAdmin } = require('../auth'); |
| 15 | const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); |
| 16 | |
| 17 | const BCRYPT_ROUNDS = 12; |
| 18 | |
| 19 | function normalizePermissions (permissions) |
| 20 | { |
| 21 | if (!permissions || typeof permissions !== 'object') return {}; |
| 22 | |
| 23 | const normalized = {}; |
| 24 | for (const [key, value] of Object.entries(permissions)) |
| 25 | { |
| 26 | if (!value || typeof value !== 'object') continue; |
| 27 | const write = !!value.write; |
| 28 | const read = !!value.read || write; |
| 29 | if (!read && !write) continue; |
| 30 | normalized[key] = { read, write }; |
| 31 | } |
| 32 | |
| 33 | return normalized; |
| 34 | } |
| 35 | |
| 36 | // All admin routes require authentication + admin privilege |
| 37 | router.use(requireAuth, requireAdmin); |
| 38 | |
| 39 | // --------------------------------------------------------------------------- |
| 40 | // GET /api/admin/users |
| 41 | // Returns all users. |
| 42 | // --------------------------------------------------------------------------- |
| 43 | router.get('/users', (req, res) => |
| 44 | { |
| 45 | const db = getDb(); |
| 46 | const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); |
| 47 | res.json({ |
| 48 | users: users.map(u => ({ |
| 49 | id: u.id, |
| 50 | username: u.username, |
| 51 | isAdmin: u.is_admin === 1, |
| 52 | permissions: JSON.parse(u.permissions || '{}'), |
| 53 | })), |
| 54 | }); |
| 55 | }); |
| 56 | |
| 57 | // --------------------------------------------------------------------------- |
| 58 | // POST /api/admin/users |
| 59 | // Body: { username, password, isAdmin, permissions } |
| 60 | // Creates a new user. |
| 61 | // --------------------------------------------------------------------------- |
| 62 | router.post('/users', (req, res) => |
| 63 | { |
| 64 | const { username, password, isAdmin, permissions } = req.body; |
| 65 | |
| 66 | if (!username || !password || password.length < 8) |
| 67 | { |
| 68 | return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); |
| 69 | } |
| 70 | |
| 71 | const db = getDb(); |
| 72 | const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]); |
| 73 | if (exists) return res.status(409).json({ error: 'Username already exists.' }); |
| 74 | |
| 75 | const normalizedPermissions = normalizePermissions(permissions); |
| 76 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 77 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( |
| 78 | [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)] |
| 79 | ); |
| 80 | |
| 81 | res.status(201).json({ ok: true }); |
| 82 | }); |
| 83 | |
| 84 | // --------------------------------------------------------------------------- |
| 85 | // PATCH /api/admin/users/:id |
| 86 | // Body: { password?, isAdmin?, permissions? } |
| 87 | // Updates an existing user. At least one field must be present. |
| 88 | // --------------------------------------------------------------------------- |
| 89 | router.patch('/users/:id', (req, res) => |
| 90 | { |
| 91 | const db = getDb(); |
| 92 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 93 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 94 | |
| 95 | const { password, isAdmin, permissions } = req.body; |
| 96 | |
| 97 | // Prevent removing the last admin |
| 98 | if (isAdmin === false || isAdmin === 0) |
| 99 | { |
| 100 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 101 | if (adminCount <= 1 && user.is_admin === 1) |
| 102 | { |
| 103 | return res.status(400).json({ error: 'Cannot remove the last admin account.' }); |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | if (password !== undefined) |
| 108 | { |
| 109 | if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); |
| 110 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 111 | db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); |
| 112 | } |
| 113 | |
| 114 | if (isAdmin !== undefined) |
| 115 | { |
| 116 | db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); |
| 117 | } |
| 118 | |
| 119 | if (permissions !== undefined) |
| 120 | { |
| 121 | const normalizedPermissions = normalizePermissions(permissions); |
| 122 | db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]); |
| 123 | } |
| 124 | |
| 125 | res.json({ ok: true }); |
| 126 | }); |
| 127 | |
| 128 | // --------------------------------------------------------------------------- |
| 129 | // DELETE /api/admin/users/:id |
| 130 | // Deletes a user. Cannot delete yourself or the last admin. |
| 131 | // --------------------------------------------------------------------------- |
| 132 | router.delete('/users/:id', (req, res) => |
| 133 | { |
| 134 | const db = getDb(); |
| 135 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 136 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 137 | |
| 138 | if (String(user.id) === String(req.user.id)) |
| 139 | { |
| 140 | return res.status(400).json({ error: 'Cannot delete your own account.' }); |
| 141 | } |
| 142 | |
| 143 | if (user.is_admin === 1) |
| 144 | { |
| 145 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 146 | if (adminCount <= 1) |
| 147 | { |
| 148 | return res.status(400).json({ error: 'Cannot delete the last admin account.' }); |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); |
| 153 | res.json({ ok: true }); |
| 154 | }); |
| 155 | |
| 156 | // --------------------------------------------------------------------------- |
| 157 | // GET /api/admin/config |
| 158 | // Returns the current server config (paths, port). |
| 159 | // --------------------------------------------------------------------------- |
| 160 | router.get('/config', (req, res) => |
| 161 | { |
| 162 | const config = loadConfig(); |
| 163 | const effective = getEffectivePaths(config.paths || []); |
| 164 | res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective }); |
| 165 | }); |
| 166 | |
| 167 | // --------------------------------------------------------------------------- |
| 168 | // PUT /api/admin/config |
| 169 | // Body: { paths: [...], port: number } |
| 170 | // Saves the config. |
| 171 | // --------------------------------------------------------------------------- |
| 172 | router.put('/config', (req, res) => |
| 173 | { |
| 174 | const { paths, port } = req.body; |
| 175 | if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); |
| 176 | |
| 177 | const config = loadConfig(); |
| 178 | config.paths = paths.map(p => p.trim()).filter(Boolean); |
| 179 | if (port !== undefined) |
| 180 | { |
| 181 | const p = parseInt(port, 10); |
| 182 | if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); |
| 183 | config.port = p; |
| 184 | } |
| 185 | |
| 186 | try |
| 187 | { |
| 188 | saveConfig(config); |
| 189 | } catch (err) |
| 190 | { |
| 191 | return res.status(500).json({ error: `Failed to save config: ${err.message}` }); |
| 192 | } |
| 193 | res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); |
| 194 | }); |
| 195 | |
| 196 | // --------------------------------------------------------------------------- |
| 197 | // GET /api/admin/update-status |
| 198 | // Returns whether the process is running under systemd and whether the git |
| 199 | // remote is ahead of the local checkout. |
| 200 | // --------------------------------------------------------------------------- |
| 201 | router.get('/update-status', async (req, res) => |
| 202 | { |
| 203 | const underSystemd = !!process.env.INVOCATION_ID; |
| 204 | if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] }); |
| 205 | |
| 206 | let commitsAhead = []; |
| 207 | try |
| 208 | { |
| 209 | await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT }); |
| 210 | const { stdout } = await execFileAsync( |
| 211 | 'git', ['log', 'HEAD..origin/HEAD', '--oneline', '--no-decorate'], |
| 212 | { cwd: PROJECT_ROOT }, |
| 213 | ); |
| 214 | commitsAhead = stdout.trim().split('\n').filter(Boolean); |
| 215 | } |
| 216 | catch |
| 217 | { |
| 218 | // git may not be available or repo may not have a remote — return empty list. |
| 219 | } |
| 220 | |
| 221 | res.json({ underSystemd: true, commitsAhead }); |
| 222 | }); |
| 223 | |
| 224 | // --------------------------------------------------------------------------- |
| 225 | // POST /api/admin/shutdown |
| 226 | // Responds immediately then gracefully closes the server and DB. |
| 227 | // --------------------------------------------------------------------------- |
| 228 | router.post('/shutdown', (req, res) => |
| 229 | { |
| 230 | res.json({ ok: true }); |
| 231 | // Defer so the response is flushed before we start closing. |
| 232 | setImmediate(() => |
| 233 | { |
| 234 | const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); |
| 235 | if (typeof fn === 'function') fn(); |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | module.exports = router; |