summaryrefslogtreecommitdiffstats
path: root/lib/utils/path.js
diff options
context:
space:
mode:
authorSamy Pessé <samypesse@gmail.com>2015-09-15 12:22:54 +0200
committerSamy Pessé <samypesse@gmail.com>2015-09-15 12:22:54 +0200
commit2a52326a454a23444bd8f0395a9ab8a1f5f68831 (patch)
treecf5f447e84e3b4ac2d74d7092d8c522bd6e67b79 /lib/utils/path.js
parent87e4ee1eeb9918cbf151407c66b3377014612d5d (diff)
downloadgitbook-2a52326a454a23444bd8f0395a9ab8a1f5f68831.zip
gitbook-2a52326a454a23444bd8f0395a9ab8a1f5f68831.tar.gz
gitbook-2a52326a454a23444bd8f0395a9ab8a1f5f68831.tar.bz2
Improve conrefs to handle all absolute file paths correctly
Add test for it
Diffstat (limited to 'lib/utils/path.js')
-rw-r--r--lib/utils/path.js39
1 files changed, 39 insertions, 0 deletions
diff --git a/lib/utils/path.js b/lib/utils/path.js
new file mode 100644
index 0000000..d5b98f7
--- /dev/null
+++ b/lib/utils/path.js
@@ -0,0 +1,39 @@
+var _ = require("lodash");
+var path = require('path');
+
+// Return true if file path is inside a folder
+function isInRoot(root, filename) {
+ filename = path.normalize(filename);
+ return (filename.substr(0, root.length) === root);
+}
+
+// Resolve paths in a specific folder
+// Throw error if file is outside this folder
+function resolveInRoot(root) {
+ var input = _.chain(arguments)
+ .toArray()
+ .slice(1)
+ .reduce(function(current, p, i) {
+ // Handle path relative to book root ('/README.md')
+ if (p[0] == '/' || p[0] == '\\') return p.slice(1);
+
+ return current? path.join(current, p) : path.normalize(p);
+ }, '')
+ .value();
+
+ var result = path.resolve(root, input);
+
+ if (!isInRoot(root, result)) {
+ err = new Error("EACCESS: '" + result + "' not in '" + root + "'");
+ err.code = "EACCESS";
+ throw err;
+ }
+
+ return result
+};
+
+
+module.exports = {
+ isInRoot: isInRoot,
+ resolveInRoot: resolveInRoot
+};