| 53 | let pendingRefresh: Promise<string> | null = null |
| 54 | |
| 55 | export async function refreshAccess(): Promise<string> { |
| 56 | if (pendingRefresh) return pendingRefresh |
| 57 | |
| 58 | const { refreshToken, updateTokens, clearAuth } = useAuthStore.getState() |
| 59 | if (!refreshToken) { |
| 60 | clearAuth() |
| 61 | throw new Error('No refresh token') |
| 62 | } |
| 63 | |
| 64 | pendingRefresh = (async (): Promise<string> => { |
| 65 | const response = await fetch('/api/v1/auth/refresh', { |
| 66 | method: 'POST', |
| 67 | headers: { 'content-type': 'application/json' }, |
| 68 | body: JSON.stringify({ refresh_token: refreshToken }), |
| 69 | }) |
| 70 | if (!response.ok) { |
| 71 | clearAuth() |
| 72 | throw new Error('Token refresh failed') |
| 73 | } |
| 74 | const auth = (await response.json()) as AuthResponse |
| 75 | updateTokens(auth) |
| 76 | return auth.access_token |
| 77 | })().finally(() => { |
| 78 | pendingRefresh = null |
| 79 | }) |
| 80 | |
| 81 | return pendingRefresh |
| 82 | } |