Compare commits
11
Commits
e9690a49f9
...
866bcd780f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
866bcd780f | ||
|
|
885e24d037 | ||
|
|
605f9070a8 | ||
|
|
037faa72f0 | ||
|
|
1c2f002eb3 | ||
|
|
60e2fb26af | ||
|
|
9a66ff7f17 | ||
|
|
478ffa59ce | ||
|
|
09ae70cb36 | ||
|
|
a771883bf5 | ||
|
|
0e7b7092ae |
+5
-11
@@ -1,11 +1,5 @@
|
|||||||
# OpenRouter (chat + function calling) - https://openrouter.ai/keys
|
# Variables lues par docker-compose.yml a la racine du depot (service "postgres").
|
||||||
OPENROUTER_API_KEY=
|
# Copier ce fichier en ".env" (jamais commite) et renseigner de vraies valeurs.
|
||||||
OPENROUTER_MODEL=deepseek/deepseek-chat
|
POSTGRES_USER=max_api
|
||||||
# Bascule automatique si le modele principal est temporairement indisponible (rate-limit/5xx)
|
POSTGRES_PASSWORD=
|
||||||
OPENROUTER_FALLBACK_MODEL=qwen/qwen-2.5-72b-instruct
|
POSTGRES_DB=max_api
|
||||||
# Modele vision (analyse d'ecran / camera) - doit accepter des images en entree
|
|
||||||
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=
|
|
||||||
|
|||||||
+15
-11
@@ -1,22 +1,33 @@
|
|||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
# Tourne uniquement sur la Pull Request, avant le clic sur "Merge" (seul moment ou un check peut
|
||||||
branches: [develop, main]
|
# encore bloquer la fusion). Un "push" sur main declenche par le merge lui-meme arriverait trop
|
||||||
|
# tard pour bloquer quoi que ce soit.
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [develop, main]
|
branches: [main]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
quality:
|
quality:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
# Le code de l'app vit dans le sous-dossier "Max Avatar" (la racine du depot garde CLAUDE.md,
|
||||||
|
# README.md, docs/, .gitea/, .husky/, .vscode/, .claude/, docker-compose*.yml).
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: Max Avatar
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
# node:sqlite (coachStore.ts, memory/store.ts, meetingStore.ts) exige Node >= 22.5, mais
|
||||||
|
# Vite/Rolldown ne le reconnaissent comme built-in qu'a partir de Node 24 (absent de
|
||||||
|
# module.builtinModules avant, bien que isBuiltin() le reconnaisse deja) : sous Node 22,
|
||||||
|
# la transformation plante avec "Cannot bundle Node.js built-in node:sqlite".
|
||||||
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
|
cache-dependency-path: 'Max Avatar/package-lock.json'
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci --ignore-scripts
|
run: npm ci --ignore-scripts
|
||||||
@@ -32,10 +43,3 @@ jobs:
|
|||||||
|
|
||||||
- name: Security audit
|
- name: Security audit
|
||||||
run: npm audit --audit-level=high
|
run: npm audit --audit-level=high
|
||||||
|
|
||||||
- name: SonarQube analysis
|
|
||||||
if: ${{ secrets.SONAR_TOKEN != '' }}
|
|
||||||
uses: sonarsource/sonarqube-scan-action@master
|
|
||||||
env:
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
|
|
||||||
|
|||||||
@@ -8,42 +8,54 @@ on:
|
|||||||
jobs:
|
jobs:
|
||||||
build-windows:
|
build-windows:
|
||||||
runs-on: windows-latest
|
runs-on: windows-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: Max Avatar
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
# node:sqlite (coachStore.ts, memory/store.ts, meetingStore.ts) exige Node >= 22.5, mais Vite/Rolldown ne le reconnait comme built-in qu a partir de Node 24.
|
||||||
|
node-version: '24'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run build:win
|
- run: npm run build:win
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: max-windows
|
name: max-windows
|
||||||
path: dist/*.exe
|
path: Max Avatar/dist/*.exe
|
||||||
|
|
||||||
build-mac:
|
build-mac:
|
||||||
runs-on: macos-latest
|
runs-on: macos-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: Max Avatar
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
# node:sqlite (coachStore.ts, memory/store.ts, meetingStore.ts) exige Node >= 22.5, mais Vite/Rolldown ne le reconnait comme built-in qu a partir de Node 24.
|
||||||
|
node-version: '24'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run build:mac
|
- run: npm run build:mac
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: max-mac
|
name: max-mac
|
||||||
path: dist/*.dmg
|
path: Max Avatar/dist/*.dmg
|
||||||
|
|
||||||
build-linux:
|
build-linux:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: Max Avatar
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '20'
|
# node:sqlite (coachStore.ts, memory/store.ts, meetingStore.ts) exige Node >= 22.5, mais Vite/Rolldown ne le reconnait comme built-in qu a partir de Node 24.
|
||||||
|
node-version: '24'
|
||||||
- run: npm ci
|
- run: npm ci
|
||||||
- run: npm run build:linux
|
- run: npm run build:linux
|
||||||
- uses: actions/upload-artifact@v4
|
- uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: max-linux
|
name: max-linux
|
||||||
path: dist/*.AppImage
|
path: Max Avatar/dist/*.AppImage
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
name: SonarQube (cron)
|
||||||
|
|
||||||
|
# Analyse SonarQube isolee du pipeline de deploiement : ne bloque jamais la CI ni les releases.
|
||||||
|
# Declenchee uniquement par cron (et manuellement via "Run workflow"), jamais sur push/PR.
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 3 * * *'
|
||||||
|
workflow_dispatch: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
sonarqube:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: ${{ secrets.SONAR_TOKEN != '' }}
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: Max Avatar
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '24'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: 'Max Avatar/package-lock.json'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci --ignore-scripts
|
||||||
|
|
||||||
|
- name: Unit tests + coverage
|
||||||
|
run: npm run test:coverage
|
||||||
|
|
||||||
|
- name: SonarQube analysis
|
||||||
|
uses: sonarsource/sonarqube-scan-action@master
|
||||||
|
with:
|
||||||
|
projectBaseDir: Max Avatar
|
||||||
|
env:
|
||||||
|
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||||
|
SONAR_HOST_URL: ${{ secrets.SONAR_HOST_URL }}
|
||||||
+1
-6
@@ -1,12 +1,7 @@
|
|||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
out
|
out
|
||||||
|
coverage
|
||||||
.DS_Store
|
.DS_Store
|
||||||
.eslintcache
|
|
||||||
*.log*
|
|
||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
coverage
|
|
||||||
playwright-report
|
|
||||||
test-results
|
|
||||||
.husky/_
|
|
||||||
|
|||||||
+1
-1
@@ -1 +1 @@
|
|||||||
npx lint-staged
|
cd "Max Avatar" && npx lint-staged
|
||||||
|
|||||||
Vendored
+4
-4
@@ -5,10 +5,10 @@
|
|||||||
"name": "Debug Main Process",
|
"name": "Debug Main Process",
|
||||||
"type": "node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"cwd": "${workspaceRoot}",
|
"cwd": "${workspaceRoot}/Max Avatar",
|
||||||
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron-vite",
|
"runtimeExecutable": "${workspaceRoot}/Max Avatar/node_modules/.bin/electron-vite",
|
||||||
"windows": {
|
"windows": {
|
||||||
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron-vite.cmd"
|
"runtimeExecutable": "${workspaceRoot}/Max Avatar/node_modules/.bin/electron-vite.cmd"
|
||||||
},
|
},
|
||||||
"runtimeArgs": ["--sourcemap"],
|
"runtimeArgs": ["--sourcemap"],
|
||||||
"env": {
|
"env": {
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
"port": 9222,
|
"port": 9222,
|
||||||
"request": "attach",
|
"request": "attach",
|
||||||
"type": "chrome",
|
"type": "chrome",
|
||||||
"webRoot": "${workspaceFolder}/src/renderer",
|
"webRoot": "${workspaceFolder}/Max Avatar/src/renderer",
|
||||||
"timeout": 60000,
|
"timeout": 60000,
|
||||||
"presentation": {
|
"presentation": {
|
||||||
"hidden": true
|
"hidden": true
|
||||||
|
|||||||
@@ -6,33 +6,87 @@
|
|||||||
|
|
||||||
## 1. Contexte du projet
|
## 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
|
### Stack technique
|
||||||
- **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)
|
|
||||||
|
|
||||||
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
|
### Ce que Max fait
|
||||||
- **Mode Assistant** — gestion emails, veille, transcription, planification
|
|
||||||
|
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
|
## 2. Architecture obligatoire
|
||||||
|
|
||||||
|
### Monorepo
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
/ ← 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)
|
main/ ← Electron main process (Node.js uniquement)
|
||||||
index.ts
|
index.ts
|
||||||
ipc/ ← Handlers IPC — un fichier par domaine
|
ipc/ ← Handlers IPC — un fichier par domaine
|
||||||
services/ ← Logique métier — un fichier par service
|
services/ ← Logique métier — un fichier par service
|
||||||
|
agent.service.ts ← Orchestrateur du pipeline 7 agents
|
||||||
|
openrouter.service.ts
|
||||||
|
elevenlabs.service.ts
|
||||||
utils/
|
utils/
|
||||||
renderer/ ← React TypeScript (UI uniquement)
|
renderer/ ← React TypeScript (UI uniquement)
|
||||||
App.tsx
|
App.tsx
|
||||||
@@ -42,19 +96,61 @@ src/
|
|||||||
types/
|
types/
|
||||||
utils/
|
utils/
|
||||||
shared/ ← Types et constantes partagés main + renderer
|
shared/ ← Types et constantes partagés main + renderer
|
||||||
types.ts
|
types.ts ← SessionStatus, LearningObjective, AgentOutput...
|
||||||
constants.ts
|
constants.ts
|
||||||
preload/
|
preload/
|
||||||
index.ts
|
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.
|
- **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.
|
- **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
|
## 3. TypeScript — Règles strictes
|
||||||
@@ -341,7 +437,7 @@ import type { Message } from '../../shared/types'
|
|||||||
## 8. Ce que l'IA NE doit PAS faire
|
## 8. Ce que l'IA NE doit PAS faire
|
||||||
|
|
||||||
| Action interdite | Alternative correcte |
|
| Action interdite | Alternative correcte |
|
||||||
| ------------------------------------------------ | ----------------------------------------------------------- |
|
| --- | --- |
|
||||||
| Ajouter une dépendance npm sans justification | Signaler le besoin, expliquer pourquoi, attendre validation |
|
| 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 |
|
| Modifier la structure des dossiers sans raison | Justifier la modification avant de la faire |
|
||||||
| Utiliser `console.log` en production | Utiliser le logger du projet |
|
| 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 |
|
| É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 |
|
| 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 |
|
| 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é
|
### Avant de commencer une fonctionnalité
|
||||||
|
|
||||||
1. Vérifier que la branche est à jour (`git pull origin develop`)
|
1. Vérifier que la branche est à jour (`git pull origin main`)
|
||||||
2. Créer une branche `feature/nom-de-la-fonctionnalite` depuis `develop`
|
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
|
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
|
### Pendant le développement
|
||||||
|
|
||||||
@@ -380,14 +480,17 @@ npm run test # tous les tests passent
|
|||||||
|
|
||||||
Husky lance ces vérifications automatiquement — un commit échoue si l'une d'elles échoue.
|
Husky lance ces vérifications automatiquement — un commit échoue si l'une d'elles échoue.
|
||||||
|
|
||||||
|
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
|
### 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
|
- Valider sujet (min 10 chars, non générique), but professionnel (min 20 chars), durée (1h-12 semaines)
|
||||||
- Ajouter la validation de réponse avant passage à l'étape suivante
|
- Ajouter validation IA avec score de cohérence sur 3 dimensions
|
||||||
- Tests unitaires pour les 5 niveaux d'indices
|
- Stocker l'objectif validé en base avant de passer à l'Agent 2
|
||||||
|
- Tests unitaires pour les cas de rejet et de validation
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -440,8 +543,8 @@ function animate() {
|
|||||||
## 12. Références rapides
|
## 12. Références rapides
|
||||||
|
|
||||||
| Besoin | Commande |
|
| Besoin | Commande |
|
||||||
| --------------------- | ----------------------- |
|
| --- | --- |
|
||||||
| Lancer en dev | `npm run dev` |
|
| Lancer en dev (depuis Max Avatar/) | `npm run dev` |
|
||||||
| Vérifier les types | `npm run typecheck` |
|
| Vérifier les types | `npm run typecheck` |
|
||||||
| Corriger le lint | `npm run lint:fix` |
|
| Corriger le lint | `npm run lint:fix` |
|
||||||
| Lancer les tests | `npm run test` |
|
| Lancer les tests | `npm run test` |
|
||||||
@@ -451,3 +554,6 @@ function animate() {
|
|||||||
| Build Mac | `npm run build:mac` |
|
| Build Mac | `npm run build:mac` |
|
||||||
| Build Linux | `npm run build:linux` |
|
| Build Linux | `npm run build:linux` |
|
||||||
| Audit sécurité | `npm audit` |
|
| 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` |
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Copier ce fichier en ".env" (jamais commite) et renseigner de vraies valeurs.
|
||||||
|
|
||||||
|
PORT=3000
|
||||||
|
|
||||||
|
# Doit correspondre a POSTGRES_USER/POSTGRES_PASSWORD/POSTGRES_DB du ".env" a la racine du depot
|
||||||
|
# (lu par docker-compose.yml pour le service "postgres").
|
||||||
|
DATABASE_URL="postgresql://max_api:changeme@localhost:5432/max_api?schema=public"
|
||||||
|
|
||||||
|
# Cle maitresse de chiffrement des cles API stockees (AES-256-GCM) : exactement 32 octets en
|
||||||
|
# hexadecimal (64 caracteres). Generer avec : node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||||
|
# 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=
|
||||||
|
SEED_USER_EMAIL=
|
||||||
|
SEED_USER_PASSWORD=
|
||||||
|
SEED_ELEVENLABS_API_KEY=
|
||||||
|
SEED_ELEVENLABS_VOICE_ID=
|
||||||
|
SEED_OPENROUTER_API_KEY=
|
||||||
|
SEED_OPENROUTER_MODEL=
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
coverage
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
*.log*
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": true,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ npm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ npm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ npm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ npm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ npm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ npm install -g @nestjs/mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
// @ts-check
|
||||||
|
import eslint from '@eslint/js';
|
||||||
|
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||||
|
import eslintPluginSecurity from 'eslint-plugin-security';
|
||||||
|
import globals from 'globals';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
{
|
||||||
|
ignores: ['eslint.config.mjs'],
|
||||||
|
},
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommendedTypeChecked,
|
||||||
|
eslintPluginSecurity.configs.recommended,
|
||||||
|
eslintPluginPrettierRecommended,
|
||||||
|
{
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
...globals.jest,
|
||||||
|
},
|
||||||
|
sourceType: 'commonjs',
|
||||||
|
parserOptions: {
|
||||||
|
projectService: true,
|
||||||
|
tsconfigRootDir: import.meta.dirname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
rules: {
|
||||||
|
// CLAUDE.md interdit tout `any`, explicite ou implicite, et toute promesse non geree :
|
||||||
|
// contrairement au defaut de @nestjs/schematics, ces deux regles restent des erreurs ici.
|
||||||
|
'@typescript-eslint/no-explicit-any': 'error',
|
||||||
|
'@typescript-eslint/no-floating-promises': 'error',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'warn',
|
||||||
|
'no-console': ['warn', { allow: ['warn', 'error'] }],
|
||||||
|
'security/detect-object-injection': 'error',
|
||||||
|
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+11120
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,107 @@
|
|||||||
|
{
|
||||||
|
"name": "max-api",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "Backend Max : detient les cles API externes (OpenRouter, ElevenLabs) cote serveur et gere les comptes utilisateurs.",
|
||||||
|
"author": "Vandal William",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"overrides": {
|
||||||
|
"multer": "2.5.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
|
||||||
|
"dev": "nest start --watch",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"",
|
||||||
|
"lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:coverage": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"prisma:generate": "prisma generate",
|
||||||
|
"prisma:migrate": "prisma migrate dev",
|
||||||
|
"prisma:deploy": "prisma migrate deploy",
|
||||||
|
"prisma:studio": "prisma studio",
|
||||||
|
"prisma:seed": "ts-node prisma/seed.ts",
|
||||||
|
"postinstall": "prisma generate"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@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",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.15.1",
|
||||||
|
"dotenv": "^18.0.9",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.2.0",
|
||||||
|
"@eslint/js": "^9.18.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/bcrypt": "^6.0.0",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^22.10.7",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"eslint": "^9.18.0",
|
||||||
|
"eslint-config-prettier": "^10.0.1",
|
||||||
|
"eslint-plugin-prettier": "^5.2.2",
|
||||||
|
"eslint-plugin-security": "^4.2.1",
|
||||||
|
"globals": "^16.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"prettier": "^3.4.2",
|
||||||
|
"prisma": "6.19.3",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3",
|
||||||
|
"typescript-eslint": "^8.20.0"
|
||||||
|
},
|
||||||
|
"prisma": {
|
||||||
|
"seed": "ts-node prisma/seed.ts"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s",
|
||||||
|
"!**/*.module.ts",
|
||||||
|
"!main.ts"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"coverageThreshold": {
|
||||||
|
"global": {
|
||||||
|
"statements": 80,
|
||||||
|
"branches": 75,
|
||||||
|
"functions": 80,
|
||||||
|
"lines": 80
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "user" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"first_name" TEXT NOT NULL,
|
||||||
|
"last_name" TEXT NOT NULL,
|
||||||
|
"email" TEXT NOT NULL,
|
||||||
|
"password" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "user_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "api_key" (
|
||||||
|
"id" SERIAL NOT NULL,
|
||||||
|
"user_id" INTEGER NOT NULL,
|
||||||
|
"service_name" TEXT NOT NULL,
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "api_key_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "user_email_key" ON "user"("email");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "api_key_user_id_service_name_key" ON "api_key"("user_id", "service_name");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "api_key" ADD CONSTRAINT "api_key_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# Please do not edit this file manually
|
||||||
|
# It should be added in your version-control system (e.g., Git)
|
||||||
|
provider = "postgresql"
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
generator client {
|
||||||
|
provider = "prisma-client-js"
|
||||||
|
}
|
||||||
|
|
||||||
|
datasource db {
|
||||||
|
provider = "postgresql"
|
||||||
|
url = env("DATABASE_URL")
|
||||||
|
}
|
||||||
|
|
||||||
|
model User {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
firstName String @map("first_name")
|
||||||
|
lastName String @map("last_name")
|
||||||
|
email String @unique
|
||||||
|
password String
|
||||||
|
apiKeys ApiKey[]
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@map("user")
|
||||||
|
}
|
||||||
|
|
||||||
|
// La colonne "key" contient la valeur chiffree (AES-256-GCM, voir EncryptionService), jamais la
|
||||||
|
// cle en clair : seul le serveur, qui detient ENCRYPTION_KEY, peut la dechiffrer.
|
||||||
|
model ApiKey {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
userId Int @map("user_id")
|
||||||
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
|
serviceName String @map("service_name")
|
||||||
|
key String
|
||||||
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
@@unique([userId, serviceName])
|
||||||
|
@@map("api_key")
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* Script de provisionnement du premier utilisateur (dev uniquement). Toutes les valeurs sensibles
|
||||||
|
* viennent de process.env (voir .env.example) : rien n'est jamais ecrit en dur ici.
|
||||||
|
* Lancer avec : npm run prisma:seed
|
||||||
|
*/
|
||||||
|
import 'dotenv/config';
|
||||||
|
import { createCipheriv, randomBytes } from 'node:crypto';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
|
||||||
|
const BCRYPT_SALT_ROUNDS = 12;
|
||||||
|
const ALGORITHM = 'aes-256-gcm';
|
||||||
|
const IV_LENGTH_BYTES = 12;
|
||||||
|
|
||||||
|
function requireEnv(key: string): string {
|
||||||
|
const value = process.env[key];
|
||||||
|
if (!value) throw new Error(`Variable d'environnement manquante : ${key}`);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplique volontairement EncryptionService.encrypt() : ce script tourne hors du contexte Nest
|
||||||
|
// (pas d'injection de dependances disponible), et cette seule fonction ne justifie pas de
|
||||||
|
// demarrer toute l'application pour un script de provisionnement ponctuel.
|
||||||
|
function encrypt(plaintext: string, masterKey: Buffer): string {
|
||||||
|
const iv = randomBytes(IV_LENGTH_BYTES);
|
||||||
|
const cipher = createCipheriv(ALGORITHM, masterKey, iv);
|
||||||
|
const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
|
||||||
|
const authTag = cipher.getAuthTag();
|
||||||
|
return [iv, authTag, ciphertext].map((buffer) => buffer.toString('hex')).join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main(): Promise<void> {
|
||||||
|
const encryptionKeyHex = requireEnv('ENCRYPTION_KEY');
|
||||||
|
const masterKey = Buffer.from(encryptionKeyHex, 'hex');
|
||||||
|
if (masterKey.length !== 32) {
|
||||||
|
throw new Error('ENCRYPTION_KEY doit faire exactement 32 octets (64 caracteres hexadecimaux)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
try {
|
||||||
|
const hashedPassword = await bcrypt.hash(requireEnv('SEED_USER_PASSWORD'), BCRYPT_SALT_ROUNDS);
|
||||||
|
|
||||||
|
const user = await prisma.user.upsert({
|
||||||
|
where: { email: requireEnv('SEED_USER_EMAIL') },
|
||||||
|
update: {},
|
||||||
|
create: {
|
||||||
|
firstName: requireEnv('SEED_USER_FIRST_NAME'),
|
||||||
|
lastName: requireEnv('SEED_USER_LAST_NAME'),
|
||||||
|
email: requireEnv('SEED_USER_EMAIL'),
|
||||||
|
password: hashedPassword,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const apiKeys: { serviceName: string; value: string }[] = [
|
||||||
|
{ serviceName: 'elevenlabs_api_key', value: requireEnv('SEED_ELEVENLABS_API_KEY') },
|
||||||
|
{ serviceName: 'elevenlabs_voice_id', value: requireEnv('SEED_ELEVENLABS_VOICE_ID') },
|
||||||
|
{ serviceName: 'openrouter_api_key', value: requireEnv('SEED_OPENROUTER_API_KEY') },
|
||||||
|
{ serviceName: 'openrouter_model', value: requireEnv('SEED_OPENROUTER_MODEL') },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const { serviceName, value } of apiKeys) {
|
||||||
|
await prisma.apiKey.upsert({
|
||||||
|
where: { userId_serviceName: { userId: user.id, serviceName } },
|
||||||
|
update: { key: encrypt(value, masterKey) },
|
||||||
|
create: { userId: user.id, serviceName, key: encrypt(value, masterKey) },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-console -- script CLI ponctuel, pas du code applicatif en continu
|
||||||
|
console.log(`Utilisateur "${user.email}" provisionne avec ${apiKeys.length} cle(s) API.`);
|
||||||
|
} finally {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error: unknown) => {
|
||||||
|
console.error('[seed] echec du provisionnement :', error);
|
||||||
|
process.exitCode = 1;
|
||||||
|
});
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { ApiKeysController } from './api-keys.controller';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
describe('ApiKeysController', () => {
|
||||||
|
let controller: ApiKeysController;
|
||||||
|
let service: Record<keyof ApiKeysService, jest.Mock>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = {
|
||||||
|
create: jest.fn(),
|
||||||
|
findAll: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
remove: jest.fn(),
|
||||||
|
getDecryptedValue: jest.fn(),
|
||||||
|
getAllDecrypted: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [ApiKeysController],
|
||||||
|
providers: [{ provide: ApiKeysService, useValue: service }],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
controller = module.get<ApiKeysController>(ApiKeysController);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate create() to the service', async () => {
|
||||||
|
const dto = {
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'sk-or-v1-x',
|
||||||
|
};
|
||||||
|
service.create.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.create(dto);
|
||||||
|
|
||||||
|
expect(service.create).toHaveBeenCalledWith(dto);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findAll() without a filter', async () => {
|
||||||
|
service.findAll.mockResolvedValue([{ id: 1 }]);
|
||||||
|
|
||||||
|
const result = await controller.findAll(undefined);
|
||||||
|
|
||||||
|
expect(service.findAll).toHaveBeenCalledWith(undefined);
|
||||||
|
expect(result).toEqual([{ id: 1 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findAll() with a userId filter', async () => {
|
||||||
|
service.findAll.mockResolvedValue([{ id: 1, userId: 1 }]);
|
||||||
|
|
||||||
|
await controller.findAll(1);
|
||||||
|
|
||||||
|
expect(service.findAll).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findOne() to the service', async () => {
|
||||||
|
service.findOne.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.findOne(1);
|
||||||
|
|
||||||
|
expect(service.findOne).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate update() to the service', async () => {
|
||||||
|
service.update.mockResolvedValue({ id: 1, serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
const result = await controller.update(1, { serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
expect(service.update).toHaveBeenCalledWith(1, {
|
||||||
|
serviceName: 'nouveau_nom',
|
||||||
|
});
|
||||||
|
expect(result).toEqual({ id: 1, serviceName: 'nouveau_nom' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate remove() to the service', async () => {
|
||||||
|
service.remove.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
await controller.remove(1);
|
||||||
|
|
||||||
|
expect(service.remove).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseIntPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { ApiKeyResponseDto } from './dto/api-key-response.dto';
|
||||||
|
import { CreateApiKeyDto } from './dto/create-api-key.dto';
|
||||||
|
import { UpdateApiKeyDto } from './dto/update-api-key.dto';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
@ApiTags('api-keys')
|
||||||
|
@Controller('api-keys')
|
||||||
|
export class ApiKeysController {
|
||||||
|
constructor(private readonly apiKeysService: ApiKeysService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Enregistrer une cle API pour un utilisateur (chiffree avant stockage)',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.CREATED, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.CONFLICT,
|
||||||
|
description: 'Cle deja presente pour ce service',
|
||||||
|
})
|
||||||
|
create(@Body() dto: CreateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.create(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@ApiOperation({
|
||||||
|
summary:
|
||||||
|
'Lister les cles API (sans leur valeur), filtrable par utilisateur',
|
||||||
|
})
|
||||||
|
@ApiQuery({ name: 'userId', required: false, type: Number })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: [ApiKeyResponseDto] })
|
||||||
|
findAll(
|
||||||
|
@Query('userId', new ParseIntPipe({ optional: true })) userId?: number,
|
||||||
|
): Promise<ApiKeyResponseDto[]> {
|
||||||
|
return this.apiKeysService.findAll(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Recuperer une cle API (sans sa valeur) par son id',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
findOne(@Param('id', ParseIntPipe) id: number): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: 'Mettre a jour une cle API (nom de service et/ou valeur)',
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: ApiKeyResponseDto })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
update(
|
||||||
|
@Param('id', ParseIntPipe) id: number,
|
||||||
|
@Body() dto: UpdateApiKeyDto,
|
||||||
|
): Promise<ApiKeyResponseDto> {
|
||||||
|
return this.apiKeysService.update(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer une cle API' })
|
||||||
|
@ApiResponse({ status: HttpStatus.NO_CONTENT })
|
||||||
|
@ApiResponse({ status: HttpStatus.NOT_FOUND, description: 'Cle introuvable' })
|
||||||
|
remove(@Param('id', ParseIntPipe) id: number): Promise<void> {
|
||||||
|
return this.apiKeysService.remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ApiKeysController } from './api-keys.controller';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [ApiKeysController],
|
||||||
|
providers: [ApiKeysService],
|
||||||
|
exports: [ApiKeysService],
|
||||||
|
})
|
||||||
|
export class ApiKeysModule {}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import { EncryptionService } from '../common/crypto/encryption.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ApiKeysService } from './api-keys.service';
|
||||||
|
|
||||||
|
function prismaKnownError(code: string): Prisma.PrismaClientKnownRequestError {
|
||||||
|
return new Prisma.PrismaClientKnownRequestError('mock', {
|
||||||
|
code,
|
||||||
|
clientVersion: 'test',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ApiKeysService', () => {
|
||||||
|
let service: ApiKeysService;
|
||||||
|
let prisma: {
|
||||||
|
apiKey: {
|
||||||
|
create: jest.Mock;
|
||||||
|
findMany: jest.Mock;
|
||||||
|
findUnique: jest.Mock;
|
||||||
|
update: jest.Mock;
|
||||||
|
delete: jest.Mock;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
let encryption: { encrypt: jest.Mock; decrypt: jest.Mock };
|
||||||
|
|
||||||
|
const dbApiKey = {
|
||||||
|
id: 1,
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'encrypted-payload',
|
||||||
|
createdAt: new Date('2026-01-01'),
|
||||||
|
updatedAt: new Date('2026-01-01'),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
apiKey: {
|
||||||
|
create: jest.fn(),
|
||||||
|
findMany: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
encryption = {
|
||||||
|
encrypt: jest.fn().mockReturnValue('encrypted-payload'),
|
||||||
|
decrypt: jest.fn().mockReturnValue('sk-or-v1-plaintext'),
|
||||||
|
};
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
ApiKeysService,
|
||||||
|
{ provide: PrismaService, useValue: prisma },
|
||||||
|
{ provide: EncryptionService, useValue: encryption },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
service = module.get<ApiKeysService>(ApiKeysService);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create()', () => {
|
||||||
|
it('should encrypt the key before storing it and never return it', async () => {
|
||||||
|
prisma.apiKey.create.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const result = await service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'sk-or-v1-plaintext',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(encryption.encrypt).toHaveBeenCalledWith('sk-or-v1-plaintext');
|
||||||
|
expect(result).not.toHaveProperty('key');
|
||||||
|
expect(result.serviceName).toBe('openrouter_api_key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException when the service already has a key for this user', async () => {
|
||||||
|
prisma.apiKey.create.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'x',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.create.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
userId: 1,
|
||||||
|
serviceName: 'openrouter_api_key',
|
||||||
|
key: 'x',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findAll()', () => {
|
||||||
|
it('should list all keys without filtering when no userId is given', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([dbApiKey]);
|
||||||
|
|
||||||
|
const result = await service.findAll();
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ where: undefined }),
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0]).not.toHaveProperty('key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should filter by userId when given', async () => {
|
||||||
|
prisma.apiKey.findMany.mockResolvedValue([dbApiKey]);
|
||||||
|
|
||||||
|
await service.findAll(1);
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findMany).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({ where: { userId: 1 } }),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findOne()', () => {
|
||||||
|
it('should return the key metadata when found', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const result = await service.findOne(1);
|
||||||
|
|
||||||
|
expect(result.id).toBe(1);
|
||||||
|
expect(result).not.toHaveProperty('key');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when missing', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(service.findOne(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('update()', () => {
|
||||||
|
it('should re-encrypt the key when a new value is provided', async () => {
|
||||||
|
prisma.apiKey.update.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await service.update(1, { key: 'nouvelle-valeur' });
|
||||||
|
|
||||||
|
expect(encryption.encrypt).toHaveBeenCalledWith('nouvelle-valeur');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not touch the key field when no new value is provided', async () => {
|
||||||
|
prisma.apiKey.update.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await service.update(1, { serviceName: 'nouveau_nom' });
|
||||||
|
|
||||||
|
const updateArgs = (
|
||||||
|
prisma.apiKey.update.mock.calls[0] as [Prisma.ApiKeyUpdateArgs]
|
||||||
|
)[0];
|
||||||
|
expect(updateArgs.data.key).toBeUndefined();
|
||||||
|
expect(encryption.encrypt).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the key does not exist', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.update(999, { serviceName: 'x' })).rejects.toThrow(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException on duplicate (userId, serviceName)', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(service.update(1, { serviceName: 'dup' })).rejects.toThrow(
|
||||||
|
ConflictException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.update.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.update(1, { serviceName: 'x' })).rejects.toThrow(
|
||||||
|
'boom',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove()', () => {
|
||||||
|
it('should delete the key', async () => {
|
||||||
|
prisma.apiKey.delete.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
await expect(service.remove(1)).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the key does not exist', async () => {
|
||||||
|
prisma.apiKey.delete.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.remove(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.apiKey.delete.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.remove(1)).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getDecryptedValue()', () => {
|
||||||
|
it('should return the decrypted plaintext value for internal use', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(dbApiKey);
|
||||||
|
|
||||||
|
const value = await service.getDecryptedValue(1, 'openrouter_api_key');
|
||||||
|
|
||||||
|
expect(prisma.apiKey.findUnique).toHaveBeenCalledWith({
|
||||||
|
where: {
|
||||||
|
userId_serviceName: { userId: 1, serviceName: 'openrouter_api_key' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(encryption.decrypt).toHaveBeenCalledWith('encrypted-payload');
|
||||||
|
expect(value).toBe('sk-or-v1-plaintext');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when no key exists for this service', async () => {
|
||||||
|
prisma.apiKey.findUnique.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getDecryptedValue(1, 'unknown_service'),
|
||||||
|
).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({});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiKey, Prisma } from '@prisma/client';
|
||||||
|
import { EncryptionService } from '../common/crypto/encryption.service';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { ApiKeyResponseDto } from './dto/api-key-response.dto';
|
||||||
|
import { CreateApiKeyDto } from './dto/create-api-key.dto';
|
||||||
|
import { UpdateApiKeyDto } from './dto/update-api-key.dto';
|
||||||
|
|
||||||
|
const UNIQUE_CONSTRAINT_VIOLATION = 'P2002';
|
||||||
|
const RECORD_NOT_FOUND = 'P2025';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ApiKeysService {
|
||||||
|
constructor(
|
||||||
|
private readonly prisma: PrismaService,
|
||||||
|
private readonly encryption: EncryptionService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(dto: CreateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
try {
|
||||||
|
const apiKey = await this.prisma.apiKey.create({
|
||||||
|
data: {
|
||||||
|
userId: dto.userId,
|
||||||
|
serviceName: dto.serviceName,
|
||||||
|
key: this.encryption.encrypt(dto.key),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === UNIQUE_CONSTRAINT_VIOLATION
|
||||||
|
) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`L'utilisateur ${dto.userId} a deja une cle enregistree pour "${dto.serviceName}"`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(userId?: number): Promise<ApiKeyResponseDto[]> {
|
||||||
|
const apiKeys = await this.prisma.apiKey.findMany({
|
||||||
|
where: userId === undefined ? undefined : { userId },
|
||||||
|
orderBy: { id: 'asc' },
|
||||||
|
});
|
||||||
|
return apiKeys.map((apiKey) => this.toResponse(apiKey));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: number): Promise<ApiKeyResponseDto> {
|
||||||
|
const apiKey = await this.prisma.apiKey.findUnique({ where: { id } });
|
||||||
|
if (!apiKey) throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: number, dto: UpdateApiKeyDto): Promise<ApiKeyResponseDto> {
|
||||||
|
const data: Prisma.ApiKeyUpdateInput = { serviceName: dto.serviceName };
|
||||||
|
if (dto.key) {
|
||||||
|
data.key = this.encryption.encrypt(dto.key);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const apiKey = await this.prisma.apiKey.update({ where: { id }, data });
|
||||||
|
return this.toResponse(apiKey);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||||
|
if (error.code === RECORD_NOT_FOUND)
|
||||||
|
throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
if (error.code === UNIQUE_CONSTRAINT_VIOLATION) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`Une cle existe deja pour ce service chez cet utilisateur`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.prisma.apiKey.delete({ where: { id } });
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === RECORD_NOT_FOUND
|
||||||
|
) {
|
||||||
|
throw new NotFoundException(`Cle API ${id} introuvable`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Usage interne uniquement (ex: futur service de proxy vers OpenRouter/ElevenLabs) : jamais
|
||||||
|
* expose directement via un controleur HTTP. Renvoie la valeur en clair.
|
||||||
|
*/
|
||||||
|
async getDecryptedValue(
|
||||||
|
userId: number,
|
||||||
|
serviceName: string,
|
||||||
|
): Promise<string> {
|
||||||
|
const apiKey = await this.prisma.apiKey.findUnique({
|
||||||
|
where: { userId_serviceName: { userId, serviceName } },
|
||||||
|
});
|
||||||
|
if (!apiKey) {
|
||||||
|
throw new NotFoundException(
|
||||||
|
`Aucune cle "${serviceName}" pour l'utilisateur ${userId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
id: apiKey.id,
|
||||||
|
userId: apiKey.userId,
|
||||||
|
serviceName: apiKey.serviceName,
|
||||||
|
createdAt: apiKey.createdAt,
|
||||||
|
updatedAt: apiKey.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ne contient jamais la valeur de la cle (ni chiffree ni dechiffree) : une fois creee, la cle
|
||||||
|
* n'est plus jamais renvoyee par l'API. Seul le backend lui-meme, via
|
||||||
|
* ApiKeysService.getDecryptedValue(), peut la lire pour appeler le service externe correspondant.
|
||||||
|
*/
|
||||||
|
export class ApiKeyResponseDto {
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
userId!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'openrouter_api_key' })
|
||||||
|
serviceName!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsInt, IsString, Min, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateApiKeyDto {
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
userId!: number;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'openrouter_api_key',
|
||||||
|
description:
|
||||||
|
'Identifiant du service cible (openrouter_api_key, elevenlabs_api_key, ...).',
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
serviceName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'sk-or-v1-...',
|
||||||
|
description:
|
||||||
|
"Valeur en clair, chiffree (AES-256-GCM) avant stockage. Jamais renvoyee telle quelle par l'API.",
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
key!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { OmitType, PartialType } from '@nestjs/swagger';
|
||||||
|
import { CreateApiKeyDto } from './create-api-key.dto';
|
||||||
|
|
||||||
|
// Changer le userId d'une cle n'a pas de sens via une mise a jour partielle : supprimer et
|
||||||
|
// recreer la cle sous le bon utilisateur plutot.
|
||||||
|
export class UpdateApiKeyDto extends PartialType(
|
||||||
|
OmitType(CreateApiKeyDto, ['userId'] as const),
|
||||||
|
) {}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { AppController } from './app.controller';
|
||||||
|
|
||||||
|
describe('AppController', () => {
|
||||||
|
let appController: AppController;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const app: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [AppController],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
appController = app.get<AppController>(AppController);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getHealth()', () => {
|
||||||
|
it('should return ok status', () => {
|
||||||
|
expect(appController.getHealth()).toEqual({ status: 'ok' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
@ApiTags('health')
|
||||||
|
@Controller()
|
||||||
|
export class AppController {
|
||||||
|
@Get('health')
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Verifie que l'API et sa base de donnees repondent",
|
||||||
|
})
|
||||||
|
getHealth(): { status: 'ok' } {
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({ isGlobal: true }),
|
||||||
|
PrismaModule,
|
||||||
|
CryptoModule,
|
||||||
|
UsersModule,
|
||||||
|
ApiKeysModule,
|
||||||
|
AuthModule,
|
||||||
|
],
|
||||||
|
controllers: [AppController],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { EncryptionService } from './encryption.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [EncryptionService],
|
||||||
|
exports: [EncryptionService],
|
||||||
|
})
|
||||||
|
export class CryptoModule {}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { EncryptionService } from './encryption.service';
|
||||||
|
|
||||||
|
const VALID_KEY_HEX = 'a'.repeat(64); // 32 octets
|
||||||
|
|
||||||
|
describe('EncryptionService', () => {
|
||||||
|
let service: EncryptionService;
|
||||||
|
let getOrThrow: jest.Mock;
|
||||||
|
|
||||||
|
async function createService(keyHex: string): Promise<EncryptionService> {
|
||||||
|
getOrThrow = jest.fn().mockReturnValue(keyHex);
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [
|
||||||
|
EncryptionService,
|
||||||
|
{ provide: ConfigService, useValue: { getOrThrow } },
|
||||||
|
],
|
||||||
|
}).compile();
|
||||||
|
return module.get<EncryptionService>(EncryptionService);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = await createService(VALID_KEY_HEX);
|
||||||
|
service.onModuleInit();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('encrypt() / decrypt()', () => {
|
||||||
|
it('should decrypt back to the original plaintext', () => {
|
||||||
|
const encrypted = service.encrypt('sk-or-v1-secret');
|
||||||
|
expect(service.decrypt(encrypted)).toBe('sk-or-v1-secret');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should produce a different ciphertext each time (random iv)', () => {
|
||||||
|
const first = service.encrypt('same-value');
|
||||||
|
const second = service.encrypt('same-value');
|
||||||
|
expect(first).not.toBe(second);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw when the payload format is invalid', () => {
|
||||||
|
expect(() => service.decrypt('not-a-valid-payload')).toThrow(
|
||||||
|
'Format de valeur chiffree invalide',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw when the auth tag has been tampered with', () => {
|
||||||
|
const encrypted = service.encrypt('sk-or-v1-secret');
|
||||||
|
const [iv, authTag, ciphertext] = encrypted.split(':');
|
||||||
|
const tampered = `${iv}:${'0'.repeat(authTag.length)}:${ciphertext}`;
|
||||||
|
expect(() => service.decrypt(tampered)).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onModuleInit()', () => {
|
||||||
|
it('should throw when ENCRYPTION_KEY is not exactly 32 bytes', async () => {
|
||||||
|
const shortKeyService = await createService('abcd');
|
||||||
|
expect(() => shortKeyService.onModuleInit()).toThrow(/32 octets/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
||||||
|
import { Injectable, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { ConfigService } from '@nestjs/config';
|
||||||
|
|
||||||
|
const ALGORITHM = 'aes-256-gcm';
|
||||||
|
const KEY_LENGTH_BYTES = 32;
|
||||||
|
const IV_LENGTH_BYTES = 12;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Chiffrement symetrique reversible (AES-256-GCM) pour les cles API stockees en base : elles
|
||||||
|
* doivent pouvoir etre dechiffrees pour appeler les services externes, contrairement a un mot de
|
||||||
|
* passe utilisateur qui lui est hache (sens unique, voir UsersService).
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class EncryptionService implements OnModuleInit {
|
||||||
|
private masterKey!: Buffer;
|
||||||
|
|
||||||
|
constructor(private readonly config: ConfigService) {}
|
||||||
|
|
||||||
|
onModuleInit(): void {
|
||||||
|
const hex = this.config.getOrThrow<string>('ENCRYPTION_KEY');
|
||||||
|
const key = Buffer.from(hex, 'hex');
|
||||||
|
if (key.length !== KEY_LENGTH_BYTES) {
|
||||||
|
throw new Error(
|
||||||
|
`ENCRYPTION_KEY doit faire exactement ${KEY_LENGTH_BYTES} octets (${KEY_LENGTH_BYTES * 2} caracteres hexadecimaux)`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.masterKey = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
encrypt(plaintext: string): string {
|
||||||
|
const iv = randomBytes(IV_LENGTH_BYTES);
|
||||||
|
const cipher = createCipheriv(ALGORITHM, this.masterKey, iv);
|
||||||
|
const ciphertext = Buffer.concat([
|
||||||
|
cipher.update(plaintext, 'utf8'),
|
||||||
|
cipher.final(),
|
||||||
|
]);
|
||||||
|
const authTag = cipher.getAuthTag();
|
||||||
|
return [iv, authTag, ciphertext]
|
||||||
|
.map((buffer) => buffer.toString('hex'))
|
||||||
|
.join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
decrypt(payload: string): string {
|
||||||
|
const [ivHex, authTagHex, ciphertextHex] = payload.split(':');
|
||||||
|
if (!ivHex || !authTagHex || !ciphertextHex) {
|
||||||
|
throw new Error('Format de valeur chiffree invalide');
|
||||||
|
}
|
||||||
|
const decipher = createDecipheriv(
|
||||||
|
ALGORITHM,
|
||||||
|
this.masterKey,
|
||||||
|
Buffer.from(ivHex, 'hex'),
|
||||||
|
);
|
||||||
|
decipher.setAuthTag(Buffer.from(authTagHex, 'hex'));
|
||||||
|
return Buffer.concat([
|
||||||
|
decipher.update(Buffer.from(ciphertextHex, 'hex')),
|
||||||
|
decipher.final(),
|
||||||
|
]).toString('utf8');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ValidationPipe } from '@nestjs/common';
|
||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
|
async function bootstrap(): Promise<void> {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
transform: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const swaggerConfig = new DocumentBuilder()
|
||||||
|
.setTitle('Max API')
|
||||||
|
.setDescription(
|
||||||
|
'Backend Max : comptes utilisateurs et cles API externes (OpenRouter, ElevenLabs) chiffrees cote serveur.',
|
||||||
|
)
|
||||||
|
.setVersion('1.0')
|
||||||
|
.build();
|
||||||
|
const swaggerDocument = SwaggerModule.createDocument(app, swaggerConfig);
|
||||||
|
SwaggerModule.setup('api/docs', app, swaggerDocument);
|
||||||
|
|
||||||
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
void bootstrap();
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [PrismaService],
|
||||||
|
exports: [PrismaService],
|
||||||
|
})
|
||||||
|
export class PrismaModule {}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { PrismaService } from './prisma.service';
|
||||||
|
|
||||||
|
describe('PrismaService', () => {
|
||||||
|
let service: PrismaService;
|
||||||
|
|
||||||
|
let connectSpy: jest.SpyInstance;
|
||||||
|
let disconnectSpy: jest.SpyInstance;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
service = new PrismaService();
|
||||||
|
connectSpy = jest.spyOn(service, '$connect').mockResolvedValue(undefined);
|
||||||
|
disconnectSpy = jest
|
||||||
|
.spyOn(service, '$disconnect')
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should connect to the database on module init', async () => {
|
||||||
|
await service.onModuleInit();
|
||||||
|
expect(connectSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should disconnect from the database on module destroy', async () => {
|
||||||
|
await service.onModuleDestroy();
|
||||||
|
expect(disconnectSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PrismaService
|
||||||
|
extends PrismaClient
|
||||||
|
implements OnModuleInit, OnModuleDestroy
|
||||||
|
{
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
await this.$connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleDestroy(): Promise<void> {
|
||||||
|
await this.$disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateUserDto {
|
||||||
|
@ApiProperty({ example: 'William' })
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
firstName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Vandal' })
|
||||||
|
@IsString()
|
||||||
|
@MinLength(1)
|
||||||
|
lastName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'william@example.com' })
|
||||||
|
@IsEmail()
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: 'un-mot-de-passe-robuste',
|
||||||
|
description:
|
||||||
|
'Hache (bcrypt) avant stockage, jamais conserve ni renvoye en clair.',
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@MinLength(8)
|
||||||
|
password!: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
import { PartialType } from '@nestjs/swagger';
|
||||||
|
import { CreateUserDto } from './create-user.dto';
|
||||||
|
|
||||||
|
export class UpdateUserDto extends PartialType(CreateUserDto) {}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
/** Ne contient jamais le mot de passe (meme hache) : voir UsersService.toResponse(). */
|
||||||
|
export class UserResponseDto {
|
||||||
|
@ApiProperty({ example: 1 })
|
||||||
|
id!: number;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'William' })
|
||||||
|
firstName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'Vandal' })
|
||||||
|
lastName!: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 'william@example.com' })
|
||||||
|
email!: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
createdAt!: Date;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
updatedAt!: Date;
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { UsersController } from './users.controller';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
describe('UsersController', () => {
|
||||||
|
let controller: UsersController;
|
||||||
|
let service: Record<keyof UsersService, jest.Mock>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
service = {
|
||||||
|
create: jest.fn(),
|
||||||
|
findAll: jest.fn(),
|
||||||
|
findOne: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
remove: jest.fn(),
|
||||||
|
findByEmailForAuth: jest.fn(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
controllers: [UsersController],
|
||||||
|
providers: [{ provide: UsersService, useValue: service }],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
controller = module.get<UsersController>(UsersController);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate create() to the service', async () => {
|
||||||
|
const dto = {
|
||||||
|
firstName: 'W',
|
||||||
|
lastName: 'V',
|
||||||
|
email: 'w@example.com',
|
||||||
|
password: 'password123',
|
||||||
|
};
|
||||||
|
service.create.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.create(dto);
|
||||||
|
|
||||||
|
expect(service.create).toHaveBeenCalledWith(dto);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findAll() to the service', async () => {
|
||||||
|
service.findAll.mockResolvedValue([{ id: 1 }]);
|
||||||
|
|
||||||
|
const result = await controller.findAll();
|
||||||
|
|
||||||
|
expect(service.findAll).toHaveBeenCalled();
|
||||||
|
expect(result).toEqual([{ id: 1 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate findOne() to the service with a parsed id', async () => {
|
||||||
|
service.findOne.mockResolvedValue({ id: 1 });
|
||||||
|
|
||||||
|
const result = await controller.findOne(1);
|
||||||
|
|
||||||
|
expect(service.findOne).toHaveBeenCalledWith(1);
|
||||||
|
expect(result).toEqual({ id: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate update() to the service', async () => {
|
||||||
|
service.update.mockResolvedValue({ id: 1, firstName: 'Nouveau' });
|
||||||
|
|
||||||
|
const result = await controller.update(1, { firstName: 'Nouveau' });
|
||||||
|
|
||||||
|
expect(service.update).toHaveBeenCalledWith(1, { firstName: 'Nouveau' });
|
||||||
|
expect(result).toEqual({ id: 1, firstName: 'Nouveau' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should delegate remove() to the service', async () => {
|
||||||
|
service.remove.mockResolvedValue(undefined);
|
||||||
|
|
||||||
|
await controller.remove(1);
|
||||||
|
|
||||||
|
expect(service.remove).toHaveBeenCalledWith(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Delete,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
HttpStatus,
|
||||||
|
Param,
|
||||||
|
ParseIntPipe,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
import { UpdateUserDto } from './dto/update-user.dto';
|
||||||
|
import { UserResponseDto } from './dto/user-response.dto';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
@ApiTags('users')
|
||||||
|
@Controller('users')
|
||||||
|
export class UsersController {
|
||||||
|
constructor(private readonly usersService: UsersService) {}
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@ApiOperation({ summary: 'Creer un utilisateur' })
|
||||||
|
@ApiResponse({ status: HttpStatus.CREATED, type: UserResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.CONFLICT,
|
||||||
|
description: 'Email deja utilise',
|
||||||
|
})
|
||||||
|
create(@Body() dto: CreateUserDto): Promise<UserResponseDto> {
|
||||||
|
return this.usersService.create(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@ApiOperation({ summary: 'Lister les utilisateurs' })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: [UserResponseDto] })
|
||||||
|
findAll(): Promise<UserResponseDto[]> {
|
||||||
|
return this.usersService.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get(':id')
|
||||||
|
@ApiOperation({ summary: 'Recuperer un utilisateur par son id' })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: UserResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
description: 'Utilisateur introuvable',
|
||||||
|
})
|
||||||
|
findOne(@Param('id', ParseIntPipe) id: number): Promise<UserResponseDto> {
|
||||||
|
return this.usersService.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch(':id')
|
||||||
|
@ApiOperation({ summary: 'Mettre a jour un utilisateur' })
|
||||||
|
@ApiResponse({ status: HttpStatus.OK, type: UserResponseDto })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
description: 'Utilisateur introuvable',
|
||||||
|
})
|
||||||
|
update(
|
||||||
|
@Param('id', ParseIntPipe) id: number,
|
||||||
|
@Body() dto: UpdateUserDto,
|
||||||
|
): Promise<UserResponseDto> {
|
||||||
|
return this.usersService.update(id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Delete(':id')
|
||||||
|
@HttpCode(HttpStatus.NO_CONTENT)
|
||||||
|
@ApiOperation({ summary: 'Supprimer un utilisateur' })
|
||||||
|
@ApiResponse({ status: HttpStatus.NO_CONTENT })
|
||||||
|
@ApiResponse({
|
||||||
|
status: HttpStatus.NOT_FOUND,
|
||||||
|
description: 'Utilisateur introuvable',
|
||||||
|
})
|
||||||
|
remove(@Param('id', ParseIntPipe) id: number): Promise<void> {
|
||||||
|
return this.usersService.remove(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { UsersController } from './users.controller';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [UsersController],
|
||||||
|
providers: [UsersService],
|
||||||
|
exports: [UsersService],
|
||||||
|
})
|
||||||
|
export class UsersModule {}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import { ConflictException, NotFoundException } from '@nestjs/common';
|
||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { Prisma } from '@prisma/client';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
function prismaKnownError(code: string): Prisma.PrismaClientKnownRequestError {
|
||||||
|
return new Prisma.PrismaClientKnownRequestError('mock', {
|
||||||
|
code,
|
||||||
|
clientVersion: 'test',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('UsersService', () => {
|
||||||
|
let service: UsersService;
|
||||||
|
let prisma: {
|
||||||
|
user: {
|
||||||
|
create: jest.Mock;
|
||||||
|
findMany: jest.Mock;
|
||||||
|
findUnique: jest.Mock;
|
||||||
|
update: jest.Mock;
|
||||||
|
delete: jest.Mock;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const dbUser = {
|
||||||
|
id: 1,
|
||||||
|
firstName: 'William',
|
||||||
|
lastName: 'Vandal',
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'hashed-password',
|
||||||
|
createdAt: new Date('2026-01-01'),
|
||||||
|
updatedAt: new Date('2026-01-01'),
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
prisma = {
|
||||||
|
user: {
|
||||||
|
create: jest.fn(),
|
||||||
|
findMany: jest.fn(),
|
||||||
|
findUnique: jest.fn(),
|
||||||
|
update: jest.fn(),
|
||||||
|
delete: jest.fn(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const module: TestingModule = await Test.createTestingModule({
|
||||||
|
providers: [UsersService, { provide: PrismaService, useValue: prisma }],
|
||||||
|
}).compile();
|
||||||
|
service = module.get<UsersService>(UsersService);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('create()', () => {
|
||||||
|
it('should hash the password and return a response without it', async () => {
|
||||||
|
prisma.user.create.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
const result = await service.create({
|
||||||
|
firstName: 'William',
|
||||||
|
lastName: 'Vandal',
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'un-mot-de-passe-robuste',
|
||||||
|
});
|
||||||
|
|
||||||
|
const createArgs = (
|
||||||
|
prisma.user.create.mock.calls[0] as [Prisma.UserCreateArgs]
|
||||||
|
)[0];
|
||||||
|
expect(createArgs.data.password).not.toBe('un-mot-de-passe-robuste');
|
||||||
|
expect(
|
||||||
|
await bcrypt.compare(
|
||||||
|
'un-mot-de-passe-robuste',
|
||||||
|
createArgs.data.password,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(result).not.toHaveProperty('password');
|
||||||
|
expect(result.email).toBe('william@example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException when the email is already used', async () => {
|
||||||
|
prisma.user.create.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
firstName: 'William',
|
||||||
|
lastName: 'Vandal',
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'un-mot-de-passe-robuste',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.user.create.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.create({
|
||||||
|
firstName: 'William',
|
||||||
|
lastName: 'Vandal',
|
||||||
|
email: 'william@example.com',
|
||||||
|
password: 'un-mot-de-passe-robuste',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('boom');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findAll()', () => {
|
||||||
|
it('should return all users without their password', async () => {
|
||||||
|
prisma.user.findMany.mockResolvedValue([dbUser]);
|
||||||
|
|
||||||
|
const result = await service.findAll();
|
||||||
|
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0]).not.toHaveProperty('password');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('findOne()', () => {
|
||||||
|
it('should return the user when found', async () => {
|
||||||
|
prisma.user.findUnique.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
const result = await service.findOne(1);
|
||||||
|
|
||||||
|
expect(result.id).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when missing', async () => {
|
||||||
|
prisma.user.findUnique.mockResolvedValue(null);
|
||||||
|
|
||||||
|
await expect(service.findOne(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('update()', () => {
|
||||||
|
it('should hash the password when provided', async () => {
|
||||||
|
prisma.user.update.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
await service.update(1, { password: 'nouveau-mot-de-passe' });
|
||||||
|
|
||||||
|
const updateArgs = (
|
||||||
|
prisma.user.update.mock.calls[0] as [Prisma.UserUpdateArgs]
|
||||||
|
)[0];
|
||||||
|
expect(
|
||||||
|
await bcrypt.compare(
|
||||||
|
'nouveau-mot-de-passe',
|
||||||
|
updateArgs.data.password as string,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should not touch the password field when not provided', async () => {
|
||||||
|
prisma.user.update.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
await service.update(1, { firstName: 'Nouveau' });
|
||||||
|
|
||||||
|
const updateArgs = (
|
||||||
|
prisma.user.update.mock.calls[0] as [Prisma.UserUpdateArgs]
|
||||||
|
)[0];
|
||||||
|
expect(updateArgs.data.password).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the user does not exist', async () => {
|
||||||
|
prisma.user.update.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.update(999, { firstName: 'X' })).rejects.toThrow(
|
||||||
|
NotFoundException,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw ConflictException on duplicate email', async () => {
|
||||||
|
prisma.user.update.mockRejectedValue(prismaKnownError('P2002'));
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.update(1, { email: 'dup@example.com' }),
|
||||||
|
).rejects.toThrow(ConflictException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.user.update.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
await expect(service.update(1, { firstName: 'X' })).rejects.toThrow(
|
||||||
|
'boom',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('remove()', () => {
|
||||||
|
it('should delete the user', async () => {
|
||||||
|
prisma.user.delete.mockResolvedValue(dbUser);
|
||||||
|
|
||||||
|
await expect(service.remove(1)).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should throw NotFoundException when the user does not exist', async () => {
|
||||||
|
prisma.user.delete.mockRejectedValue(prismaKnownError('P2025'));
|
||||||
|
|
||||||
|
await expect(service.remove(999)).rejects.toThrow(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should rethrow unexpected errors', async () => {
|
||||||
|
prisma.user.delete.mockRejectedValue(new Error('boom'));
|
||||||
|
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Prisma, User } from '@prisma/client';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { PrismaService } from '../prisma/prisma.service';
|
||||||
|
import { CreateUserDto } from './dto/create-user.dto';
|
||||||
|
import { UpdateUserDto } from './dto/update-user.dto';
|
||||||
|
import { UserResponseDto } from './dto/user-response.dto';
|
||||||
|
|
||||||
|
const BCRYPT_SALT_ROUNDS = 12;
|
||||||
|
const UNIQUE_CONSTRAINT_VIOLATION = 'P2002';
|
||||||
|
const RECORD_NOT_FOUND = 'P2025';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UsersService {
|
||||||
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
|
|
||||||
|
async create(dto: CreateUserDto): Promise<UserResponseDto> {
|
||||||
|
const hashedPassword = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
|
||||||
|
try {
|
||||||
|
const user = await this.prisma.user.create({
|
||||||
|
data: {
|
||||||
|
firstName: dto.firstName,
|
||||||
|
lastName: dto.lastName,
|
||||||
|
email: dto.email,
|
||||||
|
password: hashedPassword,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return this.toResponse(user);
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === UNIQUE_CONSTRAINT_VIOLATION
|
||||||
|
) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`Un utilisateur avec l'email "${dto.email}" existe deja`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(): Promise<UserResponseDto[]> {
|
||||||
|
const users = await this.prisma.user.findMany({ orderBy: { id: 'asc' } });
|
||||||
|
return users.map((user) => this.toResponse(user));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: number): Promise<UserResponseDto> {
|
||||||
|
const user = await this.prisma.user.findUnique({ where: { id } });
|
||||||
|
if (!user) throw new NotFoundException(`Utilisateur ${id} introuvable`);
|
||||||
|
return this.toResponse(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: number, dto: UpdateUserDto): Promise<UserResponseDto> {
|
||||||
|
const data: Prisma.UserUpdateInput = { ...dto };
|
||||||
|
if (dto.password) {
|
||||||
|
data.password = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const user = await this.prisma.user.update({ where: { id }, data });
|
||||||
|
return this.toResponse(user);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Prisma.PrismaClientKnownRequestError) {
|
||||||
|
if (error.code === RECORD_NOT_FOUND)
|
||||||
|
throw new NotFoundException(`Utilisateur ${id} introuvable`);
|
||||||
|
if (error.code === UNIQUE_CONSTRAINT_VIOLATION) {
|
||||||
|
throw new ConflictException(
|
||||||
|
`Un utilisateur avec l'email "${dto.email}" existe deja`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: number): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.prisma.user.delete({ where: { id } });
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof Prisma.PrismaClientKnownRequestError &&
|
||||||
|
error.code === RECORD_NOT_FOUND
|
||||||
|
) {
|
||||||
|
throw new NotFoundException(`Utilisateur ${id} introuvable`);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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 {
|
||||||
|
id: user.id,
|
||||||
|
firstName: user.firstName,
|
||||||
|
lastName: user.lastName,
|
||||||
|
email: user.email,
|
||||||
|
createdAt: user.createdAt,
|
||||||
|
updatedAt: user.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
|
describe('AppController (e2e)', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/health (GET)', () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get('/health')
|
||||||
|
.expect(200)
|
||||||
|
.expect({ status: 'ok' });
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"resolvePackageJsonExports": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2023",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noImplicitAny": false,
|
||||||
|
"strictBindCallApply": false,
|
||||||
|
"noFallthroughCasesInSwitch": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# OpenRouter (chat + function calling) - https://openrouter.ai/keys
|
||||||
|
OPENROUTER_API_KEY=
|
||||||
|
OPENROUTER_MODEL=deepseek/deepseek-chat
|
||||||
|
# Bascule automatique si le modele principal est temporairement indisponible (rate-limit/5xx)
|
||||||
|
OPENROUTER_FALLBACK_MODEL=qwen/qwen-2.5-72b-instruct
|
||||||
|
# Modele vision (analyse d'ecran / camera) - doit accepter des images en entree
|
||||||
|
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
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
out
|
||||||
|
.DS_Store
|
||||||
|
.eslintcache
|
||||||
|
*.log*
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
coverage
|
||||||
|
playwright-report
|
||||||
|
test-results
|
||||||
|
.husky/_
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
FROM node:20-alpine AS base
|
# node:sqlite (coachStore.ts, memory/store.ts, meetingStore.ts) exige Node >= 22.5, mais
|
||||||
|
# Vite/Rolldown ne le reconnaissent comme built-in qu'a partir de Node 24.
|
||||||
|
FROM node:24-alpine AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm ci --ignore-scripts
|
RUN npm ci --ignore-scripts
|
||||||
|
Before Width: | Height: | Size: 121 KiB After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
@@ -17,7 +17,6 @@ win:
|
|||||||
target:
|
target:
|
||||||
- target: nsis
|
- target: nsis
|
||||||
arch: [x64]
|
arch: [x64]
|
||||||
publisherName: Vandal William
|
|
||||||
nsis:
|
nsis:
|
||||||
artifactName: ${productName}-Setup-${version}.${ext}
|
artifactName: ${productName}-Setup-${version}.${ext}
|
||||||
shortcutName: ${productName}
|
shortcutName: ${productName}
|
||||||
@@ -48,6 +47,6 @@ appImage:
|
|||||||
npmRebuild: false
|
npmRebuild: false
|
||||||
publish:
|
publish:
|
||||||
provider: generic
|
provider: generic
|
||||||
# VPS Hostinger de production : adapter le chemin/sous-domaine exact une fois configure cote
|
# Sert via Caddy (conteneur max-releases, reverse_proxy forgebase.fr/releases/*) sur le VPS
|
||||||
# serveur (dossier statique servant latest.yml/latest-mac.yml/latest-linux.yml + installeurs).
|
# Hostinger : dossier statique recevant latest.yml/latest-mac.yml/latest-linux.yml + installeurs.
|
||||||
url: https://forgebase.fr/releases/
|
url: https://forgebase.fr/releases/
|
||||||
+7
-16
@@ -58,6 +58,9 @@
|
|||||||
"typescript": "^5.9.3",
|
"typescript": "^5.9.3",
|
||||||
"vite": "^8.3.4",
|
"vite": "^8.3.4",
|
||||||
"vitest": "^5.0.5"
|
"vitest": "^5.0.5"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@adobe/css-tools": {
|
"node_modules/@adobe/css-tools": {
|
||||||
@@ -7037,18 +7040,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/image-size": {
|
"node_modules/image-size": {
|
||||||
"version": "1.2.1",
|
"version": "2.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/image-size/-/image-size-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.4.tgz",
|
||||||
"integrity": "sha512-rH+46sQJ2dlwfjfhCyNx5thzrv+dtmBIhPHk0zgRUukHzZ/kRueTJXoYYsclBaKcSMBWuGbOFXtioLpzTb5euw==",
|
"integrity": "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
|
||||||
"queue": "6.0.2"
|
|
||||||
},
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"image-size": "bin/image-size.js"
|
"image-size": "bin/image-size.js"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.x"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/immediate": {
|
"node_modules/immediate": {
|
||||||
@@ -9651,15 +9651,6 @@
|
|||||||
"node": ">=16.0.0"
|
"node": ">=16.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/queue": {
|
|
||||||
"version": "6.0.2",
|
|
||||||
"resolved": "https://registry.npmjs.org/queue/-/queue-6.0.2.tgz",
|
|
||||||
"integrity": "sha512-iHZWu+q3IdFZFX36ro/lKBkSvfkztY5Y7HMiPlOUjhupPcG2JMfst2KKEpu5XndviX/3UhFbRngUPNKtgvtZiA==",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"inherits": "~2.0.3"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/quick-lru": {
|
"node_modules/quick-lru": {
|
||||||
"version": "5.1.1",
|
"version": "5.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
|
||||||
@@ -4,6 +4,9 @@
|
|||||||
"description": "Avatar de bureau IA Max, assistant vocal avec modes Coach et Assistant",
|
"description": "Avatar de bureau IA Max, assistant vocal avec modes Coach et Assistant",
|
||||||
"main": "./out/main/index.js",
|
"main": "./out/main/index.js",
|
||||||
"author": "Vandal William",
|
"author": "Vandal William",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.0.0"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"format": "prettier --write .",
|
"format": "prettier --write .",
|
||||||
"lint": "eslint --cache .",
|
"lint": "eslint --cache .",
|
||||||
@@ -24,6 +27,11 @@
|
|||||||
"test:e2e": "npm run build && playwright test",
|
"test:e2e": "npm run build && playwright test",
|
||||||
"prepare": "husky"
|
"prepare": "husky"
|
||||||
},
|
},
|
||||||
|
"overrides": {
|
||||||
|
"pptxgenjs": {
|
||||||
|
"image-size": "^2.0.4"
|
||||||
|
}
|
||||||
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{ts,tsx}": [
|
"*.{ts,tsx}": [
|
||||||
"node node_modules/eslint/bin/eslint.js --fix",
|
"node node_modules/eslint/bin/eslint.js --fix",
|
||||||
|
Before Width: | Height: | Size: 35 KiB After Width: | Height: | Size: 35 KiB |
@@ -1,10 +1,13 @@
|
|||||||
|
import { getConfigValue, requireLoggedIn } from '../auth/session'
|
||||||
|
|
||||||
function getApiKey(): string {
|
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')
|
if (!apiKey) throw new Error('ELEVENLABS_API_KEY manquante dans .env')
|
||||||
return apiKey
|
return apiKey
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function transcribeAudio(audio: Buffer, mimeType: string): Promise<string> {
|
export async function transcribeAudio(audio: Buffer, mimeType: string): Promise<string> {
|
||||||
|
requireLoggedIn()
|
||||||
const form = new FormData()
|
const form = new FormData()
|
||||||
form.append('file', new Blob([new Uint8Array(audio)], { type: mimeType }), 'audio.webm')
|
form.append('file', new Blob([new Uint8Array(audio)], { type: mimeType }), 'audio.webm')
|
||||||
form.append('model_id', 'scribe_v1')
|
form.append('model_id', 'scribe_v1')
|
||||||
@@ -62,7 +65,8 @@ function sanitizeForSpeech(text: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function synthesizeSpeech(text: string): Promise<Buffer> {
|
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')
|
if (!voiceId) throw new Error('ELEVENLABS_VOICE_ID manquante dans .env')
|
||||||
|
|
||||||
const response = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {
|
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 { recordCourseBuildTool, clearCourseBuild } from '../coach/courseBuildStepper'
|
||||||
import { logger } from '../utils/logger'
|
import { logger } from '../utils/logger'
|
||||||
import { extractFakeToolCall, extractBareJsonRetry } from './toolCallRecovery'
|
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
|
// 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).
|
// 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
|
const MAX_TOOL_ROUNDS = 40
|
||||||
|
|
||||||
export async function getAssistantReply(userText: string): Promise<string> {
|
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')
|
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
|
let activeModel = primaryModel
|
||||||
history.push({ role: 'user', content: userText })
|
history.push({ role: 'user', content: userText })
|
||||||
|
|
||||||
@@ -27,8 +27,12 @@ markdown. Tableau source :\n${JSON.stringify(texts)}`
|
|||||||
choices?: { message: { content?: string } }[]
|
choices?: { message: { content?: string } }[]
|
||||||
}
|
}
|
||||||
const content: string = data.choices?.[0]?.message.content ?? '[]'
|
const content: string = data.choices?.[0]?.message.content ?? '[]'
|
||||||
const jsonMatch = content.match(/\[[\s\S]*\]/)
|
// Extrait le tableau JSON borne par le premier "[" et le dernier "]" sans regex gourmande
|
||||||
const parsed: unknown = JSON.parse(jsonMatch ? jsonMatch[0] : content)
|
// (evite tout risque de backtracking superlineaire sur une reponse LLM de taille arbitraire).
|
||||||
|
const start = content.indexOf('[')
|
||||||
|
const end = content.lastIndexOf(']')
|
||||||
|
const jsonSlice = start !== -1 && end > start ? content.slice(start, end + 1) : content
|
||||||
|
const parsed: unknown = JSON.parse(jsonSlice)
|
||||||
if (!Array.isArray(parsed)) throw new Error('Reponse de traduction invalide')
|
if (!Array.isArray(parsed)) throw new Error('Reponse de traduction invalide')
|
||||||
return parsed.map((item) => String(item))
|
return parsed.map((item) => String(item))
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { randomUUID } from 'crypto'
|
||||||
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
||||||
import { join } from 'path'
|
import { join } from 'path'
|
||||||
import { is } from '@electron-toolkit/utils'
|
import { is } from '@electron-toolkit/utils'
|
||||||
@@ -63,29 +64,25 @@ export async function openDrawingWindow(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Revele une forme dans la fenetre deja ouverte, avec un audio optionnel (narration pas-a-pas).
|
* Attend un accuse de reception a usage unique du renderer (evenement `ackEvent` portant le meme
|
||||||
* Attend l'accuse de reception du renderer (forme dessinee + audio termine) avant de se resoudre,
|
* `requestId` que celui envoye), avec expiration et nettoyage si la fenetre se ferme entre-temps.
|
||||||
* pour que draw_schema puisse enchainer les formes au rythme de la narration.
|
* Factorise le boilerplate partage par revealShape() et playCaption().
|
||||||
*/
|
*/
|
||||||
export function revealShape(
|
function waitForAck(
|
||||||
shape: DrawShape,
|
window: BrowserWindow,
|
||||||
audio: ArrayBuffer | null,
|
ackEvent: string,
|
||||||
timeoutMs = 20000
|
timeoutMs: number,
|
||||||
|
send: (requestId: string) => void
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
if (!win || win.isDestroyed()) {
|
const requestId = randomUUID()
|
||||||
resolve()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const window = win
|
|
||||||
const requestId = Math.random().toString(36).slice(2)
|
|
||||||
|
|
||||||
let settled = false
|
let settled = false
|
||||||
const finish = (): void => {
|
const finish = (): void => {
|
||||||
if (settled) return
|
if (settled) return
|
||||||
settled = true
|
settled = true
|
||||||
clearTimeout(timeout)
|
clearTimeout(timeout)
|
||||||
ipcMain.removeListener('shape-reveal-done', handler)
|
ipcMain.removeListener(ackEvent, handler)
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,9 +92,26 @@ export function revealShape(
|
|||||||
if (id !== requestId) return
|
if (id !== requestId) return
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
ipcMain.on('shape-reveal-done', handler)
|
ipcMain.on(ackEvent, handler)
|
||||||
window.once('closed', finish)
|
window.once('closed', finish)
|
||||||
|
|
||||||
|
send(requestId)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Revele une forme dans la fenetre deja ouverte, avec un audio optionnel (narration pas-a-pas).
|
||||||
|
* Attend l'accuse de reception du renderer (forme dessinee + audio termine) avant de se resoudre,
|
||||||
|
* pour que draw_schema puisse enchainer les formes au rythme de la narration.
|
||||||
|
*/
|
||||||
|
export function revealShape(
|
||||||
|
shape: DrawShape,
|
||||||
|
audio: ArrayBuffer | null,
|
||||||
|
timeoutMs = 20000
|
||||||
|
): Promise<void> {
|
||||||
|
if (!win || win.isDestroyed()) return Promise.resolve()
|
||||||
|
const window = win
|
||||||
|
return waitForAck(window, 'shape-reveal-done', timeoutMs, (requestId) => {
|
||||||
window.webContents.send('reveal-shape', { requestId, shape, audio })
|
window.webContents.send('reveal-shape', { requestId, shape, audio })
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -112,7 +126,7 @@ export async function renderMermaid(title: string, mermaidCode: string): Promise
|
|||||||
await ready
|
await ready
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const requestId = Math.random().toString(36).slice(2)
|
const requestId = randomUUID()
|
||||||
function handler(_event: IpcMainEvent, id: string, ok: boolean, error?: string): void {
|
function handler(_event: IpcMainEvent, id: string, ok: boolean, error?: string): void {
|
||||||
if (id !== requestId) return
|
if (id !== requestId) return
|
||||||
ipcMain.removeListener('mermaid-render-done', handler)
|
ipcMain.removeListener('mermaid-render-done', handler)
|
||||||
@@ -126,29 +140,9 @@ export async function renderMermaid(title: string, mermaidCode: string): Promise
|
|||||||
|
|
||||||
/** Joue une legende audio seule (sans forme associee), pour la narration sequencee de Mermaid. */
|
/** Joue une legende audio seule (sans forme associee), pour la narration sequencee de Mermaid. */
|
||||||
export function playCaption(audio: ArrayBuffer, timeoutMs = 20000): Promise<void> {
|
export function playCaption(audio: ArrayBuffer, timeoutMs = 20000): Promise<void> {
|
||||||
return new Promise((resolve) => {
|
if (!win || win.isDestroyed()) return Promise.resolve()
|
||||||
if (!win || win.isDestroyed()) {
|
|
||||||
resolve()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
const window = win
|
const window = win
|
||||||
const requestId = Math.random().toString(36).slice(2)
|
return waitForAck(window, 'caption-done', timeoutMs, (requestId) => {
|
||||||
|
|
||||||
let settled = false
|
|
||||||
const finish = (): void => {
|
|
||||||
if (settled) return
|
|
||||||
settled = true
|
|
||||||
clearTimeout(timeout)
|
|
||||||
ipcMain.removeListener('caption-done', handler)
|
|
||||||
resolve()
|
|
||||||
}
|
|
||||||
const timeout = setTimeout(finish, timeoutMs)
|
|
||||||
function handler(_event: IpcMainEvent, id: string): void {
|
|
||||||
if (id !== requestId) return
|
|
||||||
finish()
|
|
||||||
}
|
|
||||||
ipcMain.on('caption-done', handler)
|
|
||||||
window.once('closed', finish)
|
|
||||||
window.webContents.send('play-caption', { requestId, audio })
|
window.webContents.send('play-caption', { requestId, audio })
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { randomUUID } from 'crypto'
|
||||||
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
import { BrowserWindow, ipcMain, type IpcMainEvent } from 'electron'
|
||||||
import { join } from 'path'
|
import { join } from 'path'
|
||||||
import { is } from '@electron-toolkit/utils'
|
import { is } from '@electron-toolkit/utils'
|
||||||
@@ -65,7 +66,7 @@ export function requestWrittenAnswers(
|
|||||||
window.show()
|
window.show()
|
||||||
window.moveTop()
|
window.moveTop()
|
||||||
window.focus()
|
window.focus()
|
||||||
const requestId = Math.random().toString(36).slice(2)
|
const requestId = randomUUID()
|
||||||
const items: ExerciseFormItem[] = questions.map((q, index) => ({
|
const items: ExerciseFormItem[] = questions.map((q, index) => ({
|
||||||
id: String(index),
|
id: String(index),
|
||||||
question: q.question,
|
question: q.question,
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user