| 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 | { |
| 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 | |
| 22 | function 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 | |
| 33 | function 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 | */ |
| 46 | function 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 | */ |
| 71 | function 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 | |
| 89 | module.exports = { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot }; |