Search code examples
node.jscertificatenats.io

Node server not being able to connect to NATS server


I'm trying to connect to a NATS server via nodejs and I'm running into issues with the cert.

The NATS server is behind a company VPN. Not sure if that is the issue. I can connect to the server itself when authenticated to the VPN but my code can't.

Here is the minimal code I'm trying when connecting:

const creds = `-----BEGIN NATS USER JWT-----
    eyJ0eXAiOiJqdSDJB....
  ------END NATS USER JWT------

  -----BEGIN USER NKEY SEED-----
    SUAIBDPBAUTW....
  ------END USER NKEY SEED------
`;

async connectToNats(){
 let connection;
 try{
    connection = await connect({
      servers:[`nats://stage-nats1.company.net:4222`],
      debug: true,
      authenticator: credsAuthenticator(new TextEncoder().encode(creds)),
    });
    connection.subscribe('topicImInterestedIn')
}catch(e)
  console.log(e)
}

Error:

Error [ERR_TLS_CERT_ALTNAME_INVALID] hostname/IP does not match certificate's altnames: Host: localhost. is not the cert's altnames: DNS:*.companyName.net, DNS:companyName.net

    reason: "Host: localhost. is not in the cert's altnames: DNS:*.companyName.net, DNS:companyName.net

I'm confused why this is trying to connect to localhost when I specify that the server already.


Solution

  • The answer was that I needed both the creds, aka NATS user jwt and nKey and setup tlsOptions with a cert.pem and cert.key files added to the connection.

    //Should really be read from file
    const creds = `-----BEGIN NATS USER JWT-----
        eyJ0eXAiOiJqdSDJB....
      ------END NATS USER JWT------
    
      -----BEGIN USER NKEY SEED-----
        SUAIBDPBAUTW....
      ------END USER NKEY SEED------
    `;
    
    const tlsOptions = {
      key: fs.readFileSync("key.pem"),
      cert: fs.readFileSync("cert.pem")
    };
    const nc = await connect({
      servers: ["nats://localhost:4222"],
      tls: tlsOptions,
      authenticator: credsAuthenticator(new TextEncoder().encode(creds)),
    });