summaryrefslogtreecommitdiffstats
path: root/connect.js
blob: bca3d20317d6a6290460282bf5ca9330fc499124 (plain)
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
'use strict'

const {connect: connectTls} = require('tls')
const {
	DEFAULT_PORT,
	ALPN_ID,
	MIN_TLS_VERSION,
} = require('./lib/util')

const connectToGeminiServer = (opt, cb) => {
	if (typeof opt === 'function') {
		cb = opt
		opt = {}
	}
	const {
		hostname,
		port,
		cert, key, passphrase,
		tlsOpt,
	} = {
		hostname: '127.0.0.1',
		port: DEFAULT_PORT,
		cert: null, key: null, passphrase: null,
		tlsOpt: {},
		// todo: TOFU via isTrustedCertificate()
		...opt,
	}

	const socket = connectTls({
		ALPNProtocols: [ALPN_ID],
		minVersion: MIN_TLS_VERSION,
		hostname, port,
		cert, key, passphrase,
		...tlsOpt,
	})

	let cbCalled = false
	socket.once('error', (err) => {
		if (cbCalled) return;
		cbCalled = true
		cb(err)
	})
	socket.once('secureConnect', () => {
		if (cbCalled) return;
		cbCalled = true
		cb(null, socket)
	})

	return socket
}

module.exports = connectToGeminiServer