安全path.resolve不从父母逃脱

我正在编写一个(expressjs)http服务,它在每次调用时都会获取相对path作为用户input,从基于该path的文件系统中读取文件并对其进行处理,如下所示:

app.get("/api", (req, res, next) => { var filePath = path.resolve("./datasource", req.query.path); fs.readFile(filePath, "utf8", (err, data) => { processData(data, (err, processed) => { res.json(processed); }); }); }); 

我清除error handling。 这个问题是,可以调用URL /api?path=../../../etc/passwd ,这将从服务器本身泄漏信息。 我想这个API不处理./datasource文件夹以外的文件。 我想我可以使用一些自定义的实现path.resolve ,它不会逃避父,但它看起来像我的path模块中没有这样的function。 我想到的一些例子是:

 saferesolve("./datasource", "a/b") === "./datasource/a/b" saferesolve("./datasource", "a/b/../c") === "./datasource/a/c" saferesolve("./datasource", "../..") === "./datasource" saferesolve("./datasource", "../../a/b") === "./datasource/a/b" saferesolve("./datasource", "../../a/b/..") === "./datasource/a" 

任何想法如何做到这一点,而不需要重新创build整个path模块?

这似乎通过你的testing:

 function saferesolve(base, target) { var targetPath = '.' + path.posix.normalize('/' + target) return path.posix.resolve(base, targetPath) }