nikinci nikinci - 6 months ago 253
Javascript Question

Nodejs serve static image with httpdispatcher

I am using httpdispatcher and want to serve static images. I have an /resources folder in app folder. and have below code. I tried http://localhost:3000/resources/abc.jpg to get image but didnt get any response. any idea?

var http = require('http');
var dispatcher = require('httpdispatcher');

var express = require('express');
var app = express();
dispatcher.setStatic('resources');
dispatcher.setStaticDirname('.');

const PORT=3000;

function handleRequest(request, response){
try {
console.log(request.url);
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}


dispatcher.onGet("/page1", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var response={"res":'Page One id: ' + req.params.id};
res.end(JSON.stringify(response));
});


dispatcher.onPost("/post1", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var response={"res":'Got Post Data appId: '+JSON.parse(req.body).appId};
res.end(JSON.stringify(response));
});

dispatcher.onError(function(req, res) {
res.writeHead(404);
res.end("NOT FOUND");
});



var server = http.createServer(handleRequest);


server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});

Answer

To work my comments into an answer, httpdispatcher's current static asset implementation is broken for a few reasons.

  1. Improper path parsing. (. isn't properly handled, and is joined poorly in the code) Offending line: var filename = "." + require('path').join(this.staticDirname, url.pathname);

  2. Doesn't exclude the specified resource url from the pathname it checks. So even if you specify . as the static directory, but specify resources as the URL handler, the static directory structure must include a resources folder, or the URL must include .., which seems like a ripe avenue for directory traversal attacks.

There are probably better packages for your use case that presently work, but it's worth reporting these flaws to the module author. Edit: Looks like there are already issues for the path traversal vulnerability, and the directory resolution.

At present, you could either handle the routing manually through matching in an HTTP Server handler, or you could use a different library. To name a few, Express, Diet with diet-static, etc.

EDIT: It appears that these issues may have been resolved as of 1.1.0 as stated in this issue.