wallee
Version:
TypeScript/JavaScript client for wallee
180 lines (179 loc) • 7.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebhookEncryptionService = void 0;
const Promise = require("bluebird");
const axios = require("axios");
const HMACAuthentication_1 = require("../auth/HMACAuthentication");
const ObjectSerializer_1 = require("../serializers/ObjectSerializer");
const EncryptionUtil_1 = require("../util/EncryptionUtil");
const ClientError_1 = require("../models/ClientError");
const ServerError_1 = require("../models/ServerError");
class WebhookEncryptionService {
constructor(configuration) {
this._basePath = 'https://app-wallee.com:443/api';
this._defaultHeaders = {};
this._useQuerystring = false;
this._timeout = 25;
this._defaultAuthentication = new HMACAuthentication_1.HMACAuthentication(configuration).apply;
this._defaultHeaders = configuration.default_headers;
this.setTimeout(configuration.timeout);
}
/**
* Set timeout in seconds. Default timeout: 25 seconds
* @param {number} timeout
*/
set timeout(timeout) {
this.setTimeout(timeout);
}
setTimeout(timeout) {
if (timeout !== undefined) {
if (!Number.isInteger(timeout)) {
throw new Error('Timeout value has to be integer');
}
if (timeout) {
this._timeout = timeout;
}
else {
throw new Error('Timeout value has to be greater than 0');
}
}
}
set basePath(basePath) {
this._basePath = basePath;
}
get basePath() {
return this._basePath;
}
setDefaultAuthentication(auth) {
this._defaultAuthentication = auth;
}
getVersion() {
if (typeof (process) !== 'undefined' && process && process.version) {
return 'node ' + process.version;
}
else {
return 'unknown';
}
}
/**
* Reads the entity with the given 'id' and returns it.
* @summary Read
* @param id The ID of the key version.
* @param {*} [options] Override http request options.
*/
read(id, options = {}) {
const url = '/webhook-encryption/read';
let queryParams = {};
let headers = Object.assign({}, this._defaultHeaders);
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling read.');
}
if (id !== undefined) {
queryParams['id'] = ObjectSerializer_1.ObjectSerializer.serialize(id, "string");
}
headers['Content-Type'] = '*/*';
Object.assign(headers, options.headers);
let defaultHeaders = {
"x-meta-sdk-version": "4.7.0",
"x-meta-sdk-language": "typescript",
"x-meta-sdk-provider": "wallee",
"x-meta-sdk-language-version": this.getVersion(),
};
Object.assign(headers, defaultHeaders);
let requestConfig = {
url,
method: 'GET',
baseURL: this._basePath,
headers,
params: queryParams,
timeout: this._timeout * 1000,
responseType: 'json',
};
const axiosInstance = axios.default.create();
axiosInstance.interceptors.request.use(this._defaultAuthentication);
return new Promise((resolve, reject) => {
axiosInstance.request(requestConfig)
.then(success => {
let body;
body = ObjectSerializer_1.ObjectSerializer.deserialize(success.data, "WebhookEncryptionPublicKey");
return resolve({ response: success.request.res, body: body });
}, failure => {
var _a, _b, _c, _d, _e;
let errorObject;
if ((_a = failure.response) === null || _a === void 0 ? void 0 : _a.status) {
if (failure.response.status >= 400 && failure.response.status <= 499) {
errorObject = new ClientError_1.ClientError();
}
else if (failure.response.status >= 500 && failure.response.status <= 599) {
errorObject = new ServerError_1.ServerError();
}
else {
errorObject = new Object();
}
}
else {
errorObject = new Object();
}
return reject({
errorType: errorObject.constructor.name,
date: (new Date()).toDateString(),
statusCode: ((_b = failure.response) === null || _b === void 0 ? void 0 : _b.status) && isNaN(failure.response.status) ? String(failure.response.status) : "Unknown",
statusMessage: ((_c = failure.response) === null || _c === void 0 ? void 0 : _c.statusText) != null ? failure.response.statusText : "Unknown",
body: (_d = failure.response) === null || _d === void 0 ? void 0 : _d.data,
response: (_e = failure.response) === null || _e === void 0 ? void 0 : _e.request.res
});
})
.catch(error => {
return reject(error);
});
});
}
;
/**
* Verify webhook content signature.
*
* @param signatureHeader Signature header 'X-Signature' value from the Http request
* @param contentToVerify Raw webhook content in String format
* @returns Promise<boolean> indicating if the content is valid
*/
isContentValid(signatureHeader, contentToVerify) {
return new Promise((resolve, reject) => {
const regex = /^.*,\s*keyId=([a-zA-Z0-9\-]+),\s*signature=(.+)$/g;
const match = regex.exec(signatureHeader);
if (match) {
const publicKeyId = match[1];
const contentSignature = match[2];
let publicKeyPromise;
if (WebhookEncryptionService._cache.has(publicKeyId)) {
publicKeyPromise = Promise.resolve(WebhookEncryptionService._cache.get(publicKeyId));
}
else {
publicKeyPromise = this.read(publicKeyId)
.then((response) => {
const publicKey = response.body;
if (publicKey.publicKey) {
WebhookEncryptionService._cache.set(publicKeyId, publicKey);
return publicKey;
}
else {
throw new Error(`WebhookEncryptionPublicKey with id: ${publicKeyId} not found`);
}
});
}
publicKeyPromise
.then(publicKey => {
const isValid = EncryptionUtil_1.EncryptionUtil.isContentValid(contentToVerify, contentSignature, publicKey.publicKey);
resolve(isValid);
}).catch(error => {
reject(error);
});
}
else {
reject(new Error("Invalid webhook signature header. Expected header format: 'algorithm=<algorithm>, keyId=<keyId>, signature=<signature>'"));
}
});
}
}
exports.WebhookEncryptionService = WebhookEncryptionService;
WebhookEncryptionService._cache = new Map();