public
Last active

Upgrade a regular `net.Stream` connection to a secure `tls` connection.

  • Download Gist
starttls.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
// Target API:
//
// var s = require('net').createStream(25, 'smtp.example.com');
// s.on('connect', function() {
// require('starttls')(s, options, function() {
// if (!s.authorized) {
// s.destroy();
// return;
// }
//
// s.end("hello world\n");
// });
// });
//
//
module.exports = function starttls(socket, options, cb) {
 
var sslcontext = require('crypto').createCredentials(options);
 
var pair = require('tls').createSecurePair(sslcontext, false);
 
var cleartext = pipe(pair, socket);
 
pair.on('secure', function() {
var verifyError = pair._ssl.verifyError();
 
if (verifyError) {
cleartext.authorized = false;
cleartext.authorizationError = verifyError;
} else {
cleartext.authorized = true;
}
 
if (cb) cb();
});
 
cleartext._controlReleased = true;
return cleartext;
};
 
 
function pipe(pair, socket) {
pair.encrypted.pipe(socket);
socket.pipe(pair.encrypted);
 
pair.fd = socket.fd;
var cleartext = pair.cleartext;
cleartext.socket = socket;
cleartext.encrypted = pair.encrypted;
cleartext.authorized = false;
 
function onerror(e) {
if (cleartext._controlReleased) {
cleartext.emit('error', e);
}
}
 
function onclose() {
socket.removeListener('error', onerror);
socket.removeListener('close', onclose);
}
 
socket.on('error', onerror);
socket.on('close', onclose);
 
return cleartext;
}

tls.js, where this code originates from, underwent some changes after this was posted. pair._ssl is now pair.ssl.

Unfortunately, tls.js is not documented.

@astro Thanks for the update :-)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.