liveperson-functions-client
Version:
JavaScript client for LivePerson Functions.
78 lines • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppJwtAuthentication = void 0;
const simple_oauth2_1 = require("simple-oauth2");
const jsonwebtoken_1 = require("jsonwebtoken");
const VError = require("verror");
class AppJwtAuthentication {
constructor({ accountId, clientId, clientSecret, getCsdsEntry, expirationBufferMinutes = 30, }) {
this.accountId = accountId;
this.clientId = clientId;
this.clientSecret = clientSecret;
this.getCsdsEntry = getCsdsEntry;
this.expirationBufferMinutes = expirationBufferMinutes;
this.currentJwt = {
exp: 0,
};
this.currentAccessToken = '';
}
async getHeader() {
try {
return await this.getAccessToken();
}
catch (error) {
throw new VError({
cause: error,
name: 'FaaSAppJWTAuthenticationError',
}, 'Error while creating authentication bearer via AppJWT (Client Credentials)');
}
}
async getAccessToken() {
if (this.isCurrentJwtExpiring()) {
const options = await this.getOptions();
const client = new simple_oauth2_1.ClientCredentials(options);
const access_token = await client.getToken({
scope: [],
});
const jwt = (0, jsonwebtoken_1.decode)(access_token.token.access_token);
if (jwt !== null) {
this.currentAccessToken = access_token.token.access_token;
this.currentJwt = jwt;
}
else if (this.isJwtExpired(this.currentJwt)) {
throw new VError({
name: 'FaaSAppJWTRetrievalError',
info: {
access_token,
},
}, 'Current AppJWT is expired and new Jwt could not be retrieved.');
}
}
return `Bearer ${this.currentAccessToken}`;
}
isCurrentJwtExpiring() {
return (Date.now() / 1000 >
this.currentJwt.exp - this.expirationBufferMinutes * 60);
}
isJwtExpired(jwt) {
return Date.now() / 1000 > jwt.exp;
}
async getOptions() {
const sentinelDomain = await this.getCsdsEntry(this.accountId, 'sentinel');
return {
client: {
id: this.clientId,
secret: this.clientSecret,
},
auth: {
tokenHost: `https://${sentinelDomain}`,
tokenPath: `/sentinel/api/account/${this.accountId}/app/token?v=2.0`,
},
options: {
authorizationMethod: 'body',
},
};
}
}
exports.AppJwtAuthentication = AppJwtAuthentication;
//# sourceMappingURL=appJwtAuthentication.js.map