UNPKG

zcatalyst-cli

Version:

Command Line Tool for CATALYST

262 lines (261 loc) 10.4 kB
'use strict'; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const ansi_colors_1 = require("ansi-colors"); const config_store_js_1 = __importDefault(require("../util_modules/config-store.js")); const error_js_1 = __importDefault(require("./error.js")); const index_js_1 = require("../util_modules/constants/index.js"); const auth_js_1 = __importDefault(require("./constants/auth.js")); const js_js_1 = require("../util_modules/js.js"); const index_1 = require("../util_modules/logger/index"); const api_js_1 = __importDefault(require("../internal/api.js")); const crypt_1 = __importDefault(require("./crypt")); const util_1 = require("util"); const dc_js_1 = require("../util_modules/dc.js"); const option_js_1 = require("../util_modules/option.js"); const path_1 = require("path"); class Credential { constructor(tokenObj) { if (tokenObj.token === undefined || js_js_1.JS.isEmpty(tokenObj.token) || tokenObj.token.slice(1, 2) !== '_') { const tokenOption = (0, option_js_1.getGlobalOptionValue)('token'); if (tokenOption) { throw new error_js_1.default('Invalid token passed for authentication.', { exit: 1, errorId: 'CRED-1', arg: [tokenOption, (0, ansi_colors_1.bold)('--token')] }); } throw new error_js_1.default('Invalid token for authentication', { exit: 0, errorId: 'CRED-2', arg: [(0, ansi_colors_1.bold)('catalyst login --force')] }); } this.cToken = tokenObj.token; this.cTime = tokenObj.created_time; this.salt = this.cToken.slice(0, 1); this.rToken = this.cToken.slice(2); this.client = this._getClientForSalt(this.salt); this.maxExpiry = 15 * 60; } _getClientForSalt(salt) { switch (salt) { case 'w': return auth_js_1.default.web; case 'm': return auth_js_1.default.mobile; default: return null; } } _getTokenObjFromStore(pth = 'credential') { const encryptedToken = config_store_js_1.default.get((0, dc_js_1.getActiveDC)() + '.' + pth, null); if (encryptedToken === null) { return null; } const tokenObj = Credential.crypt.decrypt(encryptedToken); const confCredential = new Credential(tokenObj); if (this.rToken === confCredential.rToken) { return tokenObj; } return null; } _setTokenObjToStore(pth) { const encryptObj = Credential.crypt.encrypt(Credential.credentialObject); config_store_js_1.default.set((0, dc_js_1.getActiveDC)() + '.' + pth, encryptObj); } _getAccessTokenFromCache() { if (js_js_1.JS.isEmpty(Credential.credentialObject)) { let tokenObj = this._getTokenObjFromStore(); tokenObj = tokenObj === null && Credential.isTempCred ? this._getTokenObjFromStore('__temp.credential') : tokenObj; if (tokenObj === null) { return null; } Credential.credentialObject = tokenObj; } if (Credential.credentialObject.access_token !== undefined && Credential.credentialObject.refresh_token === this.rToken && typeof Credential.credentialObject.expires_at === 'number' && Credential.credentialObject.expires_at > Date.now() + this.maxExpiry) { return Credential.credentialObject.access_token; } return null; } _rebuildTokenCache(res) { Credential.credentialObject = js_js_1.JS.assign({ created_time: this.cTime || Date.now(), expires_at: Date.now() + parseInt(res.body.expires_in + '', 10) * 1000, refresh_token: this.rToken }, res.body); Credential.credentialObject.token = this.salt + '_' + Credential.credentialObject.refresh_token; if (Credential.isTempCred) { this._setTokenObjToStore('__temp.credential'); } else { this._setTokenObjToStore('credential'); } } _destroyTokenObjFromStore(pth = 'credential') { const activeDC = (0, dc_js_1.getActiveDC)(); config_store_js_1.default.delete(activeDC + '.' + pth); if (pth === 'credential') { config_store_js_1.default.delete(`${activeDC}.user`); config_store_js_1.default.delete(`${activeDC}.scopes`); } } refreshAccessToken() { var _a, _b; return __awaiter(this, void 0, void 0, function* () { (0, index_1.debug)('> refreshing access token <'); const res = yield new api_js_1.default({ authNeeded: false }) .post('/oauth/v2/token', { origin: index_js_1.ORIGIN.auth, form: { refresh_token: this.rToken, client_id: (_a = this.client) === null || _a === void 0 ? void 0 : _a.id, client_secret: (_b = this.client) === null || _b === void 0 ? void 0 : _b.secret, grant_type: 'refresh_token' }, log: { skipReqBody: true } }) .catch((err) => { throw new error_js_1.default('Error when refreshing the access token', { exit: 2, original: err }); }); if (!js_js_1.JS.isString(res.body.access_token)) { throw new error_js_1.default('unable to refresh access token.', { original: (0, util_1.inspect)(res.body), exit: 0, errorId: 'CRED-2', arg: [(0, ansi_colors_1.bold)('catalyst login --force')] }); } this._rebuildTokenCache(res); return Credential.credentialObject; }); } persistMinimal(pth) { Credential.credentialObject = { created_time: Date.now(), expires_at: Date.now() + this.maxExpiry * 1000, refresh_token: this.rToken, token: this.salt + '_' + this.rToken }; this._setTokenObjToStore(pth); Credential.credentialObject = {}; } reset(pth) { this._destroyTokenObjFromStore(pth); Credential.isTempCred = false; Credential.credentialObject = {}; Credential.globalSelf = null; Credential.oneTimeToken = null; } get accessToken() { return this._getAccessTokenFromCache(); } get refreshToken() { return this.rToken; } get cliToken() { return this.cToken; } get createdTime() { return this.cTime; } static initToken(token, temp = false) { if (token.slice(1, 2) !== '_' && !Credential.crypt.isEncrypted(token)) { Credential.oneTimeToken = token; return Credential.oneTimeToken; } return this.init(token, temp); } static decrypt(token) { let tokenObj; if (Credential.crypt.isEncrypted(token)) { const decryptToken = Credential.crypt.decrypt(token); if (typeof decryptToken === 'string') { tokenObj = { token: decryptToken }; } else { tokenObj = decryptToken; } } else { tokenObj = { token }; } return tokenObj; } static init(token, temp = false) { let tokenObj; if (typeof token === 'string') { tokenObj = Credential.decrypt(token); } else { tokenObj = token; } Credential.globalSelf = new Credential(tokenObj); Credential.isTempCred = temp; return Credential.globalSelf; } static getAccessToken(forceRefresh = false) { return __awaiter(this, void 0, void 0, function* () { if (Credential.globalSelf === null) { if (Credential.oneTimeToken === null) { throw new error_js_1.default('Authentication required', { exit: 0, errorId: 'CRED-3', docPath: (0, path_1.join)(__dirname, './docs/credential.toml'), arg: [(0, ansi_colors_1.bold)('catalyst login')] }); } return Credential.oneTimeToken; } const accessToken = Credential.globalSelf.accessToken; if (accessToken === null || forceRefresh) { try { const tokenObj = yield Credential.globalSelf.refreshAccessToken(); return tokenObj.access_token; } catch (e) { if (Credential.oneTimeToken === null) { throw e; } (0, index_1.debug)('Unable to get access token: ', e); return Credential.oneTimeToken; } } return accessToken; }); } } Credential.crypt = new crypt_1.default('ZC_TRAM'); Credential.isTempCred = false; Credential.globalSelf = null; Credential.oneTimeToken = null; exports.default = Credential;