UNPKG

@asgardeo/node

Version:

Node.js runtime specific implementation of Asgardeo JavaScript SDK.

776 lines (758 loc) 25.5 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); // src/index.ts import fetch, { Headers, Request, Response } from "cross-fetch"; // src/__legacy__/core/authentication.ts import { AsgardeoAuthClient, AsgardeoAuthException } from "@asgardeo/javascript"; // src/__legacy__/stores/memory-cache-store.ts import cache from "memory-cache"; var MemoryCacheStore = class { async setData(key, value) { cache.put(key, value); } async getData(key) { return cache.get(key) ?? "{}"; } async removeData(key) { cache.del(key); } }; // src/__legacy__/utils/session-utils.ts import { validate as uuidValidate, version as uuidVersion, v4 as uuidv4 } from "uuid"; // src/__legacy__/constants/uuid-config.ts var UUID_VERSION = 4; // src/__legacy__/constants/logger-config.ts var LOGGER_CONFIG = { bgGreen: "\x1B[42m", bgRed: "\x1B[41m", bgWhite: "\x1B[47m", bgYellow: "\x1B[43m", fgBlack: "\x1B[30m", fgGreen: "\x1B[32m", fgRed: "\x1B[31m", fgWhite: "\x1B[37m", fgYellow: "\x1B[33m", reset: "\x1B[0m" }; // src/__legacy__/utils/session-utils.ts var SessionUtils = class { // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } static createUUID() { const generated_uuid = uuidv4(); return generated_uuid; } static validateUUID(uuid) { if (uuidValidate(uuid) && uuidVersion(uuid) === UUID_VERSION) { return Promise.resolve(true); } else { return Promise.resolve(false); } } static validateSession(sessionData) { const currentTime = Date.now(); const expiryTimeStamp = sessionData.created_at + parseInt(sessionData.expires_in) * 60 * 1e3; if (currentTime < expiryTimeStamp) { return Promise.resolve(true); } else { Logger.warn("Expired Session"); return Promise.resolve(false); } } }; // src/__legacy__/utils/logger-utils.ts var LogLevel = /* @__PURE__ */ ((LogLevel2) => { LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG"; LogLevel2[LogLevel2["INFO"] = 1] = "INFO"; LogLevel2[LogLevel2["WARN"] = 2] = "WARN"; LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR"; LogLevel2[LogLevel2["OFF"] = 4] = "OFF"; return LogLevel2; })(LogLevel || {}); var Logger = class { // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } static debug(message) { if (LogLevel[this.LOG_LEVEL] <= 0 /* DEBUG */) console.log( LOGGER_CONFIG.bgGreen, LOGGER_CONFIG.fgBlack, "DEBUG", LOGGER_CONFIG.reset, LOGGER_CONFIG.fgGreen, message, LOGGER_CONFIG.reset ); } static info(message) { if (LogLevel[this.LOG_LEVEL] <= 1 /* INFO */) console.log( LOGGER_CONFIG.bgWhite, LOGGER_CONFIG.fgBlack, "INFO", LOGGER_CONFIG.reset, LOGGER_CONFIG.fgWhite, message, LOGGER_CONFIG.reset ); } static warn(message) { if (LogLevel[this.LOG_LEVEL] <= 2 /* WARN */) console.log( LOGGER_CONFIG.bgYellow, LOGGER_CONFIG.fgBlack, "WARNING", LOGGER_CONFIG.reset, LOGGER_CONFIG.fgYellow, message, LOGGER_CONFIG.reset ); } static error(message) { if (LogLevel[this.LOG_LEVEL] <= 3 /* ERROR */) console.log( LOGGER_CONFIG.bgRed, LOGGER_CONFIG.fgBlack, "ERROR", LOGGER_CONFIG.reset, LOGGER_CONFIG.fgRed, message, LOGGER_CONFIG.reset ); } }; __publicField(Logger, "LOG_LEVEL", process.env["LOG_LEVEL"] ?? LogLevel[4 /* OFF */]); // src/__legacy__/utils/crypto-utils.ts import base64url from "base64url"; import sha256 from "fast-sha256"; import * as jose from "jose"; import randombytes from "secure-random-bytes"; var NodeCryptoUtils = class { // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } /** * Get URL encoded string. * * @returns {string} base 64 url encoded value. */ base64URLEncode(value) { return base64url.encode(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); } base64URLDecode(value) { return base64url.decode(value).toString(); } hashSha256(data) { return Buffer.from(sha256(new TextEncoder().encode(data))); } generateRandomBytes(length) { return randombytes(length); } async verifyJwt(idToken, jwk, algorithms, clientId, issuer, subject, clockTolerance) { const key = await jose.importJWK(jwk); return jose.jwtVerify(idToken, key, { algorithms, audience: clientId, clockTolerance, issuer, subject }).then(() => { return Promise.resolve(true); }); } }; // src/__legacy__/core/authentication.ts var AsgardeoNodeCore = class _AsgardeoNodeCore { constructor(config, store) { __publicField(this, "_auth"); __publicField(this, "_cryptoUtils"); __publicField(this, "_store"); __publicField(this, "_storageManager"); if (!store) { this._store = new MemoryCacheStore(); } else { this._store = store; } this._cryptoUtils = new NodeCryptoUtils(); this._auth = new AsgardeoAuthClient(); this._auth.initialize(config, this._store, this._cryptoUtils); this._storageManager = this._auth.getStorageManager(); Logger.debug("Initialized AsgardeoAuthClient successfully"); } async signIn(authURLCallback, userId, authorizationCode, sessionState, state, signInConfig) { if (!userId) { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-SI-NF01", "No user ID was provided.", "Unable to sign in the user as no user ID was provided." ) ); } if (await this.isSignedIn(userId)) { const sessionData = await this._storageManager.getSessionData(userId); return Promise.resolve({ accessToken: sessionData.access_token, createdAt: sessionData.created_at, expiresIn: sessionData.expires_in, idToken: sessionData.id_token, refreshToken: sessionData.refresh_token ?? "", scope: sessionData.scope, tokenType: sessionData.token_type }); } if (!authorizationCode || !state) { if (!authURLCallback || typeof authURLCallback !== "function") { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-SI-NF02", "Invalid AuthURLCallback function.", "The AuthURLCallback is not defined or is not a function." ) ); } const authURL = await this.getAuthURL(userId, signInConfig); authURLCallback(authURL); return Promise.resolve({ accessToken: "", createdAt: 0, expiresIn: "", idToken: "", refreshToken: "", scope: "", session: "", tokenType: "" }); } return this.requestAccessToken(authorizationCode, sessionState ?? "", userId, state); } async getAuthURL(userId, signInConfig) { const authURL = await this._auth.getSignInUrl(signInConfig, userId); if (authURL) { return Promise.resolve(authURL.toString()); } else { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-GAU-NF01", "Getting Authorization URL failed.", "No authorization URL was returned by the Asgardeo Auth JS SDK." ) ); } } async requestAccessToken(authorizationCode, sessionState, userId, state) { return this._auth.requestAccessToken(authorizationCode, sessionState, state, userId); } async getIdToken(userId) { const is_logged_in = await this.isSignedIn(userId); if (!is_logged_in) { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-GIT-NF01", "The user is not logged in.", "No session ID was found for the requested user. User is not logged in." ) ); } const idToken = await this._auth.getIdToken(userId); if (idToken) { return Promise.resolve(idToken); } else { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-GIT-NF02", "Requesting ID Token Failed", "No ID Token was returned by the Asgardeo Auth JS SDK." ) ); } } async refreshAccessToken(userId) { return this._auth.refreshAccessToken(userId); } async isSignedIn(userId) { try { if (!await this._auth.isSignedIn(userId)) { return Promise.resolve(false); } if (await SessionUtils.validateSession(await this._storageManager.getSessionData(userId))) { return Promise.resolve(true); } const refreshed_token = await this.refreshAccessToken(userId); if (refreshed_token) { return Promise.resolve(true); } this._storageManager.removeSessionData(userId); this._storageManager.getTemporaryData(userId); return Promise.resolve(false); } catch (error) { return Promise.reject(error); } } async signOut(userId) { const signOutURL = await this._auth.getSignOutUrl(userId); if (!signOutURL) { return Promise.reject( new AsgardeoAuthException( "NODE-AUTH_CORE-SO-NF01", "Signing out the user failed.", "Could not obtain the sign-out URL from the server." ) ); } return Promise.resolve(signOutURL); } async getUser(userId) { return this._auth.getUser(userId); } async getConfigData() { return this._storageManager.getConfigData(); } async getOpenIDProviderEndpoints() { return this._auth.getOpenIDProviderEndpoints(); } async getDecodedIdToken(userId, idToken) { return this._auth.getDecodedIdToken(userId, idToken); } async getAccessToken(userId) { return this._auth.getAccessToken(userId); } async exchangeToken(config, userId) { return this._auth.exchangeToken(config, userId); } async reInitialize(config) { return this._auth.reInitialize(config); } async revokeAccessToken(userId) { return this._auth.revokeAccessToken(userId); } static didSignOutFail(afterSignOutUrl) { return _AsgardeoNodeCore.didSignOutFail(afterSignOutUrl); } static isSignOutSuccessful(afterSignOutUrl) { return _AsgardeoNodeCore.isSignOutSuccessful(afterSignOutUrl); } getStorageManager() { return this._storageManager; } }; // src/__legacy__/client.ts var AsgardeoNodeClient = class _AsgardeoNodeClient { /** * This is the constructor method that returns an instance of the `AsgardeoNodeClient` class. * * @param {AuthClientConfig<T>} config - The configuration object. * @param {Storage} store - The store object. * * @example * ``` * const _store: Storage = new DataStore(); * const _config = { afterSignInUrl: "http://localhost:3000/sign-in", afterSignOutUrl: "http://localhost:3000/dashboard", clientId: "client ID", serverOrigin: "https://api.asgardeo.io/t/<org_name>" }; * const auth = new AsgardeoNodeClient(_config,_store); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#constructor * @preserve */ constructor() { __publicField(this, "_authCore"); } async initialize(config, store) { this._authCore = new AsgardeoNodeCore(config, store); return Promise.resolve(true); } /** * This method logs in a user. If the authorization code is not available it will resolve with the * authorization URL to authorize the user. * @param {string} authorizationCode - The authorization code obtained from Asgardeo after a user signs in. * @param {String} sessionState - The session state obtained from Asgardeo after a user signs in. * @param {string} userId - (Optional) A unique ID of the user to be authenticated. This is useful in multi-user * scenarios where each user should be uniquely identified. * @param {string} state - The state parameter in the redirect URL. * * @return {Promise<URLResponse | NodeTokenResponse>} - A Promise that resolves with the * [`URLResponse`](#URLResponse) object or a Promise that resolves with * the [`NodeTokenResponse`](#NodeTokenResponse) object. * * @example * ``` * authClient.signIn(req.query.code, req.query.session_state).then(response => { * //URL property will available if the user has not been authenticated already * if (response.hasOwnProperty('url')) { * res.redirect(response.url) * } else { * //Set the cookie * res.cookie('ASGARDEO_SESSION_ID', response.session, { maxAge: 900000, httpOnly: true, SameSite: true }); * res.status(200).send(response) * } *}); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#signIn * * @memberof AsgardeoNodeClient * */ async signIn(authURLCallback, userId, authorizationCode, sessionState, state, signInConfig) { return this._authCore.signIn(authURLCallback, userId, authorizationCode, sessionState, state, signInConfig); } /** * Method to get the configuration data. * * @returns {Promise<AuthClientConfig<Config>>} - A promise that resolves with the configuration data. */ async getConfigData() { return this._authCore.getConfigData(); } /** * This method clears all session data and returns the sign-out URL. * @param {string} userId - The userId of the user. (If you are using ExpressJS, * you may get this from the request cookies) * * @return {Promise<string>} - A Promise that resolves with the sign-out URL. * * @example * ``` * const signOutUrl = await auth.signOut(userId); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#signOut * * @memberof AsgardeoNodeClient * */ async signOut(userId) { return this._authCore.signOut(userId); } /** * This method returns a boolean value indicating if the user is authenticated or not. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return { Promise<boolean>} -A boolean value that indicates of the user is authenticated or not. * * @example * ``` * const isAuth = await authClient.isSignedIn("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isSignedIn * * @memberof AsgardeoNodeClient * */ async isSignedIn(userId) { return this._authCore.isSignedIn(userId); } /** * This method returns the id token. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<string>} -A Promise that resolves with the ID Token. * * @example * ``` * const isAuth = await authClient.getIdToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getIdToken * * @memberof AsgardeoNodeClient * */ async getIdToken(userId) { return this._authCore.getIdToken(userId); } /** * This method returns an object containing basic user information obtained from the id token. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<string>} -A Promise that resolves with the * An object containing basic user information obtained from the id token. * * @example * ``` * const basicInfo = await authClient.getUser("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getUser * * @memberof AsgardeoNodeClient * */ async getUser(userId) { return this._authCore.getUser(userId); } /** * This method returns an object containing the OIDC service endpoints returned by the `.well-known` endpoint. * @return {Promise<OIDCEndpoints>} -A Promise that resolves with * an object containing the OIDC service endpoints returned by the `.well-known` endpoint. * * @example * ``` * const oidcEndpoints = await auth.getOpenIDProviderEndpoints(); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getOpenIDProviderEndpoints * * @memberof AsgardeoNodeClient * */ async getOpenIDProviderEndpoints() { return this._authCore.getOpenIDProviderEndpoints(); } /** * This method returns the decoded ID token payload. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<IdToken>} -A Promise that resolves with * an object containing the decoded ID token payload. * * @example * ``` * const decodedIDTokenPayload = await auth.getDecodedIdToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getDecodedIdToken * * @memberof AsgardeoNodeClient * */ async getDecodedIdToken(userId, idToken) { return this._authCore.getDecodedIdToken(userId, idToken); } /** * This method returns the access token. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<string>} -A Promise that resolves with * the access token stored in the store * * @example * ``` *const accessToken = await auth.getAccessToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#getAccessToken * * @memberof AsgardeoNodeClient * */ async getAccessToken(userId) { return this._authCore.getAccessToken(userId); } /** * This method returns Promise that resolves with the token information * or the response returned by the server depending on the configuration passed. * @param {TokenExchangeRequestConfig} config - The config object contains attributes that would be used * to configure the custom grant request. * * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<TokenResponse | Response>} -A Promise that resolves with the token information * or the response returned by the server depending on the configuration passed. * * @example * ``` * const config = { * attachToken: false, * data: { * client_id: "{{clientId}}", * grant_type: "account_switch", * scope: "{{scope}}", * token: "{{token}}", * }, * id: "account-switch", * returnResponse: true, * returnsSession: true, * signInRequired: true * } * auth.exchangeToken(config).then((response)=>{ * console.log(response); * }).catch((error)=>{ * console.error(error); * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#exchangeToken * * @memberof AsgardeoNodeClient * */ async exchangeToken(config, userId) { return this._authCore.exchangeToken(config, userId); } /** * This method can be used to update the configurations passed into the constructor of the AsgardeoAuthClient. * @param {AuthClientConfig<T>} config - The config object containing the attributes * that can be used to configure the SDK * * @return {Promise<void>} -A Promise that resolves with a void. * * @example * ``` * const reInitialize = await auth.reInitialize({ * afterSignOutUrl: "http://localhost:3000/sign-out" * }); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#reInitialize * * @memberof AsgardeoNodeClient * */ async reInitialize(config) { return this._authCore.reInitialize(config); } async getSignInUrl(requestConfig, userId) { return this._authCore.getAuthURL(userId, requestConfig); } /** * This method returns a Promise that resolves with the response returned by the server. * @param {string} userId - The userId of the user. * (If you are using ExpressJS, you may get this from the request cookies) * * @return {Promise<Response>} -A Promise that resolves with the response returned by the server. * * @example * ``` * const revokeToken = await auth.revokeAccessToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927"); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#revokeAccessToken * * @memberof AsgardeoNodeClient * */ async revokeAccessToken(userId) { return this._authCore.revokeAccessToken(userId); } /** * This method refreshes the access token and returns a Promise that resolves with the new access * token and other relevant data. * * @param {string} userId - A unique ID of the user to be authenticated. This is useful in multi-user * scenarios where each user should be uniquely identified. * * @returns {Promise<TokenResponse>} - A Promise that resolves with the token response. * * @example * ``` * const tokenResponse = await auth.refreshAccessToken("a2a2972c-51cd-5e9d-a9ae-058fae9f7927") * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#refreshAccessToken * * @memberof AsgardeoNodeClient */ refreshAccessToken(userId) { return this._authCore.refreshAccessToken(userId); } /** * This method returns if the user has been successfully signed out or not. * @param {string} afterSignOutUrl - The URL to which the user is redirected to * after signing out from the server. * * @return {boolean} - A boolean value indicating if the user has been signed out or not. * * @example * ``` * const isSignedOut = auth.isSignOutSuccessful(<signout_url>);; * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#isSignOutSuccessful * * @memberof AsgardeoNodeClient * */ static isSignOutSuccessful(afterSignOutUrl) { return _AsgardeoNodeClient.isSignOutSuccessful(afterSignOutUrl); } /** * This method returns if sign-out failed or not * @param {string} afterSignOutUrl - The URL to which the user is redirected to * after signing out from the server. * * @return {boolean} - A boolean value indicating if sign-out failed or not. * * @example * ``` * const isSignedOut = auth.isSignOutSuccessful(<signout_url>); * ``` * * @link https://github.com/asgardeo/asgardeo-auth-js-sdk/tree/master#didSignOutFail * * @memberof AsgardeoNodeClient * */ static didSignOutFail(afterSignOutUrl) { return _AsgardeoNodeClient.didSignOutFail(afterSignOutUrl); } async getStorageManager() { return this._authCore.getStorageManager(); } }; // src/constants/CookieConfig.ts import { VendorConstants } from "@asgardeo/javascript"; var CookieConfig = class { // eslint-disable-next-line @typescript-eslint/no-empty-function constructor() { } }; __publicField(CookieConfig, "SESSION_COOKIE_NAME", `__${VendorConstants.VENDOR_PREFIX}__session`); __publicField(CookieConfig, "TEMP_SESSION_COOKIE_NAME", `__${VendorConstants.VENDOR_PREFIX}__temp.session`); __publicField(CookieConfig, "DEFAULT_MAX_AGE", 3600); __publicField(CookieConfig, "DEFAULT_HTTP_ONLY", true); __publicField(CookieConfig, "DEFAULT_SAME_SITE", "lax"); __publicField(CookieConfig, "DEFAULT_SECURE", true); var CookieConfig_default = CookieConfig; // src/utils/generateSessionId.ts var generateSessionId = () => (/* @__PURE__ */ new Date()).getTime().toString(36) + Math.random().toString(36).substring(2); var generateSessionId_default = generateSessionId; // src/utils/getSessionCookieOptions.ts var getSessionCookieOptions = (options) => ({ ...options, httpOnly: options.httpOnly ?? CookieConfig_default.DEFAULT_HTTP_ONLY, maxAge: options.maxAge ?? CookieConfig_default.DEFAULT_MAX_AGE, sameSite: options.sameSite ?? CookieConfig_default.DEFAULT_SAME_SITE, secure: options.secure ?? CookieConfig_default.DEFAULT_SECURE }); var getSessionCookieOptions_default = getSessionCookieOptions; // src/AsgardeoNodeClient.ts import { AsgardeoJavaScriptClient } from "@asgardeo/javascript"; var AsgardeoNodeClient2 = class extends AsgardeoJavaScriptClient { }; var AsgardeoNodeClient_default = AsgardeoNodeClient2; // src/index.ts export * from "@asgardeo/javascript"; if (!globalThis.fetch) { globalThis.fetch = fetch; globalThis.Headers = Headers; globalThis.Request = Request; globalThis.Response = Response; } export { AsgardeoNodeClient_default as AsgardeoNodeClient, CookieConfig_default as CookieConfig, AsgardeoNodeClient as LegacyAsgardeoNodeClient, Logger, generateSessionId_default as generateSessionId, getSessionCookieOptions_default as getSessionCookieOptions }; //# sourceMappingURL=index.js.map