feat: login page in Max Avatar, connects to Max API's new auth
CI / quality (pull_request) Successful in 12m5s

Step 3 of the backend plan: lets a user log in from Max Avatar and use
their account's OpenRouter/ElevenLabs keys instead of the local .env.

Max API (new AuthModule):
- POST /auth/login (bcrypt-verified, returns a 1h JWT) and GET /auth/me/keys
  (JwtAuthGuard-protected, returns the authenticated user's decrypted keys
  only — never exposed via the generic /api-keys CRUD routes).
- UsersService.findByEmailForAuth() / ApiKeysService.getAllDecrypted(): new
  internal-only methods, never exposed by a controller directly.
- Generic "Email ou mot de passe incorrect" message regardless of whether
  the email exists, to avoid confirming account existence.
- @nestjs/jwt pinned to 11.0.2 (12.x is ESM-only and breaks Jest, same issue
  already hit with @nestjs/config).

Max Avatar:
- Context menu: connection status shown first (as a pseudo-title), "Me
  connecter"/"Connecte : email" + "Se deconnecter". Voice listening and the
  Basic/Coach/Assistant modes are fully removed from the menu (not just
  disabled) while logged out; listening also gets forced unchecked. Logging
  out while in Coach/Assistant force-switches back to Basic so the user
  isn't stuck in a mode with no menu entry left to leave it.
- Real server-side gate, not just a UI one: requireLoggedIn() (session.ts)
  is called at the top of getAssistantReply()/transcribeAudio()/
  synthesizeSpeech(). Without it, voice/chat kept working whenever a local
  .env had real keys (true during this whole session), regardless of login
  state — caught by manually testing the built app, not by any test.
- session.ts holds fetched keys in memory only (no persisted session: log in
  again each launch, as requested) and falls back to the local .env only
  when logged in status allows it.
