BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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