EWS fails with 'read ECONNRESET' on Jenkins - node.js

Using these libraries to connect to ews and get emails:
"ews-javascript-api": "^0.10.3"
"ews-javascript-api-auth": "^1.2.1"
Locally it works and I can connect to email boxes but when I run it on Jenkins I get this error:
SoapFaultDetails {
message: 'read ECONNRESET',
InnerException: null,
faultCode: null,
faultString: null,
faultActor: null,
responseCode: 127,
errorCode: 0,
exceptionType: null,
lineNumber: 0,
positionWithinLine: 0,
errorDetails: DictionaryWithStringKey {
keys: [],
keysToObjs: {},
objects: {},
keyPicker: [Function (anonymous)]
},
HttpStatusCode: undefined
}
A function which connects and read the email:
function getEws(user, password, host, subject) {
ews.ConfigurationApi.ConfigureXHR(new ewsAuth.ntlmAuthXhrApi(user, password))
const service = new ews.ExchangeService(ews.ExchangeVersion.Exchange2013_SP1)
service.Credentials = new ews.WebCredentials(user, password)
service.Url = new ews.Uri(host)
service
.SubscribeToStreamingNotifications(
[new ews.FolderId(ews.WellKnownFolderName.Inbox)],
ews.EventType.NewMail,
ews.EventType.Created,
ews.EventType.Deleted,
ews.EventType.Modified,
ews.EventType.Moved,
ews.EventType.Copied,
ews.EventType.FreeBusyChanged
)
.then(function (streamingSubscription) {
var connection = new ews.StreamingSubscriptionConnection(service, 1)
connection.AddSubscription(streamingSubscription)
connection.OnNotificationEvent.push(function (obj) {
ews.EwsLogging.Log(obj, true, true)
const searchFilter = new ews.SearchFilter.SearchFilterCollection(ews.LogicalOperator.And, [
new ews.SearchFilter.ContainsSubstring(ews.ItemSchema.Subject, subject)
])
const itemview = new ews.ItemView(1)
const foundItems = service.FindItems(ews.WellKnownFolderName.Inbox, searchFilter, itemview)
const adinationalProps = []
adinationalProps.push(ews.ItemSchema.TextBody)
foundItems.then(function (response) {
for (const item of response.Items) {
item
.Load(new ews.PropertySet(ews.BasePropertySet.FirstClassProperties, adinationalProps))
.then(function () {
fs.writeFileSync('cypress/fixtures/email.txt', item.TextBody.text)
})
.catch(error => {
console.log(' ----- Load error start ----- ')
console.error(error)
console.log(' ----- Load error end ----- ')
})
}
})
})
connection.OnDisconnect.push(function (connection, subscriptionErrorEventArgsInstance) {
ews.EwsLogging.Log(subscriptionErrorEventArgsInstance, true, true)
})
connection.Open()
})
.catch(error => {
console.log(' ----- SubscribeToStreamingNotifications error start ----- ')
console.error(error)
console.log(' ----- SubscribeToStreamingNotifications error end ----- ')
})
}
I would be grateful for any ideas on how to solve this issue on Jenkins.

That was an issue with expired SSL certificates on Travis's side.

Related

Node JS(Express js)- I'm able to log the error with console.log but in postman I cannot read the error

I am doing custom post API, I can able to log and read the error but when I tried to send it through res.send(err) and when I checked it in postman, I only see an empty object in errorMessage in variable out. Can anyone please help me out.
Here is my code
const insertItemDetails = async (body, res) => {
const table = new sql.Table("table_name");
table.create = false;
table.columns.add("jsuordref", sql.VarChar(50), {
nullable: false,
primary: true,
});
table.columns.add("itemno", sql.Int, {
nullable: false,
primary: true,
});
table.columns.add("apispec", sql.VarChar(250), { nullable: false });
table.columns.add("customerspec", sql.VarChar(250), { nullable: false });
table.columns.add("grade", sql.VarChar(50), { nullable: false });
let dDate = Date();
console.log("this is --------------_______>>>" + dDate);
let smalldate = moment(dDate).format("YYYY-MM-DD");
let tmstpDate = moment(dDate).format("YYYY-MM-DD HH:mm:ss:SSSS");
for (let i = 0; i < body.itemDetails.length; i++) {
table.rows.add(
body.itemDetails[i].jsuNumber,
body.itemDetails[i].itemNo,
body.itemDetails[i].apiSpec,
body.itemDetails[i].customerSpec,
body.itemDetails[i].grade
);
}
const request = new sql.Request();
request.bulk(table, (err, rows) => {
if (!err) {
var out = {
code: 200,
status: "OK",
message: "JSUOrder successfully created!!",
jsuOrder: body.jsuNumber,
response: rows,
};
} else {
var out = {
code: 400,
message:
"Something went wrong while uploading Item Details, Please contact IT",
errorMessage: { err },
};
}
console.log(err);
res.send(out);
});
};
You are sending
errorMessage: { err },
you should be sending
errorMessage: err,
for the error object to be displayed.
remove "{ }" around err object

