UNPKG

@vzeta/zeebe-node-test

Version:

The Node.js client library for the Zeebe Workflow Automation Engine.

171 lines 6.07 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OAuthProvider = void 0; const fs = __importStar(require("fs")); const got = __importStar(require("got")); const os = __importStar(require("os")); const homedir = os.homedir(); const pkg = require("../../package.json"); const BACKOFF_TOKEN_ENDPOINT_FAILURE = 1000; class OAuthProvider { constructor({ /** OAuth Endpoint URL */ url, /** OAuth Audience */ audience, cacheDir, clientId, clientSecret, /** Cache token in memory and on filesystem? */ cacheOnDisk, }) { this.tokenCache = {}; this.failed = false; this.cachedTokenFile = (clientId) => `${this.cacheDir}/oauth-token-${clientId}.json`; this.url = url; this.audience = audience; this.clientId = clientId; this.clientSecret = clientSecret; this.useFileCache = cacheOnDisk; this.cacheDir = cacheDir || OAuthProvider.getTokenCacheDirFromEnv(); if (this.useFileCache) { try { if (!fs.existsSync(this.cacheDir)) { fs.mkdirSync(this.cacheDir); } fs.accessSync(this.cacheDir, fs.constants.W_OK); } catch (e) { throw new Error(`FATAL: Cannot write to OAuth cache dir ${cacheDir}\n` + 'If you are running on AWS Lambda, set the HOME environment variable of your lambda function to /tmp'); } } } async getToken() { if (this.tokenCache[this.clientId]) { return this.tokenCache[this.clientId].access_token; } if (this.useFileCache) { const cachedToken = this.fromFileCache(this.clientId); if (cachedToken) { return cachedToken.access_token; } } return new Promise((resolve, reject) => { setTimeout(() => { this.debouncedTokenRequest() .then(res => { this.failed = false; resolve(res); }) .catch(e => { this.failed = true; reject(e); }); }, this.failed ? BACKOFF_TOKEN_ENDPOINT_FAILURE : 1); }); } debouncedTokenRequest() { const body = JSON.stringify({ audience: this.audience, client_id: this.clientId, client_secret: this.clientSecret, grant_type: 'client_credentials', }); return got .post(this.url, { body, headers: { 'content-type': 'application/json', 'user-agent': `zeebe-client-nodejs/${pkg.version}`, }, }) .then(res => { return this.safeJSONParse(res.body).then(token => { if (this.useFileCache) { this.toFileCache(token); } this.tokenCache[this.clientId] = token; this.startExpiryTimer(token); return token.access_token; }); }); } safeJSONParse(thing) { return new Promise((resolve, reject) => { try { resolve(JSON.parse(thing)); } catch (e) { reject(e); } }); } fromFileCache(clientId) { let token; const tokenCachedInFile = fs.existsSync(this.cachedTokenFile(clientId)); if (!tokenCachedInFile) { return null; } try { token = JSON.parse(fs.readFileSync(this.cachedTokenFile(clientId), 'utf8')); if (this.isExpired(token)) { return null; } this.startExpiryTimer(token); return token; } catch (_) { return null; } } toFileCache(token) { const d = new Date(); const file = this.cachedTokenFile(this.clientId); fs.writeFile(file, JSON.stringify({ ...token, expiry: d.setSeconds(d.getSeconds() + token.expires_in), }), e => { if (!e) { return; } // tslint:disable-next-line console.error('Error writing OAuth token to file' + file); // tslint:disable-next-line console.error(e); }); } isExpired(token) { const d = new Date(); return token.expiry <= d.setSeconds(d.getSeconds()); } startExpiryTimer(token) { const d = new Date(); const current = d.setSeconds(d.getSeconds()); const validityPeriod = token.expiry - current * 1000; if (validityPeriod <= 0) { delete this.tokenCache[this.clientId]; return; } setTimeout(() => delete this.tokenCache[this.clientId], validityPeriod); } } exports.OAuthProvider = OAuthProvider; OAuthProvider.defaultTokenCache = `${homedir}/.camunda`; OAuthProvider.getTokenCacheDirFromEnv = () => process.env.ZEEBE_TOKEN_CACHE_DIR || OAuthProvider.defaultTokenCache; //# sourceMappingURL=OAuthProvider.js.map