certificate issue in nodejs https request - node.js

I have the following error while making an https get request
{ Error: write EPROTO 101057795:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:openssl\ssl\s23_clnt.c:802:
at _errnoException (util.js:992:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:864:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
I am trying to make a request to corporate internal resource where proxy is not needed.
const request = require('request')
var token= myToken
request({
method: 'post',
url: 'https://myURL',
data: {
myData
},
headers: { 'Authorization': 'Bearer myToken' },
agentOptions: {
rejectUnauthorized: false,
},
}, function (error, response, body) {
if(error){
console.log('Error: ', error)
} else {
console.log(body)
}
})
I also have strict-ssl=false in my .npmrc.
What I have notices is that I can make the same call curl with no issues.
curl -k1 -XPOST -H "Authorization: Bearer %TOKEN%" "https://%URL% -d #data,json -H "content-type: application/json"
-k1 option in curl seems to fix the issue with the certificate.
What am I doing wrong in JavaScript?

It turned out to be a bug in node version 8. I finally found a solution here - https://github.com/nodejs/node/issues/16196
One needs to add the following into her code:
require("tls").DEFAULT_ECDH_CURVE = "auto"

request({
method: 'post',
url: 'https://myURL',
data: {
myData
},
headers: { 'Authorization': 'Bearer myToken' },
rejectUnauthorized: false,
}, function (error, response, body) {
if(error){
console.log('Error: ', error)
} else {
console.log(body)
}
});
If you don't want the TLS check all over the node project
set process.env.NODE_TLS_REJECT_UNAUTHORIZED=0;

Related

Problems with getting Apple Pay payment session

A year ago we implemented ApplePay on the web in our project and everything worked just fine. But now it's unstable and payment can be successful on the third try sometimes. We are facing an ECONNRESET error while requesting POST https://apple-pay-gateway.apple.com/paymentservices/startSession and an error message “Payment not completed” on the client side
Error: read ECONNRESET at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -104,
code: 'ECONNRESET',
config: {
url: 'https://apple-pay-gateway.apple.com/paymentservices/startSession',
method: 'post',
data: '{"merchantIdentifier":"merchant.com.xxxxxxxx","displayName":"xxxxxxxxxx","initiative":"web","initiativeContext":"xxxxxxxx.xxx","domainName":"xxxxxxxx.xxx"}',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'User-Agent': 'axios/0.19.2',
'Content-Length': 191
}
},
...
response: undefined,
isAxiosError: true,
Client side code:
applePaySession.onvalidatemerchant = async (event) => {
try {
const data = {
url: event.validationURL,
method: 'post',
body: {
merchantIdentifier,
displayName,
initiative: "web",
initiativeContext: window.location.hostname
},
json: true,
}
const merchantSession = await this.$axios.$post('/apple_pay_session', data);
if (merchantSession && merchantSession.merchantSessionIdentifier) {
applePaySession.completeMerchantValidation(merchantSession)
} else {
applePaySession.abort();
}
} catch (error) {
logReqError(error)
applePaySession.abort();
}
};
Server side:
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
cert: fs.readFileSync(`uploads/apple_pay/${id}/certificate.pem`),
key: fs.readFileSync(`uploads/apple_pay/${id}/private.key`)
});
const sessionRes = await axios({
url: request.body.url,
method: request.body.method.toLowerCase(),
data: request.body.body,
headers: {'Content-Type': 'application/json'}, httpsAgent
})
We checked the status of Merchant Domain - it's verified, Apple Pay Payment Processing Certificate and Apple Pay Merchant Identity Certificate are valid. I also checked project code with the official documentation, as well as with other sources.
I hope anyone has had a similar problem. Any code samples or guesses will be helpful anyway

Error while fetching Token with certificate & RSA Key in NodeJS

I am trying to fetch oauth token in NodeJS with key , certificate & client id.
Code for the same:
var form = {
client_id : CLIENT_ID,
grant_type: 'client_credentials',
}
var headers= {
'content-type': 'application/x-www-form-urlencoded',
}
var option = {
method: 'POST',
url: CERTIFICATE_URL + "/oauth/token",
headers,
form,
httpsAgent:new https.Agent({
cert: CLIENT_CERTIFICATE.replace(/\\n/g, '\n'),
key: CLIENT_CERTIFICATE_KEY.replace(/\\n/g, '\n')
})
};
request(option, function(error, response, body) {
var token = null;
console.log(error);
console.log(JSON.parse(body).access_token)
if(!error && response.statusCode == 200) {
token = JSON.parse(body).access_token;
} else {
console.log(error)
error = error | new Error(body);
}
cb(error, token);
});
But getting the following error :
Error: write EPROTO 140062523283264:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL alert number 40
2021-10-13T23:46:56.23+0530 [APP/PROC/WEB/0] OUT at WriteWrap.afterWrite [as oncomplete] (net.js:789:14) errno: 'EPROTO', code: 'EPROTO', syscall: 'write'
The certificate & key is generated & fetched from the cloud environment itself.
This is a x509 MTLS based authentication.
Was able to do it with axios library, request library seems to be deprecated.

