process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0 not working - node.js

I'm using the node sendmail package which is giving me this error:
Error on connectMx for: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1515:34)
at TLSSocket.emit (events.js:400:28)
at TLSSocket._finishInit (_tls_wrap.js:937:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
So I put this in my code in like 5 places
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
Node says this warning when I run it:
Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
Yet I still get the error message. It's coming from this code:
const {createConnection} = require('net');
createConnection(smtpPort, data[i].exchange); // problem code
sock.on('error', function (err) {
logger.error('Error on connectMx for: ', data[i], err);
tryConnect(++i)
});
Is this a bug in NodeJS, or am I messing something up? Thanks for the help.

Related

node-fetch even though server is online it keeps saying errconrefused

Connecting to the server through browser is possible and i get http code 200, I have directly copied the url from the browser to the node fetch:
await fetch(`http://localhost:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e`)
The other server on the 9000 port is written in c# and has code like this:
HttpListener httpServer;
public void SomeFunction() {
//Some boilerplate for http server definitely not stolen amogus
httpServer = new HttpListener();
httpServer.Prefixes.Add("http://localhost:9000/");
httpServer.Start();
Task demo = Server();
demo.GetAwaiter().GetResult();
}
public async Task server() {
while(true) {
HttpListenerContext ctx = await httpServer.GetContextAsync();
HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
if(req.HttpMethod == "GET") {
if(req.Url.AbsolutePath.ToString() == "/renderAvatar.3d") {
var parameters = HttpUtility.ParseQueryString(req.Url.Query);
if(parameters.Count > 3) {
var pant = parameters[0].ToString();
var face = parameters[1].ToString();
var shirt = parameters[2].ToString();
var name = parameters[3].ToString();
// can't share more code due this is propertiary code
any access from the browser works but why node fetch doesn't work, i have very bad solution to this issue using chrome to open up avatar renderer then close the chrome programatically but this uses way too much memory and quite unncesary.
(This is on linux btw, port 9000 shouldn't be protected by firewall and this is a local server)
thrown error:
FetchError: request to http://127.0.0.1:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e failed, reason: connect ECONNREFUSED 127.0.0.1:9000
at ClientRequest.<anonymous> (file:///home/
(confidental)/backend/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:527:28)
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
Turns out changing localhost to 127.0.0.1 on the c# app solves the issue, on linux localhost is automatically converted to 127.0.0.1 but c# app doesn't do that for some odd reason.
httpServer.Prefixes.Add("http://localhost:9000/");
to
httpServer.Prefixes.Add("http://127.0.0.1:9000/");

Node: Can't bind to IPv6 localAddress while using https.request()

I can bind to localAddress just fine when using HTTP, but as soon as I switch to HTTPS I get an error: bind EINVAL. Please consider this code:
var http = require('http');
var https = require('https');
var options = { host:'icanhazip.com',path:'/',localAddress:'2604:a880:1:20::27:a00f',family:6 };
callback = function(response) {
var data = '';
response.on('data',function(chunk) { data+= chunk; });
response.on('error',function(error) { console.log("error: "+error.message); });
response.on('end',function() {
console.log(data);
});
}
http.request(options,callback).end(); // Works. IP:2604:a880:1:20::27:a00f
https.request(options,callback).end(); // Fails. IP:2604:a880:1:20::27:a00f
https.request({host:'icanhazip.com',path:'/',family:6},callback).end(); // Works. IP:2604:a880:1:20::27:a00f
Here's the error while running node v5.0.0:
Error: bind EINVAL 2604:a880:1:20::27:a00f
at Object.exports._errnoException (util.js:860:11)
at exports._exceptionWithHostPort (util.js:883:20)
at connect (net.js:809:16)
at net.js:984:7
at GetAddrInfoReqWrap.asyncCallback [as callback] (dns.js:63:16)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:82:10)
The only difference between the working and the failing code is setting localAddress and ironically, the last example binds to the correct IP address, but won't let you do it using localAddress.
The problem here is I have to make a request from a completely separate IPv6 address under my use case, and it works fine with HTTP but I need this to work for HTTPS requests. Currently I can only make this work while using cURL. Could you please provide some insight as to why this is happening or how I could make this work without additional libraries?
I had same issue as you. Figured it out. Update your node to the latest stable. They fixed it. Check it with node --version I'm on 6.6.0 and it works great.
The version I got from doing an apt-get was way too old.

intern 2 configuration for BrowserStack behind a proxy

I'm unsure what the configuration should be running intern 2 tests against BrowserStack when running behind a proxy/firewall and currently seeing errors/timeouts.
My Current configuration is:
proxyPort : 9000,
proxyUrl : 'http://localhost:9000',
tunnel : 'BrowserStackLocal',
tunnelOptions : {
username : 'myusername',
accessKey : 'myaccesskey',
hostname : '<myproxyip>',
proxy : 'http://<myproxyip>:<myproxyport>'
}
I don't think I need hostname however if I remove that I immediately see the error getaddrinfo ENOTFOUND.
If use the above configuration it seems to get further, waits for a while then see:
Listening on 0.0.0.0:9000
Starting tunnel...
BrowserStackLocal v3.3
Connecting to BrowserStack using WebSocket protocol...
Connected.
Ready
Error: [POST http://(redacted)#<myproxyip>:4444/wd/hub/session] connect ETIMEDOUT
Error: connect ETIMEDOUT
at errnoException <net.js:904:11>
at Object.afterConnect [as oncomplete] <net.js:895:19>
FATAL ERROR
Error: [POST http://(redacted)#<myproxyip>:4444/wd/hub/session] connect ETIMEDOUT
Error: connect ETIMEDOUT
at errnoException <net.js:904:11>
The [POST http://(redacted)#<myproxyip>:4444/wd/hub/session] url doesn't seem right. Obviously I have this misconfigured & would appreciate any advice. I do struggle to understand intern's documentation when running behind a proxy.
It looks like you are behind some kind of proxy.
When you are behind proxy server, in order to use Intern with BrowserStack, you need to do two things:
Get Local Testing connection to work with your proxy, which you are doing, and you can see success message.
You have to make sure the node process that runs the Intern test works with your proxy. To enable proxy in a node application, the easiest option is to use global-tunnel npm package. There is a step-by-step guide available here.
Would love to answer any queries you might have! Do drop in a mail at support#browserstack.com
Umang,
BrowserStack Support.
I'm not sure but I think there is a bug in browserStack.js. Some proxy support is missing there I think. When I use configuration browserstack_conf.js as shown below tests run okay but there is an error message when Browserstack tries to publish the test results back to www.browserstack.com
[09:43:06] E/launcher - connect ETIMEDOUT 54.152.200.70:443
[09:43:06] E/launcher - Error: connect ETIMEDOUT 54.152.200.70:443
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
[09:43:06] E/launcher - Process exited with error code 199
I can fix this error with following steps:
npm install -g http-proxy-agent
Edit browserStack.js (located for example in C:\Users\myuser\AppData\Romaing\npm\node_modules\protractor\built\driverProviders\ add a require for this and initialize a agent and add to request.
For example add require top of browserStack.js
var HttpProxyAgent = require('http-proxy-agent');
And change the section with options to
let options = {
hostname: 'www.browserstack.com',
port: 443,
path: '/automate/sessions/' + session.getId() + '.json',
method: 'GET',
headers: headers//,
agent: new HttpProxyAgent('http://myproxy:3128')
};
I start Protractor with configuration below
// browserstack.conf.js
var browserstack = require('browserstack-local');
exports.config = {
specs: ['spec.js'],
webDriverProxy: 'http://myproxy:3128',
browserstackUser: 'myuser',
browserstackKey: '*****',
capabilities: {
project: 'BrowserStack (beyond Proxy)',
browserName: 'Chrome',
browser_version: '50.0',
os: 'OS X',
os_version: 'Yosemite',
'browserstack.local': true,
'browserstack.debug': true
},
// Code to start browserstack local before start of test
beforeLaunch: function(){
console.log("Connecting local");
return new Promise(function(resolve, reject){
exports.bs_local = new browserstack.Local();
exports.bs_local.start({'key': '*****',
'proxyHost': 'myproxy', 'proxyPort': '3128',
'binarypath': 'C:\\Users\\myuser\\Downloads\\BrowserStackLocal-win32\\BrowserStackLocal.exe'},
function(error) {
if (error) return reject(error);
console.log('Connected. Now testing...');
resolve();
});
});
},
// Code to stop browserstack local after end of test
afterLaunch: function(){
return new Promise(function(resolve, reject){
exports.bs_local.stop(resolve);
});
}
};

TLS Error: socket hang up in nodejs

I'am trying to connect on a server using tls in nodejs. Here is my code :
var options = {
rejectUnauthorized: false //self signed certificate
};
co = require("tls").connect(5200, "my_host", options, function(){
co.on("data", function(data) {
//do domething
})
}
This is simplified code. If I catch the error event, I have a ECONNRESET error, if I don't, I've got this trace :
Error: socket hang up
at SecurePair.error (tls.js:1001:23)
at EncryptedStream.CryptoStream._done (tls.js:697:22)
at EncryptedStream.read [as _read] (tls.js:493:12)
at EncryptedStream.Readable.read (_stream_readable.js:320:10)
at CleartextStream.onCryptoStreamFinish (tls.js:301:47)
at CleartextStream.g (events.js:175:14)
at CleartextStream.EventEmitter.emit (events.js:92:17)
at finishMaybe (_stream_writable.js:354:12)
at endWritable (_stream_writable.js:361:3)
at CleartextStream.Writable.end (_stream_writable.js:339:5)
If I connect directly to my server using openssl s_client -connect my_host:5200 it works great. Strange thing, with node version 0.10.*, it works on ubuntu 10.04, but not on my mac neither on ubuntu 12.04. My server is also a nodejs program running ubuntu 10.04. Not sure if all of this is related but any help would be great !
Cheers
Depending on what your client/server are doing, there may be a timing issue here. You want to set your event-handlers outside the callback to ensure they are setup before data is flowing. Try this:
var options = {
rejectUnauthorized: false //self signed certificate
};
co = require("tls").connect(5200, "my_host", options, function(){
//do something
});
co.on("data", function(data) {
//do something
});

Error with ntwitter module for node.js

I'm trying to build a Twitter streaming app using node.js and the ntwitter module, here's my code :
var app = require('express').createServer(),
twitter=require('ntwitter');
app.listen(3000);
var feed = new twitter({
consumer_key: 'MY KEY',
consumer_secret:'MY SECRET KEY',
access_tocken_key:'MY ACCESS TOCKEN KEY',
access_tocken_secret:'MY ACCESS TOCKEN SECRET'
});
feed.stream('statuses/filter',{track: ['love', 'hate']}, function(stream){
stream.on('data',function(tweet){
console.log(tweet.text);
});
});
But here's what I get :
events.js:74
throw TypeError('Uncaught, unspecified "error" event.');
^
TypeError: Uncaught, unspecified "error" event.
at TypeError (<anonymous>)
at EventEmitter.emit (events.js:74:15)
at ClientRequest.<anonymous> (/Users/maximeheckel/Documents/My_Repositories/nodetwitter/node_modules/ntwitter/lib/twitter.js:251:14)
at ClientRequest.EventEmitter.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1628:21)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
at CleartextStream.socketOnData [as ondata] (http.js:1523:20)
at CleartextStream.read [as _read] (tls.js:470:10)
at CleartextStream.Readable.read (_stream_readable.js:294:10)
at EncryptedStream.write [as _write] (tls.js:344:25)
I don't understand why I'm stuck with that as I'm following very carefully a lot of tutorials. Even when I clone the authors project I'm still getting this error.
Hope you can help.
UPDATE : I added
stream.on('error', function(error, code) {
console.log("My error: " + error + ": " + code);
});
To my stream function and I'm getting a HTTP 401 error
Any ideas ?
Everything with your code looks fine except for the spelling of "token" in the parameters passed to the constructor for twitter. You need to change access_tocken_key to access_token_key and access_tocken_secret to access_token_secret. Your error (401) is an authentication issue; that change should hopefully result in ntwitter passing the correct user authentication details to the Twitter API.
I had the same problem and it was because my servers system clock had floated by six minutes. Usually, API's give you about a five minute margin of error.

Resources