| 1 | 'use strict'; |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const path = require('path'); |
| 5 | |
| 6 | const CONFIG_PATH = path.join(__dirname, '../config.json'); |
| 7 | |
| 8 | function loadConfig() { |
| 9 | try { |
| 10 | const raw = fs.readFileSync(CONFIG_PATH, 'utf8'); |
| 11 | return JSON.parse(raw); |
| 12 | } catch { |
| 13 | const defaults = { port: 3000, paths: [] }; |
| 14 | fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8'); |
| 15 | return defaults; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | function saveConfig(config) { |
| 20 | fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8'); |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Returns the de-duplicated, overlap-filtered list of configured paths. |
| 25 | * A child path is dropped when a parent path is also configured. |
| 26 | * |
| 27 | * Works on both Windows and Linux paths. |
| 28 | */ |
| 29 | function getEffectivePaths(rawPaths) { |
| 30 | if (!Array.isArray(rawPaths)) return []; |
| 31 | |
| 32 | const sep = path.sep; |
| 33 | const normalized = rawPaths.map(p => path.resolve(p)); |
| 34 | const unique = [...new Set(normalized)]; |
| 35 | |
| 36 | return unique.filter(p => { |
| 37 | // Keep p only if no OTHER path in the list is a strict parent of p |
| 38 | return !unique.some(other => other !== p && p.startsWith(other + sep)); |
| 39 | }); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Checks whether `filePath` is safely inside one of the `allowedRoots`. |
| 44 | * Returns the matching root or null. |
| 45 | */ |
| 46 | function getAllowedRoot(filePath, allowedRoots) { |
| 47 | const resolved = path.resolve(filePath); |
| 48 | const sep = path.sep; |
| 49 | |
| 50 | for (const root of allowedRoots) { |
| 51 | const resolvedRoot = path.resolve(root); |
| 52 | if (resolved === resolvedRoot || resolved.startsWith(resolvedRoot + sep)) { |
| 53 | return resolvedRoot; |
| 54 | } |
| 55 | } |
| 56 | return null; |
| 57 | } |
| 58 | |
| 59 | module.exports = { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot }; |