UNPKG

@trimble-oss/trimble-id-react

Version:

> **Important Notice:** > > As of version 1.0.0, `PersistentOptions` have been removed. By default, the SDK now supports in-memory token storage. > > When you upgrade to version 1.x, storage options will no longer be available, resulting in a breaking

739 lines (738 loc) 23.7 kB
import { OpenIdEndpointProvider as $, AuthorizationCodeGrantTokenProvider as R, AnalyticsHttpClient as h, BearerTokenHttpClientProvider as B } from "@trimble-oss/trimble-id"; import * as m from "es-cookie"; import J from "jwt-decode"; import { createContext as H, useContext as L, useState as Q, useReducer as X, useRef as q, useMemo as M, useEffect as N, useCallback as y } from "react"; import { jsx as V, Fragment as z } from "react/jsx-runtime"; class Y { /** * This function generate a encapsulation function to store * the user and token information in a secure way disabled the * access from the outside * @see {https://medium.com/javascript-scene/encapsulation-in-javascript-26be60e325b4} Encapsulation * @return {CacheStorage} Key for the token */ generateCache = /* @__PURE__ */ (function() { const e = { token: void 0, user: void 0 }; return { /** * Get token store in cache * @return {Promise<TIDAuthToken | undefined>} Token store in memory */ async getToken() { return e.token; }, /** * Get user store in cache * @return {Promise<TIDUser | undefined>} User store in memory */ async getUser() { return e.user; }, /** * Store token in cache * @param {TIDAuthToken} token - Token that you want to store in cache * @return {Promise<void>} Empty promise */ async storeToken(t) { e.token = t; }, /** * Store user in cache * @param {TIDUser} user - User that you want to store in cache * @return {Promise<void>} Empty promise */ async storeUser(t) { e.user = t; }, /** * The clear the cache from the storage * @return {Promise<void>} Empty promise */ clear() { return e.token = void 0, e.user = void 0, Promise.resolve(void 0); } }; })(); } class Z { /** * Cache option selected * @type {CacheStorage} */ cacheStorage; constructor() { this.cacheStorage = new Y().generateCache; } /** * Store token in cache * @param {TIDAuthToken} token - Token that you want to store in cache * @return {Promise<void>} Empty promise */ async setToken(e) { await this.cacheStorage.storeToken(e); } /** * Store user in cache * @param {TIDUser} user - User that you want to store in cache * @return {Promise<void>} Empty promise */ async setUser(e) { await this.cacheStorage.storeUser(e); } /** * Get user store in cache * @return {Promise<TIDUser | undefined>} Key for the user */ async getUser() { return this.cacheStorage.getUser(); } /** * Get token store in cache * @return {Promise<TIDAuthToken | undefined>} Key for the user */ async getToken() { return this.cacheStorage.getToken(); } /** * The clear the cache from the storage * @return {Promise<void>} Empty promise */ async clear() { await this.cacheStorage.clear(); } } const x = 5 * 6e4, j = ["code", "state"], A = 600 * 1e3, U = (o) => o.split("?")[0], ee = (o) => o.split("?")[1], b = (o) => { let e = o; if (!o.startsWith("?")) try { e = new URL(o).search; } catch { } return new URLSearchParams(e); }, te = (o = window.location.href, e) => { if (e != null) { const n = U(e), r = U(o ?? ""); if (n !== r) return !1; } const t = b(o); for (const n of j) if (!t.has(n)) return !1; return !0; }, oe = (o) => ({ id: o.sub, name: `${o.given_name} ${o.family_name}`, given_name: o.given_name, family_name: o.family_name, picture: o.picture, email: o.email, email_verified: o.email_verified, ...o.account_id && { account_id: o.account_id } }), ne = "@TID_COOKIE"; class re { /** * Retrieve a cookie from the browser * @param {string} key - Key to retrieve the cookies */ get(e) { const t = m.get(e); if (t == null) throw new Error("Cookie not found"); return JSON.parse(t); } /** * Store cookies in the browser * @param {string} key - Key to save and retrieve the cookies * @param {any} value - Information you want to store in cookies * @param {CookiesOptions} options - Additional options you want to add to the cookies. * @example Save cookies with one day of expiration * cookiesStorage.set('key',{data:{...}},{expires:1}) * @example Save cookies with a custom domain * cookiesStorage.set('key',{data:{...}},{domain:'https://example.com/subpath'}) */ set(e, t, n) { let r = {}; window.location.protocol === "https:" && (r = { secure: !0, sameSite: "none" }), n?.expires && (r.expires = n.expires), n?.domain && (r.domain = n.domain), m.set(e, JSON.stringify(t), r); } /** * Remove a cookie from the browser * @param {string} key - Key to remove the cookies from the browser * @param {CookiesOptions} options - Additional options used when the cookie was declared * @example Remove cookies without additional information * cookiesStorage.remove('key') * @example Remove cookies with custom domain * cookiesStorage.remove('key',{domain:'https://example.com/subpath'}) */ remove(e, t) { const n = {}; t?.domain && (n.domain = t.domain), m.remove(e, n); } } class ie { /** * Cookie full key to store and retrieve the information from cookies * @type {string} */ cookieKey; /** * Cookie storage. This object contain all functions necessary to retrieve and store tokens using cookies * @type {CookiesStorage} */ cookiesStorage; /** * Create a cookies manager to extract or save cookies in the browser * @param {CookiesManagerOptions} options - Configuration for the managing the cookies */ constructor(e) { this.cookieKey = `${ne}.${e.clientId}`, this.cookiesStorage = new re(); } /** * Store cookies in the browser * @param {Partial<CookieValue>} value - information to store */ save(e) { const n = { ...this.get() || {}, ...e }; this.cookiesStorage.set(this.cookieKey, n, { expires: 1 }); } /** * Retrieve state payload from cookies * @return {string | undefined} - State payload from cookies */ getStatePayload() { return this.get()?.state_payload; } /** * Clear state payload from cookies */ clearStatePayload() { const e = this.get(); e && (delete e.state_payload, this.cookiesStorage.set(this.cookieKey, e, { expires: 1 })); } /** * Retrieve cookies in the browser * @return {CookieValue | undefined} - Cookies from the browser */ get() { try { return this.cookiesStorage.get(this.cookieKey); } catch { return; } } /** * Clear information about the cookies stored in the browser */ clear() { this.cookiesStorage.remove(this.cookieKey); } } class O extends Error { } class D extends Error { } class ae extends Error { } const u = "@trimble-oss/trimble-id-react", g = "1.0.3", se = { configurationEndpoint: "", clientId: "", redirectUrl: "", logoutRedirectUrl: "", scopes: [] }; class ce { /** * Token provider SDK. This object handles all necessary communication with TID * @type {AuthorizationCodeGrantTokenProvider} */ tokenProvider; /** * This object manage all caching, and all configurations necessary * @type {CacheManager} */ cacheManager; /** * This object manage all cookies administration, and all configurations necessary * @type {CookiesManager} */ cookiesManager; /** * Client id of the application created in trimble developer console * @type {string} */ clientId; /** * Callback url to redirect the user after the authentication is successful * @type {string} */ redirectUrl; /** * Create a TID client to handle manage all user authentication functions and information * @param {CacheManagerOptions} props - TID client configuration */ constructor(e) { const { config: t = se } = e; if (this.redirectUrl = t.redirectUrl, t.configurationEndpoint == null || t.configurationEndpoint == "") throw new Error("Configuration endpoint not defined"); if (t.clientId == null || t.clientId == "") throw new Error("Consumer key is not defined"); this.cookiesManager = new ie({ clientId: t.clientId }); const n = this.cookiesManager.get(), r = new $(t.configurationEndpoint); let i = new R( r, t.clientId, t.redirectUrl ).WithScopes(t.scopes); t.logoutRedirectUrl && (i = i.WithLogoutRedirect(t.logoutRedirectUrl)), n?.code_verifier != null && (i = i.WithProofKeyForCodeExchange(n.code_verifier)), this.tokenProvider = i, this.cacheManager = new Z(), this.clientId = t.clientId, h.sendInitEvent("TIDClient", this.clientId, u, g), this.cleanupExpiredState(); } /** * Clean up expired state payloads to prevent storage bloat */ cleanupExpiredState() { try { const e = this.cookiesManager.getStatePayload(); if (e) { const t = atob(e), n = JSON.parse(t); Date.now() - n.timestamp > A && this.cookiesManager.clearStatePayload(); } } catch { this.cookiesManager.clearStatePayload(); } } /** * Redirect the user to TID using the browser * @param {LoginWithRedirectOptions} options - Custom configuration for the redirection * @return {Promise<void>} Empty promise * @example No configuration * loginWithRedirect() * // Automatically redirects the user to TID with all necessary parameters * // After authentication, user will be redirected back to the current page * @example Custom redirect * loginWithRedirect({onRedirect: (url) => router.navigate(url)}) * // Redirect calls onRedirect with the log-out url for TID * // So it can be handled by the developer */ async loginWithRedirect(e) { h.sendMethodEvent(this.loginWithRedirect.name, this.clientId, u, g); const { onRedirect: t } = e || {}, n = window.location.pathname + window.location.search, r = this.createStatePayload(n); this.cookiesManager.save({ state_payload: r }); const i = R.GenerateCodeVerifier(); this.cookiesManager.save({ code_verifier: i }), this.tokenProvider = this.tokenProvider.WithProofKeyForCodeExchange(i); const c = await this.tokenProvider.GetOAuthRedirect(r); t != null ? t(c) : window.location.assign(c); } /** * Authenticated the user using the url callback params * @param {string} url - Custom configuration for the redirection * @return {Promise<AuthState>} Object contain the state returned from TID and redirect path * @throws {CodeVerifierNotFoundException} Will throw an exception if the session doesn't contain the code verifier * @throws {Error} Will throw an exception if state validation fails or replay attack is detected * @example No configuration * handleCallback() * // Will automatically take the url from the browser and try to log in the user * @example Custom url * handleCallback('https://example.com?code=code....') * // Will try to log in the user with the url assign by the developer */ async handleCallback(e = window.location.href) { const t = this.cookiesManager.get(); if (t == null || t?.code_verifier == null) throw new ae("Code verifier not available"); const n = ee(e), r = b(e), i = r.get("identity_provider") ?? "", c = r.get("state") ?? "", d = this.validateStatePayload(c); if (!d.isValid) throw new Error(`State validation failed: ${d.error}`); return await this.tokenProvider.ValidateQuery(n), await this.generateToken(i), { authState: c, returnTo: d.redirectTo }; } /** * Function to generate and store the access token * @param {string} identityProvider - Type of identity provider used * @return {Promise<void>} Empty promise */ async generateToken(e) { const t = await this.tokenProvider.RetrieveToken(), n = await this.tokenProvider.RetrieveRefreshToken(), r = await this.tokenProvider.RetrieveIdToken(), i = await this.tokenProvider.RetrieveTokenExpiry(), d = new Date(i).getTime(), k = this.tokenProvider?._scopes?.join(" "); await this.cacheManager.setToken({ scope: k, state: "", session_state: "", identity_provider: e, token_type: "bearer", access_token: t, refresh_token: n, id_token: r, expires_at: d }); const v = J(r), p = oe(v); await this.cacheManager.setUser(p), await this.reloadCodeVerifier(); } async reloadCodeVerifier() { const e = await this.tokenProvider.RetrieveCodeVerifier(); this.cookiesManager.save({ code_verifier: e }), this.tokenProvider = this.tokenProvider.WithProofKeyForCodeExchange(e); } /** * Create and encode state payload for replay attack protection * @param {string} redirectTo - Path to redirect to after authentication * @return {string} - Base64 encoded state payload */ createStatePayload(e) { const t = this.generateNonce(), n = Date.now(); return btoa(JSON.stringify({ redirectTo: e, timestamp: n, nonce: t })); } /** * Generate a random nonce for state validation * @return {string} - Random nonce */ generateNonce() { const e = new Uint8Array(16); return crypto.getRandomValues(e), Array.from(e, (t) => t.toString(16).padStart(2, "0")).join(""); } /** * Validate state payload to prevent replay attacks * @param {string} receivedState - State received from OAuth callback * @return {StateValidationResult} - Validation result with redirect path if valid */ validateStatePayload(e) { try { if (!e || e.trim() === "") return { isValid: !1, error: "Empty state parameter" }; const t = this.cookiesManager.getStatePayload(); if (!t) return { isValid: !1, error: "No stored state found" }; const n = atob(e), r = JSON.parse(n), i = atob(t), c = JSON.parse(i); if (!r.nonce || !r.timestamp || !r.redirectTo) return { isValid: !1, error: "Invalid state payload structure" }; if (r.nonce !== c.nonce) return { isValid: !1, error: "State nonce mismatch" }; const k = Date.now() - r.timestamp; return k > A ? { isValid: !1, error: "State expired - possible replay attack" } : k < 0 ? { isValid: !1, error: "State timestamp is in the future - possible replay attack" } : (this.cookiesManager.clearStatePayload(), { isValid: !0, redirectTo: r.redirectTo }); } catch { return { isValid: !1, error: "Invalid state format" }; } } /** * Return the user stored in cache * @return {Promise<TIDUser | undefined>} User in cache */ async getUser() { return h.sendMethodEvent(this.getUser.name, this.clientId, u, g), await this.cacheManager.getUser(); } /** * Gets the access token from cache. If the token already expired, * will try to refresh it using the refresh token * @return {Promise<string>} Access token * @throws {TokenNotFoundException} Will throw an exception if the access token is not in cache * @throws {TokenExpiredException} Will throw an exception if the user token expired */ async getAccessTokenSilently() { h.sendMethodEvent( this.getAccessTokenSilently.name, this.clientId, u, g ); let e = await this.cacheManager.getToken(); if (e == null) throw h.sendExceptionEvent( this.getAccessTokenSilently.name, "No token available", this.clientId, u, g ), new D("No token available"); const t = new Date((/* @__PURE__ */ new Date()).getTime() + x); if (e?.expires_at == null || e?.expires_at < t.getTime()) { try { await this.tokenProvider.RetrieveToken(); } catch (n) { throw h.sendExceptionEvent( this.getAccessTokenSilently.name, n.message, this.clientId, u, g ), new O(n.message); } await this.generateToken(e?.identity_provider ?? ""), e = await this.cacheManager.getToken(); } return e?.access_token || ""; } /** * Retrieves token details from the cache, including the access token, ID token, and expiration time. * If the token already expired, will try to refresh it using the refresh token. * @return {Promise<TokenResponse>} Token response * @throws {TokenNotFoundException} Will throw an exception if there are no tokens in cache * @throws {TokenExpiredException} Will throw an exception if the user token expired */ async getTokens() { h.sendMethodEvent(this.getTokens.name, this.clientId, u, g); let e = await this.cacheManager.getToken(); if (e == null) throw h.sendExceptionEvent( this.getTokens.name, "No token available", this.clientId, u, g ), new D("No token available"); const t = new Date((/* @__PURE__ */ new Date()).getTime() + x); if (e?.expires_at == null || e?.expires_at < t.getTime()) { try { await this.tokenProvider.RetrieveToken(); } catch (n) { throw h.sendExceptionEvent( this.getTokens.name, n.message, this.clientId, u, g ), new O(n.message); } await this.generateToken(e?.identity_provider ?? ""), e = await this.cacheManager.getToken(); } return { access_token: e?.access_token || "", expires_at: e?.expires_at || 0, id_token: e?.id_token || "" }; } /** * Redirect the user to TID using the browser * @param {LogoutOptions} options - Custom configuration for teh redirection * @return {Promise<void>} Empty promise * @example No configuration * logout() * // Automatically redirects the user to TID to log out * @example Custom redirect * logout({onRedirect: (url) => router.navigate(url)}) * // Redirect calls onRedirect with the log-out url for TID * // So it can be handled by the developer */ async logout(e) { h.sendMethodEvent(this.logout.name, this.clientId, u, g); const { onRedirect: t, disabledAutoRedirect: n } = e || {}; this.cacheManager && await this.cacheManager.clear(), this.cookiesManager && this.cookiesManager.clear(); const r = await this.tokenProvider.GetOAuthLogoutRedirect("state"); if (t != null) return t(r); n || window.location.assign(r); } /** * Check if the user still has a valid session * @return {Promise<boolean>} True or false depending on if the user is session is valid or not */ async checkSession() { try { await this.getAccessTokenSilently(); } catch { return !1; } return !0; } /** * Check if the user has a session valid after a refresh * @return {Promise<void>} Empty promise */ async loadUserSession() { await this.loadCacheSessionIntoSDK(), await this.checkSession() || await this.cacheManager.clear(); } /** * Load the user session from cache into the SDK * @return {Promise<void>} Empty promise */ async loadCacheSessionIntoSDK() { const e = await this.cacheManager.getToken(); if (e == null) return; const t = e.access_token, n = e.refresh_token || "", r = e.id_token, i = e.expires_at; this.tokenProvider = this.tokenProvider.WithAccessToken(t, i).WithRefreshToken(n).WithIdToken(r); } /** * Get a http bearer token client to use it for another SDK (Ex: Processing framework) * @return {any} - BearerTokenHttpClientProvider */ getBearerTokenHttpClient(e) { return new B(this.tokenProvider, e); } /** * Get the redirect url to TID * @return {string} - Callback redirect url */ getRedirectUrl() { return this.redirectUrl; } } const T = H(null), K = () => L(T) ?? {}, de = (o, e) => { switch (e.type) { case "INIT": return { ...o, isLoading: !1, isAuthenticated: e.user != null, user: e.user, error: void 0 }; case "GET_TOKENS_COMPLETE": case "HANDLE_CALLBACK_COMPLETE": case "GET_ACCESS_TOKEN_COMPLETE": return { ...o, isLoading: !1, isAuthenticated: e.user != null, user: e.user, error: void 0 }; case "LOGOUT": return { ...o, isAuthenticated: !1, user: void 0 }; case "ERROR": return { ...o, isLoading: !1, error: e.error }; } }, le = { isLoading: !0, isAuthenticated: !1 }, he = (o) => { if (o == null || Object.keys(o).length <= 0) return !0; const e = Object.keys(o); for (const t of e) if (o[t] != null && o[t] !== "") return !1; return !0; }, ue = (o) => !he(o.config), ge = (o) => { const { children: e, configurationEndpoint: t, clientId: n, redirectUrl: r, logoutRedirectUrl: i, scopes: c, onRedirectCallback: d, checkRedirectUrlMatch: k } = o; if (L(T) != null) throw new Error("TID Provider already defined"); const p = { config: { configurationEndpoint: t ?? "", clientId: n ?? "", redirectUrl: r ?? "", logoutRedirectUrl: i ?? "", scopes: c ?? [""] } }, [a] = Q(o.tidClient ?? new ce(p)), [w, f] = X(de, le), E = q(!1), W = M( () => k ? a.getRedirectUrl() : void 0, [k, a] ); N(() => { E.current || (o.tidClient != null && ue({ config: { configurationEndpoint: t, clientId: n, redirectUrl: r, logoutRedirectUrl: i, scopes: c } }) && console.warn( "When TID client is pass as prop, any client configuration property sent directly to the TID Provider component will be ignored" ), E.current = !0, (async () => { try { let s; if (te(void 0, W)) { const l = await a.handleCallback(); s = await a.getUser(), d?.(l); } else await a.loadUserSession(), s = await a.getUser(); f({ type: "INIT", user: s }); } catch (s) { let l = s; typeof s == "string" && (l = new Error(s)), f({ type: "ERROR", error: l }); } })()); }, [a, d]); const S = y(async () => { const s = await a.getAccessTokenSilently(), l = await a.getUser(); return f({ type: "GET_ACCESS_TOKEN_COMPLETE", user: l }), s; }, [a]), _ = y(async () => { const s = await a.getTokens(), l = await a.getUser(); return f({ type: "GET_TOKENS_COMPLETE", user: l }), s; }, [a]), P = y( async (s) => { await a.loginWithRedirect(s); }, [a] ), C = y( async (s) => { await a.logout(s), s?.disabledAutoRedirect != null && s.disabledAutoRedirect && f({ type: "LOGOUT" }); }, [a] ), I = y( async (s) => { const l = await a.handleCallback(s), F = await a.getUser(); return f({ type: "HANDLE_CALLBACK_COMPLETE", user: F }), l; }, [a] ), G = M( () => ({ ...w, getAccessTokenSilently: S, getTokens: _, loginWithRedirect: P, handleCallback: I, logout: C }), [w, S, _, P, I, C] ); return /* @__PURE__ */ V(T.Provider, { value: G, children: e }); }, me = K, Te = ge, ve = ({ renderComponent: o, loader: e }) => { const { isAuthenticated: t, isLoading: n, loginWithRedirect: r } = K(); return N(() => { !n && !t && (async () => await r())(); }, [n, t, r]), t ? o : e || /* @__PURE__ */ V(z, {}); }; export { ve as AuthenticationGuard, ce as TIDClient, T as TIDContext, Te as TIDProvider, me as useAuth };