BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

files.js 21.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, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
11const { requireAuth } = require('../auth');
12const { getCachedThumbnailInfo } = require('../thumbnail-cache');
13
14// ---------------------------------------------------------------------------
15// Multer storage — files are written directly to the target directory
16// ---------------------------------------------------------------------------
17const storage = multer.diskStorage({
18 destination (req, file, cb)
19 {
20 // The target directory is resolved in the route handler, so we stash it
21 // during the multer middleware call via req._uploadDir.
22 cb(null, req._uploadDir);
23 },
24 filename (req, file, cb)
25 {
26 cb(null, file.originalname);
27 },
28});
29
30const upload = multer({
31 storage,
32 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
33});
34
35// ---------------------------------------------------------------------------
36// Helpers
37// ---------------------------------------------------------------------------
38
39function effectivePaths ()
40{
41 return getEffectivePaths(loadConfig().paths || []);
42}
43
44function rootAliasesFromConfig (config)
45{
46 if (!config || typeof config !== 'object') return {};
47 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
48 return config.rootAliases;
49}
50
51function getFreeBytes (targetPath)
52{
53 if (typeof fs.statfsSync !== 'function') return null;
54 try
55 {
56 const stat = fs.statfsSync(targetPath);
57 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
58 return stat.bavail * stat.bsize;
59 } catch
60 {
61 return null;
62 }
63}
64
65function getRecursiveSize (targetPath)
66{
67 try
68 {
69 const stat = fs.statSync(targetPath);
70 if (!stat.isDirectory()) return stat.size;
71 } catch
72 {
73 return 0;
74 }
75
76 let total = 0;
77 let entries = [];
78 try
79 {
80 entries = fs.readdirSync(targetPath, { withFileTypes: true });
81 } catch
82 {
83 return 0;
84 }
85
86 for (const entry of entries)
87 {
88 const child = path.join(targetPath, entry.name);
89 if (entry.isDirectory())
90 {
91 total += getRecursiveSize(child);
92 continue;
93 }
94 try
95 {
96 total += fs.statSync(child).size;
97 } catch
98 {
99 // Ignore files that disappear during traversal.
100 }
101 }
102
103 return total;
104}
105
106/**
107 * Verify that the user has read access to the given configured-path label.
108 * `pathLabel` is the base-name of the effective path (shown in the UI).
109 */
110function canRead (user, pathLabel)
111{
112 if (user.isAdmin) return true;
113 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
114}
115
116function canWrite (user, pathLabel)
117{
118 if (user.isAdmin) return true;
119 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
120}
121
122/**
123 * Given an absolute path and the effective-paths list, return
124 * { root, label } where label is the base-name of the root, or null.
125 */
126function resolveRoot (absPath, roots)
127{
128 const matchedRoot = getAllowedRoot(absPath, roots);
129 if (!matchedRoot) return null;
130 return { root: matchedRoot, label: path.basename(matchedRoot) };
131}
132
133function sameResolvedPath (a, b)
134{
135 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
136}
137
138function pathInsideResolved (child, root)
139{
140 const relative = path.relative(path.resolve(root), path.resolve(child));
141 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
142}
143
144function rewriteMetaPaths (fromPath, toPath)
145{
146 const db = getDb();
147 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
148 .all([fromPath, fromPath + path.sep + '%']);
149
150 if (!rows.length) return;
151
152 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
153 const upsert = db.prepare(`
154 INSERT INTO file_meta (file_path, uploader, downloaders)
155 VALUES (?, ?, ?)
156 ON CONFLICT(file_path) DO UPDATE SET
157 uploader = excluded.uploader,
158 downloaders = excluded.downloaders
159 `);
160
161 for (const row of rows)
162 {
163 const nextPath = row.file_path === fromPath
164 ? toPath
165 : toPath + row.file_path.slice(fromPath.length);
166 del.run([row.file_path]);
167 upsert.run([nextPath, row.uploader, row.downloaders]);
168 }
169}
170
171// ---------------------------------------------------------------------------
172// GET /api/files/roots
173// Returns the effective configured paths the user can read.
174// ---------------------------------------------------------------------------
175router.get('/roots', requireAuth, (req, res) =>
176{
177 const config = loadConfig();
178 const roots = getEffectivePaths(config.paths || []);
179 const rootAliases = rootAliasesFromConfig(config);
180
181 const readable = roots
182 .filter(r => canRead(req.user, path.basename(r)))
183 .map(r =>
184 {
185 const originalName = path.basename(r);
186 const alias = String(rootAliases[path.resolve(r)] || '').trim();
187 return {
188 label: alias || originalName,
189 path: r,
190 originalName,
191 alias: alias || null,
192 };
193 });
194 res.json({ roots: readable });
195});
196
197// ---------------------------------------------------------------------------
198// GET /api/files/root-access?rootPath=<absolute-root-path>
199// Returns users that can access a configured root and their mode (R / R+W).
200// ---------------------------------------------------------------------------
201router.get('/root-access', requireAuth, (req, res) =>
202{
203 const rootPath = String(req.query.rootPath || '').trim();
204 if (!rootPath)
205 {
206 return res.status(400).json({ error: 'rootPath is required.' });
207 }
208
209 const config = loadConfig();
210 const roots = getEffectivePaths(config.paths || []);
211 const info = resolveRoot(rootPath, roots);
212 if (!info) return res.status(403).json({ error: 'Access denied.' });
213 if (!sameResolvedPath(rootPath, info.root))
214 {
215 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
216 }
217 if (!canRead(req.user, info.label))
218 {
219 return res.status(403).json({ error: 'Access denied.' });
220 }
221
222 const db = getDb();
223 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
224 const users = [];
225
226 for (const row of rows)
227 {
228 if (row.is_admin === 1)
229 {
230 users.push({ username: row.username, mode: 'R+W' });
231 continue;
232 }
233
234 let permissions = {};
235 try
236 {
237 permissions = JSON.parse(row.permissions || '{}');
238 } catch
239 {
240 permissions = {};
241 }
242
243 const perm = permissions[info.label];
244 if (!perm || typeof perm !== 'object') continue;
245 const canWriteRoot = !!perm.write;
246 const canReadRoot = !!perm.read || canWriteRoot;
247 if (!canReadRoot) continue;
248 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
249 }
250
251 users.sort((a, b) => String(a.username).localeCompare(String(b.username)));
252
253 const rootAliases = rootAliasesFromConfig(config);
254 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
255 res.json({
256 root: {
257 path: info.root,
258 label: alias || info.label,
259 originalName: info.label,
260 alias: alias || null,
261 },
262 users,
263 });
264});
265
266// ---------------------------------------------------------------------------
267// POST /api/files/root-alias
268// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
269// Sets a display-only alias for a configured root.
270// ---------------------------------------------------------------------------
271router.post('/root-alias', requireAuth, (req, res) =>
272{
273 const rootPath = String(req.body && req.body.rootPath || '').trim();
274 const alias = String(req.body && req.body.alias || '').trim();
275 if (!rootPath || !alias)
276 {
277 return res.status(400).json({ error: 'rootPath and alias are required.' });
278 }
279
280 const roots = effectivePaths();
281 const info = resolveRoot(rootPath, roots);
282 if (!info) return res.status(403).json({ error: 'Access denied.' });
283 if (!sameResolvedPath(rootPath, info.root))
284 {
285 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
286 }
287 if (!canWrite(req.user, info.label))
288 {
289 return res.status(403).json({ error: 'Access denied.' });
290 }
291
292 const config = loadConfig();
293 const rootAliases = rootAliasesFromConfig(config);
294 const key = path.resolve(info.root);
295 if (alias === info.label)
296 {
297 delete rootAliases[key];
298 } else
299 {
300 rootAliases[key] = alias;
301 }
302 config.rootAliases = rootAliases;
303 saveConfig(config);
304
305 res.json({
306 ok: true,
307 root: {
308 path: info.root,
309 label: alias,
310 originalName: info.label,
311 alias,
312 },
313 });
314});
315
316// ---------------------------------------------------------------------------
317// GET /api/files/list?dir=<absolute-path>
318// Lists files and folders in the given directory.
319// ---------------------------------------------------------------------------
320router.get('/list', requireAuth, (req, res) =>
321{
322 const dir = req.query.dir;
323 if (!dir) return res.status(400).json({ error: 'dir is required.' });
324
325 const roots = effectivePaths();
326 const info = resolveRoot(dir, roots);
327 if (!info) return res.status(403).json({ error: 'Access denied.' });
328 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
329
330 let entries;
331 try
332 {
333 entries = fs.readdirSync(dir, { withFileTypes: true });
334 } catch
335 {
336 return res.status(404).json({ error: 'Directory not found.' });
337 }
338
339 const items = entries.map(e =>
340 {
341 const fullPath = path.join(dir, e.name);
342 let size = null;
343 let mtime = null;
344 try
345 {
346 const stat = fs.statSync(fullPath);
347 size = stat.size;
348 mtime = stat.mtime.toISOString();
349 } catch { /* ignore */ }
350
351 return {
352 name: e.name,
353 isDir: e.isDirectory(),
354 size,
355 mtime,
356 path: fullPath,
357 };
358 });
359
360 res.json({ items });
361});
362
363// ---------------------------------------------------------------------------
364// GET /api/files/meta?file=<absolute-path>
365// Returns file metadata from the DB.
366// ---------------------------------------------------------------------------
367router.get('/meta', requireAuth, (req, res) =>
368{
369 const file = req.query.file;
370 if (!file) return res.status(400).json({ error: 'file is required.' });
371
372 const roots = effectivePaths();
373 const info = resolveRoot(file, roots);
374 if (!info || !canRead(req.user, info.label))
375 {
376 return res.status(403).json({ error: 'Access denied.' });
377 }
378
379 let stat;
380 try
381 {
382 stat = fs.statSync(file);
383 } catch
384 {
385 return res.status(404).json({ error: 'File not found.' });
386 }
387
388 const db = getDb();
389 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
390
391 res.json({
392 name: path.basename(file),
393 size: stat.size,
394 mtime: stat.mtime.toISOString(),
395 uploader: meta ? meta.uploader : '',
396 downloaders: meta ? JSON.parse(meta.downloaders) : [],
397 });
398});
399
400// ---------------------------------------------------------------------------
401// GET /api/files/space?dir=<absolute-path>
402// Returns recursive used bytes for dir and available bytes on its root fs.
403// ---------------------------------------------------------------------------
404router.get('/space', requireAuth, (req, res) =>
405{
406 const dir = req.query.dir;
407 if (!dir) return res.status(400).json({ error: 'dir is required.' });
408
409 const roots = effectivePaths();
410 const info = resolveRoot(dir, roots);
411 if (!info || !canRead(req.user, info.label))
412 {
413 return res.status(403).json({ error: 'Access denied.' });
414 }
415
416 if (!fs.existsSync(dir))
417 {
418 return res.status(404).json({ error: 'Path not found.' });
419 }
420
421 const usedBytes = getRecursiveSize(dir);
422 const freeBytes = getFreeBytes(info.root);
423 res.json({
424 usedBytes,
425 freeBytes,
426 rootPath: info.root,
427 rootLabel: info.label,
428 });
429});
430
431// ---------------------------------------------------------------------------
432// GET /api/files/download?file=<absolute-path>
433// Streams the file to the client; records the download.
434// ---------------------------------------------------------------------------
435router.get('/download', requireAuth, (req, res) =>
436{
437 const file = req.query.file;
438 if (!file) return res.status(400).json({ error: 'file is required.' });
439
440 const roots = effectivePaths();
441 const info = resolveRoot(file, roots);
442 if (!info || !canRead(req.user, info.label))
443 {
444 return res.status(403).json({ error: 'Access denied.' });
445 }
446
447 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
448 {
449 return res.status(404).json({ error: 'File not found.' });
450 }
451
452 // Record download
453 const db = getDb();
454 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
455 if (meta)
456 {
457 const downloaders = JSON.parse(meta.downloaders);
458 if (!downloaders.includes(req.user.username))
459 {
460 downloaders.push(req.user.username);
461 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
462 .run([JSON.stringify(downloaders), file]);
463 }
464 } else
465 {
466 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
467 .run([file, '', JSON.stringify([req.user.username])]);
468 }
469
470 res.download(file, path.basename(file));
471});
472
473// ---------------------------------------------------------------------------
474// GET /api/files/thumbnail?file=<absolute-path>
475// Returns a pre-generated cached thumbnail if present.
476// ---------------------------------------------------------------------------
477router.get('/thumbnail', requireAuth, async (req, res) =>
478{
479 const file = req.query.file;
480 if (!file) return res.status(400).json({ error: 'file is required.' });
481
482 const roots = effectivePaths();
483 const info = resolveRoot(file, roots);
484 if (!info || !canRead(req.user, info.label))
485 {
486 return res.status(403).json({ error: 'Access denied.' });
487 }
488
489 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
490 {
491 return res.status(404).json({ error: 'File not found.' });
492 }
493
494 const thumb = await getCachedThumbnailInfo(file);
495 if (!thumb)
496 {
497 return res.status(404).json({ error: 'Thumbnail not ready.' });
498 }
499
500 res.type(thumb.contentType);
501 res.set('Cache-Control', 'private, max-age=10');
502 res.sendFile(thumb.thumbPath);
503});
504
505// ---------------------------------------------------------------------------
506// POST /api/files/upload?dir=<absolute-path>
507// Accepts multipart file upload.
508// ---------------------------------------------------------------------------
509router.post('/upload', requireAuth, (req, res, next) =>
510{
511 const dir = req.query.dir;
512 if (!dir) return res.status(400).json({ error: 'dir is required.' });
513
514 const roots = effectivePaths();
515 const info = resolveRoot(dir, roots);
516 if (!info || !canWrite(req.user, info.label))
517 {
518 return res.status(403).json({ error: 'Access denied.' });
519 }
520
521 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
522 {
523 return res.status(404).json({ error: 'Directory not found.' });
524 }
525
526 const announcedSize = Number(req.header('x-upload-size') || 0);
527 if (Number.isFinite(announcedSize) && announcedSize > 0)
528 {
529 const freeBytes = getFreeBytes(info.root);
530 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
531 {
532 return res.status(413).json({
533 error: 'Upload too large for remaining free space on selected root.',
534 freeBytes,
535 requiredBytes: announcedSize,
536 });
537 }
538 }
539
540 req._uploadDir = dir;
541
542 upload.array('files')(req, res, (err) =>
543 {
544 if (err) return res.status(500).json({ error: err.message });
545
546 const db = getDb();
547 for (const f of (req.files || []))
548 {
549 const filePath = path.join(dir, f.originalname);
550 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
551 if (existing)
552 {
553 db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?')
554 .run([req.user.username, filePath]);
555 } else
556 {
557 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
558 .run([filePath, req.user.username, '[]']);
559 }
560 }
561 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
562 });
563});
564
565// ---------------------------------------------------------------------------
566// POST /api/files/rename
567// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
568// ---------------------------------------------------------------------------
569router.post('/rename', requireAuth, (req, res) =>
570{
571 const { from, to } = req.body;
572 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
573
574 // Prevent path traversal in the new name
575 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
576 {
577 return res.status(400).json({ error: 'Invalid name.' });
578 }
579
580 const roots = effectivePaths();
581 const info = resolveRoot(from, roots);
582 if (!info || !canWrite(req.user, info.label))
583 {
584 return res.status(403).json({ error: 'Access denied.' });
585 }
586
587 const dest = path.join(path.dirname(from), to);
588
589 // Ensure dest is still inside the same root
590 if (!getAllowedRoot(dest, roots))
591 {
592 return res.status(403).json({ error: 'Access denied.' });
593 }
594
595 try
596 {
597 fs.renameSync(from, dest);
598 } catch (err)
599 {
600 return res.status(500).json({ error: err.message });
601 }
602
603 rewriteMetaPaths(from, dest);
604
605 res.json({ ok: true });
606});
607
608// ---------------------------------------------------------------------------
609// POST /api/files/move
610// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
611// ---------------------------------------------------------------------------
612router.post('/move', requireAuth, (req, res) =>
613{
614 const { from, toDir } = req.body;
615 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
616
617 const roots = effectivePaths();
618 const fromInfo = resolveRoot(from, roots);
619 const toInfo = resolveRoot(toDir, roots);
620 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
621 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
622 {
623 return res.status(403).json({ error: 'Access denied.' });
624 }
625
626 let sourceStat;
627 let destStat;
628 try
629 {
630 sourceStat = fs.statSync(from);
631 destStat = fs.statSync(toDir);
632 } catch
633 {
634 return res.status(404).json({ error: 'Source or destination not found.' });
635 }
636
637 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
638
639 const dest = path.join(toDir, path.basename(from));
640 if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' });
641 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest))
642 {
643 return res.status(400).json({ error: 'Cannot move onto itself.' });
644 }
645 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
646 {
647 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
648 }
649 if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' });
650
651 try
652 {
653 fs.renameSync(from, dest);
654 } catch (err)
655 {
656 return res.status(500).json({ error: err.message });
657 }
658
659 rewriteMetaPaths(from, dest);
660 res.json({ ok: true, path: dest });
661});
662
663// ---------------------------------------------------------------------------
664// POST /api/files/mkdir
665// Body: { dir: <absolute-path>, name: <folder-name> }
666// ---------------------------------------------------------------------------
667router.post('/mkdir', requireAuth, (req, res) =>
668{
669 const { dir, name } = req.body;
670 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
671
672 if (path.basename(name) !== name)
673 {
674 return res.status(400).json({ error: 'Invalid folder name.' });
675 }
676
677 const roots = effectivePaths();
678 const info = resolveRoot(dir, roots);
679 if (!info || !canWrite(req.user, info.label))
680 {
681 return res.status(403).json({ error: 'Access denied.' });
682 }
683
684 const newDir = path.join(dir, name);
685 if (!getAllowedRoot(newDir, roots))
686 {
687 return res.status(403).json({ error: 'Access denied.' });
688 }
689
690 try
691 {
692 fs.mkdirSync(newDir, { recursive: false });
693 } catch (err)
694 {
695 return res.status(500).json({ error: err.message });
696 }
697
698 res.json({ ok: true, path: newDir });
699});
700
701// ---------------------------------------------------------------------------
702// POST /api/files/delete
703// Body: { path: <absolute-path> }
704// ---------------------------------------------------------------------------
705router.post('/delete', requireAuth, (req, res) =>
706{
707 const target = req.body.path;
708 if (!target) return res.status(400).json({ error: 'path is required.' });
709
710 const roots = effectivePaths();
711 const info = resolveRoot(target, roots);
712 if (!info || !canWrite(req.user, info.label))
713 {
714 return res.status(403).json({ error: 'Access denied.' });
715 }
716
717 // Do not allow deleting a configured root itself
718 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
719 {
720 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
721 }
722
723 try
724 {
725 const stat = fs.statSync(target);
726 if (stat.isDirectory())
727 {
728 fs.rmSync(target, { recursive: true, force: true });
729 } else
730 {
731 fs.unlinkSync(target);
732 }
733 } catch (err)
734 {
735 return res.status(500).json({ error: err.message });
736 }
737
738 // Clean up any DB meta entries under that path
739 const db = getDb();
740 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
741 .run([target, target + path.sep + '%']);
742
743 res.json({ ok: true });
744});
745
746module.exports = router;