fix(ci): bump Node to 22 for node:sqlite, move SonarQube off the deploy pipeline #1
@@ -6,33 +6,87 @@
|
||||
|
||||
## 1. Contexte du projet
|
||||
|
||||
Max est une application de bureau (Windows, Mac, Linux) et mobile (Android) construite avec :
|
||||
Max est une application de bureau (Windows, Mac, Linux) construite avec Electron + React TypeScript. Max est **exclusivement un coach de formation pour freelances**. Il n'y a plus de mode Assistant ni de sélection de mode — Max démarre directement en mode Coach.
|
||||
|
||||
- **Electron 28+** — shell desktop
|
||||
- **React 18 + TypeScript 5** — interface utilisateur
|
||||
- **Vite** — bundler
|
||||
- **Three.js + GLTFLoader** — rendu 3D de l'avatar
|
||||
- **Zustand** — state management
|
||||
- **SQLite (better-sqlite3)** — stockage local
|
||||
- **OpenRouter + DeepSeek** — LLM via function calling
|
||||
- **ElevenLabs** — TTS + STT
|
||||
- **WebSocket + desktopCapturer** — captures d'écran (mode Coach)
|
||||
### Stack technique
|
||||
|
||||
L'app propose deux modes payants :
|
||||
| Couche | Technologie |
|
||||
| --- | --- |
|
||||
| Desktop shell | Electron 28+ |
|
||||
| UI | React 18 + TypeScript 5 + Vite |
|
||||
| Avatar 3D | Three.js + GLTFLoader + AnimationMixer |
|
||||
| State management | Zustand |
|
||||
| LLM | OpenRouter + DeepSeek (principal) + Qwen (secours) |
|
||||
| TTS + STT | ElevenLabs (proxy backend) |
|
||||
| Vision écran | desktopCapturer (Electron) |
|
||||
| Backend | NestJS 11 + Prisma 6 + PostgreSQL 16 (dossier `Max API/`) |
|
||||
| Base de données session | PostgreSQL via Prisma (côté backend) |
|
||||
|
||||
- **Mode Coach** — tuteur socratique avec vision écran, protocole pédagogique strict
|
||||
- **Mode Assistant** — gestion emails, veille, transcription, planification
|
||||
### Ce que Max fait
|
||||
|
||||
Max forme les freelances sur des compétences précises via un pipeline de 7 agents séquentiels. Chaque agent est un appel API séparé avec un system prompt ultra-spécialisé. Le résultat de chaque agent est stocké en base de données et passé au suivant.
|
||||
|
||||
### Pipeline des 7 agents
|
||||
|
||||
| # | Agent | Rôle |
|
||||
| --- | --- | --- |
|
||||
| 1 | Objectif | Dialogue socratique — révèle et valide l'objectif du freelance (3 piliers : sujet, but professionnel, durée) |
|
||||
| 2 | Recherche Cartographie | Recherche légère — carte des concepts clés du domaine pour construire l'évaluation de niveau |
|
||||
| 3 | Niveau | Évaluation du niveau réel via questions situationnelles (jamais un QCM) |
|
||||
| 4 | Recherche Approfondie | Corpus complet de sources fiables, parallélisé par sous-thème, calibré sur le niveau détecté |
|
||||
| 5 | Plan | Curriculum en N modules via Backward Design — objectif final d'abord, modules ensuite |
|
||||
| 6 | Rédacteur | Rédige un module à la fois — 6 sections obligatoires, méthode I Do/We Do/You Do |
|
||||
| 7 | Évaluation finale | Simulation professionnelle en deux temps : entretien client simulé + cas de mission réel |
|
||||
|
||||
### State machine de session
|
||||
|
||||
```typescript
|
||||
type SessionStatus =
|
||||
| 'objective_discovery' // Agent 1 — dialogue en cours
|
||||
| 'objective_validated' // Agent 1 — objectif confirmé par l'utilisateur
|
||||
| 'mapping' // Agent 2 — cartographie des concepts
|
||||
| 'level_assessment' // Agent 3 — évaluation du niveau
|
||||
| 'researching' // Agent 4 — recherche approfondie (parallèle)
|
||||
| 'planning' // Agent 5 — construction du curriculum
|
||||
| 'teaching' // Agent 6 — module en cours (currentModuleIndex)
|
||||
| 'evaluating' // Agent 7 — évaluation finale
|
||||
| 'completed' // Compétence validée
|
||||
```
|
||||
|
||||
Aucun agent ne démarre si l'agent précédent n'a pas produit et stocké son output en base. La state machine est gérée côté code — jamais côté LLM.
|
||||
|
||||
### Schéma de base de données — une table par agent
|
||||
|
||||
| Table | Agent | Champs principaux |
|
||||
| --- | --- | --- |
|
||||
| `session` | Mère | `session_id`, `user_id`, `status`, `created_at`, `updated_at` |
|
||||
| `session_objective` | Agent 1 | `subject`, `professional_goal`, `duration`, `trigger`, `validated_at` |
|
||||
| `session_concept_map` | Agent 2 | `concepts` (JSON), `sources_used`, `completed_at` |
|
||||
| `session_level_assessment` | Agent 3 | `questions_asked`, `user_answers`, `mastered_concepts`, `gap_concepts`, `unknown_concepts`, `overall_level`, `completed_at` |
|
||||
| `session_research` | Agent 4 | `corpus` (JSON), `subtopics_covered`, `sources_count`, `completed_at` |
|
||||
| `session_curriculum` | Agent 5 | `modules` (JSON), `total_modules`, `total_duration`, `validated_at` |
|
||||
| `session_module` | Agent 6 | `module_index`, `title`, `content` (JSON), `status`, `completed_at` |
|
||||
| `session_evaluation` | Agent 7 | `interview_score`, `practical_score`, `validated`, `feedback` (JSON), `completed_at` |
|
||||
| `freelance_profile` | Profil / Veille | `domains`, `stack`, `seniority_level`, `competences_acquired`, `veille_*` |
|
||||
| `veille_signal` | Agent Veille | `type`, `competence`, `sources`, `relevance_score`, `action_taken` |
|
||||
|
||||
---
|
||||
|
||||
## 2. Architecture obligatoire
|
||||
|
||||
### Monorepo
|
||||
|
||||
```
|
||||
/ ← Racine du dépôt Gitea
|
||||
Max Avatar/ ← Application Electron (toutes les commandes npm run depuis ici)
|
||||
src/
|
||||
main/ ← Electron main process (Node.js uniquement)
|
||||
index.ts
|
||||
ipc/ ← Handlers IPC — un fichier par domaine
|
||||
services/ ← Logique métier — un fichier par service
|
||||
agent.service.ts ← Orchestrateur du pipeline 7 agents
|
||||
openrouter.service.ts
|
||||
elevenlabs.service.ts
|
||||
utils/
|
||||
renderer/ ← React TypeScript (UI uniquement)
|
||||
App.tsx
|
||||
@@ -42,19 +96,61 @@ src/
|
||||
types/
|
||||
utils/
|
||||
shared/ ← Types et constantes partagés main + renderer
|
||||
types.ts
|
||||
types.ts ← SessionStatus, LearningObjective, AgentOutput...
|
||||
constants.ts
|
||||
preload/
|
||||
index.ts
|
||||
Max API/ ← Backend NestJS + Prisma + PostgreSQL
|
||||
src/
|
||||
common/
|
||||
crypto/ ← EncryptionService (AES-256-GCM pour les clés API)
|
||||
users/
|
||||
api-keys/ ← Gestion des clés OpenRouter par utilisateur (Provisioning API)
|
||||
sessions/ ← Pipeline agents, state machine, tables de session
|
||||
veille/ ← Agent de veille autonome
|
||||
prisma/
|
||||
schema.prisma ← Source de vérité du schéma BDD
|
||||
CLAUDE.md ← Ce fichier
|
||||
docs/ ← Documentation technique
|
||||
```
|
||||
|
||||
### Règle d'architecture absolue
|
||||
### Règles d'architecture absolues
|
||||
|
||||
- **Main process** : Node.js, accès filesystem, APIs externes, SQLite. Zéro UI.
|
||||
- **Main process** : Node.js, accès filesystem, appels backend Max API. Zéro UI.
|
||||
- **Renderer** : React, Three.js, UI. Zéro Node.js direct.
|
||||
- **Communication** : EXCLUSIVEMENT via IPC (contextBridge). Jamais d'import Node.js dans le renderer.
|
||||
- **Communication Electron** : EXCLUSIVEMENT via IPC (contextBridge). Jamais d'import Node.js dans le renderer.
|
||||
- **Appels LLM** : JAMAIS depuis le renderer. Toujours via IPC → main → Max API backend.
|
||||
- **Clés API** : JAMAIS dans le renderer, JAMAIS dans le main process. Elles vivent uniquement dans Max API, chiffrées AES-256-GCM.
|
||||
- **Shared** : uniquement des types TypeScript et des constantes. Zéro logique.
|
||||
|
||||
### Gestion des clés API par utilisateur
|
||||
|
||||
Les clés OpenRouter sont créées programmatiquement via la Provisioning API d'OpenRouter (une clé par utilisateur, limitée en crédits). ElevenLabs n'a pas de système équivalent — Max API agit en proxy avec la clé maître. Voir `Max API/src/api-keys/`.
|
||||
|
||||
### Comportements LLM à anticiper dans le code
|
||||
|
||||
Le code doit gérer ces comportements sans planter :
|
||||
|
||||
- **Réponse malformée** : HTTP 200 sans `choices` → vérifier l'existence de `choices` avant tout accès
|
||||
- **Ignore une instruction** : l'agent annonce une action sans l'exécuter → relance automatique ≤ 4 fois
|
||||
- **Bascule secours** : après 4 échecs, basculer sur Qwen avec le même contexte de conversation
|
||||
- **Texte dégénéré** : caractères non-latins → détection regex + relance
|
||||
- **Rate limit (429) / timeout (504)** : retry avec backoff exponentiel
|
||||
|
||||
```typescript
|
||||
// ✅ Pattern obligatoire pour tout appel LLM
|
||||
const response = await callWithFallback({
|
||||
primary: 'deepseek/deepseek-chat',
|
||||
fallback: 'qwen/qwen-2.5-72b-instruct',
|
||||
maxRetries: 4,
|
||||
messages,
|
||||
})
|
||||
|
||||
if (!response?.choices?.[0]?.message) {
|
||||
throw new ApiError('Réponse malformée', 'openrouter')
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. TypeScript — Règles strictes
|
||||
@@ -341,7 +437,7 @@ import type { Message } from '../../shared/types'
|
||||
## 8. Ce que l'IA NE doit PAS faire
|
||||
|
||||
| Action interdite | Alternative correcte |
|
||||
| ------------------------------------------------ | ----------------------------------------------------------- |
|
||||
| --- | --- |
|
||||
| Ajouter une dépendance npm sans justification | Signaler le besoin, expliquer pourquoi, attendre validation |
|
||||
| Modifier la structure des dossiers sans raison | Justifier la modification avant de la faire |
|
||||
| Utiliser `console.log` en production | Utiliser le logger du projet |
|
||||
@@ -352,6 +448,9 @@ import type { Message } from '../../shared/types'
|
||||
| Écrire du code sans gestion d'erreur | Toujours gérer les cas d'erreur explicitement |
|
||||
| Faire un commit fourre-tout | Un commit = une chose, message Conventional Commits |
|
||||
| Exposer des secrets dans les logs | Masquer les clés API dans les logs |
|
||||
| Appeler OpenRouter ou ElevenLabs depuis le renderer | Passer par IPC → main → Max API uniquement |
|
||||
| Stocker une clé API dans le main process Electron | Les clés vivent uniquement dans Max API chiffrées |
|
||||
| Avancer dans le pipeline sans vérifier le statut en base | Lire `session.status` avant chaque action agent |
|
||||
|
||||
---
|
||||
|
||||
@@ -359,9 +458,10 @@ import type { Message } from '../../shared/types'
|
||||
|
||||
### Avant de commencer une fonctionnalité
|
||||
|
||||
1. Vérifier que la branche est à jour (`git pull origin develop`)
|
||||
2. Créer une branche `feature/nom-de-la-fonctionnalite` depuis `develop`
|
||||
1. Vérifier que la branche est à jour (`git pull origin main`)
|
||||
2. Créer une branche `feature/nom-de-la-fonctionnalite` depuis `main`
|
||||
3. Comprendre les types existants dans `src/shared/types.ts` avant d'en créer de nouveaux
|
||||
4. Si la fonctionnalité touche le pipeline agent, lire `session.status` pour connaître l'état courant
|
||||
|
||||
### Pendant le développement
|
||||
|
||||
@@ -380,16 +480,17 @@ npm run test # tous les tests passent
|
||||
|
||||
Husky lance ces vérifications automatiquement — un commit échoue si l'une d'elles échoue.
|
||||
|
||||
verifie que le code ne contient pas d'érreur sur le sonarqube de dev (http://localhost:9000) avec le token suivant : squ_bc83f67e11ee5a4fd3c86ad19281e0c159062846
|
||||
Vérifier que le code ne contient pas d'erreur sur le SonarQube de dev (http://localhost:9000) avec le token : squ_bc83f67e11ee5a4fd3c86ad19281e0c159062846
|
||||
|
||||
### Format du message de commit
|
||||
|
||||
```
|
||||
feat(coach): ajouter la phase guidée We Do avec protocole interactif
|
||||
feat(agent-objectif): implémenter la validation des 3 piliers avec garde-fous
|
||||
|
||||
- Implémenter l'escalier d'indices en 5 niveaux
|
||||
- Ajouter la validation de réponse avant passage à l'étape suivante
|
||||
- Tests unitaires pour les 5 niveaux d'indices
|
||||
- Valider sujet (min 10 chars, non générique), but professionnel (min 20 chars), durée (1h-12 semaines)
|
||||
- Ajouter validation IA avec score de cohérence sur 3 dimensions
|
||||
- Stocker l'objectif validé en base avant de passer à l'Agent 2
|
||||
- Tests unitaires pour les cas de rejet et de validation
|
||||
```
|
||||
|
||||
---
|
||||
@@ -442,8 +543,8 @@ function animate() {
|
||||
## 12. Références rapides
|
||||
|
||||
| Besoin | Commande |
|
||||
| --------------------- | ----------------------- |
|
||||
| Lancer en dev | `npm run dev` |
|
||||
| --- | --- |
|
||||
| Lancer en dev (depuis Max Avatar/) | `npm run dev` |
|
||||
| Vérifier les types | `npm run typecheck` |
|
||||
| Corriger le lint | `npm run lint:fix` |
|
||||
| Lancer les tests | `npm run test` |
|
||||
@@ -453,3 +554,6 @@ function animate() {
|
||||
| Build Mac | `npm run build:mac` |
|
||||
| Build Linux | `npm run build:linux` |
|
||||
| Audit sécurité | `npm audit` |
|
||||
| Lancer le backend (depuis Max API/) | `npm run start:dev` |
|
||||
| Migration BDD | `npx prisma migrate dev` |
|
||||
| Seed BDD | `npm run prisma:seed` |
|
||||
@@ -11,6 +11,10 @@ DATABASE_URL="postgresql://max_api:changeme@localhost:5432/max_api?schema=public
|
||||
# Ne JAMAIS reutiliser la meme cle entre environnements, ne jamais la commiter.
|
||||
ENCRYPTION_KEY=
|
||||
|
||||
# Secret de signature des jetons JWT (route POST /auth/login). Generer avec la meme commande que
|
||||
# ENCRYPTION_KEY ci-dessus (longueur non contrainte, mais au moins 32 octets recommande).
|
||||
JWT_SECRET=
|
||||
|
||||
# --- Valeurs utilisees uniquement par prisma/seed.ts pour provisionner le premier utilisateur ---
|
||||
SEED_USER_FIRST_NAME=
|
||||
SEED_USER_LAST_NAME=
|
||||
|
||||
Generated
+130
-4
@@ -13,6 +13,7 @@
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "11.0.2",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@prisma/client": "6.19.3",
|
||||
@@ -2333,6 +2334,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/jwt": {
|
||||
"version": "11.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.2.tgz",
|
||||
"integrity": "sha512-rK8aE/3/Ma45gAWfCksAXUNbOoSOUudU0Kn3rT39htPF7wsYXtKfjALKeKKJbFrIWbLjsbqfXX5bIJNvgBugGA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/jsonwebtoken": "9.0.10",
|
||||
"jsonwebtoken": "9.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/mapped-types": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.1.1.tgz",
|
||||
@@ -3297,6 +3311,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
"integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/ms": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -3304,11 +3328,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
@@ -4766,6 +4795,12 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
@@ -5548,6 +5583,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
@@ -7763,6 +7807,49 @@
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^4.0.1",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/keyv": {
|
||||
"version": "4.5.4",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
||||
@@ -7865,6 +7952,42 @@
|
||||
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.memoize": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz",
|
||||
@@ -7879,6 +8002,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/log-symbols": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
|
||||
@@ -9259,7 +9388,6 @@
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9315,7 +9443,6 @@
|
||||
"version": "7.8.5",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
@@ -10516,7 +10643,6 @@
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "11.0.2",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@prisma/client": "6.19.3",
|
||||
|
||||
@@ -14,6 +14,7 @@ describe('ApiKeysController', () => {
|
||||
update: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
getDecryptedValue: jest.fn(),
|
||||
getAllDecrypted: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
|
||||
@@ -228,4 +228,39 @@ describe('ApiKeysService', () => {
|
||||
).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllDecrypted()', () => {
|
||||
it('should return a map of serviceName to decrypted value for every key of the user', async () => {
|
||||
prisma.apiKey.findMany.mockResolvedValue([
|
||||
dbApiKey,
|
||||
{
|
||||
...dbApiKey,
|
||||
id: 2,
|
||||
serviceName: 'elevenlabs_api_key',
|
||||
key: 'other-encrypted',
|
||||
},
|
||||
]);
|
||||
encryption.decrypt.mockImplementation((payload: string) =>
|
||||
payload === 'other-encrypted'
|
||||
? 'sk-el-plaintext'
|
||||
: 'sk-or-v1-plaintext',
|
||||
);
|
||||
|
||||
const result = await service.getAllDecrypted(1);
|
||||
|
||||
expect(prisma.apiKey.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: 1 },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
openrouter_api_key: 'sk-or-v1-plaintext',
|
||||
elevenlabs_api_key: 'sk-el-plaintext',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return an empty object when the user has no keys', async () => {
|
||||
prisma.apiKey.findMany.mockResolvedValue([]);
|
||||
|
||||
await expect(service.getAllDecrypted(1)).resolves.toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -112,6 +112,21 @@ export class ApiKeysService {
|
||||
return this.encryption.decrypt(apiKey.key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage interne uniquement (AuthService, apres connexion reussie) : dechiffre toutes les cles
|
||||
* d'un utilisateur en une fois, sous forme `{ serviceName: valeur en clair }`. Jamais expose par
|
||||
* une route generique /api-keys — uniquement via la route /auth/me/keys, protegee par JWT, qui
|
||||
* ne peut renvoyer que les cles de l'utilisateur authentifie lui-meme.
|
||||
*/
|
||||
async getAllDecrypted(userId: number): Promise<Record<string, string>> {
|
||||
const apiKeys = await this.prisma.apiKey.findMany({ where: { userId } });
|
||||
const result: Record<string, string> = {};
|
||||
for (const apiKey of apiKeys) {
|
||||
result[apiKey.serviceName] = this.encryption.decrypt(apiKey.key);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Ne jamais inclure la valeur de la cle (meme chiffree) dans une reponse HTTP. */
|
||||
private toResponse(apiKey: ApiKey): ApiKeyResponseDto {
|
||||
return {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ApiKeysModule } from './api-keys/api-keys.module';
|
||||
import { AppController } from './app.controller';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CryptoModule } from './common/crypto/crypto.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
@@ -13,6 +14,7 @@ import { UsersModule } from './users/users.module';
|
||||
CryptoModule,
|
||||
UsersModule,
|
||||
ApiKeysModule,
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
let service: Record<keyof AuthService, jest.Mock>;
|
||||
|
||||
beforeEach(async () => {
|
||||
service = {
|
||||
login: jest.fn(),
|
||||
getDecryptedKeysForUser: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
providers: [{ provide: AuthService, useValue: service }],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should delegate login() to the service', async () => {
|
||||
const dto = { email: 'william@example.com', password: 'x' };
|
||||
service.login.mockResolvedValue({ accessToken: 'jwt', user: { id: 1 } });
|
||||
|
||||
const result = await controller.login(dto);
|
||||
|
||||
expect(service.login).toHaveBeenCalledWith(dto);
|
||||
expect(result).toEqual({ accessToken: 'jwt', user: { id: 1 } });
|
||||
});
|
||||
|
||||
it('should delegate getMyKeys() to the service using the authenticated user id', async () => {
|
||||
service.getDecryptedKeysForUser.mockResolvedValue({
|
||||
openrouter_api_key: 'sk-or-v1-x',
|
||||
});
|
||||
const request = {
|
||||
user: { sub: 1, email: 'william@example.com' },
|
||||
} as AuthenticatedRequest;
|
||||
|
||||
const result = await controller.getMyKeys(request);
|
||||
|
||||
expect(service.getDecryptedKeysForUser).toHaveBeenCalledWith(1);
|
||||
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { LoginResponseDto } from './dto/login-response.dto';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: 'Authentifier un utilisateur et obtenir un jeton' })
|
||||
@ApiResponse({ status: HttpStatus.OK, type: LoginResponseDto })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
description: 'Email ou mot de passe incorrect',
|
||||
})
|
||||
login(@Body() dto: LoginDto): Promise<LoginResponseDto> {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@Get('me/keys')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Recuperer les cles API dechiffrees de l'utilisateur authentifie (service -> valeur en clair)",
|
||||
})
|
||||
@ApiResponse({ status: HttpStatus.OK })
|
||||
@ApiResponse({ status: HttpStatus.UNAUTHORIZED })
|
||||
getMyKeys(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
): Promise<Record<string, string>> {
|
||||
return this.authService.getDecryptedKeysForUser(request.user.sub);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ApiKeysModule } from '../api-keys/api-keys.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
|
||||
const ACCESS_TOKEN_TTL = '1h';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
ApiKeysModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.getOrThrow<string>('JWT_SECRET'),
|
||||
signOptions: { expiresIn: ACCESS_TOKEN_TTL },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
let usersService: { findByEmailForAuth: jest.Mock };
|
||||
let apiKeysService: { getAllDecrypted: jest.Mock };
|
||||
let jwtService: { signAsync: jest.Mock };
|
||||
|
||||
const dbUser = {
|
||||
id: 1,
|
||||
firstName: 'William',
|
||||
lastName: 'Vandal',
|
||||
email: 'william@example.com',
|
||||
password: '',
|
||||
createdAt: new Date('2026-01-01'),
|
||||
updatedAt: new Date('2026-01-01'),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
dbUser.password = await bcrypt.hash('le-bon-mot-de-passe', 12);
|
||||
|
||||
usersService = { findByEmailForAuth: jest.fn() };
|
||||
apiKeysService = { getAllDecrypted: jest.fn() };
|
||||
jwtService = { signAsync: jest.fn().mockResolvedValue('signed-jwt') };
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthService,
|
||||
{ provide: UsersService, useValue: usersService },
|
||||
{ provide: ApiKeysService, useValue: apiKeysService },
|
||||
{ provide: JwtService, useValue: jwtService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
describe('login()', () => {
|
||||
it('should return an access token and the user when the password matches', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||
|
||||
const result = await service.login({
|
||||
email: 'william@example.com',
|
||||
password: 'le-bon-mot-de-passe',
|
||||
});
|
||||
|
||||
expect(result.accessToken).toBe('signed-jwt');
|
||||
expect(result.user).not.toHaveProperty('password');
|
||||
expect(jwtService.signAsync).toHaveBeenCalledWith({
|
||||
sub: 1,
|
||||
email: 'william@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the email is unknown', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.login({ email: 'inconnu@example.com', password: 'x' }),
|
||||
).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the password is wrong', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||
|
||||
await expect(
|
||||
service.login({
|
||||
email: 'william@example.com',
|
||||
password: 'mauvais-mot-de-passe',
|
||||
}),
|
||||
).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDecryptedKeysForUser()', () => {
|
||||
it('should delegate to ApiKeysService.getAllDecrypted', async () => {
|
||||
apiKeysService.getAllDecrypted.mockResolvedValue({
|
||||
openrouter_api_key: 'sk-or-v1-x',
|
||||
});
|
||||
|
||||
const result = await service.getDecryptedKeysForUser(1);
|
||||
|
||||
expect(apiKeysService.getAllDecrypted).toHaveBeenCalledWith(1);
|
||||
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { LoginResponseDto } from './dto/login-response.dto';
|
||||
import { JwtPayload } from './jwt-payload.interface';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly apiKeysService: ApiKeysService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async login(dto: LoginDto): Promise<LoginResponseDto> {
|
||||
const user = await this.usersService.findByEmailForAuth(dto.email);
|
||||
// Message volontairement generique (ni "email inconnu" ni "mot de passe incorrect") : ne pas
|
||||
// confirmer a un attaquant qu'un email donne correspond a un compte existant.
|
||||
const invalidCredentials = (): never => {
|
||||
throw new UnauthorizedException('Email ou mot de passe incorrect');
|
||||
};
|
||||
if (!user) return invalidCredentials();
|
||||
|
||||
const passwordMatches = await bcrypt.compare(dto.password, user.password);
|
||||
if (!passwordMatches) return invalidCredentials();
|
||||
|
||||
const payload: JwtPayload = { sub: user.id, email: user.email };
|
||||
const accessToken = await this.jwtService.signAsync(payload);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Cles de l'utilisateur authentifie uniquement (userId extrait du JWT verifie, jamais du body). */
|
||||
getDecryptedKeysForUser(userId: number): Promise<Record<string, string>> {
|
||||
return this.apiKeysService.getAllDecrypted(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { UserResponseDto } from '../../users/dto/user-response.dto';
|
||||
|
||||
export class LoginResponseDto {
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Jeton JWT, a transmettre dans "Authorization: Bearer <token>".',
|
||||
})
|
||||
accessToken!: string;
|
||||
|
||||
@ApiProperty({ type: UserResponseDto })
|
||||
user!: UserResponseDto;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ example: 'william@example.com' })
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@ApiProperty({ example: 'un-mot-de-passe-robuste' })
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthenticatedRequest, JwtAuthGuard } from './jwt-auth.guard';
|
||||
|
||||
function createContext(authorization?: string): ExecutionContext {
|
||||
const request = { headers: { authorization } } as AuthenticatedRequest;
|
||||
return {
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
} as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
describe('JwtAuthGuard', () => {
|
||||
let guard: JwtAuthGuard;
|
||||
let jwtService: { verifyAsync: jest.Mock };
|
||||
|
||||
beforeEach(() => {
|
||||
jwtService = { verifyAsync: jest.fn() };
|
||||
guard = new JwtAuthGuard(jwtService as unknown as JwtService);
|
||||
});
|
||||
|
||||
it('should allow the request and attach the payload when the token is valid', async () => {
|
||||
jwtService.verifyAsync.mockResolvedValue({
|
||||
sub: 1,
|
||||
email: 'william@example.com',
|
||||
});
|
||||
const context = createContext('Bearer valid-token');
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
expect(jwtService.verifyAsync).toHaveBeenCalledWith('valid-token');
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when no Authorization header is present', async () => {
|
||||
const context = createContext(undefined);
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the header does not start with "Bearer "', async () => {
|
||||
const context = createContext('Basic abc');
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the token is invalid or expired', async () => {
|
||||
jwtService.verifyAsync.mockRejectedValue(new Error('expired'));
|
||||
const context = createContext('Bearer expired-token');
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import type { Request } from 'express';
|
||||
import type { JwtPayload } from './jwt-payload.interface';
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user: JwtPayload;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
const authHeader = request.headers.authorization;
|
||||
const token = authHeader?.startsWith('Bearer ')
|
||||
? authHeader.slice('Bearer '.length)
|
||||
: undefined;
|
||||
if (!token) throw new UnauthorizedException('Jeton manquant');
|
||||
|
||||
try {
|
||||
request.user = await this.jwtService.verifyAsync<JwtPayload>(token);
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Jeton invalide ou expire');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface JwtPayload {
|
||||
sub: number;
|
||||
email: string;
|
||||
}
|
||||
@@ -13,6 +13,7 @@ describe('UsersController', () => {
|
||||
findOne: jest.fn(),
|
||||
update: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
findByEmailForAuth: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
|
||||
@@ -201,4 +201,25 @@ describe('UsersService', () => {
|
||||
await expect(service.remove(1)).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByEmailForAuth()', () => {
|
||||
it('should return the full entity including the hashed password', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue(dbUser);
|
||||
|
||||
const result = await service.findByEmailForAuth('william@example.com');
|
||||
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
||||
where: { email: 'william@example.com' },
|
||||
});
|
||||
expect(result).toEqual(dbUser);
|
||||
});
|
||||
|
||||
it('should return null when no user matches', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.findByEmailForAuth('inconnu@example.com'),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -90,6 +90,14 @@ export class UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage interne uniquement (AuthService) : renvoie l'entite complete, mot de passe hache inclus,
|
||||
* pour verification lors de la connexion. Jamais expose directement via un controleur.
|
||||
*/
|
||||
async findByEmailForAuth(email: string): Promise<User | null> {
|
||||
return this.prisma.user.findUnique({ where: { email } });
|
||||
}
|
||||
|
||||
/** Jamais inclure le mot de passe (meme hache) dans une reponse HTTP. */
|
||||
private toResponse(user: User): UserResponseDto {
|
||||
return {
|
||||
|
||||
@@ -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,14 +179,47 @@ 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' },
|
||||
// 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() }
|
||||
@@ -190,7 +227,7 @@ app
|
||||
buildModeMenuItem('assistant', 'Mode Assistant', activeMode, [
|
||||
{
|
||||
label: transcribing ? 'Arreter la transcription' : 'Demarrer la transcription',
|
||||
type: 'checkbox',
|
||||
type: 'checkbox' as const,
|
||||
checked: transcribing,
|
||||
click: () => {
|
||||
const next = !transcribing
|
||||
@@ -198,7 +235,9 @@ app
|
||||
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,11 +144,24 @@ 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(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 () => {
|
||||
render(<App />)
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -173,8 +173,89 @@ Le scaffold par defaut de `@nestjs/cli` desactive `@typescript-eslint/no-explici
|
||||
|
||||
### Points non traites dans cette etape (pour plus tard)
|
||||
|
||||
- Pas d'authentification/autorisation sur les routes (`POST /users`, `/api-keys`, etc. sont
|
||||
ouvertes) : a traiter avant toute exposition publique du serveur.
|
||||
- Pas d'authentification/autorisation sur les routes `/users` et `/api-keys` (seul `/auth/*` est
|
||||
protege) : a traiter avant toute exposition publique du serveur.
|
||||
- Pas de pipeline CI dedie a `Max API` (le `.gitea/workflows/ci.yml` actuel ne couvre que
|
||||
`Max Avatar`) : a mettre en place dans une etape ulterieure.
|
||||
- Pas de Dockerfile pour `Max API` elle-meme (seul PostgreSQL est dockerise pour l'instant).
|
||||
|
||||
---
|
||||
|
||||
## Etape 3 — Page de connexion dans Max Avatar + authentification JWT (fait)
|
||||
|
||||
### Pourquoi
|
||||
|
||||
Jusqu'ici, `Max API` detenait les cles chiffrees mais rien ne les reliait a l'application
|
||||
desktop : Max Avatar continuait de lire son `.env` local. Cette etape relie les deux : un
|
||||
utilisateur se connecte depuis Max Avatar, et les cles de son compte remplacent celles du `.env`
|
||||
pour la duree de la session (pas de session persistee entre deux lancements, voir discussion
|
||||
precedente).
|
||||
|
||||
### Cote Max API — authentification
|
||||
|
||||
- `AuthModule` (`src/auth/`) : `POST /auth/login` (email + mot de passe, verifie via bcrypt,
|
||||
renvoie un JWT signe `{ sub, email }`, expiration 1h) et `GET /auth/me/keys` (protege par
|
||||
`JwtAuthGuard`, renvoie les cles **dechiffrees** de l'utilisateur authentifie uniquement, sous
|
||||
forme `{ serviceName: valeur }`).
|
||||
- `JwtAuthGuard` lit le header `Authorization: Bearer <token>`, verifie le JWT via `@nestjs/jwt`
|
||||
(`@nestjs/jwt@11.0.2`, pas la v12 qui est ESM-only et casse Jest — meme probleme deja rencontre
|
||||
avec `@nestjs/config`).
|
||||
- Nouvelles methodes internes (jamais exposees directement par un controleur) :
|
||||
`UsersService.findByEmailForAuth()` (entite complete, mot de passe hache inclus, pour la
|
||||
verification de connexion) et `ApiKeysService.getAllDecrypted(userId)` (dechiffre toutes les
|
||||
cles d'un utilisateur en une fois).
|
||||
- Message d'erreur volontairement generique ("Email ou mot de passe incorrect") que l'email
|
||||
existe ou non, pour ne pas confirmer a un attaquant qu'un compte existe.
|
||||
- `JWT_SECRET` ajoute a `.env`/`.env.example`.
|
||||
|
||||
### Cote Max Avatar — connexion et utilisation des cles
|
||||
|
||||
- **Menu contextuel** : statut de connexion affiche en premier (en guise de titre, Electron n'a
|
||||
pas de vrai titre de menu independant des items) — "Me connecter" si deconnecte, "Connecte :
|
||||
email" + "Se deconnecter" sinon.
|
||||
- **Ecoute vocale et modes (Basic/Coach/Assistant) inaccessibles sans connexion** : l'ecoute reste
|
||||
visible mais grisee et forcee decochee ; les 3 modes sont entierement retires du menu (pas
|
||||
seulement desactives) tant qu'aucun compte n'est connecte. A la deconnexion, si l'utilisateur
|
||||
etait en Coach/Assistant, le mode est repasse de force a Basic (sinon il resterait coince dans
|
||||
un mode qu'il ne peut plus desactiver, le menu ne montrant plus ces options).
|
||||
- **Garde-fou cote serveur, pas seulement visuel** : `requireLoggedIn()` (nouvelle fonction dans
|
||||
`src/main/auth/session.ts`) est appele au tout debut de `getAssistantReply()`,
|
||||
`transcribeAudio()` et `synthesizeSpeech()`. Sans ce garde-fou explicite, un `.env` local gardant
|
||||
de vraies cles (present pendant tout le developpement de cette fonctionnalite) aurait continue
|
||||
de faire fonctionner le chat/la voix sans connexion, par simple repli silencieux sur le `.env` —
|
||||
bug reellement observe en testant manuellement avant ce correctif.
|
||||
- `src/main/auth/session.ts` : etat en memoire uniquement (userEmail + Map de valeurs), jamais
|
||||
ecrit sur disque. `getConfigValue(envVarName)` renvoie la valeur de session si connecte, sinon le
|
||||
`.env` local (utile en dev sans connexion, mais ne contourne plus le garde-fou `requireLoggedIn`
|
||||
ci-dessus).
|
||||
- `src/main/auth/authClient.ts` : `POST /auth/login` puis `GET /auth/me/keys` en un seul
|
||||
enchainement (le JWT n'est jamais conserve au-dela de cet appel), mappe les noms de service
|
||||
backend (`openrouter_api_key`, ...) vers les noms de variable d'environnement attendus par
|
||||
`openrouter.ts`/`elevenlabs.ts`.
|
||||
- `src/main/auth/loginWindow.ts` : fenetre singleton (meme patron que les autres fenetres
|
||||
secondaires), charge `#login`. `src/renderer/src/components/LoginView.tsx` : formulaire email/
|
||||
mot de passe minimal.
|
||||
- A la connexion reussie, l'ecoute vocale est automatiquement reactivee (comme avant l'ajout de ce
|
||||
garde-fou) ; a la deconnexion, elle est explicitement desactivee.
|
||||
- `window.api.getAuthStatus()` (nouvel IPC `get-auth-status`) permet au renderer de connaitre
|
||||
l'etat de connexion au demarrage, pour initialiser `listening` correctement (faux par defaut,
|
||||
vrai seulement si deja connecte).
|
||||
|
||||
### Verification effectuee
|
||||
|
||||
- Backend : `npm run typecheck`/`lint`/`test:coverage` OK (64 tests, 100% stmts/functions/lines,
|
||||
81% branches), flux complet teste en conditions reelles (Postgres dockerise + serveur Nest
|
||||
lance) : mauvais mot de passe → 401, token manquant → 401, connexion correcte → JWT + cles
|
||||
dechiffrees recues avec les 4 noms de service attendus.
|
||||
- Max Avatar : `npm run typecheck`/`lint`/`test:coverage` OK (500 tests, ~91%/77%/91%/93%),
|
||||
testee manuellement en conditions reelles par l'utilisateur sur son propre poste (session
|
||||
d'automatisation non interactive, ne peut pas interagir avec l'UI Electron) : menu, connexion,
|
||||
deconnexion, blocage reel de la voix sans connexion (meme avec un `.env` local valide).
|
||||
|
||||
### Points non traites dans cette etape (pour plus tard)
|
||||
|
||||
- `dropped-files` et `evaluate-module` (deux autres chemins qui appellent `getAssistantReply`)
|
||||
ne remontent leur erreur qu'en `console.error`, pas a l'utilisateur : `voice-turn` est le seul
|
||||
chemin dont l'erreur "connecte-toi" s'affiche visiblement (bannière d'erreur existante).
|
||||
- Pas de refresh automatique des cles si elles changent cote backend pendant que Max Avatar est
|
||||
deja connecte (il faudrait se deconnecter/reconnecter).
|
||||
|
||||
Reference in New Issue
Block a user