import { API_URL } from '$lib/env'; import { getAuthTokens, setAuthTokens, setToken, removeAuthTokens, removeToken } from '$lib/hooks/token'; function getTokenExpiry(): number | null { try { const token = getAuthTokens()?.access_token; if (!token) return null; const payload = JSON.parse(atob(token.split('.')[1])); return payload.exp ? payload.exp * 1000 : null; } catch { return null; } } export class TokenRefresher { private timer: ReturnType | null = null; private onExpired: () => void; active = $state(false); constructor(onExpired?: () => void) { this.onExpired = onExpired ?? (() => {}); if (getAuthTokens()) { this.start(); } } start() { this.schedule(); } stop() { if (this.timer) { clearInterval(this.timer); this.timer = null; } this.active = false; } private schedule() { this.stop(); if (!getAuthTokens()) return; const exp = getTokenExpiry(); if (!exp) return; const delay = Math.max(exp - Date.now() - 120_000, 30_000); this.active = true; this.timer = setInterval(() => { this.refresh(); }, delay); } private async refresh() { const tokens = getAuthTokens(); if (!tokens?.refresh_token) { this.stop(); return; } try { const res = await fetch(`${API_URL}/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: tokens.refresh_token }) }); if (!res.ok) throw new Error('Refresh failed'); const data = await res.json(); setAuthTokens({ access_token: data.access_token, refresh_token: data.refresh_token, expires_in: data.expires_in, token_type: data.token_type }); setToken(data.access_token); this.schedule(); } catch { removeAuthTokens(); removeToken(); this.stop(); this.onExpired(); } } }