Error: read ECONNRESET when connecting from mqtt node.js - node.js

I am facing an issue when trying to connect to mqtt broker, I have installed the mosquitto and given two ports(1883,8883) as a listener in the mosquitto.conf file. When I try to run the code for connect from node.js for mqtts on port 8883 I get below error
Error: read ECONNRESET
and on mosquitto
socket error on client <unknown> disconnecting
When I try to publish a message using MQTT.fx it successfully publish the mesasge on port 8883
Below is my code
const config = {
endpoint: 'mqtts://192.168.0.0',
topic: 'test/topic/local',
payload: {message: 'HelloWorld'},
}
mqtt.connect(config.endpoint, {
clientId: 'some id',
})
Are there some configurations needs to be done?

mqtts is the tls version of mqtt , to use it you will need to either supply certs to match the backend or configure it not to validate if they are self signed.
to disable validation add this to your connect
rejectUnauthorized: false
be aware that doing this will prevent your client from being able to validate the backend safely, you should never do this in production.

Related

Unable to connect to remote redis host [nodeJS]

const redis = require('redis');
require('dotenv').config();
console.log(process.env.redisHost, ':', process.env.redisPort);
const redisClient = redis.createClient({
host: process.env.redisHost,
port: process.env.redisPort,
password: process.env.redisKey
});
redisClient.connect();
redisClient.on('error', err => console.log('Redis error: ', err.message));
redisClient.on('connect', () => console.log('Connected to redis server'));
module.exports = redisClient;
I tried this sample from redis docs but still I'm getting an error stating:
Redis error: connect ECONNREFUSED 127.0.0.1:6379
I logged the environment host and port variables to the console and I got the remote host ipv4 address, but still the client is trying to connect to localhost instead of remote host (I purposely uninstalled redis from my local device to check if the client is working as it is supposed to). I also confirmed that the remote redis host is working perfectly.
I also tried different methods like :
https://cloud.google.com/community/tutorials/nodejs-redis-on-appengine
redis.createClient(port, host, {auth_pass: password});
But still, I got the same error.
I am able to connect to the redis host via commandline:
redis-cli.exe -h XX.XX.XX.XXX -a Password
XX.XX.XX.XXX:6379> set name dhruv
OK
XX.XX.XX.XXX:6379> get name
"dhruv"
XX.XX.XX.XXX:6379> exit
I'm trying to use redis on nodejs for the first time, so don't have a proper idea but I think I am doing everything right.
Any solution/workaround will be helpful :D
It worked with this code:
const url = `redis://${process.env.redisHost}:${process.env.redisPort}`;
const redisClient = redis.createClient({
url,
password: process.env.redisKey
});
redisClient.connect();
can you check if in the destination the port is reachable. it maybe the firewall block your access

Heroku Redis Add-On Error error:1408F10B:SSL routines:ssl3_get_record:wrong version number