self signed certificate in certificate chain error when calling /ews/exchange.asmx

I have moved my Outlook web addin logic to a nodejs backend like suggested here.
Now, I get this error when I call exch.GetUserAvailability function:
Which is weird because it is not a self signed certificate. It is a certificate that has our company Root CA at the top of its certification path.
What can I do to fix this issue?
Thanks
For reference, here are an extract of my code:
const express = require("express");
const EwsJS = require("ews-javascript-api");
...
router.post("/", async (req, res, next) => {
try {
const { ewsUrl, token, appointmentDates, selectedRoomEmails } = req.body;
if (ewsUrl && token && appointmentDates?.length === 2 && selectedRoomEmails?.length > 0) {
const rooms = await fetchFreeBusy(ewsUrl, token, appointmentDates, selectedRoomEmails);
res.status(200).json(rooms);
} else {
res.status(400).json({ error: "Bad arguments!" });
}
} catch (error) {
next(error);
}
});
const fetchFreeBusy = async (ewsUrl, token, appointmentDates, selectedRoomEmails) => {
const exch = new EwsJS.ExchangeService(EwsJS.ExchangeVersion.Exchange2016);
exch.Credentials = new EwsJS.OAuthCredentials(token);
exch.Url = new EwsJS.Uri(ewsUrl);
...
return await new Promise((resolve, reject) => {
// error happens after this: self signed certificate in certificate chain
exch.GetUserAvailability(selectedRoomEmails, timeWindow, EwsJS.AvailabilityData.FreeBusyAndSuggestions).then(
function (availabilityResponse) {
resolve(availabilityResponse);
},
function (errors) {
reject(errors);
});
});
};
and the detailed error message:
2022-04-06T16:46:26: SoapFaultDetails {
2022-04-06T16:46:26: message: 'self signed certificate in certificate chain',
2022-04-06T16:46:26: InnerException: null,
2022-04-06T16:46:26: faultCode: null,
2022-04-06T16:46:26: faultString: null,
2022-04-06T16:46:26: faultActor: null,
2022-04-06T16:46:26: responseCode: 127,
2022-04-06T16:46:26: errorCode: 0,
2022-04-06T16:46:26: exceptionType: null,
2022-04-06T16:46:26: lineNumber: 0,
2022-04-06T16:46:26: positionWithinLine: 0,
2022-04-06T16:46:26: errorDetails: DictionaryWithStringKey {
2022-04-06T16:46:26: keys: [],
2022-04-06T16:46:26: keysToObjs: {},
2022-04-06T16:46:26: objects: {},
2022-04-06T16:46:26: keyPicker: [Function (anonymous)]
2022-04-06T16:46:26: },
2022-04-06T16:46:26: HttpStatusCode: 0
2022-04-06T16:46:26: }
Fixed by adding this line before instanciating the exchange service:
EwsJS.ConfigurationApi.SetXHROptions({rejectUnauthorized : false});
const exch = new EwsJS.ExchangeService(EwsJS.ExchangeVersion.Exchange2016);

React Native register form with back-end mongodb and node xpress

I have this code below related to register in react native:
handleSubmit = () =>{
event.preventDefault(event);
// console.log(this.state)
let _this = this
axios.post('http://localhost:8000/api/register', this.state.data)
.then( res => {
console.log('res', res);
if(res.data.errors){
let mainErrors = res.data.errors;
let err_msg = {
email: mainErrors.email ? mainErrors.email.msg : '',
password: mainErrors.password ? mainErrors.password.msg : '',
};
_this.setState({
error: err_msg,
success: ''
})
}else{
_this.setState({
data:{
email:'',
password:'',
},
error:{
email:'',
password:'',
},
success:'Thank you for registering'
})
}
}).catch(error => { console.log(error)})
}
My problem is that it gives me an error while running because of this line: event.preventDefault(event);
You can pass in event as an argument:
handleSubmit=(event)=>{
...
}

Push notification returns ECONNRESET in Google Cloud Functions

