BlueGit

timfa filemanager

Files

filemanager / server / config.js

config.js

fixes and updates
timfa Tim Falken · pushed by timfa · 6 months ago
0ae63c84 History
config.js 2.3 KiB Download Raw
1'use strict';
2
3const fs = require('fs');
4const path = require('path');
5
6const CONFIG_PATH = path.join(__dirname, '../config.json');
7
8function loadConfig ()
9{
10 try
11 {
12 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
13 return JSON.parse(raw);
14 } catch
15 {
16 const defaults = { port: 3000, paths: [] };
17 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
18 return defaults;
19 }
20}
21
22function saveConfig (config)
23{
24 const dir = path.dirname(CONFIG_PATH);
25 const tmp = path.join(dir, '.config.json.tmp');
26 const payload = JSON.stringify(config, null, 2);
27
28 // Atomic replace to avoid partially-written config files.
29 fs.writeFileSync(tmp, payload, 'utf8');
30 fs.renameSync(tmp, CONFIG_PATH);
31}
32
33function normalizeForCompare (p)
34{
35 const resolved = path.resolve(p);
36 // Windows paths are case-insensitive for normal filesystems.
37 return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
38}
39
40/**
41 * Returns the de-duplicated, overlap-filtered list of configured paths.
42 * A child path is dropped when a parent path is also configured.
43 *
44 * Works on both Windows and Linux paths.
45 */
46function getEffectivePaths (rawPaths)
47{
48 if (!Array.isArray(rawPaths)) return [];
49
50 const sep = path.sep;
51 const normalized = rawPaths.map(p => path.resolve(p));
52 const unique = [...new Set(normalized)];
53
54 return unique.filter(p =>
55 {
56 const cmpP = normalizeForCompare(p);
57 // Keep p only if no OTHER path in the list is a strict parent of p
58 return !unique.some(other =>
59 {
60 if (other === p) return false;
61 const cmpOther = normalizeForCompare(other);
62 return cmpP.startsWith(cmpOther + sep);
63 });
64 });
65}
66
67/**
68 * Checks whether `filePath` is safely inside one of the `allowedRoots`.
69 * Returns the matching root or null.
70 */
71function getAllowedRoot (filePath, allowedRoots)
72{
73 const resolved = path.resolve(filePath);
74 const cmpResolved = normalizeForCompare(resolved);
75 const sep = path.sep;
76
77 for (const root of allowedRoots)
78 {
79 const resolvedRoot = path.resolve(root);
80 const cmpRoot = normalizeForCompare(resolvedRoot);
81 if (cmpResolved === cmpRoot || cmpResolved.startsWith(cmpRoot + sep))
82 {
83 return resolvedRoot;
84 }
85 }
86 return null;
87}
88
89module.exports = { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot };