BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

files.js 16.3 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const multer = require('multer');
7const router = express.Router();
8
9const { getDb } = require('../db');
10const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
12
13// ---------------------------------------------------------------------------
14// Multer storage — files are written directly to the target directory
15// ---------------------------------------------------------------------------
16const storage = multer.diskStorage({
17 destination (req, file, cb)
18 {
19 // The target directory is resolved in the route handler, so we stash it
20 // during the multer middleware call via req._uploadDir.
21 cb(null, req._uploadDir);
22 },
23 filename (req, file, cb)
24 {
25 cb(null, file.originalname);
26 },
27});
28
29const upload = multer({
30 storage,
31 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
32});
33
34// ---------------------------------------------------------------------------
35// Helpers
36// ---------------------------------------------------------------------------
37
38function effectivePaths ()
39{
40 return getEffectivePaths(loadConfig().paths || []);
41}
42
43function getFreeBytes (targetPath)
44{
45 if (typeof fs.statfsSync !== 'function') return null;
46 try
47 {
48 const stat = fs.statfsSync(targetPath);
49 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
50 return stat.bavail * stat.bsize;
51 } catch
52 {
53 return null;
54 }
55}
56
57function getRecursiveSize (targetPath)
58{
59 try
60 {
61 const stat = fs.statSync(targetPath);
62 if (!stat.isDirectory()) return stat.size;
63 } catch
64 {
65 return 0;
66 }
67
68 let total = 0;
69 let entries = [];
70 try
71 {
72 entries = fs.readdirSync(targetPath, { withFileTypes: true });
73 } catch
74 {
75 return 0;
76 }
77
78 for (const entry of entries)
79 {
80 const child = path.join(targetPath, entry.name);
81 if (entry.isDirectory())
82 {
83 total += getRecursiveSize(child);
84 continue;
85 }
86 try
87 {
88 total += fs.statSync(child).size;
89 } catch
90 {
91 // Ignore files that disappear during traversal.
92 }
93 }
94
95 return total;
96}
97
98/**
99 * Verify that the user has read access to the given configured-path label.
100 * `pathLabel` is the base-name of the effective path (shown in the UI).
101 */
102function canRead (user, pathLabel)
103{
104 if (user.isAdmin) return true;
105 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
106}
107
108function canWrite (user, pathLabel)
109{
110 if (user.isAdmin) return true;
111 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
112}
113
114/**
115 * Given an absolute path and the effective-paths list, return
116 * { root, label } where label is the base-name of the root, or null.
117 */
118function resolveRoot (absPath, roots)
119{
120 const matchedRoot = getAllowedRoot(absPath, roots);
121 if (!matchedRoot) return null;
122 return { root: matchedRoot, label: path.basename(matchedRoot) };
123}
124
125function sameResolvedPath (a, b)
126{
127 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
128}
129
130function pathInsideResolved (child, root)
131{
132 const relative = path.relative(path.resolve(root), path.resolve(child));
133 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
134}
135
136function rewriteMetaPaths (fromPath, toPath)
137{
138 const db = getDb();
139 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
140 .all([fromPath, fromPath + path.sep + '%']);
141
142 if (!rows.length) return;
143
144 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
145 const upsert = db.prepare(`
146 INSERT INTO file_meta (file_path, uploader, downloaders)
147 VALUES (?, ?, ?)
148 ON CONFLICT(file_path) DO UPDATE SET
149 uploader = excluded.uploader,
150 downloaders = excluded.downloaders
151 `);
152
153 for (const row of rows)
154 {
155 const nextPath = row.file_path === fromPath
156 ? toPath
157 : toPath + row.file_path.slice(fromPath.length);
158 del.run([row.file_path]);
159 upsert.run([nextPath, row.uploader, row.downloaders]);
160 }
161}
162
163// ---------------------------------------------------------------------------
164// GET /api/files/roots
165// Returns the effective configured paths the user can read.
166// ---------------------------------------------------------------------------
167router.get('/roots', requireAuth, (req, res) =>
168{
169 const roots = effectivePaths();
170 const readable = roots
171 .filter(r => canRead(req.user, path.basename(r)))
172 .map(r => ({ label: path.basename(r), path: r }));
173 res.json({ roots: readable });
174});
175
176// ---------------------------------------------------------------------------
177// GET /api/files/list?dir=<absolute-path>
178// Lists files and folders in the given directory.
179// ---------------------------------------------------------------------------
180router.get('/list', requireAuth, (req, res) =>
181{
182 const dir = req.query.dir;
183 if (!dir) return res.status(400).json({ error: 'dir is required.' });
184
185 const roots = effectivePaths();
186 const info = resolveRoot(dir, roots);
187 if (!info) return res.status(403).json({ error: 'Access denied.' });
188 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
189
190 let entries;
191 try
192 {
193 entries = fs.readdirSync(dir, { withFileTypes: true });
194 } catch
195 {
196 return res.status(404).json({ error: 'Directory not found.' });
197 }
198
199 const items = entries.map(e =>
200 {
201 const fullPath = path.join(dir, e.name);
202 let size = null;
203 let mtime = null;
204 try
205 {
206 const stat = fs.statSync(fullPath);
207 size = stat.size;
208 mtime = stat.mtime.toISOString();
209 } catch { /* ignore */ }
210
211 return {
212 name: e.name,
213 isDir: e.isDirectory(),
214 size,
215 mtime,
216 path: fullPath,
217 };
218 });
219
220 res.json({ items });
221});
222
223// ---------------------------------------------------------------------------
224// GET /api/files/meta?file=<absolute-path>
225// Returns file metadata from the DB.
226// ---------------------------------------------------------------------------
227router.get('/meta', requireAuth, (req, res) =>
228{
229 const file = req.query.file;
230 if (!file) return res.status(400).json({ error: 'file is required.' });
231
232 const roots = effectivePaths();
233 const info = resolveRoot(file, roots);
234 if (!info || !canRead(req.user, info.label))
235 {
236 return res.status(403).json({ error: 'Access denied.' });
237 }
238
239 let stat;
240 try
241 {
242 stat = fs.statSync(file);
243 } catch
244 {
245 return res.status(404).json({ error: 'File not found.' });
246 }
247
248 const db = getDb();
249 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
250
251 res.json({
252 name: path.basename(file),
253 size: stat.size,
254 mtime: stat.mtime.toISOString(),
255 uploader: meta ? meta.uploader : '',
256 downloaders: meta ? JSON.parse(meta.downloaders) : [],
257 });
258});
259
260// ---------------------------------------------------------------------------
261// GET /api/files/space?dir=<absolute-path>
262// Returns recursive used bytes for dir and available bytes on its root fs.
263// ---------------------------------------------------------------------------
264router.get('/space', requireAuth, (req, res) =>
265{
266 const dir = req.query.dir;
267 if (!dir) return res.status(400).json({ error: 'dir is required.' });
268
269 const roots = effectivePaths();
270 const info = resolveRoot(dir, roots);
271 if (!info || !canRead(req.user, info.label))
272 {
273 return res.status(403).json({ error: 'Access denied.' });
274 }
275
276 if (!fs.existsSync(dir))
277 {
278 return res.status(404).json({ error: 'Path not found.' });
279 }
280
281 const usedBytes = getRecursiveSize(dir);
282 const freeBytes = getFreeBytes(info.root);
283 res.json({
284 usedBytes,
285 freeBytes,
286 rootPath: info.root,
287 rootLabel: info.label,
288 });
289});
290
291// ---------------------------------------------------------------------------
292// GET /api/files/download?file=<absolute-path>
293// Streams the file to the client; records the download.
294// ---------------------------------------------------------------------------
295router.get('/download', requireAuth, (req, res) =>
296{
297 const file = req.query.file;
298 if (!file) return res.status(400).json({ error: 'file is required.' });
299
300 const roots = effectivePaths();
301 const info = resolveRoot(file, roots);
302 if (!info || !canRead(req.user, info.label))
303 {
304 return res.status(403).json({ error: 'Access denied.' });
305 }
306
307 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
308 {
309 return res.status(404).json({ error: 'File not found.' });
310 }
311
312 // Record download
313 const db = getDb();
314 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
315 if (meta)
316 {
317 const downloaders = JSON.parse(meta.downloaders);
318 if (!downloaders.includes(req.user.username))
319 {
320 downloaders.push(req.user.username);
321 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
322 .run([JSON.stringify(downloaders), file]);
323 }
324 } else
325 {
326 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
327 .run([file, '', JSON.stringify([req.user.username])]);
328 }
329
330 res.download(file, path.basename(file));
331});
332
333// ---------------------------------------------------------------------------
334// POST /api/files/upload?dir=<absolute-path>
335// Accepts multipart file upload.
336// ---------------------------------------------------------------------------
337router.post('/upload', requireAuth, (req, res, next) =>
338{
339 const dir = req.query.dir;
340 if (!dir) return res.status(400).json({ error: 'dir is required.' });
341
342 const roots = effectivePaths();
343 const info = resolveRoot(dir, roots);
344 if (!info || !canWrite(req.user, info.label))
345 {
346 return res.status(403).json({ error: 'Access denied.' });
347 }
348
349 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
350 {
351 return res.status(404).json({ error: 'Directory not found.' });
352 }
353
354 const announcedSize = Number(req.header('x-upload-size') || 0);
355 if (Number.isFinite(announcedSize) && announcedSize > 0)
356 {
357 const freeBytes = getFreeBytes(info.root);
358 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
359 {
360 return res.status(413).json({
361 error: 'Upload too large for remaining free space on selected root.',
362 freeBytes,
363 requiredBytes: announcedSize,
364 });
365 }
366 }
367
368 req._uploadDir = dir;
369
370 upload.array('files')(req, res, (err) =>
371 {
372 if (err) return res.status(500).json({ error: err.message });
373
374 const db = getDb();
375 for (const f of (req.files || []))
376 {
377 const filePath = path.join(dir, f.originalname);
378 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
379 if (existing)
380 {
381 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
382 .run([req.user.username, filePath]);
383 } else
384 {
385 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
386 .run([filePath, req.user.username, '[]']);
387 }
388 }
389 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
390 });
391});
392
393// ---------------------------------------------------------------------------
394// POST /api/files/rename
395// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
396// ---------------------------------------------------------------------------
397router.post('/rename', requireAuth, (req, res) =>
398{
399 const { from, to } = req.body;
400 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
401
402 // Prevent path traversal in the new name
403 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
404 {
405 return res.status(400).json({ error: 'Invalid name.' });
406 }
407
408 const roots = effectivePaths();
409 const info = resolveRoot(from, roots);
410 if (!info || !canWrite(req.user, info.label))
411 {
412 return res.status(403).json({ error: 'Access denied.' });
413 }
414
415 const dest = path.join(path.dirname(from), to);
416
417 // Ensure dest is still inside the same root
418 if (!getAllowedRoot(dest, roots))
419 {
420 return res.status(403).json({ error: 'Access denied.' });
421 }
422
423 try
424 {
425 fs.renameSync(from, dest);
426 } catch (err)
427 {
428 return res.status(500).json({ error: err.message });
429 }
430
431 rewriteMetaPaths(from, dest);
432
433 res.json({ ok: true });
434});
435
436// ---------------------------------------------------------------------------
437// POST /api/files/move
438// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
439// ---------------------------------------------------------------------------
440router.post('/move', requireAuth, (req, res) =>
441{
442 const { from, toDir } = req.body;
443 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
444
445 const roots = effectivePaths();
446 const fromInfo = resolveRoot(from, roots);
447 const toInfo = resolveRoot(toDir, roots);
448 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
449 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
450 {
451 return res.status(403).json({ error: 'Access denied.' });
452 }
453
454 let sourceStat;
455 let destStat;
456 try
457 {
458 sourceStat = fs.statSync(from);
459 destStat = fs.statSync(toDir);
460 } catch
461 {
462 return res.status(404).json({ error: 'Source or destination not found.' });
463 }
464
465 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
466
467 const dest = path.join(toDir, path.basename(from));
468 if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
469 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
470 {
471 return res.status(400).json({ error: 'Cannot move onto itself.' });
472 }
473 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
474 {
475 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
476 }
477 if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
478
479 try
480 {
481 fs.renameSync(from, dest);
482 } catch (err)
483 {
484 return res.status(500).json({ error: err.message });
485 }
486
487 rewriteMetaPaths(from, dest);
488 res.json({ ok: true, path: dest });
489});
490
491// ---------------------------------------------------------------------------
492// POST /api/files/mkdir
493// Body: { dir: <absolute-path>, name: <folder-name> }
494// ---------------------------------------------------------------------------
495router.post('/mkdir', requireAuth, (req, res) =>
496{
497 const { dir, name } = req.body;
498 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
499
500 if (path.basename(name) !== name)
501 {
502 return res.status(400).json({ error: 'Invalid folder name.' });
503 }
504
505 const roots = effectivePaths();
506 const info = resolveRoot(dir, roots);
507 if (!info || !canWrite(req.user, info.label))
508 {
509 return res.status(403).json({ error: 'Access denied.' });
510 }
511
512 const newDir = path.join(dir, name);
513 if (!getAllowedRoot(newDir, roots))
514 {
515 return res.status(403).json({ error: 'Access denied.' });
516 }
517
518 try
519 {
520 fs.mkdirSync(newDir, { recursive: false });
521 } catch (err)
522 {
523 return res.status(500).json({ error: err.message });
524 }
525
526 res.json({ ok: true, path: newDir });
527});
528
529// ---------------------------------------------------------------------------
530// POST /api/files/delete
531// Body: { path: <absolute-path> }
532// ---------------------------------------------------------------------------
533router.post('/delete', requireAuth, (req, res) =>
534{
535 const target = req.body.path;
536 if (!target) return res.status(400).json({ error: 'path is required.' });
537
538 const roots = effectivePaths();
539 const info = resolveRoot(target, roots);
540 if (!info || !canWrite(req.user, info.label))
541 {
542 return res.status(403).json({ error: 'Access denied.' });
543 }
544
545 // Do not allow deleting a configured root itself
546 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
547 {
548 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
549 }
550
551 try
552 {
553 const stat = fs.statSync(target);
554 if (stat.isDirectory())
555 {
556 fs.rmSync(target, { recursive: true, force: true });
557 } else
558 {
559 fs.unlinkSync(target);
560 }
561 } catch (err)
562 {
563 return res.status(500).json({ error: err.message });
564 }
565
566 // Clean up any DB meta entries under that path
567 const db = getDb();
568 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
569 .run([target, target + path.sep + '%']);
570
571 res.json({ ok: true });
572});
573
574module.exports = router;