feat: login page in Max Avatar, connects to Max API's new auth
CI / quality (pull_request) Successful in 12m5s
CI / quality (pull_request) Successful in 12m5s
Step 3 of the backend plan: lets a user log in from Max Avatar and use their account's OpenRouter/ElevenLabs keys instead of the local .env. Max API (new AuthModule): - POST /auth/login (bcrypt-verified, returns a 1h JWT) and GET /auth/me/keys (JwtAuthGuard-protected, returns the authenticated user's decrypted keys only — never exposed via the generic /api-keys CRUD routes). - UsersService.findByEmailForAuth() / ApiKeysService.getAllDecrypted(): new internal-only methods, never exposed by a controller directly. - Generic "Email ou mot de passe incorrect" message regardless of whether the email exists, to avoid confirming account existence. - @nestjs/jwt pinned to 11.0.2 (12.x is ESM-only and breaks Jest, same issue already hit with @nestjs/config). Max Avatar: - Context menu: connection status shown first (as a pseudo-title), "Me connecter"/"Connecte : email" + "Se deconnecter". Voice listening and the Basic/Coach/Assistant modes are fully removed from the menu (not just disabled) while logged out; listening also gets forced unchecked. Logging out while in Coach/Assistant force-switches back to Basic so the user isn't stuck in a mode with no menu entry left to leave it. - Real server-side gate, not just a UI one: requireLoggedIn() (session.ts) is called at the top of getAssistantReply()/transcribeAudio()/ synthesizeSpeech(). Without it, voice/chat kept working whenever a local .env had real keys (true during this whole session), regardless of login state — caught by manually testing the built app, not by any test. - session.ts holds fetched keys in memory only (no persisted session: log in again each launch, as requested) and falls back to the local .env only when logged in status allows it. - authClient.ts chains POST /auth/login then GET /auth/me/keys in one go (the JWT isn't kept beyond that); maps backend service names to the env var names openrouter.ts/elevenlabs.ts already expect. - New LoginView.tsx + loginWindow.ts (same singleton pattern as the other secondary windows) and a get-auth-status IPC so the renderer knows the login state on boot (listening now defaults to false, true only if already logged in). Verified end-to-end against a real dockerized Postgres + running Nest server (wrong password -> 401, missing token -> 401, correct login -> JWT + all 4 decrypted keys), and manually in the real Electron app by the user (menu, login, logout, and the voice gate actually blocking requests even with a valid local .env). Backend: 64/64 tests, 100% stmts/functions/lines, 81% branches. Max Avatar: 500/500 tests, ~91%/77%/91%/93%. Also includes a CLAUDE.md rewrite (not authored by this session) describing the next major pivot: Max becomes a freelance-training coach exclusively, via a 7-agent pipeline, dropping Assistant/Basic mode selection. Nothing in this commit implements that yet. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
605f9070a8
commit
885e24d037
@@ -9,3 +9,8 @@ OPENROUTER_VISION_MODEL=deepseek/deepseek-v4.1-flash-1017
|
||||
# ElevenLabs (reconnaissance vocale + synthese vocale) - https://elevenlabs.io/app/settings/api-keys
|
||||
ELEVENLABS_API_KEY=
|
||||
ELEVENLABS_VOICE_ID=
|
||||
|
||||
# Backend Max API (connexion utilisateur, voir menu contextuel "Me connecter") : apres connexion
|
||||
# reussie, les 4 cles ci-dessus sont remplacees en memoire par celles du compte, jusqu'a la
|
||||
# fermeture de l'app (pas de session persistee). Defaut si absent : http://localhost:3000
|
||||
MAX_API_URL=http://localhost:3000
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { getConfigValue, requireLoggedIn } from '../auth/session'
|
||||
|
||||
function getApiKey(): string {
|
||||
const apiKey = process.env.ELEVENLABS_API_KEY
|
||||
const apiKey = getConfigValue('ELEVENLABS_API_KEY')
|
||||
if (!apiKey) throw new Error('ELEVENLABS_API_KEY manquante dans .env')
|
||||
return apiKey
|
||||
}
|
||||
|
||||
export async function transcribeAudio(audio: Buffer, mimeType: string): Promise<string> {
|
||||
requireLoggedIn()
|
||||
const form = new FormData()
|
||||
form.append('file', new Blob([new Uint8Array(audio)], { type: mimeType }), 'audio.webm')
|
||||
form.append('model_id', 'scribe_v1')
|
||||
@@ -62,7 +65,8 @@ function sanitizeForSpeech(text: string): string {
|
||||
}
|
||||
|
||||
export async function synthesizeSpeech(text: string): Promise<Buffer> {
|
||||
const voiceId = process.env.ELEVENLABS_VOICE_ID
|
||||
requireLoggedIn()
|
||||
const voiceId = getConfigValue('ELEVENLABS_VOICE_ID')
|
||||
if (!voiceId) throw new Error('ELEVENLABS_VOICE_ID manquante dans .env')
|
||||
|
||||
const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getSubjectLevel } from '../coach/coachStore'
|
||||
import { recordCourseBuildTool, clearCourseBuild } from '../coach/courseBuildStepper'
|
||||
import { logger } from '../utils/logger'
|
||||
import { extractFakeToolCall, extractBareJsonRetry } from './toolCallRecovery'
|
||||
import { getConfigValue, requireLoggedIn } from '../auth/session'
|
||||
|
||||
// Outils dont l'argument "subject" permet de suivre le sujet Coach en cours de traitement dans ce
|
||||
// tour, pour le garde-fou mecanique anti-blocage du pipeline (voir plus bas).
|
||||
@@ -469,10 +470,11 @@ const MAX_HISTORY_MESSAGES = 16
|
||||
const MAX_TOOL_ROUNDS = 40
|
||||
|
||||
export async function getAssistantReply(userText: string): Promise<string> {
|
||||
const apiKey = process.env.OPENROUTER_API_KEY
|
||||
requireLoggedIn()
|
||||
const apiKey = getConfigValue('OPENROUTER_API_KEY')
|
||||
if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env')
|
||||
|
||||
const primaryModel = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-chat'
|
||||
const primaryModel = getConfigValue('OPENROUTER_MODEL') || 'deepseek/deepseek-chat'
|
||||
let activeModel = primaryModel
|
||||
history.push({ role: 'user', content: userText })
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { LoginResult } from '../../shared/auth'
|
||||
import { 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.
|
||||
const SERVICE_TO_ENV_VAR = new Map<string, string>([
|
||||
['openrouter_api_key', 'OPENROUTER_API_KEY'],
|
||||
['openrouter_model', 'OPENROUTER_MODEL'],
|
||||
['elevenlabs_api_key', 'ELEVENLABS_API_KEY'],
|
||||
['elevenlabs_voice_id', 'ELEVENLABS_VOICE_ID']
|
||||
])
|
||||
|
||||
function getMaxApiUrl(): string {
|
||||
return process.env.MAX_API_URL || 'http://localhost:3000'
|
||||
}
|
||||
|
||||
interface LoginResponseBody {
|
||||
accessToken: string
|
||||
user: { email: string }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
export async function loginAndLoadKeys(email: string, password: string): Promise<LoginResult> {
|
||||
const baseUrl = getMaxApiUrl()
|
||||
try {
|
||||
const loginResponse = await fetch(`${baseUrl}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
})
|
||||
if (!loginResponse.ok) {
|
||||
const body = (await loginResponse.json().catch(() => null)) as { message?: string } | null
|
||||
return { ok: false, error: body?.message ?? 'Identifiants invalides' }
|
||||
}
|
||||
const { accessToken, user } = (await loginResponse.json()) as LoginResponseBody
|
||||
|
||||
const keysResponse = await fetch(`${baseUrl}/auth/me/keys`, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` }
|
||||
})
|
||||
if (!keysResponse.ok) {
|
||||
return { ok: false, error: 'Connexion reussie mais impossible de recuperer les cles API' }
|
||||
}
|
||||
const keysByService = (await keysResponse.json()) as Record<string, string>
|
||||
|
||||
const envValues = new Map<string, string>()
|
||||
for (const [serviceName, value] of Object.entries(keysByService)) {
|
||||
const envVarName = SERVICE_TO_ENV_VAR.get(serviceName)
|
||||
if (envVarName) envValues.set(envVarName, value)
|
||||
}
|
||||
setSessionValues(envValues)
|
||||
setCurrentUserEmail(user.email)
|
||||
|
||||
return { ok: true }
|
||||
} catch (error) {
|
||||
return {
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'Erreur reseau inconnue'
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { BrowserWindow } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { is } from '@electron-toolkit/utils'
|
||||
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from '../utils/windowSecurity'
|
||||
|
||||
let win: BrowserWindow | null = null
|
||||
|
||||
// Fenetre normale et independante de l'avatar, meme pattern singleton que les autres fenetres
|
||||
// secondaires (drawingWindow.ts, exerciseWindow.ts, progressWindow.ts).
|
||||
export function openLoginWindow(): void {
|
||||
if (win && !win.isDestroyed()) {
|
||||
win.show()
|
||||
win.focus()
|
||||
return
|
||||
}
|
||||
|
||||
win = new BrowserWindow({
|
||||
width: 380,
|
||||
height: 440,
|
||||
title: 'Max — connexion',
|
||||
alwaysOnTop: true,
|
||||
resizable: false,
|
||||
webPreferences: {
|
||||
preload: join(__dirname, '../preload/index.js'),
|
||||
...SECURE_WEB_PREFERENCES
|
||||
}
|
||||
})
|
||||
blockExternalNavigation(win)
|
||||
win.setAlwaysOnTop(true, 'floating')
|
||||
win.on('closed', () => {
|
||||
win = null
|
||||
})
|
||||
|
||||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||||
void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#login`)
|
||||
} else {
|
||||
void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'login' })
|
||||
}
|
||||
}
|
||||
|
||||
/** Appele apres une connexion reussie : la fenetre n'a plus de raison de rester ouverte. */
|
||||
export function closeLoginWindow(): void {
|
||||
if (win && !win.isDestroyed()) win.close()
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Cles OpenRouter/ElevenLabs recuperees aupres de Max API apres connexion, gardees en memoire
|
||||
* process (jamais persistees sur disque : reconnexion requise a chaque lancement de Max, voir
|
||||
* docs/Architecture_Monorepo_Backend.md). Tant qu'aucune connexion n'a eu lieu, getConfigValue()
|
||||
* retombe sur le .env local, pour que Max continue de fonctionner normalement sans compte.
|
||||
*/
|
||||
|
||||
let currentUserEmail: string | null = null
|
||||
const sessionValues = new Map<string, string>()
|
||||
|
||||
export function setSessionValues(values: Map<string, string>): void {
|
||||
sessionValues.clear()
|
||||
for (const [key, value] of values) sessionValues.set(key, value)
|
||||
}
|
||||
|
||||
export function setCurrentUserEmail(email: string): void {
|
||||
currentUserEmail = email
|
||||
}
|
||||
|
||||
export function clearSession(): void {
|
||||
sessionValues.clear()
|
||||
currentUserEmail = null
|
||||
}
|
||||
|
||||
export function getCurrentUserEmail(): string | null {
|
||||
return currentUserEmail
|
||||
}
|
||||
|
||||
export function isLoggedIn(): boolean {
|
||||
return currentUserEmail !== null
|
||||
}
|
||||
|
||||
/**
|
||||
* A appeler au tout debut de toute fonction qui utilise une cle OpenRouter/ElevenLabs (chat, STT,
|
||||
* TTS) : sans ca, un .env local garde en dev continuerait de faire fonctionner ces fonctions sans
|
||||
* connexion, alors que l'ecoute vocale et les modes ne doivent etre accessibles qu'une fois
|
||||
* connecte (meme si une cle locale existe par ailleurs).
|
||||
*/
|
||||
export function requireLoggedIn(): void {
|
||||
if (!isLoggedIn()) {
|
||||
throw new Error('Connecte-toi via le menu contextuel ("Me connecter") pour utiliser Max')
|
||||
}
|
||||
}
|
||||
|
||||
/** Valeur de session si connecte, sinon la variable d'environnement locale du meme nom. */
|
||||
export function getConfigValue(envVarName: string): string | undefined {
|
||||
const sessionValue = sessionValues.get(envVarName)
|
||||
if (sessionValue !== undefined) return sessionValue
|
||||
// Reflect.get plutot que process.env[envVarName] : acces dynamique legitime (nom de variable
|
||||
// parametre), mais security/detect-object-injection exige une forme non indexable directement.
|
||||
return Reflect.get(process.env, envVarName)
|
||||
}
|
||||
@@ -21,11 +21,15 @@ import {
|
||||
finishMeetingSession
|
||||
} from './meeting/meetingRecorder'
|
||||
import { getMode, setMode, type Mode } from './mode/modeState'
|
||||
import { loginAndLoadKeys } from './auth/authClient'
|
||||
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
|
||||
import { clearSession, getCurrentUserEmail, isLoggedIn } from './auth/session'
|
||||
import { startVisionCapture, stopVisionCapture } from './coach/visionCapture'
|
||||
import { openCoachProgressWindow } from './coach/progressWindow'
|
||||
import { getProgress, getModuleDetail, getCourseComplianceReport } from './coach/coachStore'
|
||||
import { startReviewScheduler } from './coach/reviewScheduler'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import { logger } from './utils/logger'
|
||||
import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowSecurity'
|
||||
import { startAutoUpdater } from './updater'
|
||||
@@ -175,30 +179,65 @@ app
|
||||
|
||||
ipcMain.on('show-context-menu', (event, listening: boolean, transcribing: boolean) => {
|
||||
const activeMode = getMode()
|
||||
const loggedIn = isLoggedIn()
|
||||
const menu = Menu.buildFromTemplate([
|
||||
// Statut de connexion en premier, en guise de titre du menu (Electron n'a pas de vrai
|
||||
// titre de menu contextuel independant des items). Ecoute vocale et modes restent
|
||||
// desactives tant qu'aucun compte n'est connecte : tous dependent des cles OpenRouter/
|
||||
// ElevenLabs, fournies par Max API une fois connecte (voir docs/Architecture_Monorepo_Backend.md).
|
||||
loggedIn
|
||||
? { label: `Connecte : ${getCurrentUserEmail()}`, enabled: false }
|
||||
: { label: 'Me connecter', click: () => openLoginWindow() },
|
||||
...(loggedIn
|
||||
? [
|
||||
{
|
||||
label: 'Se deconnecter',
|
||||
click: (): void => {
|
||||
clearSession()
|
||||
event.sender.send('toggle-listening', false)
|
||||
// Les modes Coach/Assistant sont caches du menu sans connexion : repasser en
|
||||
// Basic ici evite de laisser l'utilisateur coince dans un mode qu'il ne peut
|
||||
// plus desactiver (et arrete la capture d'ecran du mode Coach au passage).
|
||||
switchMode('basic')
|
||||
}
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: 'Ecoute vocale',
|
||||
type: 'checkbox',
|
||||
checked: listening,
|
||||
// Force a decoche/desactive sans compte connecte, quel que soit l'etat transmis par le
|
||||
// renderer (qui se remet lui-meme a false au demarrage/a la deconnexion, mais ce garde-fou
|
||||
// cote menu evite tout affichage incoherent si jamais ce n'etait pas encore le cas).
|
||||
checked: loggedIn && listening,
|
||||
enabled: loggedIn,
|
||||
click: () => event.sender.send('toggle-listening', !listening)
|
||||
},
|
||||
{ type: 'separator' },
|
||||
buildModeMenuItem('basic', 'Mode Basic', activeMode),
|
||||
buildModeMenuItem('coach', 'Mode apprentissage (Coach)', activeMode, [
|
||||
{ label: "Courbe d'apprentissage", click: () => openCoachProgressWindow() }
|
||||
]),
|
||||
buildModeMenuItem('assistant', 'Mode Assistant', activeMode, [
|
||||
{
|
||||
label: transcribing ? 'Arreter la transcription' : 'Demarrer la transcription',
|
||||
type: 'checkbox',
|
||||
checked: transcribing,
|
||||
click: () => {
|
||||
const next = !transcribing
|
||||
if (next) startMeetingSession()
|
||||
event.sender.send('toggle-meeting-transcription', next)
|
||||
}
|
||||
}
|
||||
]),
|
||||
// Les modes ne dependent d'aucun affichage particulier sans connexion : ils sont retires
|
||||
// du menu plutot que simplement desactives (demande explicite), pour ne montrer que ce qui
|
||||
// est reellement utilisable.
|
||||
...(loggedIn
|
||||
? [
|
||||
{ type: 'separator' as const },
|
||||
buildModeMenuItem('basic', 'Mode Basic', activeMode),
|
||||
buildModeMenuItem('coach', 'Mode apprentissage (Coach)', activeMode, [
|
||||
{ label: "Courbe d'apprentissage", click: () => openCoachProgressWindow() }
|
||||
]),
|
||||
buildModeMenuItem('assistant', 'Mode Assistant', activeMode, [
|
||||
{
|
||||
label: transcribing ? 'Arreter la transcription' : 'Demarrer la transcription',
|
||||
type: 'checkbox' as const,
|
||||
checked: transcribing,
|
||||
click: () => {
|
||||
const next = !transcribing
|
||||
if (next) startMeetingSession()
|
||||
event.sender.send('toggle-meeting-transcription', next)
|
||||
}
|
||||
}
|
||||
])
|
||||
]
|
||||
: []),
|
||||
{ type: 'separator' },
|
||||
{ label: 'Quitter', click: () => app.quit() }
|
||||
])
|
||||
@@ -305,6 +344,25 @@ app
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'auth-login',
|
||||
async (_event, email: string, password: string): Promise<LoginResult> => {
|
||||
const result = await loginAndLoadKeys(email, password)
|
||||
if (result.ok) {
|
||||
closeLoginWindow()
|
||||
// Restaure l'ecoute automatiquement a la connexion, comme avant l'ajout de ce garde-fou
|
||||
// (l'utilisateur n'a pas besoin de la reactiver manuellement via le menu).
|
||||
mainWindow?.webContents.send('toggle-listening', true)
|
||||
}
|
||||
return result
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle('get-auth-status', (): AuthStatus => ({
|
||||
loggedIn: isLoggedIn(),
|
||||
email: getCurrentUserEmail()
|
||||
}))
|
||||
|
||||
createWindow()
|
||||
startReviewScheduler()
|
||||
if (!is.dev) startAutoUpdater()
|
||||
|
||||
Vendored
+3
@@ -1,5 +1,6 @@
|
||||
import { ElectronAPI } from '@electron-toolkit/preload'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ExerciseForm,
|
||||
@@ -52,6 +53,8 @@ export interface ForgeAvatarApi {
|
||||
sendCameraFrameResult: (requestId: string, dataUrl: string | null) => void
|
||||
onUpdateAvailable: (callback: () => void) => () => void
|
||||
onUpdateReady: (callback: () => void) => () => void
|
||||
login: (email: string, password: string) => Promise<LoginResult>
|
||||
getAuthStatus: () => Promise<AuthStatus>
|
||||
}
|
||||
|
||||
declare global {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { contextBridge, ipcRenderer, webUtils } from 'electron'
|
||||
import { electronAPI } from '@electron-toolkit/preload'
|
||||
import type { VoiceTurnResult } from '../shared/voice'
|
||||
import type { AuthStatus, LoginResult } from '../shared/auth'
|
||||
import type {
|
||||
SubjectProgress,
|
||||
ExerciseForm,
|
||||
@@ -151,7 +152,10 @@ const api = {
|
||||
const handler = (): void => callback()
|
||||
ipcRenderer.on('update:ready', handler)
|
||||
return () => ipcRenderer.removeListener('update:ready', handler)
|
||||
}
|
||||
},
|
||||
login: (email: string, password: string): Promise<LoginResult> =>
|
||||
ipcRenderer.invoke('auth-login', email, password),
|
||||
getAuthStatus: (): Promise<AuthStatus> => ipcRenderer.invoke('get-auth-status')
|
||||
}
|
||||
|
||||
// contextIsolation est toujours actif (regle de securite absolue, jamais desactivee) : le seul
|
||||
|
||||
@@ -12,7 +12,9 @@ import { useMeetingRecorder } from './voice/useMeetingRecorder'
|
||||
|
||||
function App(): React.JSX.Element {
|
||||
const avatar = useRef<AvatarHandle | null>(null)
|
||||
const [listening, setListening] = useState(true)
|
||||
// Faux par defaut : l'ecoute (comme les modes) n'est activee que si un compte est connecte, voir
|
||||
// l'effet ci-dessous qui verifie l'etat de connexion au demarrage.
|
||||
const [listening, setListening] = useState(false)
|
||||
const listeningRef = useRef(listening)
|
||||
const [transcribing, setTranscribing] = useState(false)
|
||||
const transcribingRef = useRef(transcribing)
|
||||
@@ -47,6 +49,15 @@ function App(): React.JSX.Element {
|
||||
}, [transcribing])
|
||||
|
||||
useEffect(() => window.api.onToggleListening(setListening), [])
|
||||
// Restaure l'ecoute par defaut si l'app demarre deja connectee (ex: redemarrage apres une
|
||||
// connexion precedente dans la meme session OS, bien qu'aucune session ne soit persistee entre
|
||||
// deux lancements de Max pour l'instant).
|
||||
useEffect(() => {
|
||||
window.api
|
||||
.getAuthStatus()
|
||||
.then((status) => setListening(status.loggedIn))
|
||||
.catch(() => setListening(false))
|
||||
}, [])
|
||||
useEffect(() => window.api.onToggleMeetingTranscription(setTranscribing), [])
|
||||
useEffect(() => window.api.onProactiveSpeech(() => setVoiceState('speaking')), [])
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
export default function LoginView(): React.JSX.Element {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
const [success, setSuccess] = useState(false)
|
||||
|
||||
const canSubmit = email.trim() !== '' && password !== '' && !submitting
|
||||
|
||||
const submit = (event: React.FormEvent): void => {
|
||||
event.preventDefault()
|
||||
if (!canSubmit) return
|
||||
setSubmitting(true)
|
||||
setError(null)
|
||||
window.api
|
||||
.login(email.trim(), password)
|
||||
.then((result) => {
|
||||
if (result.ok) {
|
||||
setSuccess(true)
|
||||
} else {
|
||||
setError(result.error)
|
||||
}
|
||||
})
|
||||
.catch(() => setError('Erreur inattendue'))
|
||||
.finally(() => setSubmitting(false))
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
background: '#1e1e1e',
|
||||
color: '#eee',
|
||||
minHeight: '100vh',
|
||||
padding: 24,
|
||||
fontFamily: 'sans-serif',
|
||||
boxSizing: 'border-box'
|
||||
}}
|
||||
>
|
||||
<h1 style={{ fontSize: 18, marginBottom: 20 }}>Connexion a Max</h1>
|
||||
|
||||
{success ? (
|
||||
<p style={{ color: '#8bc34a' }}>
|
||||
Connexion reussie. Cette fenetre se ferme automatiquement...
|
||||
</p>
|
||||
) : (
|
||||
<form onSubmit={submit}>
|
||||
<label style={{ display: 'block', marginBottom: 12 }}>
|
||||
<span style={{ display: 'block', marginBottom: 4, fontSize: 13, color: '#aaa' }}>
|
||||
Email
|
||||
</span>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoFocus
|
||||
style={{
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
padding: 10,
|
||||
background: '#111',
|
||||
color: '#eee',
|
||||
border: '1px solid #444',
|
||||
borderRadius: 4
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label style={{ display: 'block', marginBottom: 16 }}>
|
||||
<span style={{ display: 'block', marginBottom: 4, fontSize: 13, color: '#aaa' }}>
|
||||
Mot de passe
|
||||
</span>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
style={{
|
||||
width: '100%',
|
||||
boxSizing: 'border-box',
|
||||
padding: 10,
|
||||
background: '#111',
|
||||
color: '#eee',
|
||||
border: '1px solid #444',
|
||||
borderRadius: 4
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error && (
|
||||
<p style={{ color: '#e57373', fontSize: 13, marginBottom: 16 }} role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!canSubmit}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 24px',
|
||||
fontSize: 14,
|
||||
background: canSubmit ? '#3f6fd1' : '#444',
|
||||
color: '#fff',
|
||||
border: 'none',
|
||||
borderRadius: 4,
|
||||
cursor: canSubmit ? 'pointer' : 'not-allowed'
|
||||
}}
|
||||
>
|
||||
{submitting ? 'Connexion...' : 'Se connecter'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import App from './App'
|
||||
import CoachProgressView from './components/CoachProgressView'
|
||||
import CoachExerciseView from './components/CoachExerciseView'
|
||||
import CoachDrawingView from './components/CoachDrawingView'
|
||||
import LoginView from './components/LoginView'
|
||||
|
||||
// Fenetres secondaires (ouvertes via le menu contextuel ou par Max en mode Coach) : chargent ce
|
||||
// meme bundle avec un hash different pour afficher une autre vue que l'avatar. La fenetre avatar,
|
||||
@@ -14,6 +15,7 @@ function renderForHash(): React.JSX.Element {
|
||||
if (location.hash === '#coach-progress') return <CoachProgressView />
|
||||
if (location.hash === '#coach-exercise') return <CoachExerciseView />
|
||||
if (location.hash === '#coach-drawing') return <CoachDrawingView />
|
||||
if (location.hash === '#login') return <LoginView />
|
||||
return <App />
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
export type LoginResult = { ok: true } | { ok: false; error: string }
|
||||
|
||||
export interface AuthStatus {
|
||||
loggedIn: boolean
|
||||
email: string | null
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const setSessionValues = vi.fn()
|
||||
const setCurrentUserEmail = vi.fn()
|
||||
vi.mock('../../src/main/auth/session', () => ({
|
||||
setSessionValues,
|
||||
setCurrentUserEmail
|
||||
}))
|
||||
|
||||
const { loginAndLoadKeys } = await import('../../src/main/auth/authClient')
|
||||
|
||||
function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response {
|
||||
return {
|
||||
ok,
|
||||
status,
|
||||
json: () => Promise.resolve(body)
|
||||
} as Response
|
||||
}
|
||||
|
||||
describe('authClient.loginAndLoadKeys()', () => {
|
||||
const originalFetch = global.fetch
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch
|
||||
})
|
||||
|
||||
it('should log in, fetch the decrypted keys, and map them to the expected env var names', async () => {
|
||||
global.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ accessToken: 'jwt-token', user: { email: 'william@example.com' } })
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({
|
||||
openrouter_api_key: 'sk-or-v1-x',
|
||||
openrouter_model: 'deepseek/deepseek-chat',
|
||||
elevenlabs_api_key: 'sk-el-x',
|
||||
elevenlabs_voice_id: 'voice-123',
|
||||
unknown_service: 'should-be-ignored'
|
||||
})
|
||||
)
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'password')
|
||||
|
||||
expect(result).toEqual({ ok: true })
|
||||
expect(setSessionValues).toHaveBeenCalledWith(
|
||||
new Map([
|
||||
['OPENROUTER_API_KEY', 'sk-or-v1-x'],
|
||||
['OPENROUTER_MODEL', 'deepseek/deepseek-chat'],
|
||||
['ELEVENLABS_API_KEY', 'sk-el-x'],
|
||||
['ELEVENLABS_VOICE_ID', 'voice-123']
|
||||
])
|
||||
)
|
||||
expect(setCurrentUserEmail).toHaveBeenCalledWith('william@example.com')
|
||||
|
||||
const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock
|
||||
.calls
|
||||
const loginCall = calls.at(0)
|
||||
const keysCall = calls.at(1)
|
||||
expect(loginCall?.[0]).toContain('/auth/login')
|
||||
expect(keysCall?.[0]).toContain('/auth/me/keys')
|
||||
expect((keysCall?.[1]?.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer jwt-token'
|
||||
)
|
||||
})
|
||||
|
||||
it('should return the server error message when login fails', async () => {
|
||||
global.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ message: 'Email ou mot de passe incorrect' }, false, 401)
|
||||
)
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'mauvais-mot-de-passe')
|
||||
|
||||
expect(result).toEqual({ ok: false, error: 'Email ou mot de passe incorrect' })
|
||||
expect(setSessionValues).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should report a generic error when login fails without a JSON body', async () => {
|
||||
global.fetch = vi.fn().mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 500,
|
||||
json: () => Promise.reject(new Error('not json'))
|
||||
})
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'x')
|
||||
|
||||
expect(result).toEqual({ ok: false, error: 'Identifiants invalides' })
|
||||
})
|
||||
|
||||
it('should report an error when the keys request fails after a successful login', async () => {
|
||||
global.fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse({ accessToken: 'jwt-token', user: { email: 'william@example.com' } })
|
||||
)
|
||||
.mockResolvedValueOnce(jsonResponse({ message: 'nope' }, false, 500))
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'password')
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: 'Connexion reussie mais impossible de recuperer les cles API'
|
||||
})
|
||||
})
|
||||
|
||||
it('should report a network error message when fetch throws', async () => {
|
||||
global.fetch = vi.fn().mockRejectedValue(new Error('network down'))
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'x')
|
||||
|
||||
expect(result).toEqual({ ok: false, error: 'network down' })
|
||||
})
|
||||
|
||||
it('should report a generic message when a non-Error value is thrown', async () => {
|
||||
global.fetch = vi.fn().mockRejectedValue('boom')
|
||||
|
||||
const result = await loginAndLoadKeys('william@example.com', 'x')
|
||||
|
||||
expect(result).toEqual({ ok: false, error: 'Erreur reseau inconnue' })
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,10 @@ const getPathForFile = vi.fn(() => 'C:\\fichier.txt')
|
||||
const showContextMenu = vi.fn()
|
||||
const getWindowBounds = vi.fn(async () => ({ x: 0, y: 0, width: 100, height: 100 }))
|
||||
const setWindowPosition = vi.fn()
|
||||
const getAuthStatus = vi.fn(async (): Promise<{ loggedIn: boolean; email: string | null }> => ({
|
||||
loggedIn: false,
|
||||
email: null
|
||||
}))
|
||||
|
||||
function setupWindowApi(): void {
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||
@@ -61,7 +65,8 @@ function setupWindowApi(): void {
|
||||
sendDroppedFiles,
|
||||
showContextMenu,
|
||||
getWindowBounds,
|
||||
setWindowPosition
|
||||
setWindowPosition,
|
||||
getAuthStatus
|
||||
}
|
||||
}
|
||||
|
||||
@@ -139,10 +144,23 @@ describe('<App />', () => {
|
||||
})
|
||||
|
||||
it('should request the context menu with the current listening/transcribing state', () => {
|
||||
// Faux par defaut (ecoute non activee tant qu'aucun compte n'est connecte, voir
|
||||
// getAuthStatus ci-dessus qui renvoie loggedIn: false).
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
fireEvent.contextMenu(container)
|
||||
expect(showContextMenu).toHaveBeenCalledWith(true, false)
|
||||
expect(showContextMenu).toHaveBeenCalledWith(false, false)
|
||||
})
|
||||
|
||||
it('should enable listening once getAuthStatus reports an existing session', async () => {
|
||||
getAuthStatus.mockResolvedValueOnce({ loggedIn: true, email: 'william@example.com' })
|
||||
render(<App />)
|
||||
const container = screen.getByTestId('avatar-viewer').parentElement!
|
||||
|
||||
await waitFor(() => {
|
||||
fireEvent.contextMenu(container)
|
||||
expect(showContextMenu).toHaveBeenCalledWith(true, false)
|
||||
})
|
||||
})
|
||||
|
||||
it('should start dragging the window on mouse down and stop on mouse up', async () => {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
|
||||
import LoginView from '../../../src/renderer/src/components/LoginView'
|
||||
|
||||
const login = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
;(window as unknown as { api: Record<string, unknown> }).api = { login }
|
||||
})
|
||||
|
||||
describe('LoginView', () => {
|
||||
it('should keep the submit button disabled until both fields are filled', () => {
|
||||
render(<LoginView />)
|
||||
|
||||
const submit = screen.getByRole('button', { name: 'Se connecter' })
|
||||
expect(submit).toBeDisabled()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'william@example.com' } })
|
||||
expect(submit).toBeDisabled()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Mot de passe'), { target: { value: 'password123' } })
|
||||
expect(submit).toBeEnabled()
|
||||
})
|
||||
|
||||
it('should call window.api.login with the trimmed email and show a success message', async () => {
|
||||
login.mockResolvedValue({ ok: true })
|
||||
render(<LoginView />)
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Email'), {
|
||||
target: { value: ' william@example.com ' }
|
||||
})
|
||||
fireEvent.change(screen.getByLabelText('Mot de passe'), { target: { value: 'password123' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Se connecter' }))
|
||||
|
||||
expect(login).toHaveBeenCalledWith('william@example.com', 'password123')
|
||||
await waitFor(() => expect(screen.getByText(/Connexion reussie/)).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('should display the error message returned by the API on failure', async () => {
|
||||
login.mockResolvedValue({ ok: false, error: 'Email ou mot de passe incorrect' })
|
||||
render(<LoginView />)
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'william@example.com' } })
|
||||
fireEvent.change(screen.getByLabelText('Mot de passe'), { target: { value: 'mauvais' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Se connecter' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Email ou mot de passe incorrect')
|
||||
)
|
||||
})
|
||||
|
||||
it('should display a generic error message when the IPC call itself rejects', async () => {
|
||||
login.mockRejectedValue(new Error('IPC down'))
|
||||
render(<LoginView />)
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'william@example.com' } })
|
||||
fireEvent.change(screen.getByLabelText('Mot de passe'), { target: { value: 'password123' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Se connecter' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('Erreur inattendue'))
|
||||
})
|
||||
|
||||
it('should not submit when the fields are empty', () => {
|
||||
render(<LoginView />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Se connecter' }))
|
||||
|
||||
expect(login).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,24 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { transcribeAudio } from '../../src/main/ai/elevenlabs'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { synthesizeSpeech, transcribeAudio } from '../../src/main/ai/elevenlabs'
|
||||
import { clearSession, setCurrentUserEmail } from '../../src/main/auth/session'
|
||||
|
||||
describe('transcribeAudio()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.ELEVENLABS_API_KEY = 'test-key'
|
||||
process.env.ELEVENLABS_VOICE_ID = 'test-voice'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSession()
|
||||
})
|
||||
|
||||
it('should throw when no user is logged in, even if a local API key is configured', async () => {
|
||||
clearSession()
|
||||
await expect(transcribeAudio(Buffer.from('audio'), 'audio/webm')).rejects.toThrow(
|
||||
/Connecte-toi/
|
||||
)
|
||||
})
|
||||
|
||||
it('should return the trimmed transcript when the API call succeeds', async () => {
|
||||
@@ -46,3 +60,36 @@ describe('transcribeAudio()', () => {
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('synthesizeSpeech()', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.ELEVENLABS_API_KEY = 'test-key'
|
||||
process.env.ELEVENLABS_VOICE_ID = 'test-voice'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSession()
|
||||
})
|
||||
|
||||
it('should throw when no user is logged in, even if a local voice id is configured', async () => {
|
||||
clearSession()
|
||||
await expect(synthesizeSpeech('bonjour')).rejects.toThrow(/Connecte-toi/)
|
||||
})
|
||||
|
||||
it('should return the audio buffer when the API call succeeds', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: true,
|
||||
arrayBuffer: () => Promise.resolve(new Uint8Array([1, 2, 3]).buffer)
|
||||
} as Response)
|
||||
|
||||
const result = await synthesizeSpeech('bonjour')
|
||||
expect(Buffer.from(result)).toEqual(Buffer.from([1, 2, 3]))
|
||||
})
|
||||
|
||||
it('should throw when the voice id is missing', async () => {
|
||||
delete process.env.ELEVENLABS_VOICE_ID
|
||||
await expect(synthesizeSpeech('bonjour')).rejects.toThrow(/ELEVENLABS_VOICE_ID/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
class FakeWebContents extends EventEmitter {}
|
||||
|
||||
class FakeBrowserWindow extends EventEmitter {
|
||||
webContents = new FakeWebContents()
|
||||
show = vi.fn()
|
||||
focus = vi.fn()
|
||||
setAlwaysOnTop = vi.fn()
|
||||
loadURL = vi.fn()
|
||||
loadFile = vi.fn()
|
||||
close = vi.fn()
|
||||
destroyed = false
|
||||
isDestroyed(): boolean {
|
||||
return this.destroyed
|
||||
}
|
||||
}
|
||||
|
||||
let lastWindow: FakeBrowserWindow | null = null
|
||||
function createBrowserWindow(): FakeBrowserWindow {
|
||||
const window = new FakeBrowserWindow()
|
||||
lastWindow = window
|
||||
return window
|
||||
}
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
BrowserWindow: vi.fn(createBrowserWindow)
|
||||
}))
|
||||
|
||||
const { openLoginWindow, closeLoginWindow } = await import('../../src/main/auth/loginWindow')
|
||||
|
||||
describe('loginWindow', () => {
|
||||
beforeEach(() => {
|
||||
lastWindow?.emit('closed')
|
||||
vi.clearAllMocks()
|
||||
lastWindow = null
|
||||
})
|
||||
|
||||
describe('openLoginWindow()', () => {
|
||||
it('should create and show a window loading the #login hash', () => {
|
||||
openLoginWindow()
|
||||
|
||||
expect(lastWindow?.show).not.toHaveBeenCalled()
|
||||
expect(lastWindow?.loadFile).toHaveBeenCalledWith(
|
||||
expect.stringContaining('index.html'),
|
||||
expect.objectContaining({ hash: 'login' })
|
||||
)
|
||||
})
|
||||
|
||||
it('should reuse the existing window and bring it to front on a second call', () => {
|
||||
openLoginWindow()
|
||||
const firstWindow = lastWindow
|
||||
openLoginWindow()
|
||||
|
||||
expect(lastWindow).toBe(firstWindow)
|
||||
expect(firstWindow?.show).toHaveBeenCalled()
|
||||
expect(firstWindow?.focus).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should create a new window once the previous one was closed', () => {
|
||||
openLoginWindow()
|
||||
const firstWindow = lastWindow
|
||||
firstWindow?.emit('closed')
|
||||
|
||||
openLoginWindow()
|
||||
|
||||
expect(lastWindow).not.toBe(firstWindow)
|
||||
})
|
||||
})
|
||||
|
||||
describe('closeLoginWindow()', () => {
|
||||
it('should close the window when one is open', () => {
|
||||
openLoginWindow()
|
||||
closeLoginWindow()
|
||||
|
||||
expect(lastWindow?.close).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should do nothing when no window is open', () => {
|
||||
expect(() => closeLoginWindow()).not.toThrow()
|
||||
})
|
||||
|
||||
it('should do nothing when the window is already destroyed', () => {
|
||||
openLoginWindow()
|
||||
lastWindow!.destroyed = true
|
||||
|
||||
closeLoginWindow()
|
||||
|
||||
expect(lastWindow?.close).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { setCurrentUserEmail, clearSession } from '../../src/main/auth/session'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
@@ -71,6 +72,11 @@ describe('getAssistantReply()', () => {
|
||||
currentMode = 'basic'
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSession()
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
@@ -205,6 +211,7 @@ describe('getAssistantReply() — garde-fous du pipeline Coach', () => {
|
||||
currentMode = 'coach'
|
||||
getSubjectLevel.mockReturnValue(null)
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
currentSkills = [
|
||||
{
|
||||
name: 'research_topic',
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import {
|
||||
clearSession,
|
||||
getConfigValue,
|
||||
getCurrentUserEmail,
|
||||
isLoggedIn,
|
||||
setCurrentUserEmail,
|
||||
setSessionValues
|
||||
} from '../../src/main/auth/session'
|
||||
|
||||
describe('session', () => {
|
||||
const originalEnv = process.env.OPENROUTER_API_KEY
|
||||
|
||||
beforeEach(() => {
|
||||
clearSession()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSession()
|
||||
if (originalEnv === undefined) delete process.env.OPENROUTER_API_KEY
|
||||
else process.env.OPENROUTER_API_KEY = originalEnv
|
||||
})
|
||||
|
||||
it('should report not logged in and fall back to process.env before any session is set', () => {
|
||||
process.env.OPENROUTER_API_KEY = 'env-value'
|
||||
|
||||
expect(isLoggedIn()).toBe(false)
|
||||
expect(getCurrentUserEmail()).toBeNull()
|
||||
expect(getConfigValue('OPENROUTER_API_KEY')).toBe('env-value')
|
||||
})
|
||||
|
||||
it('should return the session value instead of process.env once set', () => {
|
||||
process.env.OPENROUTER_API_KEY = 'env-value'
|
||||
setSessionValues(new Map([['OPENROUTER_API_KEY', 'session-value']]))
|
||||
|
||||
expect(getConfigValue('OPENROUTER_API_KEY')).toBe('session-value')
|
||||
})
|
||||
|
||||
it('should report logged in with the given email once set', () => {
|
||||
setCurrentUserEmail('william@example.com')
|
||||
|
||||
expect(isLoggedIn()).toBe(true)
|
||||
expect(getCurrentUserEmail()).toBe('william@example.com')
|
||||
})
|
||||
|
||||
it('should clear both the session values and the logged-in state', () => {
|
||||
setSessionValues(new Map([['OPENROUTER_API_KEY', 'session-value']]))
|
||||
setCurrentUserEmail('william@example.com')
|
||||
|
||||
clearSession()
|
||||
|
||||
expect(isLoggedIn()).toBe(false)
|
||||
expect(getCurrentUserEmail()).toBeNull()
|
||||
expect(getConfigValue('OPENROUTER_API_KEY')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should return undefined when neither session nor process.env have the variable', () => {
|
||||
delete process.env.SOME_VAR_THAT_DOES_NOT_EXIST
|
||||
expect(getConfigValue('SOME_VAR_THAT_DOES_NOT_EXIST')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user