Blog / Article
Node.js SSL Server Example
Posted 25 Sep, 2010 by Kord Campbell
in Code and Log Management
A buddy of mine pinged me today because he saw my name on Silas Sewell’s howto post on doing HTTP/SSL with Node.js. I emailed Silas a few days ago to have him update his cert handling to include toString() on the end of each filesystem read, and he was kind enough to give a shout out to me.
The nut of the problem was that Node.js puts a carriage return or some such cruft on the end when it reads from the filesystem. It was causing me fits with cert validation and I only found the answer by digging through the Node.js IRC channel logs. Logs, heh.
I had already expounded a bit on Silas’s solution because our signing agent uses a key chain. My buddy was also asking me for an example of how to do SSL and listen on multiple ports, so I pastebin’d him up a solution. Figure it was worth posting here too!
// includes
var sys = require("sys"),
http = require("http"),
net = require("net"),
url = require("url"),
fs = require("fs"),
crypto = require("crypto");
// crypto
var privatekey = fs.readFileSync('/some/path/foobar.com.key');
privatekey = privatekey.toString();
var certificate = fs.readFileSync('/some/path/foobar.com.crt');
certificate = certificate.toString();
var chain = fs.readFileSync('/some/path/intermediate.crt');
chain = chain.toString();
var credentials = crypto.createCredentials({key: privatekey, cert: certificate, ca: chain});
// server object
var handler = function (request, response) {
var content = "";
var remoteip = request.connection.remoteAddress;
request.addListener("data", function(chunk) {
content += chunk;
if (content.length > 32768) {
response.writeHead(413, {"Content-Type": "application/json"});
response.write("{ 'response': 'error: oversized event' }\n");
response.end();
return;
}
});
request.addListener("end", function() {
response.writeHead(201, {"Content-Type": "application/json"});
response.write("{ 'response': 'success', 'length': "+content.length+" }\n");
response.end();
return;
});
};
// ssl'd http
var sslserver = http.createServer();
sslserver.setSecure(credentials);
sslserver.addListener("request", handler);
sslserver.listen(443);
// regular ol' http
var httpserver = http.createServer();
httpserver.addListener("request", handler);
httpserver.listen(80);
I should note that your keys and certs need to be readable by the Node.js server’s user. Obviously.
chrelad 2 Dec, 2010 12:05pm
Nice, thanks for the example :)