After upgrading my Heroku Redis add-on to v6.2.3 from v4, Heroku papertrail logs display this error: Error accepting a client connection: error:1408F10B:SSL routines:ssl3_get_record:wrong version number I am connecting to Redis using NodeJs and the bull npm package (https://www.npmjs.com/package/bull). I found similar questions related to this error, along with Heroku documentation, and based on that I have set my bull redis options to the following:
redis: {
host: redisURL.hostname,
port: Number(redisURL.port),
password: redisURL.password,
tls: {
rejectUnauthorized: false,
},
},
Note the tls parameter. I have set it to Heroku's recommendations here: https://devcenter.heroku.com/articles/heroku-redis#connecting-in-node-js After getting stuck for a while, I attempted to simply comment out any client code that connects to Redis, delete the add-on, and re-provision the add-on. I expected to see no redis logs in papertrail when I did this, but I still see the same error, even when no code that connects to redis is being run... This leads me to believe maybe it's a setting on the actual Redis add-on instance, rather than an issue with my code, but I am at a loss.
Updates:
I logged into the redis:cli and did some investigation. client list reveals 2 client connections. 1 is the instance of the redis:cli I am running in my terminal, and another is the a client with a flag that means "the client is a replica node connection to this instance" (see https://redis.io/commands/client-list). What is interesting is the error that is being logged in papertrail shows the file descriptor for the client connection that is having the SSL error fd=12, while the 2 clients shown in client list have the file descriptors fd=10 and fd=11. So there must be another client connection with fd=12 that isn't appearing in client list command causing the error shown above.
Jasper Kennis' answer is correct. Adding tls: {rejectUnauthorized: false} fixed this issue for me. Unfortunately, Heroku only gives you a full REDIS_URL connection string, so you need to parse the password/host/port yourself (you can't specify both a URL and tls settings). Here's my BullModule.forRoot() config object if it helps:
redis: {
password: process.env.REDIS_URL.split('#')[0].split(':')[2],
host: process.env.REDIS_URL.split('#')[1].split(':')[0],
port: parseInt(process.env.REDIS_URL.split('#')[1].split(':')[1]),
tls: { rejectUnauthorized: false },
}
Using:
#nestjs/bull: 0.6.0,
Heroku redis: 6.2.3
Ran into the same problem. In addition to rejectUnauthorized: false, adding requestCert: true, solved it for me. In addition, some clients need agent: false, (but the version of Bull I'm using doesn't recognise that argument)
redis: {
host: redisURL.hostname,
port: Number(redisURL.port),
password: redisURL.password,
tls: {
rejectUnauthorized: false,
requestCert: true,
// agent: false, (not all clients accept this)
},
},

Kubernetes + consul: kv.get: connect ETIMEDOUT

I have deployed consul using hashicorp-consul-helm-chart
now, I want to connect to the consul from my Node.js project.
Therefore, I created an object like this : (using 'consul' npm package)
import consul from 'consul';
var consulObj = new consul({
host: 'xxx.xxx.xxx.xxx',
promisify: true
});
var watch = consulObj.watch({
method: consulObj.kv.get,
options: { key: 'config' },
backoffFactor: 1000,
});
I have got the host value from kubectl get endpoints
used the value opposite to consul-server
still, i get consul: kv.get: connect ETIMEDOUT when I run the code.
what could be the reason?
Thanks in advance!
You should be accessing the Consul client which is running on the node where your app is located instead of directly accessing the server.
Details can be found in the accepted answer for Hashicorp Consul, Agent/Client access.

Cannot connect to AWS SES SMTP endpoint

I'm building an application that will use AWS SES to send email via SMTP. I've properly configured a domain and confirmed I can send email from that domain using the AWS SDK. I've created SMTP credentials and ensured the IAM user is properly configured with the right permissions. I've written a test script that uses Nodemailer to send the email.
The test script runs successfully using my personal development machine on my home network, but the script will NOT work when using the development laptop issued by my corporate client on my home network. The corporate laptop runs many security tools, including ZScaler. I also know that, due to the ZScaler service, NPM must be set to use a self-signed certificate (the command is npm config set cafile {CA_FILEPATH}).
I don't know why the script won't work on the corporate laptop, and I would appreciate some help in figuring what to try next.
Here's the script:
'use strict';
const nodemailer = require('nodemailer');
const runtest = async function() {
console.debug('Creating the SMTP transport');
const transporter = nodemailer.createTransport({
host: 'email-smtp.us-west-2.amazonaws.com',
port: 465,
secure: true,
auth: {
user: 'myusername',
pass: 'mypassword',
},
});
console.debug('Building mail options');
const mailOptions = {
from: 'me#example.com',
to: 'you#example.com',
subject: 'subject',
text: 'body',
html: '<h1>Hi</h1',
};
console.debug('Sending mail...');
const info = await transporter.sendMail(mailOptions);
console.debug(`Sent mail. Info: ${JSON.stringify(info, null, 2)}`);
console.info('Message sent!');
};
runtest().catch(console.error);
Here's the result when run from the corporate laptop:
Creating the SMTP transport
Building mail options
Sending mail...
Error: read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:200:27) {
errno: 'ECONNRESET',
code: 'ESOCKET',
syscall: 'read',
command: 'CONN'
}
Things I've tried:
Playing with TLS settings such as rejectUnauthorized: false and specifying the TLS version
Connecting to or disconnecting from the corporate VPN
I found a reference on this Github issue that suggested testing the connection with openssl. I ran this command openssl s_client -connect email-smtp.us-west-2.amazonaws.com:465, and this was the result (seems ok):
CONNECTED(0000021C)
write:errno=10054
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 336 bytes
Verification: OK
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
Early data was not sent
Verify return code: 0 (ok)
---
In my case, it was the node version that caused this error. I have upgraded my node version to v12.x to fix the issue.

Can redis client work without a redis datastore installed?

In my node web server, I am using a the npm module redis.
when I run my code...
const client = redis.createClient();
client.on("error", function (err) {
console.log("Error " + err);
});
client.hmset(["key", "test keys 1", "test val 1", "test keys 2", "test val 2"], function (err, res) {});
I get an error:
Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
I don't have a redis database installed. Do I need that?
If not, anything I have missed in my code?
Yes, you need to install Redis and ensure the server is running. This is a link to the official page for downloading the redis.
In your application code, you need to ensure you are connecting to Redis server with the right port and host address. By default, Redis server should be running on 127.0.0.1:6379 and that is where redis.createClient would try to connect to by default. If your Redis server is running on another port or host, then you need to specify those details when connecting e.g:
redis.createClient({
host: '<the host where redis is running>',
port: '<the port where redis is running>'
});
You can check here for more info on the options you can provide when connecting to Redis server with redis.createClient.

Resources