/src/handler.js |
@@ -11,17 +11,18 @@ |
const auth = require("http-auth"); |
|
// Checks whether userPath is a child of rootPath. |
function isRooted(userPath, rootPath, separator) { |
function isRooted(userPath, rootPath, separator, callback) { |
process.nextTick(() => { |
userPath = userPath.split(separator).filter(Boolean); |
rootPath = rootPath.split(separator).filter(Boolean); |
return userPath.length >= rootPath.length && |
rootPath.every((e, i) => e === userPath[i]); |
callback(userPath.length >= rootPath.length && |
rootPath.every((e, i) => e === userPath[i])); |
}); |
} |
|
// Serves files. |
function files(config, request, response, resource, callback) { |
// Check if the file is accessible. |
process.nextTick(() => { |
fs.access(resource, fs.constants.R_OK, (error) => { |
if (error) { |
response.statusCode = 403; |
@@ -45,13 +46,10 @@ |
}); |
|
}); |
}); |
} |
|
// Serves a directory index. |
function index(config, request, response, resource, callback) { |
process.nextTick(() => { |
const root = path.resolve(resource, config.site.index); |
// Serves a directory listing or the document index in case it exists. |
function index(config, request, response, resource, root, callback) { |
fs.stat(root, (error, stats) => { |
if (error) { |
fs.readdir(resource, (error, paths) => { |
@@ -80,6 +78,7 @@ |
return; |
} |
|
// Serve the document index. |
fs.access(resource, fs.constants.R_OK, (error) => { |
if (error) { |
process.nextTick(() => { |
@@ -110,14 +109,11 @@ |
}); |
|
}); |
|
}); |
}); |
} |
|
// Determines whether the requested resource is a directory or a file. |
function serve(config, request, response, resource, callback) { |
process.nextTick(() => { |
fs.stat(resource, (error, stats) => { |
// Document does not exist. |
if (error) { |
@@ -128,7 +124,7 @@ |
|
switch (stats.isDirectory()) { |
case true: // Directory is requested so provide directory indexes. |
index(config, request, response, resource, callback) |
index(config, request, response, resource, path.resolve(resource, config.site.index), callback) |
break; |
default: // Browser requesting file. |
files(config, request, response, resource, callback); |
@@ -135,7 +131,6 @@ |
break; |
} |
}); |
}); |
} |
|
module.exports = { |
@@ -171,7 +166,8 @@ |
path.join(root, trimmedPath) : |
path.resolve(root, trimmedPath); |
|
if (!isRooted(resource, root, path.sep)) { |
isRooted(resource, root, path.sep, (rooted) => { |
if (!rooted) { |
process.nextTick(() => { |
callback('Attempted path traversal: ' + |
requestAddress.address + ':' + |
@@ -186,6 +182,7 @@ |
return; |
} |
|
// Check if the requested path requires authentication. |
switch (config.auth.locations.some( |
(authPath) => authPath.toUpperCase() === requestedURL.pathname.toUpperCase())) { |
case true: |
@@ -217,5 +214,6 @@ |
break; |
} |
}); |
}); |
} |
}; |