Skip to content

Commit

Permalink
Merge pull request #527 from JK0N/master
Browse files Browse the repository at this point in the history
Fix serve.js module, prevent access to files in parent directories.
  • Loading branch information
amark authored Apr 17, 2019
2 parents 7ae2f3d + 2e41cef commit 8bc815e
Showing 1 changed file with 14 additions and 23 deletions.
37 changes: 14 additions & 23 deletions lib/serve.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,8 @@
var fs = require('fs');
var path = require('path');
var dot = /\.\.+/g;
var slash = /\/\/+/g;
var normalize = require('path').normalize;
var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/

function CDN(dir){
return function(req, res){
req.url = (req.url||'').replace(dot,'').replace(slash,'/');
if(serve(req, res)){ return } // filters GUN requests!
fs.createReadStream(path.join(dir, req.url)).on('error',function(tmp){ // static files!
try{ tmp = fs.readFileSync(path.join(dir, 'index.html')) }catch(e){}
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(tmp+''); // or default to index
}).pipe(res); // stream
}
}
module.exports = function serve(req, res, next){

function serve(req, res, next){
if(typeof req === 'string'){ return CDN(req) }
if(!req || !res){ return false }
next = next || serve;
if(!req.url){ return next() }
Expand All @@ -25,16 +11,21 @@ function serve(req, res, next){
res.end(serve.js = serve.js || require('fs').readFileSync(__dirname + '/../gun.js'));
return true;
}
if(0 <= req.url.indexOf('gun/')){
res.writeHead(200, {'Content-Type': 'text/javascript'});
var path = __dirname + '/../' + req.url.split('/').slice(2).join('/'), file;
if(0 === req.url.indexOf('/gun/')){
var root = normalize(__dirname + '/../'), file;
var path = root + req.url.split('/').slice(2).join('/');

if (UP_PATH_REGEXP.test(path)) {
res.status(403).end();
return true;
}

try{file = require('fs').readFileSync(path)}catch(e){}
if(file){
res.writeHead(200, {'Content-Type': 'text/javascript'});
res.end(file);
return true;
}
}
return next();
}

module.exports = serve;
}

0 comments on commit 8bc815e

Please sign in to comment.