feat(sessions): keep JWT in memory and wire IPC to the sessions API
Max Avatar can now call Max API's /sessions endpoints: session.ts keeps the access token in memory after login (never persisted, cleared on logout, same lifecycle as the existing email/keys state), a new sessionsClient.ts wraps the 4 endpoints with the Bearer header, and index.ts exposes them as sessions:create/get/send-objective-message/ confirm-objective IPC handlers (input-validated, requireLoggedIn() gated) surfaced to the renderer as window.api.sessions.*. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
ef4cd41ad4
commit
00619add9f
@@ -0,0 +1,70 @@
|
||||
import { getAccessToken } from '../auth/session'
|
||||
import type {
|
||||
ObjectiveMessageResponse,
|
||||
SessionObjectiveResponse,
|
||||
SessionResponse
|
||||
} from '../../shared/session'
|
||||
|
||||
export class MaxApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public readonly statusCode?: number
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'MaxApiError'
|
||||
}
|
||||
}
|
||||
|
||||
function getMaxApiUrl(): string {
|
||||
return process.env.MAX_API_URL || 'http://localhost:3000'
|
||||
}
|
||||
|
||||
async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const token = getAccessToken()
|
||||
if (!token) throw new MaxApiError("Aucun jeton de session : connecte-toi d'abord")
|
||||
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(`${getMaxApiUrl()}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
...init.headers,
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
} catch (error) {
|
||||
throw new MaxApiError(
|
||||
`Max API injoignable: ${error instanceof Error ? error.message : String(error)}`
|
||||
)
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { message?: string } | null
|
||||
throw new MaxApiError(body?.message ?? `Max API a renvoye ${response.status}`, response.status)
|
||||
}
|
||||
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
export function createSession(): Promise<SessionResponse> {
|
||||
return call('/sessions', { method: 'POST' })
|
||||
}
|
||||
|
||||
export function getSession(id: number): Promise<SessionResponse> {
|
||||
return call(`/sessions/${id}`)
|
||||
}
|
||||
|
||||
export function sendObjectiveMessage(
|
||||
id: number,
|
||||
message: string
|
||||
): Promise<ObjectiveMessageResponse> {
|
||||
return call(`/sessions/${id}/objective/message`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ message } satisfies { message: string })
|
||||
})
|
||||
}
|
||||
|
||||
export function confirmObjective(id: number): Promise<SessionObjectiveResponse> {
|
||||
return call(`/sessions/${id}/objective/confirm`, { method: 'POST' })
|
||||
}
|
||||
Reference in New Issue
Block a user