From 1129031a30a7b0a8f3ca3898e692403e8a7c74ef Mon Sep 17 00:00:00 2001 From: Melsy Huamani Date: Fri, 3 Jul 2026 08:28:36 -0500 Subject: [PATCH] fix: sonar issue in path --- index.js | 4 +++- src/utils/safePath.js | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 src/utils/safePath.js diff --git a/index.js b/index.js index 5bb1cc2..b8fba5b 100644 --- a/index.js +++ b/index.js @@ -19,13 +19,15 @@ const argv = require('yargs')(process.argv.slice(2)) .argv const fs = require('fs'); const { Console } = require('console'); +const resolveSafePath = require('./src/utils/safePath.js'); //PARSER-------------------------------- */ let configurationFile try { if (argv.configuration) { - configurationFile = JSON.parse(fs.readFileSync(argv.configuration, "utf8")) + const configurationPath = resolveSafePath(argv.configuration) + configurationFile = JSON.parse(fs.readFileSync(configurationPath, "utf8")) } else { try{ let filename = path.basename(argv.file, path.extname(argv.file)); diff --git a/src/utils/safePath.js b/src/utils/safePath.js new file mode 100644 index 0000000..ec570aa --- /dev/null +++ b/src/utils/safePath.js @@ -0,0 +1,20 @@ +/** Part of APIAddicts. See LICENSE fileor full copyright and licensing details. Supported by Madrid Digital and CloudAPPi **/ + +'use strict' + +const path = require('node:path') + +module.exports = function resolveSafePath(userPath, baseDir) { + if (typeof userPath !== 'string' || userPath.trim() === '') { + throw new Error('a file path is required'); + } + + const base = path.resolve(baseDir || process.env.O2P_ALLOWED_DIR || process.cwd()); + const resolved = path.resolve(base, userPath); + + if (resolved !== base && !resolved.startsWith(base + path.sep)) { + throw new Error('path "' + userPath + '" escapes the allowed directory "' + base + '"'); + } + + return resolved; +}