UNPKG

homebridge-fenix-tft-wifi

Version:

Homebridge plugin which adds a Fenix TFT WiFi thermostat as HomeKit device.

142 lines 6.48 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (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; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const jwt_check_expiry_1 = __importStar(require("jwt-check-expiry")); const axios_1 = __importDefault(require("axios")); const fs_extra_1 = __importDefault(require("fs-extra")); class TokenManager { constructor(token, refreshToken, logger, hbApi) { this.token = token; this.refreshToken = refreshToken; this.logger = logger; this.hbApi = hbApi; this.ttl = 60 * 60; // one hour this.axiosClient = axios_1.default.create(); } async loadInitialTokens() { await this.loadTokensFromCustomConfig(); this.logger.debug('Check tokens from custom config'); this.refreshTokens(); try { this.parsedJwt = (0, jwt_check_expiry_1.decode)(this.token); } catch (error) { this.logger.error(`JWT Token is not valid! ${error}`); } setInterval(() => { if (this.isJwtTokenNearToExpireExpired()) { this.refreshTokens(); } }, 15 * 60000); } isJwtTokenNearToExpireExpired() { var _a, _b, _c; const currentDate = new Date(); currentDate.setTime(currentDate.getTime() + (this.ttl * 1000)); const currentTime = currentDate.getTime() / 1000; return currentTime > ((_c = (_b = (_a = this.parsedJwt) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.exp) !== null && _c !== void 0 ? _c : 0); } isJwtTokenExpired(token) { return (0, jwt_check_expiry_1.default)(token); } get sub() { var _a, _b, _c; return (_c = (_b = (_a = this.parsedJwt) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.sub) !== null && _c !== void 0 ? _c : ''; } refreshTokens() { var _a, _b; if (!this.isJwtTokenNearToExpireExpired()) { this.logger.debug('Token is not expired.'); return; } if (!((_b = (_a = this.parsedJwt) === null || _a === void 0 ? void 0 : _a.payload) === null || _b === void 0 ? void 0 : _b.client_id)) { this.logger.error('The token does not contain a client_id. ' + this.newTokenHint); return; } const searchParams = new URLSearchParams(); searchParams.append('grant_type', 'refresh_token'); searchParams.append('client_id', this.parsedJwt.payload.client_id); searchParams.append('refresh_token', this.refreshToken); this.axiosClient.post('https://vs2-fe-identity-prod.azurewebsites.net/connect/token', searchParams, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Authorization: 'Basic ' + this.token, }, }).then((response) => { this.logger.info('Tokens are refreshed'); fs_extra_1.default.writeJsonSync(this.customConfigPath, { accessToken: response.data.access_token, refreshToken: response.data.refresh_token }); this.loadTokensFromCustomConfig() .then(() => this.logger.debug('Tokens are refreshed and loaded')) .catch(() => this.logger.error('Tokens are cannot be loaded')); }).catch(() => this.logger.error('Token is not possible to refresh')); } get accessToken() { return this.token; } get customConfigPath() { return this.hbApi.user.storagePath() + '/.fenixTftWifi.config.json'; } async loadTokensFromCustomConfig() { if (!await this.isCustomConfigExists()) { this.logger.debug('Creating custom config'); if (this.isJwtTokenExpired(this.token)) { throw new Error('JWT token is invalid. ' + this.newTokenHint); } this.logger.debug(this.token); await fs_extra_1.default.writeJsonSync(this.customConfigPath, { accessToken: this.token, refreshToken: this.refreshToken }); } this.logger.debug('Loading tokens from custom config'); const config = await fs_extra_1.default.readJson(this.customConfigPath); if (this.isJwtTokenExpired(config.accessToken) && !this.isJwtTokenExpired(this.token)) { this.logger.info('Removing custom config, because contain expired token'); await fs_extra_1.default.remove(this.customConfigPath); return; } this.token = config.accessToken; this.refreshToken = config.refreshToken; if (this.isJwtTokenExpired(this.token)) { throw new Error('JWT token is invalid. ' + this.newTokenHint); } try { this.parsedJwt = (0, jwt_check_expiry_1.decode)(this.token); } catch (error) { await fs_extra_1.default.remove(this.customConfigPath); throw new Error('JWT token is invalid. ' + this.newTokenHint); } } isCustomConfigExists() { return fs_extra_1.default.pathExists(this.customConfigPath); } get newTokenHint() { return 'Please get a new token according to the documentation on ' + 'https://github.com/tomas-kulhanek/homebridge-fenix-tft-wifi#fenix-tokens'; } } exports.default = TokenManager; //# sourceMappingURL=TokenManager.js.map