|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + useCallback, |
| 4 | + useContext, |
| 5 | + useEffect, |
| 6 | + useState, |
| 7 | +} from "react"; |
| 8 | +import { jwtVerify } from "jose"; |
| 9 | + |
| 10 | +interface TokenCacheEntry { |
| 11 | + token: string; |
| 12 | + expiresAt: number; |
| 13 | +} |
| 14 | + |
| 15 | +const SESSION_STORAGE_PREFIX = "amp-labs_jwt_"; |
| 16 | + |
| 17 | +const DEFAULT_TOKEN_EXPIRATION_TIME = 10 * 60 * 1000; // 10 minutes |
| 18 | + |
| 19 | +const createCacheKey = (consumerRef: string, groupRef: string) => |
| 20 | + `${consumerRef}:${groupRef}`; |
| 21 | + |
| 22 | +const getSessionStorageKey = (cacheKey: string) => |
| 23 | + `${SESSION_STORAGE_PREFIX}${cacheKey}`; |
| 24 | + |
| 25 | +interface JwtTokenContextValue { |
| 26 | + getToken?: (consumerRef: string, groupRef: string) => Promise<string>; |
| 27 | +} |
| 28 | + |
| 29 | +const JwtTokenContext = createContext<JwtTokenContextValue | null>(null); |
| 30 | + |
| 31 | +interface JwtTokenProviderProps { |
| 32 | + getTokenCallback: |
| 33 | + | ((consumerRef: string, groupRef: string) => Promise<string>) |
| 34 | + | null; |
| 35 | + children: React.ReactNode; |
| 36 | +} |
| 37 | + |
| 38 | +/** |
| 39 | + * Extract JWT token expiration time |
| 40 | + */ |
| 41 | +const getTokenExpirationTime = async ( |
| 42 | + token: string, |
| 43 | +): Promise<number | null> => { |
| 44 | + try { |
| 45 | + const decoded = await jwtVerify(token, new Uint8Array(0), { |
| 46 | + algorithms: [], // Skip signature verification |
| 47 | + }); |
| 48 | + const payload = decoded.payload; |
| 49 | + return payload.exp && typeof payload.exp === "number" |
| 50 | + ? payload.exp * 1000 // jwt expiration is in seconds, convert to milliseconds |
| 51 | + : null; |
| 52 | + } catch (error) { |
| 53 | + console.warn("Failed to decode JWT token:", error); |
| 54 | + return null; |
| 55 | + } |
| 56 | +}; |
| 57 | + |
| 58 | +/** |
| 59 | + * Simplified JWT token provider with cleaner caching logic |
| 60 | + */ |
| 61 | +export function JwtTokenProvider({ |
| 62 | + getTokenCallback, |
| 63 | + children, |
| 64 | +}: JwtTokenProviderProps) { |
| 65 | + const [tokenCache, setTokenCache] = useState<Map<string, TokenCacheEntry>>( |
| 66 | + new Map(), |
| 67 | + ); |
| 68 | + |
| 69 | + // Load cached tokens from sessionStorage on mount |
| 70 | + useEffect(() => { |
| 71 | + try { |
| 72 | + const newCache = new Map<string, TokenCacheEntry>(); |
| 73 | + const now = Date.now(); // current time in milliseconds |
| 74 | + |
| 75 | + Object.keys(sessionStorage).forEach((key) => { |
| 76 | + if (key.startsWith(SESSION_STORAGE_PREFIX)) { |
| 77 | + const cacheKey = key.replace(SESSION_STORAGE_PREFIX, ""); |
| 78 | + const stored = sessionStorage.getItem(key); |
| 79 | + |
| 80 | + if (stored) { |
| 81 | + try { |
| 82 | + const cacheEntry: TokenCacheEntry = JSON.parse(stored); |
| 83 | + if (cacheEntry.expiresAt > now) { |
| 84 | + newCache.set(cacheKey, cacheEntry); |
| 85 | + } else { |
| 86 | + sessionStorage.removeItem(key); |
| 87 | + } |
| 88 | + } catch { |
| 89 | + sessionStorage.removeItem(key); |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + }); |
| 94 | + |
| 95 | + if (newCache.size > 0) { |
| 96 | + setTokenCache(newCache); |
| 97 | + } |
| 98 | + } catch { |
| 99 | + console.warn("Failed to load JWT tokens from sessionStorage"); |
| 100 | + } |
| 101 | + }, []); |
| 102 | + |
| 103 | + /** |
| 104 | + * Get a cached token from the in-memory cache or sessionStorage |
| 105 | + * @param consumerRef - The consumer reference |
| 106 | + * @param groupRef - The group reference |
| 107 | + * @returns The cached token or null if not found |
| 108 | + */ |
| 109 | + const getCachedToken = useCallback( |
| 110 | + (consumerRef: string, groupRef: string): string | null => { |
| 111 | + const cacheKey = createCacheKey(consumerRef, groupRef); |
| 112 | + const now = Date.now(); |
| 113 | + |
| 114 | + // Check in-memory cache first |
| 115 | + const cached = tokenCache.get(cacheKey); |
| 116 | + if (cached && cached.expiresAt > now) { |
| 117 | + return cached.token; |
| 118 | + } else { |
| 119 | + tokenCache.delete(cacheKey); |
| 120 | + } |
| 121 | + |
| 122 | + // Check sessionStorage |
| 123 | + const sessionKey = getSessionStorageKey(cacheKey); |
| 124 | + const stored = sessionStorage.getItem(sessionKey); |
| 125 | + |
| 126 | + if (stored) { |
| 127 | + try { |
| 128 | + const cacheEntry: TokenCacheEntry = JSON.parse(stored); |
| 129 | + if (cacheEntry.expiresAt > now) { |
| 130 | + // Update in-memory cache |
| 131 | + setTokenCache((prev) => new Map(prev).set(cacheKey, cacheEntry)); |
| 132 | + return cacheEntry.token; |
| 133 | + } else { |
| 134 | + sessionStorage.removeItem(sessionKey); |
| 135 | + } |
| 136 | + } catch { |
| 137 | + sessionStorage.removeItem(sessionKey); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + return null; |
| 142 | + }, |
| 143 | + [tokenCache], |
| 144 | + ); |
| 145 | + |
| 146 | + const setCachedToken = useCallback( |
| 147 | + async (consumerRef: string, groupRef: string, token: string) => { |
| 148 | + const cacheKey = createCacheKey(consumerRef, groupRef); |
| 149 | + const tokenExpiration = await getTokenExpirationTime(token); |
| 150 | + const expiresAt = |
| 151 | + tokenExpiration || Date.now() + DEFAULT_TOKEN_EXPIRATION_TIME; |
| 152 | + |
| 153 | + const cacheEntry: TokenCacheEntry = { token, expiresAt }; |
| 154 | + |
| 155 | + // Update both in-memory cache |
| 156 | + setTokenCache((prev) => new Map(prev).set(cacheKey, cacheEntry)); |
| 157 | + |
| 158 | + // Update sessionStorage |
| 159 | + try { |
| 160 | + sessionStorage.setItem( |
| 161 | + getSessionStorageKey(cacheKey), |
| 162 | + JSON.stringify(cacheEntry), |
| 163 | + ); |
| 164 | + } catch { |
| 165 | + console.warn("Failed to store JWT token in sessionStorage"); |
| 166 | + } |
| 167 | + }, |
| 168 | + [], |
| 169 | + ); |
| 170 | + |
| 171 | + const getToken = useCallback( |
| 172 | + async (consumerRef: string, groupRef: string): Promise<string> => { |
| 173 | + // Check all caches first |
| 174 | + const cachedToken = getCachedToken(consumerRef, groupRef); |
| 175 | + if (cachedToken) { |
| 176 | + return cachedToken; |
| 177 | + } |
| 178 | + |
| 179 | + // Fetch new token if no callback provided |
| 180 | + if (!getTokenCallback) { |
| 181 | + throw new Error("JWT token callback not provided"); |
| 182 | + } |
| 183 | + |
| 184 | + try { |
| 185 | + const token = await getTokenCallback(consumerRef, groupRef); |
| 186 | + await setCachedToken(consumerRef, groupRef, token); |
| 187 | + return token; |
| 188 | + } catch (error) { |
| 189 | + console.error("Failed to get JWT token:", error); |
| 190 | + throw new Error("Failed to get JWT token"); |
| 191 | + } |
| 192 | + }, |
| 193 | + [getTokenCallback, getCachedToken, setCachedToken], |
| 194 | + ); |
| 195 | + |
| 196 | + const contextValue: JwtTokenContextValue = { |
| 197 | + getToken: getTokenCallback ? getToken : undefined, |
| 198 | + }; |
| 199 | + |
| 200 | + return ( |
| 201 | + <JwtTokenContext.Provider value={contextValue}> |
| 202 | + {children} |
| 203 | + </JwtTokenContext.Provider> |
| 204 | + ); |
| 205 | +} |
| 206 | + |
| 207 | +export const useJwtToken = () => { |
| 208 | + const context = useContext(JwtTokenContext); |
| 209 | + if (!context) { |
| 210 | + throw new Error("useJwtToken must be used within a JwtTokenProvider"); |
| 211 | + } |
| 212 | + return context; |
| 213 | +}; |
0 commit comments