self signed certificate in certificate chain error when calling /ews/exchange.asmx - outlook-web-addins

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);

Related

Error: Error occurred while verifying paramssubVerifierParams need to equal threshold 1 while using the web3auth/node-sdk

i am recieving Error: Error occurred while verifying paramssubVerifierParams need to equal threshold 1
web3auth.ts
import { Web3Auth } from '#web3auth/node-sdk';
import { CHAIN_NAMESPACES, SafeEventEmitterProvider } from '#web3auth/base';
import { WEB3AUTH } from '../config/globals';
import logger from '../config/logger';
export const web3auth = new Web3Auth({
clientId: WEB3AUTH.clientId,
chainConfig: {
chainNamespace: CHAIN_NAMESPACES.EIP155,
chainId: WEB3AUTH.chainId,
rpcTarget: WEB3AUTH.rpcTarget,
displayName: 'Polygon Mainnet',
blockExplorer: 'https://polygonscan.com',
ticker: 'MATIC',
tickerName: 'Matic',
},
web3AuthNetwork: process.env.NODE_ENV === 'production' ? 'mainnet' : 'testnet',
});
export const connect = async (token: string): Promise<void> => {
try {
const provider = (await web3auth.connect({
verifier: WEB3AUTH.verifier, // replace with your verifier name
verifierId: WEB3AUTH.verifierId, // replace with your verifier id, setup while creating the verifier on Web3Auth's Dashboard
idToken: token, // replace with your newly created unused JWT Token.
subVerifierInfoArray: [
{
verifier: 'ga-google',
idToken: token,
},
{
verifier: 'zt-email',
idToken: token,
},
],
})) as SafeEventEmitterProvider;
if (!provider) logger.error('error');
const ethPrivKey = await provider.request({ method: 'eth_private_key' });
logger.info('ETH Private Key', ethPrivKey);
} catch (error) {
throw error;
}
};
controller.ts
web3authHandler = asyncHandler(async (req: Request, res: Response, next: NextFunction) => {
try {
web3auth.init();
const accessToken: string = res.locals.accessToken;
const data = await connect(accessToken);
console.log('data: ', data);
return new SuccessResponse('Successful web3auth', { data }).send(res);
} catch (error) {
throw error;
}
});
What should i do now? I am completely stuck here. Also provide me with more insights of web3auth. What should I use as the verifier and verifierId?

EWS fails with 'read ECONNRESET' on Jenkins

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.

Image uploading to Azure blob storage

I am using Angular 2 for the frontend and Node.js for the backend. I am trying to upload a file to Azure storage blob container but keep getting an error when trying to send the image to api. Any help will be appreciated thanks.
This is the error on the server side:
contentType: files.myfile.type,
TypeError: Cannot read property 'type' of undefined
The error on client side
core.js:1521 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
error
:
ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message
:
"Http failure response for (unknown url): 0 Unknown Error"
name
:
"HttpErrorResponse"
ok
:
false
status
:
0
statusText
:
"Unknown Error"
url
:
null
__proto__
:
HttpResponseBase
upload.component.ts
export class UploadComponent implements OnInit {
selectedFile: File = null;
onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
}
onUpload() {
const fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('http://localhost:3000/upload', fd , {
reportProgress : true,
observe: 'events'
}).subscribe( event => {
console.log(event);
});
}
constructor(private http: HttpClient) {}
ngOnInit() {
}
}
server.js
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var options = {
contentType: files.myfile.type,
metadata: { fileName: files.myfile.name }
};
blobSvc.createBlockBlobFromLocalFile('images', files.myfile.name, files.myfile.path, options, function(error, result, response) {
if(!error){
// file uploaded
res.send('file uploaded!');
}
});
});
});
As i see the object File which you are passing to the server is null, so it throws the above error.
You could check the issue on the network tab on chrome developer tools and see if your file is being selected. Hope it helps.

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

Prevent console error with Mongoose, node and graphql

I'm making an API server with Express, Graphql (Apollo server) and mongoose.
I'm testing the user creation. When the email is duplicated mongoose throws an error (Validation error. Unique = true) and graphql handles very good. But the console (terminal) shows the error too. How can i prevent that issue?
Resolver:
const MODEL_PATH = '../../models';
const User = require(MODEL_PATH + '/User');
const { register } = require('../../controllers/auth/RegisterController');
module.exports = {
RootQuery: {
users() {
return User.find({});
}
},
Mutation: {
registerUser(_, data) {
return register(data);
}
}
};
RegisterController (register function)
exports.register = function(data) {
const { email, password } = data;
const user = new User({
email,
password
});
return new Promise((resolve, reject) => {
user.save().then((user) => {
resolve(user);
}).catch((err) => {
reject(err);
});
});
};
And the error in the console (I DON'T WANT THAT. I HANDLED THE ERROR IN THE CONTROLLER. I WANT THE ERROR ONLY IN THE GRAPHQL RESPONSE)
MongoError: E11000 duplicate key error collection: y.users index: email_1 dup key: { : "test#example.com" }
at Function.MongoError.create (/Volumes/Datos/x/code/y/server/node_modules/mongodb-core/lib/error.js:31:11)
at toError (/Volumes/Datos/x/code/y/server/node_modules/mongodb/lib/utils.js:114:22)
....
Response in Graphiql (That is ok)
{
"data": {
"registerUser": null
},
"errors": [
{
"message": "E11000 duplicate key error collection: y.users index: email_1 dup key: { : \"test#example.com\" }",
"locations": [
{
"line": 9,
"column": 3
}
],
"path": [
"registerUser"
]
}
]
}
Thank you
According to: http://dev.apollodata.com/tools/graphql-server/setup.html
in server
app.use('/graphql', bodyParser.json(), graphqlExpress({ schema: myschema, debug: false }));
debug false did the trick.
Now. I'm check the packages for better error handling
Thanks
check out apollo-errors:
https://github.com/thebigredgeek/apollo-errors
and apollo-resolvers:
https://github.com/thebigredgeek/apollo-resolvers
These packages, together, were made to handle issues like the one you describe

Resources