Code
js
'use strict';
const net = require('node:net');
const tls = require('node:tls');
// SNI must be a DNS name. An IP address is never sent as SNI.
function sniName(host, servername) {
const name = servername || host;
if (!name || net.isIP(name) !== 0) {
throw new Error('Set servername to the DNS name on the certificate');
}
return name;
}
function buildTlsOptions({ host, port = 993, servername, socket }) {
const options = { servername: sniName(host, servername) };
if (socket) {
options.socket = socket; // STARTTLS or proxy: upgrade the existing socket
} else {
options.host = host;
options.port = port;
}
return options;
}
// Certificate checks stay on. Node.js verifies the certificate against servername.
function connectImapTls(target, tlsImpl = tls) {
return new Promise((resolve, reject) => {
const socket = tlsImpl.connect(buildTlsOptions(target), () => resolve(socket));
socket.once('error', reject);
});
}
module.exports = { sniName, buildTlsOptions, connectImapTls };
// Usage:
// const socket = await connectImapTls({ host: 'example.com', port: 993 });
// // After STARTTLS on a plain socket:
// const secure = await connectImapTls({ host: 'example.com', socket: plainSocket });Why it happens
Many mail providers host thousands of names on the same address. The TLS client must say which name it wants, in a field called SNI. If that field is missing, the server cannot choose and returns a placeholder certificate with an "invalid" name. Node.js then rejects it, because the name does not match your host.
Node.js sends SNI by itself only when it knows a host name. It does not know one when you connect by IP address, or when you hand it an already open socket (STARTTLS, or a tunnel through a proxy).
Steps
sniNamepicks the name to send: the explicitservername, or elsehost.- It throws early if that name is an IP address, because SNI only carries DNS names.
buildTlsOptionsalways setsservername. It addssocketfor an upgrade, orhostandportfor a new connection.connectImapTlscallstls.connectand resolves once the handshake and the certificate check pass.- Any handshake or certificate error rejects the promise, so the caller sees it.
Pitfalls
- Do not switch off certificate verification to make the error go away. That hides the real problem and exposes the mailbox password.
servernamemust match a name on the certificate. Use the public host name, not an internal alias or an IP address.- If you use an IMAP library, look for its TLS options object and set
servernamethere. Most libraries pass it through totls.connect. - Port 993 uses TLS from the first byte. Port 143 starts in plain text and needs STARTTLS, which is the
socketcase above.
Seen on: Own project ·
Related service: Python automation and data collection