UNPKG

1.17 kBJavaScriptView Raw
1'use strict'
2var tls = require('tls')
3
4function buildBuilder (mqttClient, opts) {
5 var connection
6 opts.port = opts.port || 8883
7 opts.host = opts.hostname || opts.host || 'localhost'
8
9 opts.rejectUnauthorized = opts.rejectUnauthorized !== false
10
11 delete opts.path
12
13 connection = tls.connect(opts)
14 /* eslint no-use-before-define: [2, "nofunc"] */
15 connection.on('secureConnect', function () {
16 if (opts.rejectUnauthorized && !connection.authorized) {
17 connection.emit('error', new Error('TLS not authorized'))
18 } else {
19 connection.removeListener('error', handleTLSerrors)
20 }
21 })
22
23 function handleTLSerrors (err) {
24 // How can I get verify this error is a tls error?
25 if (opts.rejectUnauthorized) {
26 mqttClient.emit('error', err)
27 }
28
29 // close this connection to match the behaviour of net
30 // otherwise all we get is an error from the connection
31 // and close event doesn't fire. This is a work around
32 // to enable the reconnect code to work the same as with
33 // net.createConnection
34 connection.end()
35 }
36
37 connection.on('error', handleTLSerrors)
38 return connection
39}
40
41module.exports = buildBuilder