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:
william
2026-10-31 21:41:35 +01:00
co-authored by Claude Sonnet 5
parent ef4cd41ad4
commit 00619add9f
11 changed files with 1820 additions and 16 deletions
+1506 -8
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -48,8 +48,12 @@
"@fontsource/jetbrains-mono": "^5.3.0",
"dotenv": "^18.0.8",
"electron-updater": "^6.8.11",
"lucide-react": "^1.66.0",
"pdf-lib": "^1.17.1",
"three": "^0.186.1"
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"three": "^0.186.1",
"zustand": "^5.0.16"
},
"devDependencies": {
"@electron-toolkit/eslint-config-prettier": "^3.0.1",
+70
View File
@@ -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' })
}
+6 -4
View File
@@ -1,5 +1,5 @@
import type { LoginResult } from '../../shared/auth'
import { setCurrentUserEmail, setSessionValues } from './session'
import { setAccessToken, setCurrentUserEmail, setSessionValues } from './session'
// Correspondance entre les noms de service stockes par Max API (snake_case, voir prisma/seed.ts
// cote backend) et les variables d'environnement que openrouter.ts/elevenlabs.ts consomment deja.
@@ -20,9 +20,10 @@ interface LoginResponseBody {
}
/**
* Authentifie aupres de Max API puis recupere immediatement les cles dechiffrees de l'utilisateur
* (un seul aller-retour supplementaire, le jeton n'est pas conserve au-dela). En cas de succes, les
* cles remplacent celles du .env local jusqu'a la fin du processus (voir session.ts).
* Authentifie aupres de Max API puis recupere immediatement les cles dechiffrees de l'utilisateur.
* Le jeton JWT est conserve en memoire (session.ts) pour authentifier les appels ulterieurs au
* pipeline (/sessions/*). En cas de succes, les cles remplacent celles du .env local jusqu'a la fin
* du processus.
*/
export async function loginAndLoadKeys(email: string, password: string): Promise<LoginResult> {
const baseUrl = getMaxApiUrl()
@@ -53,6 +54,7 @@ export async function loginAndLoadKeys(email: string, password: string): Promise
}
setSessionValues(envValues)
setCurrentUserEmail(user.email)
setAccessToken(accessToken)
return { ok: true }
} catch (error) {
+14
View File
@@ -6,6 +6,7 @@
*/
let currentUserEmail: string | null = null
let currentAccessToken: string | null = null
const sessionValues = new Map<string, string>()
export function setSessionValues(values: Map<string, string>): void {
@@ -17,9 +18,22 @@ export function setCurrentUserEmail(email: string): void {
currentUserEmail = email
}
/**
* Jeton JWT de /auth/login, garde en memoire process (jamais sur disque) le temps de la session
* pour authentifier les appels au pipeline (/sessions/*). Efface comme le reste a la deconnexion.
*/
export function setAccessToken(token: string): void {
currentAccessToken = token
}
export function getAccessToken(): string | null {
return currentAccessToken
}
export function clearSession(): void {
sessionValues.clear()
currentUserEmail = null
currentAccessToken = null
}
export function getCurrentUserEmail(): string | null {
+51 -1
View File
@@ -8,9 +8,20 @@ import { setMainWindow } from './windowBridge'
import { stripWakeWord } from './wakeWord'
import { loginAndLoadKeys } from './auth/authClient'
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
import { clearSession, getCurrentUserEmail, isLoggedIn } from './auth/session'
import { clearSession, getCurrentUserEmail, isLoggedIn, requireLoggedIn } from './auth/session'
import {
confirmObjective,
createSession,
getSession,
sendObjectiveMessage
} from './api/sessionsClient'
import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveMessageResponse,
SessionObjectiveResponse,
SessionResponse
} from '../shared/session'
import { logger } from './utils/logger'
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowSecurity'
import { startAutoUpdater } from './updater'
@@ -221,6 +232,45 @@ app
email: getCurrentUserEmail()
}))
ipcMain.handle('sessions:create', (): Promise<SessionResponse> => {
requireLoggedIn()
return createSession()
})
ipcMain.handle('sessions:get', (_event, id: unknown): Promise<SessionResponse> => {
requireLoggedIn()
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) {
throw new Error('id de session invalide')
}
return getSession(id)
})
ipcMain.handle(
'sessions:send-objective-message',
(_event, id: unknown, message: unknown): Promise<ObjectiveMessageResponse> => {
requireLoggedIn()
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) {
throw new Error('id de session invalide')
}
if (typeof message !== 'string' || message.trim().length === 0) {
throw new Error('message vide')
}
if (message.length > 2000) throw new Error('message trop long')
return sendObjectiveMessage(id, message)
}
)
ipcMain.handle(
'sessions:confirm-objective',
(_event, id: unknown): Promise<SessionObjectiveResponse> => {
requireLoggedIn()
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) {
throw new Error('id de session invalide')
}
return confirmObjective(id)
}
)
createWindow()
if (!is.dev) startAutoUpdater()
+13
View File
@@ -1,6 +1,18 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveMessageResponse,
SessionObjectiveResponse,
SessionResponse
} from '../shared/session'
export interface SessionsApi {
create: () => Promise<SessionResponse>
get: (id: number) => Promise<SessionResponse>
sendObjectiveMessage: (id: number, message: string) => Promise<ObjectiveMessageResponse>
confirmObjective: (id: number) => Promise<SessionObjectiveResponse>
}
export interface ForgeAvatarApi {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }) => void
@@ -14,6 +26,7 @@ export interface ForgeAvatarApi {
onUpdateReady: (callback: () => void) => () => void
login: (email: string, password: string) => Promise<LoginResult>
getAuthStatus: () => Promise<AuthStatus>
sessions: SessionsApi
}
declare global {
+14 -1
View File
@@ -2,6 +2,11 @@ import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth'
import type {
ObjectiveMessageResponse,
SessionObjectiveResponse,
SessionResponse
} from '../shared/session'
const api = {
setIgnoreMouseEvents: (ignore: boolean, options?: { forward: boolean }): void => {
@@ -40,7 +45,15 @@ const api = {
},
login: (email: string, password: string): Promise<LoginResult> =>
ipcRenderer.invoke('auth-login', email, password),
getAuthStatus: (): Promise<AuthStatus> => ipcRenderer.invoke('get-auth-status')
getAuthStatus: (): Promise<AuthStatus> => ipcRenderer.invoke('get-auth-status'),
sessions: {
create: (): Promise<SessionResponse> => ipcRenderer.invoke('sessions:create'),
get: (id: number): Promise<SessionResponse> => ipcRenderer.invoke('sessions:get', id),
sendObjectiveMessage: (id: number, message: string): Promise<ObjectiveMessageResponse> =>
ipcRenderer.invoke('sessions:send-objective-message', id, message),
confirmObjective: (id: number): Promise<SessionObjectiveResponse> =>
ipcRenderer.invoke('sessions:confirm-objective', id)
}
}
// contextIsolation est toujours actif (regle de securite absolue, jamais desactivee) : le seul
+39
View File
@@ -0,0 +1,39 @@
// Types paralleles aux DTO de Max API (src/sessions/dto/*.ts) : Max Avatar ne peut pas importer
// le client Prisma du backend, ces types sont donc recopies a la main et doivent rester en phase
// avec le contrat HTTP reel (voir docs/Max Refonte Coach Freelance.md section "State machine").
export type SessionStatus =
| 'objective_discovery'
| 'objective_validated'
| 'mapping'
| 'level_assessment'
| 'researching'
| 'planning'
| 'teaching'
| 'evaluating'
| 'completed'
export interface ObjectiveDraft {
subject: string
professionalGoal: string
duration: string
}
export interface SessionObjectiveResponse extends ObjectiveDraft {
id: number
sessionId: number
validatedAt: string
}
export interface SessionResponse {
id: number
status: SessionStatus
createdAt: string
updatedAt: string
objective?: SessionObjectiveResponse
}
export interface ObjectiveMessageResponse {
reply: string
ready: boolean
draft?: ObjectiveDraft
}
+4 -1
View File
@@ -2,9 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const setSessionValues = vi.fn()
const setCurrentUserEmail = vi.fn()
const setAccessToken = vi.fn()
vi.mock('../../src/main/auth/session', () => ({
setSessionValues,
setCurrentUserEmail
setCurrentUserEmail,
setAccessToken
}))
const { loginAndLoadKeys } = await import('../../src/main/auth/authClient')
@@ -56,6 +58,7 @@ describe('authClient.loginAndLoadKeys()', () => {
])
)
expect(setCurrentUserEmail).toHaveBeenCalledWith('william@example.com')
expect(setAccessToken).toHaveBeenCalledWith('jwt-token')
const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock
.calls
@@ -0,0 +1,98 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const getAccessToken = vi.fn<() => string | null>(() => 'jwt-token')
vi.mock('../../src/main/auth/session', () => ({ getAccessToken }))
const { createSession, getSession, sendObjectiveMessage, confirmObjective, MaxApiError } =
await import('../../src/main/api/sessionsClient')
function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response {
return { ok, status, json: () => Promise.resolve(body) } as Response
}
describe('sessionsClient', () => {
const originalFetch = global.fetch
beforeEach(() => {
vi.clearAllMocks()
getAccessToken.mockReturnValue('jwt-token')
})
afterEach(() => {
global.fetch = originalFetch
})
it('should throw MaxApiError when there is no access token', async () => {
getAccessToken.mockReturnValue(null)
await expect(createSession()).rejects.toThrow(MaxApiError)
})
it('should create a session with the bearer token', async () => {
global.fetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse({ id: 1, status: 'objective_discovery' }))
const result = await createSession()
expect(result).toEqual({ id: 1, status: 'objective_discovery' })
const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock
.calls
const call = calls.at(0)
expect(call?.[0]).toContain('/sessions')
expect((call?.[1]?.headers as Record<string, string>)?.Authorization).toBe('Bearer jwt-token')
})
it('should fetch a session by id', async () => {
global.fetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse({ id: 1, status: 'objective_discovery' }))
await getSession(1)
const calls = (global.fetch as unknown as { mock: { calls: [string][] } }).mock.calls
expect(calls.at(0)?.[0]).toContain('/sessions/1')
})
it('should send an objective message', async () => {
global.fetch = vi
.fn()
.mockResolvedValueOnce(jsonResponse({ reply: 'Quel est ton sujet ?', ready: false }))
const result = await sendObjectiveMessage(1, 'Je veux apprendre')
expect(result.ready).toBe(false)
const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock
.calls
const body = calls.at(0)?.[1]?.body as string
expect(JSON.parse(body)).toEqual({ message: 'Je veux apprendre' })
})
it('should confirm the objective', async () => {
global.fetch = vi.fn().mockResolvedValueOnce(
jsonResponse({
id: 1,
sessionId: 1,
subject: 'x',
professionalGoal: 'y',
duration: '2 semaines',
validatedAt: '2026-01-01T00:00:00.000Z'
})
)
const result = await confirmObjective(1)
expect(result.sessionId).toBe(1)
})
it('should throw MaxApiError with the server message on a non-ok response', async () => {
global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ message: 'Conflit' }, false, 409))
await expect(createSession()).rejects.toThrow('Conflit')
})
it('should throw MaxApiError when the network call fails', async () => {
global.fetch = vi.fn().mockRejectedValueOnce(new Error('ECONNREFUSED'))
await expect(createSession()).rejects.toThrow(MaxApiError)
})
})