I am having a function in Firebase Cloud Functions that is retrieves the user's device group id in order to send a push notification, and after sends a push notification. This works well if the function gets called only once, but if I have an array of users I want to send a push notification too, the sendPushNotification function returns error : FAILED err= { RequestError: Error: read ECONNRESET
at new RequestError (/user_code/node_modules/request-promise/node_modules/request-promise-core/lib/errors.js:14:15) for every try to send push
From what i understand ECONNRESET means that the connection gets closed at one end before finishing the operation, can some help/explain me why this is:
here is my code:
function sendFollowNotification(snapshot) {
const notificationMsg = getFollowNotificationMsg() //returns a string
snapshot.forEach(function(singleUser, index) {
const userId = singleUser.key;
const userObject = singleUser.val();
console.log("will get device group")
if (index + 1 == snapshot.numChildren()) {
return getDeviceGroupNotificationKey(userId, "Discover new artists", notificationMsg, "", true);
} else {
getDeviceGroupNotificationKey(userId, "Discover new artists", notificationMsg, "", false);
}
}
function getDeviceGroupNotificationKey(groupId, notificationTitle, notificationBody, notificationSubject, shouldReturn) {
const pathToDeviceGroup = admin.database().ref('deviceGroups').child(groupId);
pathToDeviceGroup.once("value").then( function(snapshot) {
const deviceGroupObj = snapshot.val();
const notification_key = deviceGroupObj.notification_key;
console.log("got notification key")
console.log(notification_key)
if (notification_key !== undefined) {
return sendPushToDeviceGroupOld(notification_key, notificationTitle, notificationBody, "notificationKeyOld2", notificationSubject, shouldReturn);
} else {
return
}
}).catch(reason => {
console.log("user device group not there")
return
})
}
function sendPushToDeviceGroupOld(notification_key, title, body, subject, message, shouldReturn) {
console.log('sending push to ' + notification_key)
const serverKey = '-';
const senderId = '-';
const options = {
method: 'POST',
uri: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=' + serverKey,
'project_id': senderId
},
body: {
to: notification_key,
data: {
subject: message
},
notification: {
title: title,
body: body,
badge: 1,
sound: "default",
},
priority : 'high',
content_available: true
},
json: true
};
return rqstProm(options)
.then((parsedBody) => {
console.log('SUCCESS response=', parsedBody);
return
})
.catch((err) => {
console.log('FAILED', err);
return
});
}

PouchDB syncing not working

I am trying to setup PouchDB to sync between browser (React + Redux stack) and my databases behind a node proxy (which checks authentication using JWT). here is my proxy code:
this.app.all('/database/*', bodyParser.urlencoded({extended: true}), bodyParser.json(), (req, res) => {
// req.pause();
const headers = this.auth.proxyRequestDecorator()({headers: {...req.headers}}, req);
const remoteUrl = req.url.slice(10);
const opts = Object.assign({
method: req.method,
url: `http://${config.get('couchHost')}:${config.get('couchPort')}/${remoteUrl}`,
...headers,
}, req.method !== 'GET' ? {body: JSON.stringify(req.body)} : {});
mainStory.info('http', `${req.method} ${req.url} -> http://${config.get('couchHost')}:${config.get('couchPort')}/${remoteUrl}`, {
attach: opts,
attachLevel: 'trace'
});
const remoteReq = request(opts).pipe(res);
});
Here is the code I use to sync the database in the browser:
function syncDB (dbs: string[], max: number): thunk.ThunkAction<void, Defs.CompactdState, void> {
return (dispatch, getState) => {
const dbName = dbs[0];
const db = new PouchDB(dbName);
const remote = getDatabase(dbName);
db.sync(remote).on('complete', (info) => {
dispatch({
type: UPDATE_SYNC,
progress: (max - dbs.length + 1) / max
});
db.sync(remote, {live: true}).on('change', (info) => {
console.log(info);
}).on('error', (err) => {
console.log(dbName, err);
}).on('paused', function (info) {
console.log(dbName+' pause', info);
});
if (dbs.length > 1) {
return (syncDB(dbs.slice(1), max) as any)(dispatch, getState);
} else {
setTimeout(() =>
dispatch({
type: END_SYNC
}), 250);
}
});
}
}
function sync (): thunk.ThunkAction<void, Defs.CompactdState, void> {
return (dispatch, getState) => {
if (getState().app.syncing) {
return;
}
const dbs = [ 'artists', 'albums', 'tracks', 'files', 'trackers'];
(syncDB(dbs, dbs.length) as any)(dispatch, getState);
}
}
But when in the browser I create a new tracker document, it doesn't get synceed and if I clear site data, and reload the page the new document doesn't exists (nor in the couchdb ui).
Here is the log :
trackers pause undefined
trackers pause undefined
artists CustomPouchError {code: "ETIMEDOUT", status: 0, result: {…}}
albums CustomPouchError {code: "ETIMEDOUT", status: 0, result: {…}}
tracks CustomPouchError {code: "ETIMEDOUT", status: 0, result: {…}}
files CustomPouchError {code: "ETIMEDOUT", status: 0, result: {…}}code: "ETIMEDOUT"result: {ok: false, start_time: Sun Sep 17 2017 19:58:29 GMT+0200 (Paris, Madrid (heure d’été)), docs_read: 0, docs_written: 0, doc_write_failures: 0, …}status: 0__proto__: Error
trackers CustomPouchError {code: "ETIMEDOUT", status: 0, result: {…}}
It also blocks the page from reloading when f5 isnpressed until connection times out

Resources