Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,18 @@ pub(crate) async fn refresh_access_token_into_state(
}
}

/// Exchanges the stored refresh token for a new access token. The frontend
/// calls this when the backend refuses its token (it expires after an hour),
/// so a long-running session keeps working without reopening the app.
/// Returns None when the refresh fails.
#[tauri::command]
async fn refresh_session(
state: tauri::State<'_, AppState>,
app_handle: tauri::AppHandle,
) -> Result<Option<String>, String> {
Ok(refresh_access_token_into_state(&state, &app_handle).await)
}

/// Auto-login: Check if there are stored tokens and validate them
/// Returns the access token if valid, None otherwise
#[tauri::command]
Expand Down Expand Up @@ -1318,6 +1330,7 @@ fn main() {
get_device_id,
nodea_usage,
auto_login,
refresh_session,
check_stored_auth,
connect_grpc,
disconnect_grpc,
Expand Down
1 change: 1 addition & 0 deletions src/components/layout/Sidebar.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const { invoke, apiClient } = vi.hoisted(() => ({
apiClient: {
setToken: vi.fn(),
setAccountDeletedHandler: vi.fn(),
setTokenRefresher: vi.fn(),
getMe: vi.fn(),
getOrganization: vi.fn(),
getOrganizationMembers: vi.fn(),
Expand Down
16 changes: 16 additions & 0 deletions src/contexts/AuthContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

// Access tokens expire after an hour. The app is set up once, so a request
// refused with an expired token gets a new one from the refresh token -
// through the Rust host, which owns the stored tokens, or the Supabase SDK
// in web mode - and is retried.
useEffect(() => {
if (demoMode) return
apiClient.setTokenRefresher(async () => {
if (isTauriApp()) return invoke<string | null>('refresh_session')
const { data, error } = await supabase.auth.refreshSession()
if (error) throw error
return data.session?.access_token ?? null
})
return () => apiClient.setTokenRefresher(null)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

// Membership changes made elsewhere: leaving or being removed in the web
// console, an admin deactivating the account, deleting it. Checked on load,
// whenever the window regains focus, and every minute.
Expand Down
9 changes: 9 additions & 0 deletions src/hooks/useApiToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useSyncExternalStore } from 'react'
import { apiClient } from '@/lib/api'

// The API client's current access token. A stream puts the token in its URL,
// so an effect that opens one lists this in its dependencies to reopen the
// stream after the token is refreshed.
export function useApiToken(): string | null {
return useSyncExternalStore(apiClient.onTokenChange, () => apiClient.getToken())
}
109 changes: 109 additions & 0 deletions src/lib/api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const { invoke } = vi.hoisted(() => ({ invoke: vi.fn() }))
vi.mock('@tauri-apps/api/core', () => ({ invoke }))
vi.mock('./demoMode', () => ({ isDemoMode: () => false }))

import { apiClient, ApiError } from './api'

const ok = (body: unknown) => new Response(JSON.stringify(body), { status: 200 })
const unauthorized = (body: unknown = {}) => new Response(JSON.stringify(body), { status: 401 })

const sentToken = (fetchMock: ReturnType<typeof vi.fn>, call: number) =>
(fetchMock.mock.calls[call][1] as RequestInit & { headers: Record<string, string> }).headers.Authorization

describe('ApiClient token refresh', () => {
let fetchMock: ReturnType<typeof vi.fn>

beforeEach(() => {
invoke.mockResolvedValue(undefined)
fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
apiClient.setToken('expired')
})

afterEach(() => {
apiClient.setTokenRefresher(null)
vi.unstubAllGlobals()
})

it('refreshes an expired token and retries the request with the new one', async () => {
const refresher = vi.fn().mockResolvedValue('fresh')
apiClient.setTokenRefresher(refresher)
fetchMock.mockResolvedValueOnce(unauthorized()).mockResolvedValueOnce(ok({ uuid: 'u1' }))

await expect(apiClient.getMe()).resolves.toEqual({ uuid: 'u1' })

expect(refresher).toHaveBeenCalledTimes(1)
expect(sentToken(fetchMock, 0)).toBe('Bearer expired')
expect(sentToken(fetchMock, 1)).toBe('Bearer fresh')
expect(apiClient.getToken()).toBe('fresh')
})

it('shares one refresh between requests refused together', async () => {
let resolve!: (token: string) => void
const refresher = vi.fn(() => new Promise<string>((r) => (resolve = r)))
apiClient.setTokenRefresher(refresher)
fetchMock.mockImplementation((_url: string, init: RequestInit & { headers: Record<string, string> }) =>
Promise.resolve(init.headers.Authorization === 'Bearer fresh' ? ok({}) : unauthorized())
)

const requests = Promise.all([apiClient.getMe(), apiClient.getOrganization()])
await vi.waitFor(() => expect(refresher).toHaveBeenCalled())
resolve('fresh')
await requests

expect(refresher).toHaveBeenCalledTimes(1)
})

it('retries without refreshing again when the token changed while the request was in flight', async () => {
const refresher = vi.fn().mockResolvedValue('unused')
apiClient.setTokenRefresher(refresher)
fetchMock
.mockImplementationOnce(async () => {
apiClient.setToken('fresh')
return unauthorized()
})
.mockResolvedValueOnce(ok({}))

await apiClient.getMe()

expect(refresher).not.toHaveBeenCalled()
expect(sentToken(fetchMock, 1)).toBe('Bearer fresh')
})

it('gives up with the 401 when the refresh fails, and retries only once', async () => {
apiClient.setTokenRefresher(vi.fn().mockResolvedValue(null))
fetchMock.mockResolvedValue(unauthorized())
await expect(apiClient.getMe()).rejects.toMatchObject({ status: 401 })
expect(fetchMock).toHaveBeenCalledTimes(1)

apiClient.setTokenRefresher(vi.fn().mockResolvedValue('still-refused'))
fetchMock.mockClear()
await expect(apiClient.getMe()).rejects.toBeInstanceOf(ApiError)
expect(fetchMock).toHaveBeenCalledTimes(2)
})

it('does not refresh for a deleted account', async () => {
const refresher = vi.fn().mockResolvedValue('fresh')
apiClient.setTokenRefresher(refresher)
fetchMock.mockResolvedValue(unauthorized({ code: 'account_deleted' }))

await expect(apiClient.getMe()).rejects.toMatchObject({ code: 'account_deleted' })
expect(refresher).not.toHaveBeenCalled()
})

it('tells listeners when the token changes', () => {
const listener = vi.fn()
const unsubscribe = apiClient.onTokenChange(listener)

apiClient.setToken('expired')
expect(listener).not.toHaveBeenCalled()
apiClient.setToken('fresh')
expect(listener).toHaveBeenCalledTimes(1)

unsubscribe()
apiClient.setToken('other')
expect(listener).toHaveBeenCalledTimes(1)
})
})
58 changes: 55 additions & 3 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,50 @@ class ApiError extends Error {
class ApiClient {
private token: string | null = null
private accountDeletedHandler: (() => void) | null = null
private tokenRefresher: (() => Promise<string | null>) | null = null
private refreshing: Promise<string | null> | null = null
private tokenListeners = new Set<() => void>()

setToken(token: string) {
if (token === this.token) return
this.token = token
this.tokenListeners.forEach((listener) => listener())
}

getToken(): string | null {
return this.token
}

// Streams put the token in their URL, so they reopen when it changes.
onTokenChange = (listener: () => void): (() => void) => {
this.tokenListeners.add(listener)
return () => this.tokenListeners.delete(listener)
}

// How to get a new access token when the backend refuses the current one
// (it expires after an hour). Resolves to null when that is not possible.
setTokenRefresher(refresher: (() => Promise<string | null>) | null) {
this.tokenRefresher = refresher
}

// Requests refused together share one refresh.
private refreshToken(): Promise<string | null> {
if (!this.tokenRefresher) return Promise.resolve(null)
if (!this.refreshing) {
this.refreshing = this.tokenRefresher()
.then((token) => {
if (token) this.setToken(token)
return token
})
.catch((e) => {
console.error('[Api] Token refresh failed:', e)
return null
})
.finally(() => {
this.refreshing = null
})
}
return this.refreshing
}

// Called when any request is refused because the account was deleted - a
Expand All @@ -202,7 +243,8 @@ class ApiClient {

private async fetch<T>(
endpoint: string,
options: RequestInit = {}
options: RequestInit = {},
retried = false
): Promise<T> {
const startTime = performance.now()
const method = options.method || 'GET'
Expand All @@ -212,8 +254,9 @@ class ApiClient {
'Content-Type': 'application/json',
}

if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`
const sentToken = this.token
if (sentToken) {
headers['Authorization'] = `Bearer ${sentToken}`
}

// Merge with options headers if provided
Expand All @@ -224,6 +267,7 @@ class ApiClient {
let responseBody: string | undefined
let statusCode: number
let error: Error | undefined
let tokenRefused = false

try {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
Expand All @@ -248,6 +292,7 @@ class ApiClient {
code
)
if (response.status === 401 && code === 'account_deleted') this.accountDeletedHandler?.()
else if (response.status === 401 && sentToken && !retried) tokenRefused = true
} else {
const responseText = await response.text()
responseBody = responseText
Expand Down Expand Up @@ -277,6 +322,13 @@ class ApiClient {
this.logApiCall(method, endpoint, statusCode, requestBody, responseBody, duration)
}

// An expired token: retry once with a new one. A request sent before
// another one's refresh finished just retries with the new token.
if (tokenRefused) {
const token = this.token !== sentToken ? this.token : await this.refreshToken()
if (token) return this.fetch<T>(endpoint, options, true)
}

throw error!
}

Expand Down
5 changes: 5 additions & 0 deletions src/lib/mockApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,11 @@ export class MockApiClient {
return this.token
}

// Demo mode never refreshes its token.
onTokenChange = (_listener: () => void): (() => void) => () => {}

setTokenRefresher(_refresher: (() => Promise<string | null>) | null) {}

async getApiKeys(): Promise<ApiKeyResponse[]> {
await delay(300)
return [...this.apiKeys]
Expand Down
4 changes: 3 additions & 1 deletion src/pages/FleetPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import { apiClient, type DeviceResponse } from '@/lib/api'
import { isDemoMode, mockInvoke } from '@/lib/mockTauri'
import { WEB_CONSOLE_URL, consoleDeviceUrl } from '@/lib/webConsole'
import { ConsoleLink } from '@/components/ConsoleLink'
import { useApiToken } from '@/hooks/useApiToken'

/* Open to every member of the organization: the roster it shows is the
* organization's, not the signed-in user's, so there is nothing here a
* standard member should not see. */
export function FleetPage() {
const [devices, setDevices] = useState<DeviceResponse[]>([])
const [thisDeviceId, setThisDeviceId] = useState<string | null>(null)
const token = useApiToken()

useEffect(() => {
const es = apiClient.createFleetStream()
Expand All @@ -23,7 +25,7 @@ export function FleetPage() {
}
}
return () => es.close()
}, [])
}, [token])

useEffect(() => {
const demo = isDemoMode()
Expand Down
11 changes: 7 additions & 4 deletions src/pages/PlaygroundPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { apiClient } from '@/lib/api'
import { useApiToken } from '@/hooks/useApiToken'
import { StreamingMarkdown } from '@/components/StreamingMarkdown'

interface Message {
Expand All @@ -39,6 +40,7 @@ export function PlaygroundPage() {

const messagesEndRef = useRef<HTMLDivElement>(null)
const eventSourceRef = useRef<EventSource | null>(null)
const token = useApiToken()

useEffect(() => {
console.log('[Playground] Connecting to models stream...')
Expand Down Expand Up @@ -76,11 +78,12 @@ export function PlaygroundPage() {
return () => {
console.log('[Playground] Closing models stream')
modelsStream.close()
if (eventSourceRef.current) {
eventSourceRef.current.close()
}
}
}, [])
}, [token])

// Apart from the models stream: a reply in progress keeps its stream when
// the token is refreshed.
useEffect(() => () => eventSourceRef.current?.close(), [])

useEffect(() => {
scrollToBottom()
Expand Down
Loading