| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const bcrypt = require('bcrypt'); |
| 5 | const fs = require('fs'); |
| 6 | const path = require('path'); |
| 7 | const { execFile } = require('child_process'); |
| 8 | const { promisify } = require('util'); |
| 9 | const router = express.Router(); |
| 10 | |
| 11 | const execFileAsync = promisify(execFile); |
| 12 | const PROJECT_ROOT = path.resolve(__dirname, '../../'); |
| 13 | |
| 14 | /** |
| 15 | * Ensures that a personal subfolder exists for each registered user under userPath. |
| 16 | * Non-fatal: logs errors but does not throw. |
| 17 | */ |
| 18 | function ensureUserFolders (userPath) |
| 19 | { |
| 20 | if (!userPath) return; |
| 21 | try |
| 22 | { |
| 23 | fs.mkdirSync(userPath, { recursive: true }); |
| 24 | } catch (err) |
| 25 | { |
| 26 | console.error('Failed to create user folder root:', err.message); |
| 27 | return; |
| 28 | } |
| 29 | |
| 30 | const db = require('../db').getDb(); |
| 31 | const users = db.prepare('SELECT username FROM users').all(); |
| 32 | for (const { username } of users) |
| 33 | { |
| 34 | const folder = path.join(userPath, username); |
| 35 | try |
| 36 | { |
| 37 | fs.mkdirSync(folder, { recursive: true }); |
| 38 | } catch (err) |
| 39 | { |
| 40 | console.error(`Failed to create user folder for ${username}:`, err.message); |
| 41 | } |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | const { getDb } = require('../db'); |
| 46 | const { requireAuth, requireAdmin, clearAuthUserCache } = require('../auth'); |
| 47 | const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); |
| 48 | const debugRouter = require('./debug'); |
| 49 | |
| 50 | const BCRYPT_ROUNDS = 12; |
| 51 | const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']); |
| 52 | const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/; |
| 53 | |
| 54 | function normaliseScheduledRestartConfig (value, fallback = null) |
| 55 | { |
| 56 | const defaults = fallback && typeof fallback === 'object' |
| 57 | ? fallback |
| 58 | : { enabled: false, cadence: 'daily', time: '04:00' }; |
| 59 | const raw = value && typeof value === 'object' ? value : {}; |
| 60 | |
| 61 | const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase(); |
| 62 | const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence; |
| 63 | |
| 64 | const timeRaw = String(raw.time || defaults.time || '').trim(); |
| 65 | const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time; |
| 66 | |
| 67 | return { |
| 68 | enabled: !!raw.enabled, |
| 69 | cadence, |
| 70 | time, |
| 71 | }; |
| 72 | } |
| 73 | |
| 74 | function normalizePermissions (permissions) |
| 75 | { |
| 76 | if (!permissions || typeof permissions !== 'object') return {}; |
| 77 | |
| 78 | const normalized = {}; |
| 79 | for (const [key, value] of Object.entries(permissions)) |
| 80 | { |
| 81 | if (!value || typeof value !== 'object') continue; |
| 82 | const write = !!value.write; |
| 83 | const read = !!value.read || write; |
| 84 | if (!read && !write) continue; |
| 85 | normalized[key] = { read, write }; |
| 86 | } |
| 87 | |
| 88 | return normalized; |
| 89 | } |
| 90 | |
| 91 | function userFolderRootFromConfig (config) |
| 92 | { |
| 93 | const raw = config && typeof config.userPath === 'string' ? config.userPath.trim() : ''; |
| 94 | return raw ? path.resolve(raw) : null; |
| 95 | } |
| 96 | |
| 97 | function removeIfEmptyDir (dirPath) |
| 98 | { |
| 99 | try |
| 100 | { |
| 101 | const entries = fs.readdirSync(dirPath); |
| 102 | if (entries.length !== 0) return false; |
| 103 | fs.rmdirSync(dirPath); |
| 104 | return true; |
| 105 | } catch |
| 106 | { |
| 107 | return false; |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | function listOrphanUserFolders (userFolderRoot, options = {}) |
| 112 | { |
| 113 | const deleteEmpty = !!options.deleteEmpty; |
| 114 | if (!userFolderRoot) return []; |
| 115 | |
| 116 | let entries = []; |
| 117 | try |
| 118 | { |
| 119 | entries = fs.readdirSync(userFolderRoot, { withFileTypes: true }); |
| 120 | } catch |
| 121 | { |
| 122 | return []; |
| 123 | } |
| 124 | |
| 125 | const db = getDb(); |
| 126 | const users = db.prepare('SELECT username FROM users').all(); |
| 127 | const usernames = new Set(users.map((u) => String(u.username || '').toLowerCase())); |
| 128 | |
| 129 | const out = []; |
| 130 | for (const entry of entries) |
| 131 | { |
| 132 | if (!entry.isDirectory()) continue; |
| 133 | |
| 134 | const folderName = String(entry.name || ''); |
| 135 | if (!folderName) continue; |
| 136 | if (usernames.has(folderName.toLowerCase())) continue; |
| 137 | |
| 138 | const folderPath = path.join(userFolderRoot, folderName); |
| 139 | let itemCount = 0; |
| 140 | try |
| 141 | { |
| 142 | itemCount = fs.readdirSync(folderPath).length; |
| 143 | } catch |
| 144 | { |
| 145 | continue; |
| 146 | } |
| 147 | |
| 148 | if (itemCount === 0 && deleteEmpty) |
| 149 | { |
| 150 | const removed = removeIfEmptyDir(folderPath); |
| 151 | if (removed) continue; |
| 152 | } |
| 153 | |
| 154 | out.push({ |
| 155 | folderName, |
| 156 | path: folderPath, |
| 157 | itemCount, |
| 158 | }); |
| 159 | } |
| 160 | |
| 161 | out.sort((a, b) => a.folderName.localeCompare(b.folderName)); |
| 162 | return out; |
| 163 | } |
| 164 | |
| 165 | // All admin routes require authentication + admin privilege |
| 166 | router.use(requireAuth, requireAdmin); |
| 167 | router.use(debugRouter); |
| 168 | |
| 169 | // --------------------------------------------------------------------------- |
| 170 | // GET /api/admin/users |
| 171 | // Returns all users. |
| 172 | // --------------------------------------------------------------------------- |
| 173 | router.get('/users', (req, res) => |
| 174 | { |
| 175 | const db = getDb(); |
| 176 | const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); |
| 177 | res.json({ |
| 178 | users: users.map(u => ({ |
| 179 | id: u.id, |
| 180 | username: u.username, |
| 181 | isAdmin: u.is_admin === 1, |
| 182 | permissions: JSON.parse(u.permissions || '{}'), |
| 183 | })), |
| 184 | }); |
| 185 | }); |
| 186 | |
| 187 | // --------------------------------------------------------------------------- |
| 188 | // GET /api/admin/orphan-userfolders |
| 189 | // Returns non-empty user folders that are not linked to an existing user. |
| 190 | // Empty orphan folders are auto-deleted. |
| 191 | // --------------------------------------------------------------------------- |
| 192 | router.get('/orphan-userfolders', (req, res) => |
| 193 | { |
| 194 | const config = loadConfig(); |
| 195 | const userFolderRoot = userFolderRootFromConfig(config); |
| 196 | const folders = listOrphanUserFolders(userFolderRoot, { deleteEmpty: true }); |
| 197 | res.json({ folders }); |
| 198 | }); |
| 199 | |
| 200 | // --------------------------------------------------------------------------- |
| 201 | // POST /api/admin/users |
| 202 | // Body: { username, password, isAdmin, permissions } |
| 203 | // Creates a new user. |
| 204 | // --------------------------------------------------------------------------- |
| 205 | router.post('/users', (req, res) => |
| 206 | { |
| 207 | const { username, password, isAdmin, permissions } = req.body; |
| 208 | |
| 209 | if (!username || !password || password.length < 8) |
| 210 | { |
| 211 | return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); |
| 212 | } |
| 213 | |
| 214 | const db = getDb(); |
| 215 | const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]); |
| 216 | if (exists) return res.status(409).json({ error: 'Username already exists.' }); |
| 217 | |
| 218 | const normalizedPermissions = normalizePermissions(permissions); |
| 219 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 220 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( |
| 221 | [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)] |
| 222 | ); |
| 223 | |
| 224 | // Create personal folder for the new user if a userPath is configured. |
| 225 | const config = loadConfig(); |
| 226 | if (config.userPath) |
| 227 | { |
| 228 | const folder = path.join(config.userPath, username); |
| 229 | try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ } |
| 230 | } |
| 231 | |
| 232 | clearAuthUserCache(username); |
| 233 | res.status(201).json({ ok: true }); |
| 234 | }); |
| 235 | |
| 236 | // --------------------------------------------------------------------------- |
| 237 | // PATCH /api/admin/users/:id |
| 238 | // Body: { password?, isAdmin?, permissions? } |
| 239 | // Updates an existing user. At least one field must be present. |
| 240 | // --------------------------------------------------------------------------- |
| 241 | router.patch('/users/:id', (req, res) => |
| 242 | { |
| 243 | const db = getDb(); |
| 244 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 245 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 246 | |
| 247 | const { password, isAdmin, permissions } = req.body; |
| 248 | |
| 249 | // Admins may not remove admin privileges from their own account. |
| 250 | if ((isAdmin === false || isAdmin === 0) && String(user.id) === String(req.user.id)) |
| 251 | { |
| 252 | return res.status(400).json({ error: 'Cannot remove your own admin privileges.' }); |
| 253 | } |
| 254 | |
| 255 | // Prevent removing the last admin |
| 256 | if (isAdmin === false || isAdmin === 0) |
| 257 | { |
| 258 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 259 | if (adminCount <= 1 && user.is_admin === 1) |
| 260 | { |
| 261 | return res.status(400).json({ error: 'Cannot remove the last admin account.' }); |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | if (password !== undefined) |
| 266 | { |
| 267 | if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); |
| 268 | const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); |
| 269 | db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); |
| 270 | } |
| 271 | |
| 272 | if (isAdmin !== undefined) |
| 273 | { |
| 274 | db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); |
| 275 | } |
| 276 | |
| 277 | if (permissions !== undefined) |
| 278 | { |
| 279 | const normalizedPermissions = normalizePermissions(permissions); |
| 280 | db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]); |
| 281 | } |
| 282 | |
| 283 | clearAuthUserCache(user.username); |
| 284 | res.json({ ok: true }); |
| 285 | }); |
| 286 | |
| 287 | // --------------------------------------------------------------------------- |
| 288 | // DELETE /api/admin/users/:id |
| 289 | // Deletes a user. Cannot delete yourself or the last admin. |
| 290 | // --------------------------------------------------------------------------- |
| 291 | router.delete('/users/:id', (req, res) => |
| 292 | { |
| 293 | const db = getDb(); |
| 294 | const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); |
| 295 | if (!user) return res.status(404).json({ error: 'User not found.' }); |
| 296 | |
| 297 | if (String(user.id) === String(req.user.id)) |
| 298 | { |
| 299 | return res.status(400).json({ error: 'Cannot delete your own account.' }); |
| 300 | } |
| 301 | |
| 302 | if (user.is_admin === 1) |
| 303 | { |
| 304 | const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; |
| 305 | if (adminCount <= 1) |
| 306 | { |
| 307 | return res.status(400).json({ error: 'Cannot delete the last admin account.' }); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); |
| 312 | clearAuthUserCache(user.username); |
| 313 | |
| 314 | // If the deleted user's personal folder is now empty, remove it automatically. |
| 315 | const config = loadConfig(); |
| 316 | const userFolderRoot = userFolderRootFromConfig(config); |
| 317 | if (userFolderRoot) |
| 318 | { |
| 319 | const folderPath = path.join(userFolderRoot, String(user.username || '')); |
| 320 | removeIfEmptyDir(folderPath); |
| 321 | } |
| 322 | |
| 323 | res.json({ ok: true }); |
| 324 | }); |
| 325 | |
| 326 | // --------------------------------------------------------------------------- |
| 327 | // GET /api/admin/config |
| 328 | // Returns the current server config (paths, port, userPath, userFolderSizeLimit). |
| 329 | // --------------------------------------------------------------------------- |
| 330 | router.get('/config', (req, res) => |
| 331 | { |
| 332 | const config = loadConfig(); |
| 333 | const effective = getEffectivePaths(config.paths || []); |
| 334 | const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart); |
| 335 | res.json({ |
| 336 | port: config.port || 3000, |
| 337 | paths: config.paths || [], |
| 338 | effectivePaths: effective, |
| 339 | userPath: config.userPath || null, |
| 340 | userFolderSizeLimit: config.userFolderSizeLimit || null, |
| 341 | scheduledRestart, |
| 342 | }); |
| 343 | }); |
| 344 | |
| 345 | // --------------------------------------------------------------------------- |
| 346 | // PUT /api/admin/config |
| 347 | // Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null } |
| 348 | // Saves the config. |
| 349 | // --------------------------------------------------------------------------- |
| 350 | router.put('/config', (req, res) => |
| 351 | { |
| 352 | const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body; |
| 353 | if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); |
| 354 | |
| 355 | const config = loadConfig(); |
| 356 | config.paths = paths.map(p => p.trim()).filter(Boolean); |
| 357 | |
| 358 | if (port !== undefined) |
| 359 | { |
| 360 | const p = parseInt(port, 10); |
| 361 | if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); |
| 362 | config.port = p; |
| 363 | } |
| 364 | |
| 365 | // userPath — a single directory for per-user storage. |
| 366 | // Only update when explicitly provided so path-only saves do not clear it. |
| 367 | if (userPath !== undefined) |
| 368 | { |
| 369 | const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : ''; |
| 370 | config.userPath = cleanUserPath || null; |
| 371 | } |
| 372 | |
| 373 | // userFolderSizeLimit — stored as bytes (number) or null = unlimited. |
| 374 | // Only update when explicitly provided. |
| 375 | if (userFolderSizeLimit !== undefined) |
| 376 | { |
| 377 | if (userFolderSizeLimit === null) |
| 378 | { |
| 379 | config.userFolderSizeLimit = null; |
| 380 | } else |
| 381 | { |
| 382 | const lim = Number(userFolderSizeLimit); |
| 383 | config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null; |
| 384 | } |
| 385 | } |
| 386 | |
| 387 | if (scheduledRestart !== undefined) |
| 388 | { |
| 389 | if (!process.env.INVOCATION_ID) |
| 390 | { |
| 391 | return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' }); |
| 392 | } |
| 393 | |
| 394 | if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart)) |
| 395 | { |
| 396 | return res.status(400).json({ error: 'scheduledRestart must be an object.' }); |
| 397 | } |
| 398 | |
| 399 | const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase(); |
| 400 | if (!SCHEDULED_RESTART_CADENCES.has(cadence)) |
| 401 | { |
| 402 | return res.status(400).json({ error: 'Invalid scheduled restart cadence.' }); |
| 403 | } |
| 404 | |
| 405 | const time = String(scheduledRestart.time || '').trim(); |
| 406 | if (!SCHEDULED_RESTART_TIME_RE.test(time)) |
| 407 | { |
| 408 | return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' }); |
| 409 | } |
| 410 | |
| 411 | config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart); |
| 412 | } |
| 413 | |
| 414 | try |
| 415 | { |
| 416 | saveConfig(config); |
| 417 | } catch (err) |
| 418 | { |
| 419 | return res.status(500).json({ error: `Failed to save config: ${err.message}` }); |
| 420 | } |
| 421 | |
| 422 | // Ensure personal subfolders exist for all current users. |
| 423 | if (config.userPath) ensureUserFolders(config.userPath); |
| 424 | |
| 425 | res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); |
| 426 | }); |
| 427 | |
| 428 | // --------------------------------------------------------------------------- |
| 429 | // GET /api/admin/update-status |
| 430 | // Returns whether the process is running under systemd and whether the git |
| 431 | // remote is ahead of the local checkout. |
| 432 | // --------------------------------------------------------------------------- |
| 433 | router.get('/update-status', async (req, res) => |
| 434 | { |
| 435 | const underSystemd = !!process.env.INVOCATION_ID; |
| 436 | if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] }); |
| 437 | |
| 438 | let commitsAhead = []; |
| 439 | try |
| 440 | { |
| 441 | await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT }); |
| 442 | const { stdout } = await execFileAsync( |
| 443 | 'git', ['log', 'HEAD..origin/HEAD', '--no-decorate', '--no-merges', '--pretty=format:%H%x1f%s%x1f%b%x1e'], |
| 444 | { cwd: PROJECT_ROOT }, |
| 445 | ); |
| 446 | const records = String(stdout || '').split('\x1e').map(line => line.trim()).filter(Boolean); |
| 447 | commitsAhead = records.map((record) => |
| 448 | { |
| 449 | const parts = record.split('\x1f'); |
| 450 | const hash = String(parts[0] || '').trim(); |
| 451 | const subject = String(parts[1] || '').trim(); |
| 452 | const body = String(parts.slice(2).join('\x1f') || '').trim(); |
| 453 | if (!subject) return null; |
| 454 | return { hash, subject, body }; |
| 455 | }).filter(Boolean); |
| 456 | } |
| 457 | catch |
| 458 | { |
| 459 | // git may not be available or repo may not have a remote — return empty list. |
| 460 | } |
| 461 | |
| 462 | res.json({ underSystemd: true, commitsAhead }); |
| 463 | }); |
| 464 | |
| 465 | // --------------------------------------------------------------------------- |
| 466 | // POST /api/admin/shutdown |
| 467 | // Responds immediately then gracefully closes the server and DB. |
| 468 | // --------------------------------------------------------------------------- |
| 469 | router.post('/shutdown', (req, res) => |
| 470 | { |
| 471 | res.json({ ok: true }); |
| 472 | // Defer so the response is flushed before we start closing. |
| 473 | setImmediate(() => |
| 474 | { |
| 475 | const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); |
| 476 | if (typeof fn === 'function') fn(); |
| 477 | }); |
| 478 | }); |
| 479 | |
| 480 | module.exports = router; |