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 { 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 { 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 { 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 { 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 { 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 { const apiKey = await this.prisma.apiKey.findUnique({ where: { userId_serviceName: { userId, serviceName } }, }); if (!apiKey) { throw new NotFoundException( `Aucune cle "${serviceName}" pour l'utilisateur ${userId}`, ); } return this.encryption.decrypt(apiKey.key); } /** * Usage interne uniquement (AuthService, apres connexion reussie) : dechiffre toutes les cles * d'un utilisateur en une fois, sous forme `{ serviceName: valeur en clair }`. Jamais expose par * une route generique /api-keys — uniquement via la route /auth/me/keys, protegee par JWT, qui * ne peut renvoyer que les cles de l'utilisateur authentifie lui-meme. */ async getAllDecrypted(userId: number): Promise> { const apiKeys = await this.prisma.apiKey.findMany({ where: { userId } }); const result: Record = {}; for (const apiKey of apiKeys) { result[apiKey.serviceName] = this.encryption.decrypt(apiKey.key); } return result; } /** Ne jamais inclure la valeur de la cle (meme chiffree) dans une reponse HTTP. */ private toResponse(apiKey: ApiKey): ApiKeyResponseDto { return { id: apiKey.id, userId: apiKey.userId, serviceName: apiKey.serviceName, createdAt: apiKey.createdAt, updatedAt: apiKey.updatedAt, }; } }