|
| 1 | +import {API_URL, RECAPTCHA_V3_SITE_KEY} from './constants'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Silent reCAPTCHA v3 session tokens. The backend mints a session token from a |
| 5 | + * reCAPTCHA v3 token (POST /api/session) and gated endpoints require it in the |
| 6 | + * X-Districtr-Session header. Everything here is best-effort: any failure |
| 7 | + * (script blocked, Google down, backend error) yields null and the request |
| 8 | + * proceeds without the header. |
| 9 | + */ |
| 10 | + |
| 11 | +declare global { |
| 12 | + interface Window { |
| 13 | + grecaptcha?: { |
| 14 | + ready: (cb: () => void) => void; |
| 15 | + execute: (siteKey: string, options: {action: string}) => Promise<string>; |
| 16 | + }; |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const STORAGE_KEY = 'districtr_session'; |
| 21 | +// Refresh when within 5 minutes of expiry. |
| 22 | +const EXPIRY_BUFFER_MS = 5 * 60 * 1000; |
| 23 | + |
| 24 | +type CachedSession = {token: string; expiresAt: number}; |
| 25 | + |
| 26 | +let cached: CachedSession | null = null; |
| 27 | +let inflight: Promise<string | null> | null = null; |
| 28 | +let scriptPromise: Promise<void> | null = null; |
| 29 | + |
| 30 | +const isFresh = (session: CachedSession | null): session is CachedSession => |
| 31 | + !!session && session.expiresAt - EXPIRY_BUFFER_MS > Date.now(); |
| 32 | + |
| 33 | +const readStorage = (): CachedSession | null => { |
| 34 | + try { |
| 35 | + const raw = window.localStorage.getItem(STORAGE_KEY); |
| 36 | + if (!raw) return null; |
| 37 | + const parsed = JSON.parse(raw); |
| 38 | + if (typeof parsed?.token === 'string' && typeof parsed?.expiresAt === 'number') { |
| 39 | + return parsed; |
| 40 | + } |
| 41 | + } catch { |
| 42 | + // ignore storage/parse errors |
| 43 | + } |
| 44 | + return null; |
| 45 | +}; |
| 46 | + |
| 47 | +const writeStorage = (session: CachedSession) => { |
| 48 | + try { |
| 49 | + window.localStorage.setItem(STORAGE_KEY, JSON.stringify(session)); |
| 50 | + } catch { |
| 51 | + // ignore storage errors (private mode, quota) |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +const loadRecaptchaScript = (): Promise<void> => { |
| 56 | + if (window.grecaptcha) return Promise.resolve(); |
| 57 | + if (!scriptPromise) { |
| 58 | + scriptPromise = new Promise<void>((resolve, reject) => { |
| 59 | + const script = document.createElement('script'); |
| 60 | + script.src = `https://www.google.com/recaptcha/api.js?render=${RECAPTCHA_V3_SITE_KEY}`; |
| 61 | + script.async = true; |
| 62 | + script.onload = () => resolve(); |
| 63 | + script.onerror = () => { |
| 64 | + scriptPromise = null; // allow retry on a later call |
| 65 | + reject(new Error('recaptcha script failed to load')); |
| 66 | + }; |
| 67 | + document.head.appendChild(script); |
| 68 | + }); |
| 69 | + } |
| 70 | + return scriptPromise; |
| 71 | +}; |
| 72 | + |
| 73 | +const mintSession = async (): Promise<string | null> => { |
| 74 | + try { |
| 75 | + await loadRecaptchaScript(); |
| 76 | + const grecaptcha = window.grecaptcha; |
| 77 | + if (!grecaptcha) return null; |
| 78 | + await new Promise<void>(resolve => grecaptcha.ready(resolve)); |
| 79 | + const recaptchaToken = await grecaptcha.execute(RECAPTCHA_V3_SITE_KEY, {action: 'session'}); |
| 80 | + const response = await fetch(`${API_URL || ''}/api/session`, { |
| 81 | + method: 'POST', |
| 82 | + headers: {'Content-Type': 'application/json'}, |
| 83 | + body: JSON.stringify({recaptcha_token: recaptchaToken}), |
| 84 | + }); |
| 85 | + if (!response.ok) return null; |
| 86 | + const data = await response.json(); |
| 87 | + const expiresAt = Date.parse(data.expires_at); |
| 88 | + if (typeof data.token !== 'string' || isNaN(expiresAt)) return null; |
| 89 | + cached = {token: data.token, expiresAt}; |
| 90 | + writeStorage(cached); |
| 91 | + return cached.token; |
| 92 | + } catch { |
| 93 | + return null; |
| 94 | + } |
| 95 | +}; |
| 96 | + |
| 97 | +/** |
| 98 | + * Get a session token for the X-Districtr-Session header, minting one via |
| 99 | + * silent reCAPTCHA v3 if needed. Never throws; returns null on any failure, |
| 100 | + * on the server, or when no site key is configured. |
| 101 | + */ |
| 102 | +export async function getSessionToken(): Promise<string | null> { |
| 103 | + if (typeof window === 'undefined' || !RECAPTCHA_V3_SITE_KEY) return null; |
| 104 | + if (isFresh(cached)) return cached.token; |
| 105 | + const stored = readStorage(); |
| 106 | + if (isFresh(stored)) { |
| 107 | + cached = stored; |
| 108 | + return stored.token; |
| 109 | + } |
| 110 | + if (!inflight) { |
| 111 | + inflight = mintSession().finally(() => { |
| 112 | + inflight = null; |
| 113 | + }); |
| 114 | + } |
| 115 | + return inflight; |
| 116 | +} |
| 117 | + |
| 118 | +/** |
| 119 | + * fetch() that attaches the X-Districtr-Session header when a token is |
| 120 | + * available and, on a 401 {"detail": "session_required"} response, re-mints |
| 121 | + * the session and retries the request once. |
| 122 | + */ |
| 123 | +export async function fetchWithSession(url: string, init: RequestInit = {}): Promise<Response> { |
| 124 | + const headers = new Headers(init.headers); |
| 125 | + const token = await getSessionToken(); |
| 126 | + if (token) headers.set('X-Districtr-Session', token); |
| 127 | + const response = await fetch(url, {...init, headers}); |
| 128 | + if (response.status !== 401) return response; |
| 129 | + const detail = await response |
| 130 | + .clone() |
| 131 | + .json() |
| 132 | + .then(error => error?.detail) |
| 133 | + .catch(() => null); |
| 134 | + if (detail !== 'session_required') return response; |
| 135 | + clearSessionToken(); |
| 136 | + const freshToken = await getSessionToken(); |
| 137 | + if (!freshToken) return response; |
| 138 | + headers.set('X-Districtr-Session', freshToken); |
| 139 | + return fetch(url, {...init, headers}); |
| 140 | +} |
| 141 | + |
| 142 | +/** Clear the cached session token (used when the backend rejects it). */ |
| 143 | +export function clearSessionToken() { |
| 144 | + cached = null; |
| 145 | + if (typeof window !== 'undefined') { |
| 146 | + try { |
| 147 | + window.localStorage.removeItem(STORAGE_KEY); |
| 148 | + } catch { |
| 149 | + // ignore storage errors |
| 150 | + } |
| 151 | + } |
| 152 | +} |
0 commit comments