|
| 1 | +/** |
| 2 | + * PKCE code_verifier persistence in sessionStorage for browser SPAs. |
| 3 | + * Survives OAuth redirects; not used in Node. RFC 7636 / OAuth 2.0 for Browser-Based Apps. |
| 4 | + */ |
| 5 | + |
| 6 | +const PKCE_STORAGE_KEY_PREFIX = 'contentstack_oauth_pkce' |
| 7 | +const PKCE_STORAGE_EXPIRY_MS = 10 * 60 * 1000 // 10 minutes |
| 8 | + |
| 9 | +function isBrowser () { |
| 10 | + return typeof window !== 'undefined' && typeof window.sessionStorage !== 'undefined' |
| 11 | +} |
| 12 | + |
| 13 | +function getStorageKey (appId, clientId, redirectUri) { |
| 14 | + return `${PKCE_STORAGE_KEY_PREFIX}_${appId}_${clientId}_${redirectUri}` |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {string} appId |
| 19 | + * @param {string} clientId |
| 20 | + * @param {string} redirectUri |
| 21 | + * @returns {string|null} code_verifier if valid and not expired, otherwise null |
| 22 | + */ |
| 23 | +export function getStoredCodeVerifier (appId, clientId, redirectUri) { |
| 24 | + if (!isBrowser()) return null |
| 25 | + try { |
| 26 | + const raw = window.sessionStorage.getItem(getStorageKey(appId, clientId, redirectUri)) |
| 27 | + if (!raw) return null |
| 28 | + const { codeVerifier, expiresAt } = JSON.parse(raw) |
| 29 | + if (!codeVerifier || !expiresAt || Date.now() > expiresAt) return null |
| 30 | + return codeVerifier |
| 31 | + } catch { |
| 32 | + return null |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * @param {string} appId |
| 38 | + * @param {string} clientId |
| 39 | + * @param {string} redirectUri |
| 40 | + * @param {string} codeVerifier |
| 41 | + */ |
| 42 | +export function storeCodeVerifier (appId, clientId, redirectUri, codeVerifier) { |
| 43 | + if (!isBrowser()) return |
| 44 | + try { |
| 45 | + const key = getStorageKey(appId, clientId, redirectUri) |
| 46 | + const value = JSON.stringify({ |
| 47 | + codeVerifier, |
| 48 | + expiresAt: Date.now() + PKCE_STORAGE_EXPIRY_MS |
| 49 | + }) |
| 50 | + window.sessionStorage.setItem(key, value) |
| 51 | + } catch { |
| 52 | + // Ignore storage errors (e.g. private mode); fall back to memory-only |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * @param {string} appId |
| 58 | + * @param {string} clientId |
| 59 | + * @param {string} redirectUri |
| 60 | + */ |
| 61 | +export function clearStoredCodeVerifier (appId, clientId, redirectUri) { |
| 62 | + if (!isBrowser()) return |
| 63 | + try { |
| 64 | + window.sessionStorage.removeItem(getStorageKey(appId, clientId, redirectUri)) |
| 65 | + } catch { |
| 66 | + // Ignore |
| 67 | + } |
| 68 | +} |
0 commit comments