-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
tls.ts
54 lines (43 loc) · 1.32 KB
/
tls.ts
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
import tls from 'tls'
import net from 'net'
import _debug from 'debug'
import { StreamBuilder } from '../shared'
const debug = _debug('mqttjs:tls')
const buildStream: StreamBuilder = (client, opts) => {
opts.port = opts.port || 8883
opts.host = opts.hostname || opts.host || 'localhost'
if (net.isIP(opts.host) === 0) {
opts.servername = opts.host
}
opts.rejectUnauthorized = opts.rejectUnauthorized !== false
delete opts.path
debug(
'port %d host %s rejectUnauthorized %b',
opts.port,
opts.host,
opts.rejectUnauthorized,
)
const connection = tls.connect(opts)
connection.on('secureConnect', () => {
if (opts.rejectUnauthorized && !connection.authorized) {
connection.emit('error', new Error('TLS not authorized'))
} else {
connection.removeListener('error', handleTLSerrors)
}
})
function handleTLSerrors(err: Error) {
// How can I get verify this error is a tls error?
if (opts.rejectUnauthorized) {
client.emit('error', err)
}
// close this connection to match the behaviour of net
// otherwise all we get is an error from the connection
// and close event doesn't fire. This is a work around
// to enable the reconnect code to work the same as with
// net.createConnection
connection.end()
}
connection.on('error', handleTLSerrors)
return connection
}
export default buildStream