BlueGit

timfa filemanager

Files

filemanager / server / config.js

config.js

Cursor Optimisation pass
timfa Tim Falken · pushed by timfa · 5 months ago
7e6dfc52 History
config.js 4.1 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
8let cachedConfig = null;
9let cachedConfigMtimeMs = null;
10
11const DEFAULT_SCHEDULED_RESTART = {
12 enabled: false,
13 cadence: 'daily',
14 time: '04:00',
15};
16
17function normalizeScheduledRestart (value)
18{
19 const raw = value && typeof value === 'object' ? value : {};
20 const cadence = String(raw.cadence || '').trim().toLowerCase();
21 const allowedCadences = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
22 const time = String(raw.time || '').trim();
23
24 return {
25 enabled: !!raw.enabled,
26 cadence: allowedCadences.has(cadence) ? cadence : DEFAULT_SCHEDULED_RESTART.cadence,
27 time: /^([01]\d|2[0-3]):([0-5]\d)$/.test(time) ? time : DEFAULT_SCHEDULED_RESTART.time,
28 };
29}
30
31function normalizeLoadedConfig (parsed)
32{
33 if (!parsed || typeof parsed !== 'object')
34 {
35 return { port: 3000, paths: [], rootAliases: {} };
36 }
37 if (!parsed.rootAliases || typeof parsed.rootAliases !== 'object')
38 {
39 parsed.rootAliases = {};
40 }
41 parsed.scheduledRestart = normalizeScheduledRestart(parsed.scheduledRestart);
42 return parsed;
43}
44
45function loadConfig ()
46{
47 try
48 {
49 const stat = fs.statSync(CONFIG_PATH);
50 if (cachedConfig && cachedConfigMtimeMs === stat.mtimeMs)
51 {
52 return cachedConfig;
53 }
54
55 const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
56 const parsed = normalizeLoadedConfig(JSON.parse(raw));
57 cachedConfig = parsed;
58 cachedConfigMtimeMs = stat.mtimeMs;
59 return parsed;
60 } catch
61 {
62 const defaults = { port: 3000, paths: [], rootAliases: {}, scheduledRestart: { ...DEFAULT_SCHEDULED_RESTART } };
63 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
64 const stat = fs.statSync(CONFIG_PATH);
65 cachedConfig = defaults;
66 cachedConfigMtimeMs = stat.mtimeMs;
67 return defaults;
68 }
69}
70
71function saveConfig (config)
72{
73 const dir = path.dirname(CONFIG_PATH);
74 const tmp = path.join(dir, '.config.json.tmp');
75 const payload = JSON.stringify(config, null, 2);
76
77 // Atomic replace to avoid partially-written config files.
78 fs.writeFileSync(tmp, payload, 'utf8');
79 fs.renameSync(tmp, CONFIG_PATH);
80
81 const normalized = normalizeLoadedConfig(config);
82 cachedConfig = normalized;
83 try
84 {
85 cachedConfigMtimeMs = fs.statSync(CONFIG_PATH).mtimeMs;
86 } catch
87 {
88 cachedConfigMtimeMs = null;
89 }
90}
91
92function invalidateConfigCache ()
93{
94 cachedConfig = null;
95 cachedConfigMtimeMs = null;
96}
97
98function normalizeForCompare (p)
99{
100 const resolved = path.resolve(p);
101 // Windows paths are case-insensitive for normal filesystems.
102 return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
103}
104
105/**
106 * Returns the de-duplicated, overlap-filtered list of configured paths.
107 * A child path is dropped when a parent path is also configured.
108 *
109 * Works on both Windows and Linux paths.
110 */
111function getEffectivePaths (rawPaths)
112{
113 if (!Array.isArray(rawPaths)) return [];
114
115 const sep = path.sep;
116 const normalized = rawPaths.map(p => path.resolve(p));
117 const unique = [...new Set(normalized)];
118
119 return unique.filter(p =>
120 {
121 const cmpP = normalizeForCompare(p);
122 // Keep p only if no OTHER path in the list is a strict parent of p
123 return !unique.some(other =>
124 {
125 if (other === p) return false;
126 const cmpOther = normalizeForCompare(other);
127 return cmpP.startsWith(cmpOther + sep);
128 });
129 });
130}
131
132/**
133 * Checks whether `filePath` is safely inside one of the `allowedRoots`.
134 * Returns the matching root or null.
135 */
136function getAllowedRoot (filePath, allowedRoots)
137{
138 const resolved = path.resolve(filePath);
139 const cmpResolved = normalizeForCompare(resolved);
140 const sep = path.sep;
141
142 for (const root of allowedRoots)
143 {
144 const resolvedRoot = path.resolve(root);
145 const cmpRoot = normalizeForCompare(resolvedRoot);
146 if (cmpResolved === cmpRoot || cmpResolved.startsWith(cmpRoot + sep))
147 {
148 return resolvedRoot;
149 }
150 }
151 return null;
152}
153
154module.exports = {
155 loadConfig,
156 saveConfig,
157 invalidateConfigCache,
158 getEffectivePaths,
159 getAllowedRoot,
160};