HOW-TO

How to send the SNI server name for IMAP over TLS in Node.js

Published · Updated

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

  1. sniName picks the name to send: the explicit servername, or else host.
  2. It throws early if that name is an IP address, because SNI only carries DNS names.
  3. buildTlsOptions always sets servername. It adds socket for an upgrade, or host and port for a new connection.
  4. connectImapTls calls tls.connect and resolves once the handshake and the certificate check pass.
  5. 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.
  • servername must 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 servername there. Most libraries pass it through to tls.connect.
  • Port 993 uses TLS from the first byte. Port 143 starts in plain text and needs STARTTLS, which is the socket case above.

Seen on: Own project ·

Related service: Python automation and data collection