alan
/
sfs
1
Fork 0

add basic filtering of served paths

This commit is contained in:
Alan Faubert 2021-08-08 10:40:42 -04:00
parent 5ca455d66f
commit e2c28c2792
2 changed files with 12 additions and 4 deletions

View File

@ -11,7 +11,7 @@ Clone. Install npm dependencies. Optionally symlink to `sfs.js` from somewhere i
## Usage
```
sfs.js [host:]<port>
sfs.js [host:]<port> [path]...
```
Starts a server on the given `port` for the current working directory. Binds to localhost only unless `host` is specified.

14
sfs.js
View File

@ -32,8 +32,8 @@ const humanize_size = size => {
return t ? `${size.toFixed(1)} ${prefixes[t]}B` : `${size} B`;
};
if (process.argv.length !== 3) {
console.error('Arguments: [host:]<port>');
if (process.argv.length < 3) {
console.error('Arguments: [host:]<port> [path]...');
process.exit(1);
}
@ -41,6 +41,10 @@ const p = process.argv[2].indexOf(':');
const port = +process.argv[2].slice(p + 1);
const host = p > -1 ? process.argv[2].slice(0, p) : 'localhost';
const normalize_path = path => path.replace(/\\/g, '/').replace(/^(\.?\/)?/, '').replace(/\/$/, '') + '/';
const allowed_paths = process.argv.slice(3).map(normalize_path);
const is_allowed = path => allowed_paths.length === 0 || (path = normalize_path(path)) === '/' || allowed_paths.some(allowed_path => allowed_path.startsWith(path) || path.startsWith(allowed_path));
http
.createServer(async (req, res) => {
const path = '.' + decodeURIComponent(req.url);
@ -52,6 +56,10 @@ http
send_error(res, 403, 'Forbidden');
return;
}
if (!is_allowed(path)) {
send_error(res, 404, 'Not Found');
return;
}
let stats;
try {
stats = await stat(path);
@ -99,7 +107,7 @@ http
res.end();
return;
}
const dir = (await Promise.all((await readdir(path)).map(async file => [
const dir = (await Promise.all((await readdir(path)).filter(name => is_allowed(path + name)).map(async file => [
file,
await stat(path + file),
file.replace(/\d+/g, _ => '1'.repeat(_.length - 1) + '0' + _),