'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 } = require('../auth'); const { loadConfig, saveConfig, getEffectivePaths } = require('../config'); const BCRYPT_ROUNDS = 12; 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; } // All admin routes require authentication + admin privilege router.use(requireAuth, requireAdmin); // --------------------------------------------------------------------------- // 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 || '{}'), })), }); }); // --------------------------------------------------------------------------- // 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 */ } } 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; // 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]); } 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]); 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 || []); res.json({ port: config.port || 3000, paths: config.paths || [], effectivePaths: effective, userPath: config.userPath || null, userFolderSizeLimit: config.userFolderSizeLimit || null, }); }); // --------------------------------------------------------------------------- // 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 } = 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; } } 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', '--oneline', '--no-decorate'], { cwd: PROJECT_ROOT }, ); commitsAhead = stdout.trim().split('\n').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;