Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supporting TLSSocket for Node 12.x or higher #67

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 35 additions & 22 deletions src/starttls.coffee
Original file line number Diff line number Diff line change
@@ -1,22 +1,46 @@

# Supporting 0.11+ and beyond environment
module.exports = (socket, options, cb) ->
sslcontext = require('tls').createSecureContext(options)
pair = require('tls').createSecurePair(sslcontext, false)
cleartext = pipe(pair, socket)
tls = require('tls')
secureContext = tls.createSecureContext(options)

if tls.TLSSocket
secureSocket = new tls.TLSSocket(socket, { isServer: false, secureContext })
else
pair = tls.createSecurePair(sslcontext, false)
secureSocket = pipe(pair, socket)

pair.on 'secure', ->
verifyError = pair.ssl.verifyError()
secureSocket.on 'secure', ->
verifyError = secureSocket.ssl.verifyError()

if verifyError
cleartext.authorized = false
cleartext.authorizationError = verifyError
secureSocket.authorized = false
secureSocket.authorizationError = verifyError
else
cleartext.authorized = true
secureSocket.authorized = true

cb() if cb

secureSocket.authorized = false
secureSocket._controlReleased = true

onError = (e) ->
secureSocket.emit('error', e) if (secureSocket._controlReleased)

onClose = ->
socket.removeListener('error', onError)
socket.removeListener('close', onClose)

socket.on 'error', onError
socket.on 'close', onClose

if tls.TLSSocket

cleartext._controlReleased = true
return cleartext;
secureSocket.on '_tlsError', (e) =>
console.log '_tlsError', e

secureSocket._start();

return secureSocket;


pipe = (pair, socket) =>
Expand All @@ -27,16 +51,5 @@ pipe = (pair, socket) =>
cleartext = pair.cleartext
cleartext.socket = socket
cleartext.encrypted = pair.encrypted
cleartext.authorized = false

onError = (e) ->
cleartext.emit('error', e) if (cleartext._controlReleased)

onClose = ->
socket.removeListener('error', onError)
socket.removeListener('close', onClose)

socket.on 'error', onError
socket.on 'close', onClose

return cleartext