'use strict'; const express = require('express'); const bcrypt = require('bcrypt'); const fs = require('fs'); const path = require('path'); const { execFile } = require('child_process'); const { promisify } = require('util'); const router = express.Router(); const execFileAsync = promisify(execFile); const PROJECT_ROOT = path.resolve(__dirname, '../../'); /** * Ensures that a personal subfolder exists for each registered user under userPath. * Non-fatal: logs errors but does not throw. */ function ensureUserFolders (userPath) { if (!userPath) return; try { fs.mkdirSync(userPath, { recursive: true }); } catch (err) { console.error('Failed to create user folder root:', err.message); return; } const db = require('../db').getDb(); const users = db.prepare('SELECT username FROM users').all(); for (const { username } of users) { const folder = path.join(userPath, username); try { fs.mkdirSync(folder, { recursive: true }); } catch (err) { console.error(`Failed to create user folder for ${username}:`, err.message); } } } const { getDb } = require('../db'); const { requireAuth, requireAdmin, clearAuthUserCache } = require('../auth'); const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); const debugRouter = require('./debug'); const BCRYPT_ROUNDS = 12; const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']); const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/; function normaliseScheduledRestartConfig (value, fallback = null) { const defaults = fallback && typeof fallback === 'object' ? fallback : { enabled: false, cadence: 'daily', time: '04:00' }; const raw = value && typeof value === 'object' ? value : {}; const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase(); const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence; const timeRaw = String(raw.time || defaults.time || '').trim(); const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time; return { enabled: !!raw.enabled, cadence, time, }; } function normalizePermissions (permissions) { if (!permissions || typeof permissions !== 'object') return {}; const normalized = {}; for (const [key, value] of Object.entries(permissions)) { if (!value || typeof value !== 'object') continue; const write = !!value.write; const read = !!value.read || write; if (!read && !write) continue; normalized[key] = { read, write }; } return normalized; } function userFolderRootFromConfig (config) { const raw = config && typeof config.userPath === 'string' ? config.userPath.trim() : ''; return raw ? path.resolve(raw) : null; } function removeIfEmptyDir (dirPath) { try { const entries = fs.readdirSync(dirPath); if (entries.length !== 0) return false; fs.rmdirSync(dirPath); return true; } catch { return false; } } function listOrphanUserFolders (userFolderRoot, options = {}) { const deleteEmpty = !!options.deleteEmpty; if (!userFolderRoot) return []; let entries = []; try { entries = fs.readdirSync(userFolderRoot, { withFileTypes: true }); } catch { return []; } const db = getDb(); const users = db.prepare('SELECT username FROM users').all(); const usernames = new Set(users.map((u) => String(u.username || '').toLowerCase())); const out = []; for (const entry of entries) { if (!entry.isDirectory()) continue; const folderName = String(entry.name || ''); if (!folderName) continue; if (usernames.has(folderName.toLowerCase())) continue; const folderPath = path.join(userFolderRoot, folderName); let itemCount = 0; try { itemCount = fs.readdirSync(folderPath).length; } catch { continue; } if (itemCount === 0 && deleteEmpty) { const removed = removeIfEmptyDir(folderPath); if (removed) continue; } out.push({ folderName, path: folderPath, itemCount, }); } out.sort((a, b) => a.folderName.localeCompare(b.folderName)); return out; } // All admin routes require authentication + admin privilege router.use(requireAuth, requireAdmin); router.use(debugRouter); // --------------------------------------------------------------------------- // GET /api/admin/users // Returns all users. // --------------------------------------------------------------------------- router.get('/users', (req, res) => { const db = getDb(); const users = db.prepare('SELECT id, username, is_admin, permissions FROM users').all(); res.json({ users: users.map(u => ({ id: u.id, username: u.username, isAdmin: u.is_admin === 1, permissions: JSON.parse(u.permissions || '{}'), })), }); }); // --------------------------------------------------------------------------- // GET /api/admin/orphan-userfolders // Returns non-empty user folders that are not linked to an existing user. // Empty orphan folders are auto-deleted. // --------------------------------------------------------------------------- router.get('/orphan-userfolders', (req, res) => { const config = loadConfig(); const userFolderRoot = userFolderRootFromConfig(config); const folders = listOrphanUserFolders(userFolderRoot, { deleteEmpty: true }); res.json({ folders }); }); // --------------------------------------------------------------------------- // POST /api/admin/users // Body: { username, password, isAdmin, permissions } // Creates a new user. // --------------------------------------------------------------------------- router.post('/users', (req, res) => { const { username, password, isAdmin, permissions } = req.body; if (!username || !password || password.length < 8) { return res.status(400).json({ error: 'Username required and password must be at least 8 characters.' }); } const db = getDb(); const exists = db.prepare('SELECT id FROM users WHERE username = ? COLLATE NOCASE').get([username]); if (exists) return res.status(409).json({ error: 'Username already exists.' }); const normalizedPermissions = normalizePermissions(permissions); const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)').run( [username, hash, isAdmin ? 1 : 0, JSON.stringify(normalizedPermissions)] ); // Create personal folder for the new user if a userPath is configured. const config = loadConfig(); if (config.userPath) { const folder = path.join(config.userPath, username); try { fs.mkdirSync(folder, { recursive: true }); } catch { /* non-fatal */ } } clearAuthUserCache(username); res.status(201).json({ ok: true }); }); // --------------------------------------------------------------------------- // PATCH /api/admin/users/:id // Body: { password?, isAdmin?, permissions? } // Updates an existing user. At least one field must be present. // --------------------------------------------------------------------------- router.patch('/users/:id', (req, res) => { const db = getDb(); const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); if (!user) return res.status(404).json({ error: 'User not found.' }); const { password, isAdmin, permissions } = req.body; // Admins may not remove admin privileges from their own account. if ((isAdmin === false || isAdmin === 0) && String(user.id) === String(req.user.id)) { return res.status(400).json({ error: 'Cannot remove your own admin privileges.' }); } // Prevent removing the last admin if (isAdmin === false || isAdmin === 0) { const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; if (adminCount <= 1 && user.is_admin === 1) { return res.status(400).json({ error: 'Cannot remove the last admin account.' }); } } if (password !== undefined) { if (password.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters.' }); const hash = bcrypt.hashSync(password, BCRYPT_ROUNDS); db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run([hash, user.id]); } if (isAdmin !== undefined) { db.prepare('UPDATE users SET is_admin = ? WHERE id = ?').run([isAdmin ? 1 : 0, user.id]); } if (permissions !== undefined) { const normalizedPermissions = normalizePermissions(permissions); db.prepare('UPDATE users SET permissions = ? WHERE id = ?').run([JSON.stringify(normalizedPermissions), user.id]); } clearAuthUserCache(user.username); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // DELETE /api/admin/users/:id // Deletes a user. Cannot delete yourself or the last admin. // --------------------------------------------------------------------------- router.delete('/users/:id', (req, res) => { const db = getDb(); const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); if (!user) return res.status(404).json({ error: 'User not found.' }); if (String(user.id) === String(req.user.id)) { return res.status(400).json({ error: 'Cannot delete your own account.' }); } if (user.is_admin === 1) { const adminCount = db.prepare('SELECT COUNT(*) as n FROM users WHERE is_admin = 1').get().n; if (adminCount <= 1) { return res.status(400).json({ error: 'Cannot delete the last admin account.' }); } } db.prepare('DELETE FROM users WHERE id = ?').run([user.id]); clearAuthUserCache(user.username); // If the deleted user's personal folder is now empty, remove it automatically. const config = loadConfig(); const userFolderRoot = userFolderRootFromConfig(config); if (userFolderRoot) { const folderPath = path.join(userFolderRoot, String(user.username || '')); removeIfEmptyDir(folderPath); } res.json({ ok: true }); }); // --------------------------------------------------------------------------- // GET /api/admin/config // Returns the current server config (paths, port, userPath, userFolderSizeLimit). // --------------------------------------------------------------------------- router.get('/config', (req, res) => { const config = loadConfig(); const effective = getEffectivePaths(config.paths || []); const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart); res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective, userPath: config.userPath || null, userFolderSizeLimit: config.userFolderSizeLimit || null, scheduledRestart, }); }); // --------------------------------------------------------------------------- // PUT /api/admin/config // Body: { paths: [...], port: number, userPath: string|null, userFolderSizeLimit: number|null } // Saves the config. // --------------------------------------------------------------------------- router.put('/config', (req, res) => { const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body; if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' }); const config = loadConfig(); config.paths = paths.map(p => p.trim()).filter(Boolean); if (port !== undefined) { const p = parseInt(port, 10); if (isNaN(p) || p < 1 || p > 65535) return res.status(400).json({ error: 'Invalid port.' }); config.port = p; } // userPath — a single directory for per-user storage. // Only update when explicitly provided so path-only saves do not clear it. if (userPath !== undefined) { const cleanUserPath = typeof userPath === 'string' ? userPath.trim() : ''; config.userPath = cleanUserPath || null; } // userFolderSizeLimit — stored as bytes (number) or null = unlimited. // Only update when explicitly provided. if (userFolderSizeLimit !== undefined) { if (userFolderSizeLimit === null) { config.userFolderSizeLimit = null; } else { const lim = Number(userFolderSizeLimit); config.userFolderSizeLimit = Number.isFinite(lim) && lim > 0 ? lim : null; } } if (scheduledRestart !== undefined) { if (!process.env.INVOCATION_ID) { return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' }); } if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart)) { return res.status(400).json({ error: 'scheduledRestart must be an object.' }); } const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase(); if (!SCHEDULED_RESTART_CADENCES.has(cadence)) { return res.status(400).json({ error: 'Invalid scheduled restart cadence.' }); } const time = String(scheduledRestart.time || '').trim(); if (!SCHEDULED_RESTART_TIME_RE.test(time)) { return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' }); } config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart); } try { saveConfig(config); } catch (err) { return res.status(500).json({ error: `Failed to save config: ${err.message}` }); } // Ensure personal subfolders exist for all current users. if (config.userPath) ensureUserFolders(config.userPath); res.json({ ok: true, effectivePaths: getEffectivePaths(config.paths) }); }); // --------------------------------------------------------------------------- // GET /api/admin/update-status // Returns whether the process is running under systemd and whether the git // remote is ahead of the local checkout. // --------------------------------------------------------------------------- router.get('/update-status', async (req, res) => { const underSystemd = !!process.env.INVOCATION_ID; if (!underSystemd) return res.json({ underSystemd: false, commitsAhead: [] }); let commitsAhead = []; try { await execFileAsync('git', ['fetch', '--quiet', 'origin'], { cwd: PROJECT_ROOT }); const { stdout } = await execFileAsync( 'git', ['log', 'HEAD..origin/HEAD', '--no-decorate', '--no-merges', '--pretty=format:%H%x1f%s%x1f%b%x1e'], { cwd: PROJECT_ROOT }, ); const records = String(stdout || '').split('\x1e').map(line => line.trim()).filter(Boolean); commitsAhead = records.map((record) => { const parts = record.split('\x1f'); const hash = String(parts[0] || '').trim(); const subject = String(parts[1] || '').trim(); const body = String(parts.slice(2).join('\x1f') || '').trim(); if (!subject) return null; return { hash, subject, body }; }).filter(Boolean); } catch { // git may not be available or repo may not have a remote — return empty list. } res.json({ underSystemd: true, commitsAhead }); }); // --------------------------------------------------------------------------- // POST /api/admin/shutdown // Responds immediately then gracefully closes the server and DB. // --------------------------------------------------------------------------- router.post('/shutdown', (req, res) => { res.json({ ok: true }); // Defer so the response is flushed before we start closing. setImmediate(() => { const fn = req.app.get('shutdownForRestart') || req.app.get('shutdown'); if (typeof fn === 'function') fn(); }); }); module.exports = router;