| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const path = require('path'); |
| 5 | const fs = require('fs'); |
| 6 | const multer = require('multer'); |
| 7 | const router = express.Router(); |
| 8 | |
| 9 | const { getDb } = require('../db'); |
| 10 | const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config'); |
| 11 | const { requireAuth } = require('../auth'); |
| 12 | |
| 13 | // --------------------------------------------------------------------------- |
| 14 | // Multer storage — files are written directly to the target directory |
| 15 | // --------------------------------------------------------------------------- |
| 16 | const storage = multer.diskStorage({ |
| 17 | destination(req, file, cb) { |
| 18 | // The target directory is resolved in the route handler, so we stash it |
| 19 | // during the multer middleware call via req._uploadDir. |
| 20 | cb(null, req._uploadDir); |
| 21 | }, |
| 22 | filename(req, file, cb) { |
| 23 | cb(null, file.originalname); |
| 24 | }, |
| 25 | }); |
| 26 | |
| 27 | const upload = multer({ |
| 28 | storage, |
| 29 | limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB |
| 30 | }); |
| 31 | |
| 32 | // --------------------------------------------------------------------------- |
| 33 | // Helpers |
| 34 | // --------------------------------------------------------------------------- |
| 35 | |
| 36 | function effectivePaths() { |
| 37 | return getEffectivePaths(loadConfig().paths || []); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Verify that the user has read access to the given configured-path label. |
| 42 | * `pathLabel` is the base-name of the effective path (shown in the UI). |
| 43 | */ |
| 44 | function canRead(user, pathLabel) { |
| 45 | if (user.isAdmin) return true; |
| 46 | return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read); |
| 47 | } |
| 48 | |
| 49 | function canWrite(user, pathLabel) { |
| 50 | if (user.isAdmin) return true; |
| 51 | return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Given an absolute path and the effective-paths list, return |
| 56 | * { root, label } where label is the base-name of the root, or null. |
| 57 | */ |
| 58 | function resolveRoot(absPath, roots) { |
| 59 | const matchedRoot = getAllowedRoot(absPath, roots); |
| 60 | if (!matchedRoot) return null; |
| 61 | return { root: matchedRoot, label: path.basename(matchedRoot) }; |
| 62 | } |
| 63 | |
| 64 | // --------------------------------------------------------------------------- |
| 65 | // GET /api/files/roots |
| 66 | // Returns the effective configured paths the user can read. |
| 67 | // --------------------------------------------------------------------------- |
| 68 | router.get('/roots', requireAuth, (req, res) => { |
| 69 | const roots = effectivePaths(); |
| 70 | const readable = roots |
| 71 | .filter(r => canRead(req.user, path.basename(r))) |
| 72 | .map(r => ({ label: path.basename(r), path: r })); |
| 73 | res.json({ roots: readable }); |
| 74 | }); |
| 75 | |
| 76 | // --------------------------------------------------------------------------- |
| 77 | // GET /api/files/list?dir=<absolute-path> |
| 78 | // Lists files and folders in the given directory. |
| 79 | // --------------------------------------------------------------------------- |
| 80 | router.get('/list', requireAuth, (req, res) => { |
| 81 | const dir = req.query.dir; |
| 82 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 83 | |
| 84 | const roots = effectivePaths(); |
| 85 | const info = resolveRoot(dir, roots); |
| 86 | if (!info) return res.status(403).json({ error: 'Access denied.' }); |
| 87 | if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' }); |
| 88 | |
| 89 | let entries; |
| 90 | try { |
| 91 | entries = fs.readdirSync(dir, { withFileTypes: true }); |
| 92 | } catch { |
| 93 | return res.status(404).json({ error: 'Directory not found.' }); |
| 94 | } |
| 95 | |
| 96 | const items = entries.map(e => { |
| 97 | const fullPath = path.join(dir, e.name); |
| 98 | let size = null; |
| 99 | let mtime = null; |
| 100 | try { |
| 101 | const stat = fs.statSync(fullPath); |
| 102 | size = stat.size; |
| 103 | mtime = stat.mtime.toISOString(); |
| 104 | } catch { /* ignore */ } |
| 105 | |
| 106 | return { |
| 107 | name: e.name, |
| 108 | isDir: e.isDirectory(), |
| 109 | size, |
| 110 | mtime, |
| 111 | path: fullPath, |
| 112 | }; |
| 113 | }); |
| 114 | |
| 115 | res.json({ items }); |
| 116 | }); |
| 117 | |
| 118 | // --------------------------------------------------------------------------- |
| 119 | // GET /api/files/meta?file=<absolute-path> |
| 120 | // Returns file metadata from the DB. |
| 121 | // --------------------------------------------------------------------------- |
| 122 | router.get('/meta', requireAuth, (req, res) => { |
| 123 | const file = req.query.file; |
| 124 | if (!file) return res.status(400).json({ error: 'file is required.' }); |
| 125 | |
| 126 | const roots = effectivePaths(); |
| 127 | const info = resolveRoot(file, roots); |
| 128 | if (!info || !canRead(req.user, info.label)) { |
| 129 | return res.status(403).json({ error: 'Access denied.' }); |
| 130 | } |
| 131 | |
| 132 | let stat; |
| 133 | try { |
| 134 | stat = fs.statSync(file); |
| 135 | } catch { |
| 136 | return res.status(404).json({ error: 'File not found.' }); |
| 137 | } |
| 138 | |
| 139 | const db = getDb(); |
| 140 | const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); |
| 141 | |
| 142 | res.json({ |
| 143 | name: path.basename(file), |
| 144 | size: stat.size, |
| 145 | mtime: stat.mtime.toISOString(), |
| 146 | uploader: meta ? meta.uploader : '', |
| 147 | downloaders: meta ? JSON.parse(meta.downloaders) : [], |
| 148 | }); |
| 149 | }); |
| 150 | |
| 151 | // --------------------------------------------------------------------------- |
| 152 | // GET /api/files/download?file=<absolute-path> |
| 153 | // Streams the file to the client; records the download. |
| 154 | // --------------------------------------------------------------------------- |
| 155 | router.get('/download', requireAuth, (req, res) => { |
| 156 | const file = req.query.file; |
| 157 | if (!file) return res.status(400).json({ error: 'file is required.' }); |
| 158 | |
| 159 | const roots = effectivePaths(); |
| 160 | const info = resolveRoot(file, roots); |
| 161 | if (!info || !canRead(req.user, info.label)) { |
| 162 | return res.status(403).json({ error: 'Access denied.' }); |
| 163 | } |
| 164 | |
| 165 | if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { |
| 166 | return res.status(404).json({ error: 'File not found.' }); |
| 167 | } |
| 168 | |
| 169 | // Record download |
| 170 | const db = getDb(); |
| 171 | const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); |
| 172 | if (meta) { |
| 173 | const downloaders = JSON.parse(meta.downloaders); |
| 174 | if (!downloaders.includes(req.user.username)) { |
| 175 | downloaders.push(req.user.username); |
| 176 | db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?') |
| 177 | .run([JSON.stringify(downloaders), file]); |
| 178 | } |
| 179 | } else { |
| 180 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 181 | .run([file, '', JSON.stringify([req.user.username])]); |
| 182 | } |
| 183 | |
| 184 | res.download(file, path.basename(file)); |
| 185 | }); |
| 186 | |
| 187 | // --------------------------------------------------------------------------- |
| 188 | // POST /api/files/upload?dir=<absolute-path> |
| 189 | // Accepts multipart file upload. |
| 190 | // --------------------------------------------------------------------------- |
| 191 | router.post('/upload', requireAuth, (req, res, next) => { |
| 192 | const dir = req.query.dir; |
| 193 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 194 | |
| 195 | const roots = effectivePaths(); |
| 196 | const info = resolveRoot(dir, roots); |
| 197 | if (!info || !canWrite(req.user, info.label)) { |
| 198 | return res.status(403).json({ error: 'Access denied.' }); |
| 199 | } |
| 200 | |
| 201 | if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { |
| 202 | return res.status(404).json({ error: 'Directory not found.' }); |
| 203 | } |
| 204 | |
| 205 | req._uploadDir = dir; |
| 206 | |
| 207 | upload.array('files')(req, res, (err) => { |
| 208 | if (err) return res.status(500).json({ error: err.message }); |
| 209 | |
| 210 | const db = getDb(); |
| 211 | for (const f of (req.files || [])) { |
| 212 | const filePath = path.join(dir, f.originalname); |
| 213 | const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]); |
| 214 | if (existing) { |
| 215 | db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?') |
| 216 | .run([req.user.username, filePath]); |
| 217 | } else { |
| 218 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 219 | .run([filePath, req.user.username, '[]']); |
| 220 | } |
| 221 | } |
| 222 | res.json({ uploaded: (req.files || []).map(f => f.originalname) }); |
| 223 | }); |
| 224 | }); |
| 225 | |
| 226 | // --------------------------------------------------------------------------- |
| 227 | // POST /api/files/rename |
| 228 | // Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path) |
| 229 | // --------------------------------------------------------------------------- |
| 230 | router.post('/rename', requireAuth, (req, res) => { |
| 231 | const { from, to } = req.body; |
| 232 | if (!from || !to) return res.status(400).json({ error: 'from and to are required.' }); |
| 233 | |
| 234 | // Prevent path traversal in the new name |
| 235 | if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) { |
| 236 | return res.status(400).json({ error: 'Invalid name.' }); |
| 237 | } |
| 238 | |
| 239 | const roots = effectivePaths(); |
| 240 | const info = resolveRoot(from, roots); |
| 241 | if (!info || !canWrite(req.user, info.label)) { |
| 242 | return res.status(403).json({ error: 'Access denied.' }); |
| 243 | } |
| 244 | |
| 245 | const dest = path.join(path.dirname(from), to); |
| 246 | |
| 247 | // Ensure dest is still inside the same root |
| 248 | if (!getAllowedRoot(dest, roots)) { |
| 249 | return res.status(403).json({ error: 'Access denied.' }); |
| 250 | } |
| 251 | |
| 252 | try { |
| 253 | fs.renameSync(from, dest); |
| 254 | } catch (err) { |
| 255 | return res.status(500).json({ error: err.message }); |
| 256 | } |
| 257 | |
| 258 | // Update DB meta key |
| 259 | const db = getDb(); |
| 260 | db.prepare('UPDATE file_meta SET file_path = ? WHERE file_path = ?').run([dest, from]); |
| 261 | |
| 262 | res.json({ ok: true }); |
| 263 | }); |
| 264 | |
| 265 | // --------------------------------------------------------------------------- |
| 266 | // POST /api/files/mkdir |
| 267 | // Body: { dir: <absolute-path>, name: <folder-name> } |
| 268 | // --------------------------------------------------------------------------- |
| 269 | router.post('/mkdir', requireAuth, (req, res) => { |
| 270 | const { dir, name } = req.body; |
| 271 | if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' }); |
| 272 | |
| 273 | if (path.basename(name) !== name) { |
| 274 | return res.status(400).json({ error: 'Invalid folder name.' }); |
| 275 | } |
| 276 | |
| 277 | const roots = effectivePaths(); |
| 278 | const info = resolveRoot(dir, roots); |
| 279 | if (!info || !canWrite(req.user, info.label)) { |
| 280 | return res.status(403).json({ error: 'Access denied.' }); |
| 281 | } |
| 282 | |
| 283 | const newDir = path.join(dir, name); |
| 284 | if (!getAllowedRoot(newDir, roots)) { |
| 285 | return res.status(403).json({ error: 'Access denied.' }); |
| 286 | } |
| 287 | |
| 288 | try { |
| 289 | fs.mkdirSync(newDir, { recursive: false }); |
| 290 | } catch (err) { |
| 291 | return res.status(500).json({ error: err.message }); |
| 292 | } |
| 293 | |
| 294 | res.json({ ok: true, path: newDir }); |
| 295 | }); |
| 296 | |
| 297 | // --------------------------------------------------------------------------- |
| 298 | // POST /api/files/delete |
| 299 | // Body: { path: <absolute-path> } |
| 300 | // --------------------------------------------------------------------------- |
| 301 | router.post('/delete', requireAuth, (req, res) => { |
| 302 | const target = req.body.path; |
| 303 | if (!target) return res.status(400).json({ error: 'path is required.' }); |
| 304 | |
| 305 | const roots = effectivePaths(); |
| 306 | const info = resolveRoot(target, roots); |
| 307 | if (!info || !canWrite(req.user, info.label)) { |
| 308 | return res.status(403).json({ error: 'Access denied.' }); |
| 309 | } |
| 310 | |
| 311 | // Do not allow deleting a configured root itself |
| 312 | if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) { |
| 313 | return res.status(403).json({ error: 'Cannot delete a configured root path.' }); |
| 314 | } |
| 315 | |
| 316 | try { |
| 317 | const stat = fs.statSync(target); |
| 318 | if (stat.isDirectory()) { |
| 319 | fs.rmSync(target, { recursive: true, force: true }); |
| 320 | } else { |
| 321 | fs.unlinkSync(target); |
| 322 | } |
| 323 | } catch (err) { |
| 324 | return res.status(500).json({ error: err.message }); |
| 325 | } |
| 326 | |
| 327 | // Clean up any DB meta entries under that path |
| 328 | const db = getDb(); |
| 329 | db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?") |
| 330 | .run([target, target + path.sep + '%']); |
| 331 | |
| 332 | res.json({ ok: true }); |
| 333 | }); |
| 334 | |
| 335 | module.exports = router; |