'use strict'; const fs = require('fs'); const path = require('path'); const CONFIG_PATH = path.join(__dirname, '../config.json'); function loadConfig() { try { const raw = fs.readFileSync(CONFIG_PATH, 'utf8'); return JSON.parse(raw); } catch { const defaults = { port: 3000, paths: [] }; fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8'); return defaults; } } function saveConfig(config) { fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); } /** * Returns the de-duplicated, overlap-filtered list of configured paths. * A child path is dropped when a parent path is also configured. * * Works on both Windows and Linux paths. */ function getEffectivePaths(rawPaths) { if (!Array.isArray(rawPaths)) return []; const sep = path.sep; const normalized = rawPaths.map(p => path.resolve(p)); const unique = [...new Set(normalized)]; return unique.filter(p => { // Keep p only if no OTHER path in the list is a strict parent of p return !unique.some(other => other !== p && p.startsWith(other + sep)); }); } /** * Checks whether `filePath` is safely inside one of the `allowedRoots`. * Returns the matching root or null. */ function getAllowedRoot(filePath, allowedRoots) { const resolved = path.resolve(filePath); const sep = path.sep; for (const root of allowedRoots) { const resolvedRoot = path.resolve(root); if (resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep)) { return resolvedRoot; } } return null; } module.exports = { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot };