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,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);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user