feat: add Max API backend (NestJS + Prisma + PostgreSQL)
Step 2 of the backend plan: holds OpenRouter/ElevenLabs API keys server-side instead of shipping them in the Max Avatar installer. - NestJS 11 (not 12, which just defaulted to oxlint + pure ESM + Vitest — incompatible with CLAUDE.md's mandated ESLint and the chosen Jest runner). - Prisma 6.19.3, pinned explicitly: the `prisma` package's npm "latest" tag currently points to an unstable 8.0.0-rc.x build, and Prisma 7 dropped schema.prisma's `datasource.url` in favor of a prisma.config.ts adapter system not worth the complexity here. - PostgreSQL 16 added as a new "postgres" service in the root docker-compose.yml. - Two Prisma models: User (bcrypt-hashed password) and ApiKey (AES-256-GCM encrypted value, unique per user+serviceName). - class-validator + class-transformer with a global ValidationPipe (whitelist, forbidNonWhitelisted, transform) on every route. - @nestjs/swagger documentation from the DTOs, served at /api/docs. - ApiKeyResponseDto never includes the key value (encrypted or not) on any route, including GET — only an internal, never-controller-exposed ApiKeysService.getDecryptedValue() can read it, for the future OpenRouter/ElevenLabs proxy service. - prisma/seed.ts provisions the first user and their 4 keys (elevenlabs_api_key, elevenlabs_voice_id, openrouter_api_key, openrouter_model) entirely from env vars, nothing hardcoded. - Re-enabled @typescript-eslint/no-explicit-any and no-floating-promises as errors (the Nest 11 scaffold ships them weakened) and added eslint-plugin-security, matching Max Avatar's config. - Fixed a real high-severity multer DoS (via @nestjs/platform-express) with an npm override pinning the patched version. Verified: typecheck, lint, 50/50 tests (100% stmts/functions/lines, 81.8% branches), build, a real Prisma migration + seed against a dockerized Postgres, and live HTTP requests against every route (including validation errors, 404s, and confirming API key values never leak in responses). Known gaps for a later step: no auth/authorization on the routes yet, no CI pipeline for Max API, no Dockerfile for the Nest app itself. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
037faa72f0
commit
605f9070a8
@@ -0,0 +1,85 @@
|
||||
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(),
|
||||
};
|
||||
|
||||
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,231 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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,19 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { ApiKeysModule } from './api-keys/api-keys.module';
|
||||
import { AppController } from './app.controller';
|
||||
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,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
export class AppModule {}
|
||||
@@ -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,75 @@
|
||||
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(),
|
||||
};
|
||||
|
||||
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,204 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user