feat: login page in Max Avatar, connects to Max API's new auth
CI / quality (pull_request) Successful in 12m5s
CI / quality (pull_request) Successful in 12m5s
Step 3 of the backend plan: lets a user log in from Max Avatar and use their account's OpenRouter/ElevenLabs keys instead of the local .env. Max API (new AuthModule): - POST /auth/login (bcrypt-verified, returns a 1h JWT) and GET /auth/me/keys (JwtAuthGuard-protected, returns the authenticated user's decrypted keys only — never exposed via the generic /api-keys CRUD routes). - UsersService.findByEmailForAuth() / ApiKeysService.getAllDecrypted(): new internal-only methods, never exposed by a controller directly. - Generic "Email ou mot de passe incorrect" message regardless of whether the email exists, to avoid confirming account existence. - @nestjs/jwt pinned to 11.0.2 (12.x is ESM-only and breaks Jest, same issue already hit with @nestjs/config). Max Avatar: - Context menu: connection status shown first (as a pseudo-title), "Me connecter"/"Connecte : email" + "Se deconnecter". Voice listening and the Basic/Coach/Assistant modes are fully removed from the menu (not just disabled) while logged out; listening also gets forced unchecked. Logging out while in Coach/Assistant force-switches back to Basic so the user isn't stuck in a mode with no menu entry left to leave it. - Real server-side gate, not just a UI one: requireLoggedIn() (session.ts) is called at the top of getAssistantReply()/transcribeAudio()/ synthesizeSpeech(). Without it, voice/chat kept working whenever a local .env had real keys (true during this whole session), regardless of login state — caught by manually testing the built app, not by any test. - session.ts holds fetched keys in memory only (no persisted session: log in again each launch, as requested) and falls back to the local .env only when logged in status allows it. - authClient.ts chains POST /auth/login then GET /auth/me/keys in one go (the JWT isn't kept beyond that); maps backend service names to the env var names openrouter.ts/elevenlabs.ts already expect. - New LoginView.tsx + loginWindow.ts (same singleton pattern as the other secondary windows) and a get-auth-status IPC so the renderer knows the login state on boot (listening now defaults to false, true only if already logged in). Verified end-to-end against a real dockerized Postgres + running Nest server (wrong password -> 401, missing token -> 401, correct login -> JWT + all 4 decrypted keys), and manually in the real Electron app by the user (menu, login, logout, and the voice gate actually blocking requests even with a valid local .env). Backend: 64/64 tests, 100% stmts/functions/lines, 81% branches. Max Avatar: 500/500 tests, ~91%/77%/91%/93%. Also includes a CLAUDE.md rewrite (not authored by this session) describing the next major pivot: Max becomes a freelance-training coach exclusively, via a 7-agent pipeline, dropping Assistant/Basic mode selection. Nothing in this commit implements that yet. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
605f9070a8
commit
885e24d037
@@ -11,6 +11,10 @@ DATABASE_URL="postgresql://max_api:changeme@localhost:5432/max_api?schema=public
|
||||
# Ne JAMAIS reutiliser la meme cle entre environnements, ne jamais la commiter.
|
||||
ENCRYPTION_KEY=
|
||||
|
||||
# Secret de signature des jetons JWT (route POST /auth/login). Generer avec la meme commande que
|
||||
# ENCRYPTION_KEY ci-dessus (longueur non contrainte, mais au moins 32 octets recommande).
|
||||
JWT_SECRET=
|
||||
|
||||
# --- Valeurs utilisees uniquement par prisma/seed.ts pour provisionner le premier utilisateur ---
|
||||
SEED_USER_FIRST_NAME=
|
||||
SEED_USER_LAST_NAME=
|
||||
|
||||
Generated
+130
-4
@@ -13,6 +13,7 @@
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "11.0.2",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@prisma/client": "6.19.3",
|
||||
@@ -2333,6 +2334,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/jwt": {
|
||||
"version": "11.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/jwt/-/jwt-11.0.2.tgz",
|
||||
"integrity": "sha512-rK8aE/3/Ma45gAWfCksAXUNbOoSOUudU0Kn3rT39htPF7wsYXtKfjALKeKKJbFrIWbLjsbqfXX5bIJNvgBugGA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/jsonwebtoken": "9.0.10",
|
||||
"jsonwebtoken": "9.0.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/mapped-types": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.1.1.tgz",
|
||||
@@ -3297,6 +3311,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/jsonwebtoken": {
|
||||
"version": "9.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.10.tgz",
|
||||
"integrity": "sha512-asx5hIG9Qmf/1oStypjanR7iKTv0gXQ1Ov/jfrX6kS/EO0OFni8orbmGCn0672NHR3kXHwpAwR+B368ZGN/2rA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/ms": "*",
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/methods": {
|
||||
"version": "1.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/methods/-/methods-1.1.4.tgz",
|
||||
@@ -3304,11 +3328,16 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/ms": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
|
||||
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "22.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
|
||||
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
@@ -4766,6 +4795,12 @@
|
||||
"ieee754": "^1.1.13"
|
||||
}
|
||||
},
|
||||
"node_modules/buffer-equal-constant-time": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
|
||||
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/buffer-from": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
|
||||
@@ -5548,6 +5583,15 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/ecdsa-sig-formatter": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
|
||||
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/ee-first": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
|
||||
@@ -7763,6 +7807,49 @@
|
||||
"graceful-fs": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"node_modules/jsonwebtoken": {
|
||||
"version": "9.0.3",
|
||||
"resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz",
|
||||
"integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jws": "^4.0.1",
|
||||
"lodash.includes": "^4.3.0",
|
||||
"lodash.isboolean": "^3.0.3",
|
||||
"lodash.isinteger": "^4.0.4",
|
||||
"lodash.isnumber": "^3.0.3",
|
||||
"lodash.isplainobject": "^4.0.6",
|
||||
"lodash.isstring": "^4.0.1",
|
||||
"lodash.once": "^4.0.0",
|
||||
"ms": "^2.1.1",
|
||||
"semver": "^7.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12",
|
||||
"npm": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/jwa": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
|
||||
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"buffer-equal-constant-time": "^1.0.1",
|
||||
"ecdsa-sig-formatter": "1.0.11",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/jws": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
|
||||
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"jwa": "^2.0.1",
|
||||
"safe-buffer": "^5.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/keyv": {
|
||||
"version": "4.5.4",
|
||||
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
|
||||
@@ -7865,6 +7952,42 @@
|
||||
"integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.includes": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz",
|
||||
"integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isboolean": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
|
||||
"integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isinteger": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz",
|
||||
"integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isnumber": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz",
|
||||
"integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isplainobject": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
|
||||
"integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.isstring": {
|
||||
"version": "4.0.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz",
|
||||
"integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.memoize": {
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz",
|
||||
@@ -7879,6 +8002,12 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/lodash.once": {
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz",
|
||||
"integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/log-symbols": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz",
|
||||
@@ -9259,7 +9388,6 @@
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9315,7 +9443,6 @@
|
||||
"version": "7.8.5",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
|
||||
"integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
"semver": "bin/semver.js"
|
||||
@@ -10516,7 +10643,6 @@
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/universalify": {
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "4.0.4",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "11.0.2",
|
||||
"@nestjs/platform-express": "^11.0.1",
|
||||
"@nestjs/swagger": "^11.4.7",
|
||||
"@prisma/client": "6.19.3",
|
||||
|
||||
@@ -14,6 +14,7 @@ describe('ApiKeysController', () => {
|
||||
update: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
getDecryptedValue: jest.fn(),
|
||||
getAllDecrypted: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
|
||||
@@ -228,4 +228,39 @@ describe('ApiKeysService', () => {
|
||||
).rejects.toThrow(NotFoundException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllDecrypted()', () => {
|
||||
it('should return a map of serviceName to decrypted value for every key of the user', async () => {
|
||||
prisma.apiKey.findMany.mockResolvedValue([
|
||||
dbApiKey,
|
||||
{
|
||||
...dbApiKey,
|
||||
id: 2,
|
||||
serviceName: 'elevenlabs_api_key',
|
||||
key: 'other-encrypted',
|
||||
},
|
||||
]);
|
||||
encryption.decrypt.mockImplementation((payload: string) =>
|
||||
payload === 'other-encrypted'
|
||||
? 'sk-el-plaintext'
|
||||
: 'sk-or-v1-plaintext',
|
||||
);
|
||||
|
||||
const result = await service.getAllDecrypted(1);
|
||||
|
||||
expect(prisma.apiKey.findMany).toHaveBeenCalledWith({
|
||||
where: { userId: 1 },
|
||||
});
|
||||
expect(result).toEqual({
|
||||
openrouter_api_key: 'sk-or-v1-plaintext',
|
||||
elevenlabs_api_key: 'sk-el-plaintext',
|
||||
});
|
||||
});
|
||||
|
||||
it('should return an empty object when the user has no keys', async () => {
|
||||
prisma.apiKey.findMany.mockResolvedValue([]);
|
||||
|
||||
await expect(service.getAllDecrypted(1)).resolves.toEqual({});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -112,6 +112,21 @@ export class ApiKeysService {
|
||||
return this.encryption.decrypt(apiKey.key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage interne uniquement (AuthService, apres connexion reussie) : dechiffre toutes les cles
|
||||
* d'un utilisateur en une fois, sous forme `{ serviceName: valeur en clair }`. Jamais expose par
|
||||
* une route generique /api-keys — uniquement via la route /auth/me/keys, protegee par JWT, qui
|
||||
* ne peut renvoyer que les cles de l'utilisateur authentifie lui-meme.
|
||||
*/
|
||||
async getAllDecrypted(userId: number): Promise<Record<string, string>> {
|
||||
const apiKeys = await this.prisma.apiKey.findMany({ where: { userId } });
|
||||
const result: Record<string, string> = {};
|
||||
for (const apiKey of apiKeys) {
|
||||
result[apiKey.serviceName] = this.encryption.decrypt(apiKey.key);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Ne jamais inclure la valeur de la cle (meme chiffree) dans une reponse HTTP. */
|
||||
private toResponse(apiKey: ApiKey): ApiKeyResponseDto {
|
||||
return {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ApiKeysModule } from './api-keys/api-keys.module';
|
||||
import { AppController } from './app.controller';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { CryptoModule } from './common/crypto/crypto.module';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
import { UsersModule } from './users/users.module';
|
||||
@@ -13,6 +14,7 @@ import { UsersModule } from './users/users.module';
|
||||
CryptoModule,
|
||||
UsersModule,
|
||||
ApiKeysModule,
|
||||
AuthModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||
|
||||
describe('AuthController', () => {
|
||||
let controller: AuthController;
|
||||
let service: Record<keyof AuthService, jest.Mock>;
|
||||
|
||||
beforeEach(async () => {
|
||||
service = {
|
||||
login: jest.fn(),
|
||||
getDecryptedKeysForUser: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
controllers: [AuthController],
|
||||
providers: [{ provide: AuthService, useValue: service }],
|
||||
})
|
||||
.overrideGuard(JwtAuthGuard)
|
||||
.useValue({ canActivate: () => true })
|
||||
.compile();
|
||||
|
||||
controller = module.get<AuthController>(AuthController);
|
||||
});
|
||||
|
||||
it('should delegate login() to the service', async () => {
|
||||
const dto = { email: 'william@example.com', password: 'x' };
|
||||
service.login.mockResolvedValue({ accessToken: 'jwt', user: { id: 1 } });
|
||||
|
||||
const result = await controller.login(dto);
|
||||
|
||||
expect(service.login).toHaveBeenCalledWith(dto);
|
||||
expect(result).toEqual({ accessToken: 'jwt', user: { id: 1 } });
|
||||
});
|
||||
|
||||
it('should delegate getMyKeys() to the service using the authenticated user id', async () => {
|
||||
service.getDecryptedKeysForUser.mockResolvedValue({
|
||||
openrouter_api_key: 'sk-or-v1-x',
|
||||
});
|
||||
const request = {
|
||||
user: { sub: 1, email: 'william@example.com' },
|
||||
} as AuthenticatedRequest;
|
||||
|
||||
const result = await controller.getMyKeys(request);
|
||||
|
||||
expect(service.getDecryptedKeysForUser).toHaveBeenCalledWith(1);
|
||||
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
HttpStatus,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
ApiOperation,
|
||||
ApiResponse,
|
||||
ApiTags,
|
||||
} from '@nestjs/swagger';
|
||||
import { AuthService } from './auth.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { LoginResponseDto } from './dto/login-response.dto';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
import type { AuthenticatedRequest } from './jwt-auth.guard';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
@Post('login')
|
||||
@ApiOperation({ summary: 'Authentifier un utilisateur et obtenir un jeton' })
|
||||
@ApiResponse({ status: HttpStatus.OK, type: LoginResponseDto })
|
||||
@ApiResponse({
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
description: 'Email ou mot de passe incorrect',
|
||||
})
|
||||
login(@Body() dto: LoginDto): Promise<LoginResponseDto> {
|
||||
return this.authService.login(dto);
|
||||
}
|
||||
|
||||
@Get('me/keys')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({
|
||||
summary:
|
||||
"Recuperer les cles API dechiffrees de l'utilisateur authentifie (service -> valeur en clair)",
|
||||
})
|
||||
@ApiResponse({ status: HttpStatus.OK })
|
||||
@ApiResponse({ status: HttpStatus.UNAUTHORIZED })
|
||||
getMyKeys(
|
||||
@Req() request: AuthenticatedRequest,
|
||||
): Promise<Record<string, string>> {
|
||||
return this.authService.getDecryptedKeysForUser(request.user.sub);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ApiKeysModule } from '../api-keys/api-keys.module';
|
||||
import { UsersModule } from '../users/users.module';
|
||||
import { AuthController } from './auth.controller';
|
||||
import { AuthService } from './auth.service';
|
||||
import { JwtAuthGuard } from './jwt-auth.guard';
|
||||
|
||||
const ACCESS_TOKEN_TTL = '1h';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
ApiKeysModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
secret: config.getOrThrow<string>('JWT_SECRET'),
|
||||
signOptions: { expiresIn: ACCESS_TOKEN_TTL },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, JwtAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
let usersService: { findByEmailForAuth: jest.Mock };
|
||||
let apiKeysService: { getAllDecrypted: jest.Mock };
|
||||
let jwtService: { signAsync: jest.Mock };
|
||||
|
||||
const dbUser = {
|
||||
id: 1,
|
||||
firstName: 'William',
|
||||
lastName: 'Vandal',
|
||||
email: 'william@example.com',
|
||||
password: '',
|
||||
createdAt: new Date('2026-01-01'),
|
||||
updatedAt: new Date('2026-01-01'),
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
dbUser.password = await bcrypt.hash('le-bon-mot-de-passe', 12);
|
||||
|
||||
usersService = { findByEmailForAuth: jest.fn() };
|
||||
apiKeysService = { getAllDecrypted: jest.fn() };
|
||||
jwtService = { signAsync: jest.fn().mockResolvedValue('signed-jwt') };
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
AuthService,
|
||||
{ provide: UsersService, useValue: usersService },
|
||||
{ provide: ApiKeysService, useValue: apiKeysService },
|
||||
{ provide: JwtService, useValue: jwtService },
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<AuthService>(AuthService);
|
||||
});
|
||||
|
||||
describe('login()', () => {
|
||||
it('should return an access token and the user when the password matches', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||
|
||||
const result = await service.login({
|
||||
email: 'william@example.com',
|
||||
password: 'le-bon-mot-de-passe',
|
||||
});
|
||||
|
||||
expect(result.accessToken).toBe('signed-jwt');
|
||||
expect(result.user).not.toHaveProperty('password');
|
||||
expect(jwtService.signAsync).toHaveBeenCalledWith({
|
||||
sub: 1,
|
||||
email: 'william@example.com',
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the email is unknown', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.login({ email: 'inconnu@example.com', password: 'x' }),
|
||||
).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the password is wrong', async () => {
|
||||
usersService.findByEmailForAuth.mockResolvedValue(dbUser);
|
||||
|
||||
await expect(
|
||||
service.login({
|
||||
email: 'william@example.com',
|
||||
password: 'mauvais-mot-de-passe',
|
||||
}),
|
||||
).rejects.toThrow(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDecryptedKeysForUser()', () => {
|
||||
it('should delegate to ApiKeysService.getAllDecrypted', async () => {
|
||||
apiKeysService.getAllDecrypted.mockResolvedValue({
|
||||
openrouter_api_key: 'sk-or-v1-x',
|
||||
});
|
||||
|
||||
const result = await service.getDecryptedKeysForUser(1);
|
||||
|
||||
expect(apiKeysService.getAllDecrypted).toHaveBeenCalledWith(1);
|
||||
expect(result).toEqual({ openrouter_api_key: 'sk-or-v1-x' });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import * as bcrypt from 'bcrypt';
|
||||
import { ApiKeysService } from '../api-keys/api-keys.service';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { LoginDto } from './dto/login.dto';
|
||||
import { LoginResponseDto } from './dto/login-response.dto';
|
||||
import { JwtPayload } from './jwt-payload.interface';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly apiKeysService: ApiKeysService,
|
||||
private readonly jwtService: JwtService,
|
||||
) {}
|
||||
|
||||
async login(dto: LoginDto): Promise<LoginResponseDto> {
|
||||
const user = await this.usersService.findByEmailForAuth(dto.email);
|
||||
// Message volontairement generique (ni "email inconnu" ni "mot de passe incorrect") : ne pas
|
||||
// confirmer a un attaquant qu'un email donne correspond a un compte existant.
|
||||
const invalidCredentials = (): never => {
|
||||
throw new UnauthorizedException('Email ou mot de passe incorrect');
|
||||
};
|
||||
if (!user) return invalidCredentials();
|
||||
|
||||
const passwordMatches = await bcrypt.compare(dto.password, user.password);
|
||||
if (!passwordMatches) return invalidCredentials();
|
||||
|
||||
const payload: JwtPayload = { sub: user.id, email: user.email };
|
||||
const accessToken = await this.jwtService.signAsync(payload);
|
||||
|
||||
return {
|
||||
accessToken,
|
||||
user: {
|
||||
id: user.id,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
email: user.email,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Cles de l'utilisateur authentifie uniquement (userId extrait du JWT verifie, jamais du body). */
|
||||
getDecryptedKeysForUser(userId: number): Promise<Record<string, string>> {
|
||||
return this.apiKeysService.getAllDecrypted(userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { UserResponseDto } from '../../users/dto/user-response.dto';
|
||||
|
||||
export class LoginResponseDto {
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Jeton JWT, a transmettre dans "Authorization: Bearer <token>".',
|
||||
})
|
||||
accessToken!: string;
|
||||
|
||||
@ApiProperty({ type: UserResponseDto })
|
||||
user!: UserResponseDto;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class LoginDto {
|
||||
@ApiProperty({ example: 'william@example.com' })
|
||||
@IsEmail()
|
||||
email!: string;
|
||||
|
||||
@ApiProperty({ example: 'un-mot-de-passe-robuste' })
|
||||
@IsString()
|
||||
@MinLength(1)
|
||||
password!: string;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { AuthenticatedRequest, JwtAuthGuard } from './jwt-auth.guard';
|
||||
|
||||
function createContext(authorization?: string): ExecutionContext {
|
||||
const request = { headers: { authorization } } as AuthenticatedRequest;
|
||||
return {
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
} as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
describe('JwtAuthGuard', () => {
|
||||
let guard: JwtAuthGuard;
|
||||
let jwtService: { verifyAsync: jest.Mock };
|
||||
|
||||
beforeEach(() => {
|
||||
jwtService = { verifyAsync: jest.fn() };
|
||||
guard = new JwtAuthGuard(jwtService as unknown as JwtService);
|
||||
});
|
||||
|
||||
it('should allow the request and attach the payload when the token is valid', async () => {
|
||||
jwtService.verifyAsync.mockResolvedValue({
|
||||
sub: 1,
|
||||
email: 'william@example.com',
|
||||
});
|
||||
const context = createContext('Bearer valid-token');
|
||||
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
expect(jwtService.verifyAsync).toHaveBeenCalledWith('valid-token');
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when no Authorization header is present', async () => {
|
||||
const context = createContext(undefined);
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the header does not start with "Bearer "', async () => {
|
||||
const context = createContext('Basic abc');
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw UnauthorizedException when the token is invalid or expired', async () => {
|
||||
jwtService.verifyAsync.mockRejectedValue(new Error('expired'));
|
||||
const context = createContext('Bearer expired-token');
|
||||
|
||||
await expect(guard.canActivate(context)).rejects.toThrow(
|
||||
UnauthorizedException,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import type { Request } from 'express';
|
||||
import type { JwtPayload } from './jwt-payload.interface';
|
||||
|
||||
export interface AuthenticatedRequest extends Request {
|
||||
user: JwtPayload;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<AuthenticatedRequest>();
|
||||
const authHeader = request.headers.authorization;
|
||||
const token = authHeader?.startsWith('Bearer ')
|
||||
? authHeader.slice('Bearer '.length)
|
||||
: undefined;
|
||||
if (!token) throw new UnauthorizedException('Jeton manquant');
|
||||
|
||||
try {
|
||||
request.user = await this.jwtService.verifyAsync<JwtPayload>(token);
|
||||
return true;
|
||||
} catch {
|
||||
throw new UnauthorizedException('Jeton invalide ou expire');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface JwtPayload {
|
||||
sub: number;
|
||||
email: string;
|
||||
}
|
||||
@@ -13,6 +13,7 @@ describe('UsersController', () => {
|
||||
findOne: jest.fn(),
|
||||
update: jest.fn(),
|
||||
remove: jest.fn(),
|
||||
findByEmailForAuth: jest.fn(),
|
||||
};
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
|
||||
@@ -201,4 +201,25 @@ describe('UsersService', () => {
|
||||
await expect(service.remove(1)).rejects.toThrow('boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByEmailForAuth()', () => {
|
||||
it('should return the full entity including the hashed password', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue(dbUser);
|
||||
|
||||
const result = await service.findByEmailForAuth('william@example.com');
|
||||
|
||||
expect(prisma.user.findUnique).toHaveBeenCalledWith({
|
||||
where: { email: 'william@example.com' },
|
||||
});
|
||||
expect(result).toEqual(dbUser);
|
||||
});
|
||||
|
||||
it('should return null when no user matches', async () => {
|
||||
prisma.user.findUnique.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
service.findByEmailForAuth('inconnu@example.com'),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -90,6 +90,14 @@ export class UsersService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage interne uniquement (AuthService) : renvoie l'entite complete, mot de passe hache inclus,
|
||||
* pour verification lors de la connexion. Jamais expose directement via un controleur.
|
||||
*/
|
||||
async findByEmailForAuth(email: string): Promise<User | null> {
|
||||
return this.prisma.user.findUnique({ where: { email } });
|
||||
}
|
||||
|
||||
/** Jamais inclure le mot de passe (meme hache) dans une reponse HTTP. */
|
||||
private toResponse(user: User): UserResponseDto {
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user