- authClient.ts chains POST /auth/login then GET /auth/me/keys in one go
  (the JWT isn't kept beyond that); maps backend service names to the env
  var names openrouter.ts/elevenlabs.ts already expect.
- New LoginView.tsx + loginWindow.ts (same singleton pattern as the other
  secondary windows) and a get-auth-status IPC so the renderer knows the
  login state on boot (listening now defaults to false, true only if
  already logged in).

Verified end-to-end against a real dockerized Postgres + running Nest
server (wrong password -> 401, missing token -> 401, correct login -> JWT +
all 4 decrypted keys), and manually in the real Electron app by the user
(menu, login, logout, and the voice gate actually blocking requests even
with a valid local .env).

Backend: 64/64 tests, 100% stmts/functions/lines, 81% branches.
Max Avatar: 500/500 tests, ~91%/77%/91%/93%.

Also includes a CLAUDE.md rewrite (not authored by this session) describing
the next major pivot: Max becomes a freelance-training coach exclusively,
via a 7-agent pipeline, dropping Assistant/Basic mode selection. Nothing in
this commit implements that yet.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-31 17:29:37 +01:00
co-authored by Claude Sonnet 5
parent 605f9070a8
commit 885e24d037
42 changed files with 1689 additions and 99 deletions
@@ -14,6 +14,7 @@ describe('ApiKeysController', () => {
update: jest.fn(),
remove: jest.fn(),
getDecryptedValue: jest.fn(),
getAllDecrypted: jest.fn(),
};
const module: TestingModule = await Test.createTestingModule({
@@ -228,4 +228,39 @@ describe('ApiKeysService', () => {
).rejects.toThrow(NotFoundException);
});
});
describe('getAllDecrypted()', () => {
it('should return a map of serviceName to decrypted value for every key of the user', async () => {
prisma.apiKey.findMany.mockResolvedValue([
dbApiKey,
{
...dbApiKey,
id: 2,
serviceName: 'elevenlabs_api_key',
key: 'other-encrypted',
},
]);
encryption.decrypt.mockImplementation((payload: string) =>
payload === 'other-encrypted'
? 'sk-el-plaintext'
: 'sk-or-v1-plaintext',
);
const result = await service.getAllDecrypted(1);
expect(prisma.apiKey.findMany).toHaveBeenCalledWith({
where: { userId: 1 },
});
expect(result).toEqual({
openrouter_api_key: 'sk-or-v1-plaintext',
elevenlabs_api_key: 'sk-el-plaintext',
});
});
it('should return an empty object when the user has no keys', async () => {
prisma.apiKey.findMany.mockResolvedValue([]);
await expect(service.getAllDecrypted(1)).resolves.toEqual({});
});
});
});
+15
View File
@@ -112,6 +112,21 @@ export class ApiKeysService {
return this.encryption.decrypt(apiKey.key);
}
/**
* Usage interne uniquement (AuthService, apres connexion reussie) : dechiffre toutes les cles
* d'un utilisateur en une fois, sous forme `{ serviceName: valeur en clair }`. Jamais expose par
* une route generique /api-keys — uniquement via la route /auth/me/keys, protegee par JWT, qui
* ne peut renvoyer que les cles de l'utilisateur authentifie lui-meme.
*/
async getAllDecrypted(userId: number): Promise<Record<string, string>> {
const apiKeys = await this.prisma.apiKey.findMany({ where: { userId } });
const result: Record<string, string> = {};
for (const apiKey of apiKeys) {
result[apiKey.serviceName] = this.encryption.decrypt(apiKey.key);
}
return result;
}
/** Ne jamais inclure la valeur de la cle (meme chiffree) dans une reponse HTTP. */
private toResponse(apiKey: ApiKey): ApiKeyResponseDto {
return {
+2
View File
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { ApiKeysModule } from './api-keys/api-keys.module';
import { AppController } from './app.controller';
import { AuthModule } from './auth/auth.module';
import { CryptoModule } from './common/crypto/crypto.module';
import { PrismaModule } from './prisma/prisma.module';
import { UsersModule } from './users/users.module';
@@ -13,6 +14,7 @@ import { UsersModule } from './users/users.module';
CryptoModule,
UsersModule,
ApiKeysModule,
AuthModule,
],
controllers: [AppController],
})
+51
View File
@@ -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' });
});
});
+52
View File
@@ -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);
}
}
+28
View File
@@ -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 {}
+93
View File
@@ -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' });
});
});
});
+50
View File
@@ -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;
}
+13
View File
@@ -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;
}
+56
View File
@@ -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,
);
});
});
+34
View File
@@ -0,0 +1,34 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import type { Request } from 'express';
import type { JwtPayload } from './jwt-payload.interface';
export interface AuthenticatedRequest extends Request {
user: JwtPayload;
}
@Injectable()
export class JwtAuthGuard implements CanActivate {
constructor(private readonly jwtService: JwtService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
const authHeader = request.headers.authorization;
const token = authHeader?.startsWith('Bearer ')
? authHeader.slice('Bearer '.length)
: undefined;
if (!token) throw new UnauthorizedException('Jeton manquant');
try {
request.user = await this.jwtService.verifyAsync<JwtPayload>(token);
return true;
} catch {
throw new UnauthorizedException('Jeton invalide ou expire');
}
}
}
@@ -0,0 +1,4 @@
export interface JwtPayload {
sub: number;
email: string;
}
@@ -13,6 +13,7 @@ describe('UsersController', () => {
findOne: jest.fn(),
update: jest.fn(),
remove: jest.fn(),
findByEmailForAuth: jest.fn(),
};
const module: TestingModule = await Test.createTestingModule({
+21
View File
@@ -201,4 +201,25 @@ describe('UsersService', () => {
await expect(service.remove(1)).rejects.toThrow('boom');
});
});
describe('findByEmailForAuth()', () => {
it('should return the full entity including the hashed password', async () => {
prisma.user.findUnique.mockResolvedValue(dbUser);
const result = await service.findByEmailForAuth('william@example.com');
expect(prisma.user.findUnique).toHaveBeenCalledWith({
where: { email: 'william@example.com' },
});
expect(result).toEqual(dbUser);
});
it('should return null when no user matches', async () => {
prisma.user.findUnique.mockResolvedValue(null);
await expect(
service.findByEmailForAuth('inconnu@example.com'),
).resolves.toBeNull();
});
});
});
+8
View File
@@ -90,6 +90,14 @@ export class UsersService {
}
}
/**
* Usage interne uniquement (AuthService) : renvoie l'entite complete, mot de passe hache inclus,
* pour verification lors de la connexion. Jamais expose directement via un controleur.
*/
async findByEmailForAuth(email: string): Promise<User | null> {
return this.prisma.user.findUnique({ where: { email } });
}
/** Jamais inclure le mot de passe (meme hache) dans une reponse HTTP. */
private toResponse(user: User): UserResponseDto {
return {