UNPKG

keycloak-typescript

Version:

A user friendly library to use keycloak in nodejs projects

233 lines 10.7 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 () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); 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()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const ITokenManager_1 = require("./Interfaces/ITokenManager"); // Helpers const request_builder_1 = require("../helpers/request-builder"); // External const querystring = __importStar(require("querystring")); class TokenManager extends ITokenManager_1.ITokenManager { constructor(url, observers) { super(); this.requestOfflineAccess = true; this.isRefreshing = false; this.hasWarnedShortTokens = false; this.initializeManager = (keycloakLogin) => __awaiter(this, void 0, void 0, function* () { var _a; this.clientSecret = keycloakLogin.clientSecret; this.clientId = keycloakLogin.clientId; this.username = keycloakLogin.username; this.password = keycloakLogin.password; this.requestOfflineAccess = (_a = keycloakLogin.requestOfflineAccess) !== null && _a !== void 0 ? _a : true; const body = { client_id: this.clientId, username: keycloakLogin.username, password: keycloakLogin.password, grant_type: 'password' }; if (this.clientSecret) { body.client_secret = this.clientSecret; } if (this.requestOfflineAccess) { body.scope = 'offline_access'; } const apiConfig = { url: this.url, method: 'POST', headers: {}, body: querystring.stringify(body) }; yield this.makeRefreshRequest(apiConfig); this.scheduleTokenRefresh(); }); this.makeRefreshRequest = (apiConfig) => __awaiter(this, void 0, void 0, function* () { const { url, method = 'get', headers = {}, body } = apiConfig; const response = yield (0, request_builder_1.requestBuilder)({ url, method, headers, body }); this.accessToken = response === null || response === void 0 ? void 0 : response.data.access_token; this.refreshToken = response === null || response === void 0 ? void 0 : response.data.refresh_token; this.accessTokenExpireTime = response === null || response === void 0 ? void 0 : response.data.expires_in; this.refreshTokenExpireTime = response === null || response === void 0 ? void 0 : response.data.refresh_expires_in; //notify observers about new access token this.notify(); }); this.refreshAccessToken = () => __awaiter(this, void 0, void 0, function* () { // Prevent multiple simultaneous refresh attempts if (this.isRefreshing) { return; } this.isRefreshing = true; try { const body = { client_id: this.clientId, client_secret: this.clientSecret, refresh_token: this.refreshToken, grant_type: 'refresh_token' }; const apiConfig = { url: this.url, method: 'POST', headers: {}, body: querystring.stringify(body) }; yield this.makeRefreshRequest(apiConfig); // Reschedule the refresh based on new expiration times this.scheduleTokenRefresh(); } catch (error) { // If refresh token is expired or invalid, re-authenticate with password grant // eslint-disable-next-line no-console console.error('Token refresh failed, attempting re-authentication:', error); yield this.reauthenticateWithPassword(); } finally { this.isRefreshing = false; } }); /** * Re-authenticate using the password grant type when refresh token expires */ this.reauthenticateWithPassword = () => __awaiter(this, void 0, void 0, function* () { if (!this.username || !this.password) { throw new Error('Cannot re-authenticate: username or password not stored'); } try { const body = { client_id: this.clientId, username: this.username, password: this.password, grant_type: 'password' }; if (this.clientSecret) { body.client_secret = this.clientSecret; } if (this.requestOfflineAccess) { body.scope = 'offline_access'; } const apiConfig = { url: this.url, method: 'POST', headers: {}, body: querystring.stringify(body) }; yield this.makeRefreshRequest(apiConfig); this.isRefreshing = false; this.scheduleTokenRefresh(); } catch (error) { // eslint-disable-next-line no-console console.error('Re-authentication failed:', error); this.isRefreshing = false; throw error; } }); /** * Schedule token refresh based on the expiration times returned by Keycloak */ this.scheduleTokenRefresh = () => { if (this.refreshIntervalId) { clearInterval(this.refreshIntervalId); this.refreshIntervalId = undefined; } if (this.accessTokenExpireTime == undefined) { // eslint-disable-next-line no-console console.warn('Cannot schedule token refresh: accessTokenExpireTime is undefined'); return; } if (!this.hasWarnedShortTokens && this.accessTokenExpireTime < 60) { this.hasWarnedShortTokens = true; // eslint-disable-next-line no-console console.warn('Access token lifespan is very short. This will cause frequent refreshes.', { accessTokenExpireTime: this.accessTokenExpireTime, recommendation: 'Recommended: at least 1 minute for development, 5+ minutes for production' }); } // Use a dynamic margin that's a percentage of token lifetime (min 5s, max 60s) // This prevents issues when tokens have very short lifespans const marginInSeconds = Math.min(Math.max(Math.floor(this.accessTokenExpireTime * 0.2), 5), 60); const minimumIntervalSeconds = 10; const accessTokenInterval = this.accessTokenExpireTime - marginInSeconds; let refreshInterval; if (this.refreshTokenExpireTime == undefined || this.refreshTokenExpireTime === 0) { // refresh_expires_in is 0 or not provided // Using offline_access or SSO session settings refreshInterval = accessTokenInterval; } else { const refreshTokenInterval = this.refreshTokenExpireTime - marginInSeconds; // Use the shorter interval to ensure we always refresh before expiration refreshInterval = Math.min(accessTokenInterval, refreshTokenInterval); } if (refreshInterval > 0) { refreshInterval = Math.max(refreshInterval, minimumIntervalSeconds); this.refreshIntervalId = setInterval(() => { this.refreshAccessToken(); }, refreshInterval * 1000); } else { // Token too short to schedule safely - attempt immediate refresh // This will likely trigger re-authentication setTimeout(() => { if (!this.isRefreshing) { this.refreshAccessToken(); } }, 1000); } }; this.notify = () => { this.observers.forEach((observer) => { observer.update(this, [this.accessToken ? this.accessToken : '']); }); }; this.url = url; //Attaching initial observers if any if (observers) { observers.forEach((observer) => { this.attach(observer); }); } } } exports.default = TokenManager; //# sourceMappingURL=TokenManager.js.map