Axios - Getting socket hang up error while running it on docker container

I am trying to get results from third party API by using Axios npm. Using nested request, first request is to get the token and another one is to get results.
Below code is working fine in my local machine but not in Docker container.
var config = {
method: 'post',
url: gsecConfig.tokenUrl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
};
axios(config)
.then(function (response) {
if (response.data.access_token) {
const config = {
headers: { Accept: 'application/json', Authorization: `Bearer ${response.data.access_token}` }
};
axios.get(gsecConfig.gsecUrl + gsecid, config)
.then(function (response) {
let supplierData = response.data;
res.status(200).json({
"data": supplierData
});
}).catch(function (error) {
res.json({
"errors": error.message,
"name": error.name
});
});
}
})
.catch(function (tokenError) {
if (tokenError) {
res.json({
"errors": tokenError.message,
"name": tokenError.name
});
}
});
});
Getting error like below
"message": "socket hang up",
"name": "Error",
"stack": "Error: socket hang up\n at createHangUpError (_http_client.js:323:15)\n at Socket.socketOnEnd (_http_client.js:426:23)\n at Socket.emit (events.js:203:15)\n at endReadableNT (_stream_readable.js:1129:12)\n at process._tickCallback (internal/process/next_tick.js:63:19)",
"code": "ECONNRESET"
Thanks in advance!
If your server is not Kubernetes, you can change the publish mode to host (default is ingress), the problem will be solved. check this
You can change it in docker-stack like below:
ports:
- target: 3001
published: 3001
protocol: tcp
mode: host
But if this is Kubernetes with node clusters, you should use the ingress mode, I'm facing this issue and still stuck here. Hope someone can help.

nodeJS request POST To localhost:3000 ECONNREFUSED

At one point I just want to make a POST request to my rails server running on localhost:3000
If a use like postman on even cUrl I can ping my API
But kow, with my node app I want to do this :
var req_body = {
'my_id': id,
'dataTable': data }
var options = {
method: 'POST',
url: config.get('api_url') + 'end_tracking',
json: true,
body: req_body
}
// config.get('api_url') return http://localhost:3000/
request(options, function (error, response, body) {
console.log(error)
... }
this is what I get :
{ Error: connect ECONNREFUSED 127.0.0.1:3000
at Object.exports._errnoException (util.js:896:11)
at exports._exceptionWithHostPort (util.js:919:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1073:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3000 }
and as I said, if I do this request directly with postman, everything works !
I finally did it !
For a unknown reason, accessing localhost:3000, launched with rails s didn't work at all on my node server
but I worked when I started the rails server with rails s -b 0.0.0.0 !
how i did this , just use the same structure and i hope it works for you
request({
url: url, //URL to hit
method: 'post',
headers: headers,
timeout: 10000,
body: JSON.stringify(body)
}, function (error, result, body) {
if (error) {
console.log(error);
} else if (result.statusCode == 500) {
console.log('not found');
} else {
console.log('success')
}
});
hope it works.

'Error: connect ECONNREFUSED' When calling http.request

I am trying to run the following node code,
function getQuestions() {
var options = {
host: 'mysite.com',
path: '/services/v2/question.json',
headers: {
"Content-Type": "application/json",
"accept": "application/json; charset=UTF-8",
'Authorization': auth
}
};
http.request(options, function(response) {
console.log("Everything worked!");
}).on('error', function(e) {
console.log('problem with request: ' + e.stack);
});
}
But it always errors saying...
problem with request: Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
When I put the same info into Postman it works fine. Is there a way to debug this?
Update
Tried this...
var options = {
host: "google.com"
};
Same result so something must be wrong in my code. Any ideas?
It did end up being a proxy issue this...
var options = {
host: "proxy",
port: 80,
path: 'http://google.com'
};
Notice the proxy in host. I will mark as duplicate of this post

Resources