Compare commits
6 Commits
main
...
feat/llm-s
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16b5af3365 | ||
|
|
39721e37ff | ||
|
|
0baeb1104a | ||
|
|
04ad02be5e | ||
|
|
0172b4518d | ||
|
|
f7e865721a |
@@ -23,7 +23,8 @@ LLM_MAX_RETRIES=1
|
|||||||
LLM_TEMPERATURE=0.7
|
LLM_TEMPERATURE=0.7
|
||||||
LLM_MAX_TOKENS=2048
|
LLM_MAX_TOKENS=2048
|
||||||
|
|
||||||
# Rate limits (login uses progressive lockout: 5/10/20 failed attempts -> 15m/1h/24h block)
|
# Rate limits
|
||||||
|
RATE_LIMIT_LOGIN=5
|
||||||
RATE_LIMIT_REGISTER=3
|
RATE_LIMIT_REGISTER=3
|
||||||
RATE_LIMIT_FORGOT_PASSWORD=3
|
RATE_LIMIT_FORGOT_PASSWORD=3
|
||||||
RATE_LIMIT_VERIFY_EMAIL=5
|
RATE_LIMIT_VERIFY_EMAIL=5
|
||||||
|
|||||||
@@ -69,21 +69,6 @@ Implement Agent H tasks from AGENT_TASKS.md. Work in branch feat/testing.
|
|||||||
Do H1–H7, commit after each. Target ≥70% coverage on services.
|
Do H1–H7, commit after each. Target ≥70% coverage on services.
|
||||||
```
|
```
|
||||||
|
|
||||||
**Agent A2 (Progressive Login Lockout):**
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Agent A2 task from AGENT_TASKS.md. Work in branch feat/progressive-login-lockout.
|
|
||||||
Branch from dev. Do task A2-1. Commit with the message from the table.
|
|
||||||
```
|
|
||||||
|
|
||||||
**Agent A2-2 (Fix Login Lockout Tests):**
|
|
||||||
|
|
||||||
```text
|
|
||||||
Implement Agent A2-2 task from AGENT_TASKS.md. Work in branch fix/login-lockout-test-mock.
|
|
||||||
Branch from dev. Do task A2-2. Commit with the message from the table.
|
|
||||||
Ensure tests/integration/auth.routes.test.ts passes.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Текущее состояние репозитория
|
## Текущее состояние репозитория
|
||||||
|
|
||||||
Часть работы уже выполнена одним агентом:
|
Часть работы уже выполнена одним агентом:
|
||||||
@@ -153,69 +138,6 @@ Ensure tests/integration/auth.routes.test.ts passes.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Agent A2: Progressive Login Lockout
|
|
||||||
|
|
||||||
**Зависимости:** Agent A (redis, rateLimit), Agent C (auth routes). Уже есть Auth и rateLimit.
|
|
||||||
|
|
||||||
**Ветка:** `feat/progressive-login-lockout`
|
|
||||||
|
|
||||||
**Контекст:** Сейчас `POST /auth/login` использует фиксированный лимит через `@fastify/rate-limit` (N попыток на 15 мин). По [security.md](samreshu_docs/principles/security.md) нужен **прогрессивный lockout** — считаются только **неудачные** попытки входа, с нарастающим временем блокировки:
|
|
||||||
|
|
||||||
| Неудачных попыток | Блокировка |
|
|
||||||
|-------------------|------------|
|
|
||||||
| 5 за 15 мин | 15 минут |
|
|
||||||
| 10 за 1 час | 1 час |
|
|
||||||
| 20 за 24 часа | 24 часа |
|
|
||||||
|
|
||||||
Счётчики в Redis по ключу `lockout:<ip>`. При успешном логине — сброс счётчиков.
|
|
||||||
|
|
||||||
**Задача A2-1:**
|
|
||||||
|
|
||||||
1. **Создать `src/utils/loginLockout.ts`** — утилита для работы с Redis:
|
|
||||||
- `checkBlocked(redis, ip: string)` → `{ blocked: boolean, retryAfter?: number }` — проверяет `lockout:blocked:<ip>`; если ключ есть и TTL > 0, возвращает `{ blocked: true, retryAfter }`.
|
|
||||||
- `recordFailedAttempt(redis, ip: string)` — INCR по ключам `lockout:15m:<ip>`, `lockout:1h:<ip>`, `lockout:24h:<ip>` с TTL 15m/1h/24h; при достижении порогов (5/10/20) устанавливает `lockout:blocked:<ip>` с соответствующим TTL.
|
|
||||||
- `clearOnSuccess(redis, ip: string)` — DEL всех ключей `lockout:*:<ip>` и `lockout:blocked:<ip>`.
|
|
||||||
|
|
||||||
2. **Обновить `src/plugins/rateLimit.ts`** — убрать `login` из `rateLimitOptions` (больше не используется для login). Остальные endpoints без изменений.
|
|
||||||
|
|
||||||
3. **Обновить `src/routes/auth.ts`** — для `POST /login`:
|
|
||||||
- Убрать `config: { rateLimit: rateLimitOptions.login }`.
|
|
||||||
- Добавить `preValidation`: вызвать `checkBlocked(app.redis, req.ip)`; если `blocked` — `reply.status(429).send({ error: { code: 'RATE_LIMIT_EXCEEDED', message: '...', retryAfter } })`.
|
|
||||||
- В handler: обернуть `authService.login(...)` в try/catch; при успехе — `clearOnSuccess(app.redis, ip)`; при throw (например `unauthorized`) — `recordFailedAttempt(app.redis, ip)`, затем rethrow.
|
|
||||||
|
|
||||||
4. **Опционально** — вынести пороги (5, 10, 20) и окна в `env.ts` или оставить константами в `loginLockout.ts` (документация security.md указывает фиксированные значения).
|
|
||||||
|
|
||||||
**Коммит:** `feat: replace fixed login rate limit with progressive lockout`
|
|
||||||
|
|
||||||
**Итого:** 1 коммит. После — PR в `dev`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Agent A2-2: Fix Login Lockout Tests (после A2)
|
|
||||||
|
|
||||||
**Зависимости:** Agent A2 выполнен.
|
|
||||||
|
|
||||||
**Ветка:** `fix/login-lockout-test-mock`
|
|
||||||
|
|
||||||
**Проблема:** Auth routes используют `app.redis` для `checkBlocked`, `recordFailedAttempt`, `clearOnSuccess`. В `buildAuthTestApp` Redis не подключён — тесты `POST /auth/login` падают с 500.
|
|
||||||
|
|
||||||
**Задача A2-2:**
|
|
||||||
|
|
||||||
1. **Добавить mock Redis** в `tests/helpers/build-test-app.ts`:
|
|
||||||
- Создать объект, реализующий минимальный интерфейс ioredis для loginLockout: `ttl`, `setex`, `del`, `eval`.
|
|
||||||
- `ttl(key)` → -2 (ключ не существует) или -1/положительное значение для тестов.
|
|
||||||
- `setex`, `del` → no-op или простая in-memory имитация.
|
|
||||||
- `eval(script, keysCount, ...keys, ...args)` → вернуть `[0, 0, 0]` (счётчики не достигли порога).
|
|
||||||
- `app.decorate('redis', mockRedis)` перед регистрацией auth routes.
|
|
||||||
|
|
||||||
2. **Обновить `rateLimitOptions`** в buildAuthTestApp — убрать `login` (его больше нет в типе из rateLimit.ts).
|
|
||||||
|
|
||||||
**Коммит:** `test: add mock Redis for auth integration tests with login lockout`
|
|
||||||
|
|
||||||
**Итого:** 1 коммит. Проверить: `npm run test -- tests/integration/auth.routes.test.ts` проходит.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Agent B: Data Model & Drizzle Schema
|
## Agent B: Data Model & Drizzle Schema
|
||||||
|
|
||||||
**Зависимости:** Agent A (нужен database plugin). Может стартовать после A4.
|
**Зависимости:** Agent A (нужен database plugin). Может стартовать после A4.
|
||||||
|
|||||||
@@ -7,9 +7,6 @@ import rateLimitPlugin from './plugins/rateLimit.js';
|
|||||||
import authPlugin from './plugins/auth.js';
|
import authPlugin from './plugins/auth.js';
|
||||||
import subscriptionPlugin from './plugins/subscription.js';
|
import subscriptionPlugin from './plugins/subscription.js';
|
||||||
import { authRoutes } from './routes/auth.js';
|
import { authRoutes } from './routes/auth.js';
|
||||||
import { profileRoutes } from './routes/profile.js';
|
|
||||||
import { testsRoutes } from './routes/tests.js';
|
|
||||||
import { adminQuestionsRoutes } from './routes/admin/questions.js';
|
|
||||||
import { env } from './config/env.js';
|
import { env } from './config/env.js';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
@@ -78,9 +75,6 @@ export async function buildApp(): Promise<FastifyInstance> {
|
|||||||
await app.register(authPlugin);
|
await app.register(authPlugin);
|
||||||
await app.register(subscriptionPlugin);
|
await app.register(subscriptionPlugin);
|
||||||
await app.register(authRoutes, { prefix: '/auth' });
|
await app.register(authRoutes, { prefix: '/auth' });
|
||||||
await app.register(profileRoutes, { prefix: '/profile' });
|
|
||||||
await app.register(testsRoutes, { prefix: '/tests' });
|
|
||||||
await app.register(adminQuestionsRoutes, { prefix: '/admin' });
|
|
||||||
|
|
||||||
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ const envSchema = z.object({
|
|||||||
LLM_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.7),
|
LLM_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.7),
|
||||||
LLM_MAX_TOKENS: z.coerce.number().default(2048),
|
LLM_MAX_TOKENS: z.coerce.number().default(2048),
|
||||||
|
|
||||||
|
RATE_LIMIT_LOGIN: z.coerce.number().default(5),
|
||||||
RATE_LIMIT_REGISTER: z.coerce.number().default(3),
|
RATE_LIMIT_REGISTER: z.coerce.number().default(3),
|
||||||
RATE_LIMIT_FORGOT_PASSWORD: z.coerce.number().default(3),
|
RATE_LIMIT_FORGOT_PASSWORD: z.coerce.number().default(3),
|
||||||
RATE_LIMIT_VERIFY_EMAIL: z.coerce.number().default(5),
|
RATE_LIMIT_VERIFY_EMAIL: z.coerce.number().default(5),
|
||||||
|
|||||||
@@ -1,14 +1,11 @@
|
|||||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||||
import fp from 'fastify-plugin';
|
import fp from 'fastify-plugin';
|
||||||
import { eq } from 'drizzle-orm';
|
|
||||||
import { verifyToken, isAccessPayload } from '../utils/jwt.js';
|
import { verifyToken, isAccessPayload } from '../utils/jwt.js';
|
||||||
import { unauthorized, forbidden } from '../utils/errors.js';
|
import { unauthorized } from '../utils/errors.js';
|
||||||
import { users } from '../db/schema/users.js';
|
|
||||||
|
|
||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
interface FastifyInstance {
|
interface FastifyInstance {
|
||||||
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
||||||
authenticateAdmin: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
|
|
||||||
}
|
}
|
||||||
interface FastifyRequest {
|
interface FastifyRequest {
|
||||||
user?: { id: string; email: string };
|
user?: { id: string; email: string };
|
||||||
@@ -37,22 +34,9 @@ export async function authenticate(req: FastifyRequest, _reply: FastifyReply): P
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function authenticateAdmin(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
|
|
||||||
if (!req.user) {
|
|
||||||
throw unauthorized('Authentication required');
|
|
||||||
}
|
|
||||||
|
|
||||||
const [user] = await req.server.db.select({ role: users.role }).from(users).where(eq(users.id, req.user.id));
|
|
||||||
|
|
||||||
if (!user || user.role !== 'admin') {
|
|
||||||
throw forbidden('Admin access required');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const authPlugin = async (app: FastifyInstance) => {
|
const authPlugin = async (app: FastifyInstance) => {
|
||||||
app.decorateRequest('user', undefined);
|
app.decorateRequest('user', undefined);
|
||||||
app.decorate('authenticate', authenticate);
|
app.decorate('authenticate', authenticate);
|
||||||
app.decorate('authenticateAdmin', authenticateAdmin);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default fp(authPlugin, { name: 'auth', dependencies: ['database'] });
|
export default fp(authPlugin, { name: 'auth' });
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { env } from '../config/env.js';
|
|||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
interface FastifyInstance {
|
interface FastifyInstance {
|
||||||
rateLimitOptions: {
|
rateLimitOptions: {
|
||||||
|
login: { max: number; timeWindow: string };
|
||||||
register: { max: number; timeWindow: string };
|
register: { max: number; timeWindow: string };
|
||||||
forgotPassword: { max: number; timeWindow: string };
|
forgotPassword: { max: number; timeWindow: string };
|
||||||
verifyEmail: { max: number; timeWindow: string };
|
verifyEmail: { max: number; timeWindow: string };
|
||||||
@@ -17,6 +18,7 @@ declare module 'fastify' {
|
|||||||
|
|
||||||
const rateLimitPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
|
const rateLimitPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
|
||||||
const options = {
|
const options = {
|
||||||
|
login: { max: env.RATE_LIMIT_LOGIN, timeWindow: '15 minutes' },
|
||||||
register: { max: env.RATE_LIMIT_REGISTER, timeWindow: '1 hour' },
|
register: { max: env.RATE_LIMIT_REGISTER, timeWindow: '1 hour' },
|
||||||
forgotPassword: { max: env.RATE_LIMIT_FORGOT_PASSWORD, timeWindow: '1 hour' },
|
forgotPassword: { max: env.RATE_LIMIT_FORGOT_PASSWORD, timeWindow: '1 hour' },
|
||||||
verifyEmail: { max: env.RATE_LIMIT_VERIFY_EMAIL, timeWindow: '15 minutes' },
|
verifyEmail: { max: env.RATE_LIMIT_VERIFY_EMAIL, timeWindow: '15 minutes' },
|
||||||
|
|||||||
@@ -1,131 +0,0 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
|
||||||
import { AdminQuestionService } from '../../services/admin/admin-question.service.js';
|
|
||||||
import type { EditQuestionInput } from '../../services/admin/admin-question.service.js';
|
|
||||||
|
|
||||||
const STACKS = ['html', 'css', 'js', 'ts', 'react', 'vue', 'nodejs', 'git', 'web_basics'] as const;
|
|
||||||
const LEVELS = ['basic', 'beginner', 'intermediate', 'advanced', 'expert'] as const;
|
|
||||||
const QUESTION_TYPES = ['single_choice', 'multiple_select', 'true_false', 'short_text'] as const;
|
|
||||||
|
|
||||||
const listPendingQuerySchema = {
|
|
||||||
querystring: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
limit: { type: 'integer', minimum: 1, maximum: 100 },
|
|
||||||
offset: { type: 'integer', minimum: 0 },
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const questionIdParamsSchema = {
|
|
||||||
params: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['questionId'],
|
|
||||||
properties: {
|
|
||||||
questionId: { type: 'string', format: 'uuid' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const editQuestionSchema = {
|
|
||||||
params: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['questionId'],
|
|
||||||
properties: {
|
|
||||||
questionId: { type: 'string', format: 'uuid' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
body: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
stack: { type: 'string', enum: [...STACKS] },
|
|
||||||
level: { type: 'string', enum: [...LEVELS] },
|
|
||||||
type: { type: 'string', enum: [...QUESTION_TYPES] },
|
|
||||||
questionText: { type: 'string', minLength: 1 },
|
|
||||||
options: {
|
|
||||||
type: 'array',
|
|
||||||
items: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['key', 'text'],
|
|
||||||
properties: {
|
|
||||||
key: { type: 'string' },
|
|
||||||
text: { type: 'string' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
correctAnswer: {
|
|
||||||
oneOf: [
|
|
||||||
{ type: 'string' },
|
|
||||||
{ type: 'array', items: { type: 'string' } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
explanation: { type: 'string', minLength: 1 },
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function adminQuestionsRoutes(app: FastifyInstance) {
|
|
||||||
const adminQuestionService = new AdminQuestionService(app.db);
|
|
||||||
const { rateLimitOptions } = app;
|
|
||||||
|
|
||||||
app.get(
|
|
||||||
'/questions/pending',
|
|
||||||
{
|
|
||||||
schema: listPendingQuerySchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate, app.authenticateAdmin],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const { limit, offset } = (req.query as { limit?: number; offset?: number }) ?? {};
|
|
||||||
const result = await adminQuestionService.listPending(limit, offset);
|
|
||||||
return reply.send(result);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post(
|
|
||||||
'/questions/:questionId/approve',
|
|
||||||
{
|
|
||||||
schema: questionIdParamsSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate, app.authenticateAdmin],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const adminId = req.user!.id;
|
|
||||||
const { questionId } = req.params as { questionId: string };
|
|
||||||
await adminQuestionService.approve(questionId, adminId);
|
|
||||||
return reply.status(204).send();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post(
|
|
||||||
'/questions/:questionId/reject',
|
|
||||||
{
|
|
||||||
schema: questionIdParamsSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate, app.authenticateAdmin],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const adminId = req.user!.id;
|
|
||||||
const { questionId } = req.params as { questionId: string };
|
|
||||||
await adminQuestionService.reject(questionId, adminId);
|
|
||||||
return reply.status(204).send();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
app.patch(
|
|
||||||
'/questions/:questionId',
|
|
||||||
{
|
|
||||||
schema: editQuestionSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate, app.authenticateAdmin],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const adminId = req.user!.id;
|
|
||||||
const { questionId } = req.params as { questionId: string };
|
|
||||||
const body = req.body as EditQuestionInput;
|
|
||||||
const question = await adminQuestionService.edit(questionId, body, adminId);
|
|
||||||
return reply.send(question);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
import type { FastifyInstance } from 'fastify';
|
||||||
import { AuthService } from '../services/auth/auth.service.js';
|
import { AuthService } from '../services/auth/auth.service.js';
|
||||||
import { checkBlocked, clearOnSuccess, recordFailedAttempt } from '../utils/loginLockout.js';
|
|
||||||
|
|
||||||
const registerSchema = {
|
const registerSchema = {
|
||||||
body: {
|
body: {
|
||||||
@@ -90,43 +89,20 @@ export async function authRoutes(app: FastifyInstance) {
|
|||||||
|
|
||||||
app.post(
|
app.post(
|
||||||
'/login',
|
'/login',
|
||||||
{
|
{ schema: loginSchema, config: { rateLimit: rateLimitOptions.login } },
|
||||||
schema: loginSchema,
|
|
||||||
preValidation: async (req, reply) => {
|
|
||||||
const ip = req.ip ?? 'unknown';
|
|
||||||
const { blocked, retryAfter } = await checkBlocked(app.redis, ip);
|
|
||||||
if (blocked) {
|
|
||||||
if (retryAfter !== undefined) {
|
|
||||||
reply.header('Retry-After', String(retryAfter));
|
|
||||||
}
|
|
||||||
return reply.status(429).send({
|
|
||||||
error: {
|
|
||||||
code: 'RATE_LIMIT_EXCEEDED',
|
|
||||||
message: 'Too many failed login attempts. Please try again later.',
|
|
||||||
retryAfter,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
async (req, reply) => {
|
||||||
const body = req.body as { email: string; password: string };
|
const body = req.body as { email: string; password: string };
|
||||||
const userAgent = req.headers['user-agent'];
|
const userAgent = req.headers['user-agent'];
|
||||||
const ip = req.ip ?? 'unknown';
|
const ipAddress = req.ip;
|
||||||
|
|
||||||
try {
|
const result = await authService.login({
|
||||||
const result = await authService.login({
|
email: body.email,
|
||||||
email: body.email,
|
password: body.password,
|
||||||
password: body.password,
|
userAgent,
|
||||||
userAgent,
|
ipAddress,
|
||||||
ipAddress: ip,
|
});
|
||||||
});
|
|
||||||
await clearOnSuccess(app.redis, ip);
|
return reply.send(result);
|
||||||
return reply.send(result);
|
|
||||||
} catch (err) {
|
|
||||||
await recordFailedAttempt(app.redis, ip);
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,185 +0,0 @@
|
|||||||
import type { FastifyInstance } from 'fastify';
|
|
||||||
import { LlmService } from '../services/llm/llm.service.js';
|
|
||||||
import { QuestionService } from '../services/questions/question.service.js';
|
|
||||||
import { TestsService } from '../services/tests/tests.service.js';
|
|
||||||
import { notFound } from '../utils/errors.js';
|
|
||||||
import type { CreateTestInput } from '../services/tests/tests.service.js';
|
|
||||||
import type { TestSnapshot } from '../services/tests/tests.service.js';
|
|
||||||
|
|
||||||
const STACKS = ['html', 'css', 'js', 'ts', 'react', 'vue', 'nodejs', 'git', 'web_basics'] as const;
|
|
||||||
const LEVELS = ['basic', 'beginner', 'intermediate', 'advanced', 'expert'] as const;
|
|
||||||
|
|
||||||
const createTestSchema = {
|
|
||||||
body: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['stack', 'level', 'questionCount'],
|
|
||||||
properties: {
|
|
||||||
stack: { type: 'string', enum: STACKS },
|
|
||||||
level: { type: 'string', enum: LEVELS },
|
|
||||||
questionCount: { type: 'integer', minimum: 1, maximum: 50 },
|
|
||||||
mode: { type: 'string', enum: ['fixed', 'infinite', 'marathon'] },
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const testIdParamsSchema = {
|
|
||||||
params: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['testId'],
|
|
||||||
properties: {
|
|
||||||
testId: { type: 'string', format: 'uuid' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const answerSchema = {
|
|
||||||
params: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['testId'],
|
|
||||||
properties: {
|
|
||||||
testId: { type: 'string', format: 'uuid' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
body: {
|
|
||||||
type: 'object',
|
|
||||||
required: ['questionId', 'answer'],
|
|
||||||
properties: {
|
|
||||||
questionId: { type: 'string', format: 'uuid' },
|
|
||||||
answer: {
|
|
||||||
oneOf: [
|
|
||||||
{ type: 'string' },
|
|
||||||
{ type: 'array', items: { type: 'string' } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const historyQuerySchema = {
|
|
||||||
querystring: {
|
|
||||||
type: 'object',
|
|
||||||
properties: {
|
|
||||||
limit: { type: 'integer', minimum: 1, maximum: 100 },
|
|
||||||
offset: { type: 'integer', minimum: 0 },
|
|
||||||
},
|
|
||||||
additionalProperties: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
function stripAnswersForClient(
|
|
||||||
q: TestSnapshot
|
|
||||||
): Omit<TestSnapshot, 'correctAnswer' | 'explanation'> {
|
|
||||||
const { correctAnswer: _, explanation: __, ...rest } = q;
|
|
||||||
return rest;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function testsRoutes(app: FastifyInstance) {
|
|
||||||
const llmService = new LlmService();
|
|
||||||
const questionService = new QuestionService(app.db, llmService);
|
|
||||||
const testsService = new TestsService(app.db, questionService);
|
|
||||||
const { rateLimitOptions } = app;
|
|
||||||
|
|
||||||
app.get(
|
|
||||||
'/',
|
|
||||||
{
|
|
||||||
schema: historyQuerySchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const userId = req.user!.id;
|
|
||||||
const { limit, offset } = (req.query as { limit?: number; offset?: number }) ?? {};
|
|
||||||
const { tests: testList, total } = await testsService.getHistory(
|
|
||||||
userId,
|
|
||||||
{ limit, offset }
|
|
||||||
);
|
|
||||||
return reply.send({ tests: testList, total });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post(
|
|
||||||
'/',
|
|
||||||
{
|
|
||||||
schema: createTestSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate, app.withSubscription],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const userId = req.user!.id;
|
|
||||||
const body = req.body as CreateTestInput;
|
|
||||||
const test = await testsService.createTest(userId, body);
|
|
||||||
const hideAnswers = test.status === 'in_progress';
|
|
||||||
const response = {
|
|
||||||
...test,
|
|
||||||
questions: hideAnswers
|
|
||||||
? test.questions.map(stripAnswersForClient)
|
|
||||||
: test.questions,
|
|
||||||
};
|
|
||||||
return reply.status(201).send(response);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post(
|
|
||||||
'/:testId/answer',
|
|
||||||
{
|
|
||||||
schema: answerSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const userId = req.user!.id;
|
|
||||||
const { testId } = req.params as { testId: string };
|
|
||||||
const { questionId, answer } = req.body as { questionId: string; answer: string | string[] };
|
|
||||||
const snapshot = await testsService.answerQuestion(
|
|
||||||
userId,
|
|
||||||
testId,
|
|
||||||
questionId,
|
|
||||||
answer
|
|
||||||
);
|
|
||||||
return reply.send(snapshot);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
app.post(
|
|
||||||
'/:testId/finish',
|
|
||||||
{
|
|
||||||
schema: testIdParamsSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const userId = req.user!.id;
|
|
||||||
const { testId } = req.params as { testId: string };
|
|
||||||
const test = await testsService.finishTest(userId, testId);
|
|
||||||
return reply.send(test);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
app.get(
|
|
||||||
'/:testId',
|
|
||||||
{
|
|
||||||
schema: testIdParamsSchema,
|
|
||||||
config: { rateLimit: rateLimitOptions.apiAuthed },
|
|
||||||
preHandler: [app.authenticate],
|
|
||||||
},
|
|
||||||
async (req, reply) => {
|
|
||||||
const userId = req.user!.id;
|
|
||||||
const { testId } = req.params as { testId: string };
|
|
||||||
const test = await testsService.getById(userId, testId);
|
|
||||||
if (!test) {
|
|
||||||
throw notFound('Test not found');
|
|
||||||
}
|
|
||||||
const hideAnswers = test.status === 'in_progress';
|
|
||||||
const response = {
|
|
||||||
...test,
|
|
||||||
questions: hideAnswers
|
|
||||||
? test.questions.map(stripAnswersForClient)
|
|
||||||
: test.questions,
|
|
||||||
};
|
|
||||||
return reply.send(response);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
import { eq, asc, count } from 'drizzle-orm';
|
|
||||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
|
||||||
import type * as schema from '../../db/schema/index.js';
|
|
||||||
import { questionBank, auditLogs } from '../../db/schema/index.js';
|
|
||||||
import { notFound } from '../../utils/errors.js';
|
|
||||||
import type { Stack, Level, QuestionType } from '../../db/schema/enums.js';
|
|
||||||
|
|
||||||
type Db = NodePgDatabase<typeof schema>;
|
|
||||||
|
|
||||||
export type PendingQuestion = {
|
|
||||||
id: string;
|
|
||||||
stack: Stack;
|
|
||||||
level: Level;
|
|
||||||
type: QuestionType;
|
|
||||||
questionText: string;
|
|
||||||
options: Array<{ key: string; text: string }> | null;
|
|
||||||
correctAnswer: string | string[];
|
|
||||||
explanation: string;
|
|
||||||
source: string;
|
|
||||||
createdAt: Date;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type EditQuestionInput = {
|
|
||||||
stack?: Stack;
|
|
||||||
level?: Level;
|
|
||||||
type?: QuestionType;
|
|
||||||
questionText?: string;
|
|
||||||
options?: Array<{ key: string; text: string }> | null;
|
|
||||||
correctAnswer?: string | string[];
|
|
||||||
explanation?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListPendingResult = {
|
|
||||||
questions: PendingQuestion[];
|
|
||||||
total: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export class AdminQuestionService {
|
|
||||||
constructor(private readonly db: Db) {}
|
|
||||||
|
|
||||||
async listPending(limit = 50, offset = 0): Promise<ListPendingResult> {
|
|
||||||
const questions = await this.db
|
|
||||||
.select({
|
|
||||||
id: questionBank.id,
|
|
||||||
stack: questionBank.stack,
|
|
||||||
level: questionBank.level,
|
|
||||||
type: questionBank.type,
|
|
||||||
questionText: questionBank.questionText,
|
|
||||||
options: questionBank.options,
|
|
||||||
correctAnswer: questionBank.correctAnswer,
|
|
||||||
explanation: questionBank.explanation,
|
|
||||||
source: questionBank.source,
|
|
||||||
createdAt: questionBank.createdAt,
|
|
||||||
})
|
|
||||||
.from(questionBank)
|
|
||||||
.where(eq(questionBank.status, 'pending'))
|
|
||||||
.orderBy(asc(questionBank.createdAt))
|
|
||||||
.limit(limit)
|
|
||||||
.offset(offset);
|
|
||||||
|
|
||||||
const [{ count: totalCount }] = await this.db
|
|
||||||
.select({ count: count() })
|
|
||||||
.from(questionBank)
|
|
||||||
.where(eq(questionBank.status, 'pending'));
|
|
||||||
|
|
||||||
return {
|
|
||||||
questions: questions.map((q) => ({
|
|
||||||
id: q.id,
|
|
||||||
stack: q.stack,
|
|
||||||
level: q.level,
|
|
||||||
type: q.type,
|
|
||||||
questionText: q.questionText,
|
|
||||||
options: q.options,
|
|
||||||
correctAnswer: q.correctAnswer,
|
|
||||||
explanation: q.explanation,
|
|
||||||
source: q.source,
|
|
||||||
createdAt: q.createdAt,
|
|
||||||
})),
|
|
||||||
total: totalCount ?? 0,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async approve(questionId: string, adminId: string): Promise<void> {
|
|
||||||
const [updated] = await this.db
|
|
||||||
.update(questionBank)
|
|
||||||
.set({
|
|
||||||
status: 'approved',
|
|
||||||
approvedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(questionBank.id, questionId))
|
|
||||||
.returning({ id: questionBank.id });
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
throw notFound('Question not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.db.insert(auditLogs).values({
|
|
||||||
adminId,
|
|
||||||
action: 'question_approved',
|
|
||||||
targetType: 'question',
|
|
||||||
targetId: questionId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async reject(questionId: string, adminId: string): Promise<void> {
|
|
||||||
const [updated] = await this.db
|
|
||||||
.update(questionBank)
|
|
||||||
.set({ status: 'rejected' })
|
|
||||||
.where(eq(questionBank.id, questionId))
|
|
||||||
.returning({ id: questionBank.id });
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
throw notFound('Question not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.db.insert(auditLogs).values({
|
|
||||||
adminId,
|
|
||||||
action: 'question_rejected',
|
|
||||||
targetType: 'question',
|
|
||||||
targetId: questionId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async edit(questionId: string, input: EditQuestionInput, adminId: string): Promise<PendingQuestion> {
|
|
||||||
const updates: Partial<{
|
|
||||||
stack: Stack;
|
|
||||||
level: Level;
|
|
||||||
type: QuestionType;
|
|
||||||
questionText: string;
|
|
||||||
options: Array<{ key: string; text: string }> | null;
|
|
||||||
correctAnswer: string | string[];
|
|
||||||
explanation: string;
|
|
||||||
}> = {};
|
|
||||||
|
|
||||||
if (input.stack !== undefined) updates.stack = input.stack;
|
|
||||||
if (input.level !== undefined) updates.level = input.level;
|
|
||||||
if (input.type !== undefined) updates.type = input.type;
|
|
||||||
if (input.questionText !== undefined) updates.questionText = input.questionText;
|
|
||||||
if (input.options !== undefined) updates.options = input.options;
|
|
||||||
if (input.correctAnswer !== undefined) updates.correctAnswer = input.correctAnswer;
|
|
||||||
if (input.explanation !== undefined) updates.explanation = input.explanation;
|
|
||||||
|
|
||||||
if (Object.keys(updates).length === 0) {
|
|
||||||
const [existing] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(questionBank)
|
|
||||||
.where(eq(questionBank.id, questionId));
|
|
||||||
if (!existing) throw notFound('Question not found');
|
|
||||||
return {
|
|
||||||
id: existing.id,
|
|
||||||
stack: existing.stack,
|
|
||||||
level: existing.level,
|
|
||||||
type: existing.type,
|
|
||||||
questionText: existing.questionText,
|
|
||||||
options: existing.options,
|
|
||||||
correctAnswer: existing.correctAnswer,
|
|
||||||
explanation: existing.explanation,
|
|
||||||
source: existing.source,
|
|
||||||
createdAt: existing.createdAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const [updated] = await this.db
|
|
||||||
.update(questionBank)
|
|
||||||
.set(updates)
|
|
||||||
.where(eq(questionBank.id, questionId))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
throw notFound('Question not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.db.insert(auditLogs).values({
|
|
||||||
adminId,
|
|
||||||
action: 'question_edited',
|
|
||||||
targetType: 'question',
|
|
||||||
targetId: questionId,
|
|
||||||
details: updates as Record<string, unknown>,
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: updated.id,
|
|
||||||
stack: updated.stack,
|
|
||||||
level: updated.level,
|
|
||||||
type: updated.type,
|
|
||||||
questionText: updated.questionText,
|
|
||||||
options: updated.options,
|
|
||||||
correctAnswer: updated.correctAnswer,
|
|
||||||
explanation: updated.explanation,
|
|
||||||
source: updated.source,
|
|
||||||
createdAt: updated.createdAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
9
src/services/llm/index.ts
Normal file
9
src/services/llm/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export {
|
||||||
|
LlmService,
|
||||||
|
type ILlmService,
|
||||||
|
type LlmConfig,
|
||||||
|
type LlmGenerationMeta,
|
||||||
|
type GenerateQuestionsInput,
|
||||||
|
type GenerateQuestionsResult,
|
||||||
|
type GeneratedQuestion,
|
||||||
|
} from './llm.service.js';
|
||||||
@@ -71,7 +71,12 @@ export interface GenerateQuestionsResult {
|
|||||||
meta: LlmGenerationMeta;
|
meta: LlmGenerationMeta;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class LlmService {
|
/** Interface for QuestionService dependency injection and testing */
|
||||||
|
export interface ILlmService {
|
||||||
|
generateQuestions(input: GenerateQuestionsInput): Promise<GenerateQuestionsResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class LlmService implements ILlmService {
|
||||||
private readonly config: LlmConfig;
|
private readonly config: LlmConfig;
|
||||||
|
|
||||||
constructor(config?: Partial<LlmConfig>) {
|
constructor(config?: Partial<LlmConfig>) {
|
||||||
|
|||||||
@@ -1,197 +0,0 @@
|
|||||||
import { eq, and, sql, asc, inArray } from 'drizzle-orm';
|
|
||||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
|
||||||
import type * as schema from '../../db/schema/index.js';
|
|
||||||
import {
|
|
||||||
questionBank,
|
|
||||||
questionCacheMeta,
|
|
||||||
userQuestionLog,
|
|
||||||
} from '../../db/schema/index.js';
|
|
||||||
import { internalError, AppError, ERROR_CODES } from '../../utils/errors.js';
|
|
||||||
import type { Stack, Level, QuestionType } from '../../db/schema/enums.js';
|
|
||||||
import type {
|
|
||||||
GeneratedQuestion,
|
|
||||||
GenerateQuestionsResult,
|
|
||||||
} from '../llm/llm.service.js';
|
|
||||||
|
|
||||||
type Db = NodePgDatabase<typeof schema>;
|
|
||||||
|
|
||||||
export type QuestionForTest = {
|
|
||||||
questionBankId: string;
|
|
||||||
type: QuestionType;
|
|
||||||
questionText: string;
|
|
||||||
options: Array<{ key: string; text: string }> | null;
|
|
||||||
correctAnswer: string | string[];
|
|
||||||
explanation: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface LlmServiceInterface {
|
|
||||||
generateQuestions(input: {
|
|
||||||
stack: Stack;
|
|
||||||
level: Level;
|
|
||||||
count: number;
|
|
||||||
types?: QuestionType[];
|
|
||||||
}): Promise<GenerateQuestionsResult>;
|
|
||||||
}
|
|
||||||
|
|
||||||
function shuffle<T>(arr: T[]): T[] {
|
|
||||||
const result = [...arr];
|
|
||||||
for (let i = result.length - 1; i > 0; i--) {
|
|
||||||
const j = Math.floor(Math.random() * (i + 1));
|
|
||||||
[result[i], result[j]] = [result[j]!, result[i]!];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class QuestionService {
|
|
||||||
constructor(
|
|
||||||
private readonly db: Db,
|
|
||||||
private readonly llmService: LlmServiceInterface
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get questions for a test. Fetches approved questions from question_bank.
|
|
||||||
* If not enough, generates via LLM, persists to question_bank and question_cache_meta.
|
|
||||||
*/
|
|
||||||
async getQuestionsForTest(
|
|
||||||
userId: string,
|
|
||||||
stack: Stack,
|
|
||||||
level: Level,
|
|
||||||
count: number
|
|
||||||
): Promise<QuestionForTest[]> {
|
|
||||||
const approved = await this.db
|
|
||||||
.select({
|
|
||||||
id: questionBank.id,
|
|
||||||
type: questionBank.type,
|
|
||||||
questionText: questionBank.questionText,
|
|
||||||
options: questionBank.options,
|
|
||||||
correctAnswer: questionBank.correctAnswer,
|
|
||||||
explanation: questionBank.explanation,
|
|
||||||
})
|
|
||||||
.from(questionBank)
|
|
||||||
.where(
|
|
||||||
and(eq(questionBank.stack, stack), eq(questionBank.level, level), eq(questionBank.status, 'approved'))
|
|
||||||
)
|
|
||||||
.orderBy(asc(questionBank.usageCount));
|
|
||||||
|
|
||||||
const seenIds = await this.db
|
|
||||||
.select({ questionBankId: userQuestionLog.questionBankId })
|
|
||||||
.from(userQuestionLog)
|
|
||||||
.where(eq(userQuestionLog.userId, userId));
|
|
||||||
|
|
||||||
const seenSet = new Set(seenIds.map((r) => r.questionBankId));
|
|
||||||
const preferred = approved.filter((q) => !seenSet.has(q.id));
|
|
||||||
const pool = preferred.length >= count ? preferred : approved;
|
|
||||||
const shuffled = shuffle(pool);
|
|
||||||
|
|
||||||
const fromBank: QuestionForTest[] = shuffled.slice(0, count).map((q) => ({
|
|
||||||
questionBankId: q.id,
|
|
||||||
type: q.type,
|
|
||||||
questionText: q.questionText,
|
|
||||||
options: q.options,
|
|
||||||
correctAnswer: q.correctAnswer,
|
|
||||||
explanation: q.explanation,
|
|
||||||
}));
|
|
||||||
|
|
||||||
let result = fromBank;
|
|
||||||
|
|
||||||
if (result.length < count) {
|
|
||||||
const generated = await this.generateAndPersistQuestions(
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
count - result.length
|
|
||||||
);
|
|
||||||
result = [...result, ...generated];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.length < count) {
|
|
||||||
throw new AppError(
|
|
||||||
ERROR_CODES.QUESTIONS_UNAVAILABLE,
|
|
||||||
'Not enough questions available for this stack and level',
|
|
||||||
422
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.length > 0) {
|
|
||||||
await this.db.insert(userQuestionLog).values(
|
|
||||||
result.map((q) => ({
|
|
||||||
userId,
|
|
||||||
questionBankId: q.questionBankId,
|
|
||||||
}))
|
|
||||||
);
|
|
||||||
|
|
||||||
const ids = result.map((q) => q.questionBankId);
|
|
||||||
await this.db
|
|
||||||
.update(questionBank)
|
|
||||||
.set({
|
|
||||||
usageCount: sql`${questionBank.usageCount} + 1`,
|
|
||||||
})
|
|
||||||
.where(inArray(questionBank.id, ids));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async generateAndPersistQuestions(
|
|
||||||
stack: Stack,
|
|
||||||
level: Level,
|
|
||||||
count: number
|
|
||||||
): Promise<QuestionForTest[]> {
|
|
||||||
let generated: GeneratedQuestion[];
|
|
||||||
let meta: GenerateQuestionsResult['meta'];
|
|
||||||
|
|
||||||
try {
|
|
||||||
const result = await this.llmService.generateQuestions({
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
count,
|
|
||||||
});
|
|
||||||
generated = result.questions;
|
|
||||||
meta = result.meta;
|
|
||||||
} catch (err) {
|
|
||||||
throw internalError(
|
|
||||||
'Failed to generate questions',
|
|
||||||
err instanceof Error ? err : undefined
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const inserted: QuestionForTest[] = [];
|
|
||||||
|
|
||||||
for (const q of generated) {
|
|
||||||
const [row] = await this.db
|
|
||||||
.insert(questionBank)
|
|
||||||
.values({
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
type: q.type as QuestionType,
|
|
||||||
questionText: q.questionText,
|
|
||||||
options: q.options ?? null,
|
|
||||||
correctAnswer: q.correctAnswer,
|
|
||||||
explanation: q.explanation,
|
|
||||||
status: 'approved',
|
|
||||||
source: 'llm_generated',
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (row) {
|
|
||||||
await this.db.insert(questionCacheMeta).values({
|
|
||||||
questionBankId: row.id,
|
|
||||||
llmModel: meta.llmModel,
|
|
||||||
promptHash: meta.promptHash,
|
|
||||||
generationTimeMs: meta.generationTimeMs,
|
|
||||||
rawResponse: meta.rawResponse,
|
|
||||||
});
|
|
||||||
|
|
||||||
inserted.push({
|
|
||||||
questionBankId: row.id,
|
|
||||||
type: row.type,
|
|
||||||
questionText: row.questionText,
|
|
||||||
options: row.options,
|
|
||||||
correctAnswer: row.correctAnswer,
|
|
||||||
explanation: row.explanation,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return inserted;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,399 +0,0 @@
|
|||||||
import { eq, and, desc } from 'drizzle-orm';
|
|
||||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
|
||||||
import type * as schema from '../../db/schema/index.js';
|
|
||||||
import { tests, testQuestions, userStats } from '../../db/schema/index.js';
|
|
||||||
import { notFound, conflict, AppError, ERROR_CODES } from '../../utils/errors.js';
|
|
||||||
import type { Stack, Level, TestMode } from '../../db/schema/enums.js';
|
|
||||||
import type { QuestionService } from '../questions/question.service.js';
|
|
||||||
|
|
||||||
type Db = NodePgDatabase<typeof schema>;
|
|
||||||
|
|
||||||
export type CreateTestInput = {
|
|
||||||
stack: Stack;
|
|
||||||
level: Level;
|
|
||||||
questionCount: number;
|
|
||||||
mode?: TestMode;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TestSnapshot = {
|
|
||||||
id: string;
|
|
||||||
testId: string;
|
|
||||||
questionBankId: string | null;
|
|
||||||
orderNumber: number;
|
|
||||||
type: string;
|
|
||||||
questionText: string;
|
|
||||||
options: Array<{ key: string; text: string }> | null;
|
|
||||||
correctAnswer: string | string[];
|
|
||||||
explanation: string;
|
|
||||||
userAnswer?: string | string[] | null;
|
|
||||||
isCorrect?: boolean | null;
|
|
||||||
answeredAt?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TestWithQuestions = {
|
|
||||||
id: string;
|
|
||||||
userId: string;
|
|
||||||
stack: string;
|
|
||||||
level: string;
|
|
||||||
questionCount: number;
|
|
||||||
mode: string;
|
|
||||||
status: string;
|
|
||||||
score: number | null;
|
|
||||||
startedAt: string;
|
|
||||||
finishedAt: string | null;
|
|
||||||
timeLimitSeconds: number | null;
|
|
||||||
questions: TestSnapshot[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export class TestsService {
|
|
||||||
constructor(
|
|
||||||
private readonly db: Db,
|
|
||||||
private readonly questionService: QuestionService
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new test: fetch questions, create test record, snapshot questions into test_questions.
|
|
||||||
*/
|
|
||||||
async createTest(userId: string, input: CreateTestInput): Promise<TestWithQuestions> {
|
|
||||||
const { stack, level, questionCount, mode = 'fixed' } = input;
|
|
||||||
|
|
||||||
if (questionCount < 1 || questionCount > 50) {
|
|
||||||
throw new AppError(
|
|
||||||
ERROR_CODES.BAD_REQUEST,
|
|
||||||
'questionCount must be between 1 and 50',
|
|
||||||
400
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const questions = await this.questionService.getQuestionsForTest(
|
|
||||||
userId,
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
questionCount
|
|
||||||
);
|
|
||||||
|
|
||||||
const [test] = await this.db
|
|
||||||
.insert(tests)
|
|
||||||
.values({
|
|
||||||
userId,
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
questionCount,
|
|
||||||
mode,
|
|
||||||
status: 'in_progress',
|
|
||||||
})
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (!test) {
|
|
||||||
throw new AppError(
|
|
||||||
ERROR_CODES.INTERNAL_ERROR,
|
|
||||||
'Failed to create test',
|
|
||||||
500
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const tqValues = questions.map((q, i) => ({
|
|
||||||
testId: test.id,
|
|
||||||
questionBankId: q.questionBankId,
|
|
||||||
orderNumber: i + 1,
|
|
||||||
type: q.type,
|
|
||||||
questionText: q.questionText,
|
|
||||||
options: q.options,
|
|
||||||
correctAnswer: q.correctAnswer,
|
|
||||||
explanation: q.explanation,
|
|
||||||
}));
|
|
||||||
|
|
||||||
await this.db.insert(testQuestions).values(tqValues);
|
|
||||||
|
|
||||||
const questionsRows = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(eq(testQuestions.testId, test.id))
|
|
||||||
.orderBy(testQuestions.orderNumber);
|
|
||||||
|
|
||||||
return this.toTestWithQuestions(test, questionsRows);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Submit an answer for a question in an in-progress test.
|
|
||||||
*/
|
|
||||||
async answerQuestion(
|
|
||||||
userId: string,
|
|
||||||
testId: string,
|
|
||||||
testQuestionId: string,
|
|
||||||
userAnswer: string | string[]
|
|
||||||
): Promise<TestSnapshot> {
|
|
||||||
const [test] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(tests)
|
|
||||||
.where(and(eq(tests.id, testId), eq(tests.userId, userId)))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!test) {
|
|
||||||
throw notFound('Test not found');
|
|
||||||
}
|
|
||||||
if (test.status !== 'in_progress') {
|
|
||||||
throw conflict(ERROR_CODES.TEST_ALREADY_FINISHED, 'Test is already finished');
|
|
||||||
}
|
|
||||||
|
|
||||||
const [tq] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(testQuestions.id, testQuestionId),
|
|
||||||
eq(testQuestions.testId, testId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!tq) {
|
|
||||||
throw conflict(ERROR_CODES.WRONG_QUESTION, 'Question does not belong to this test');
|
|
||||||
}
|
|
||||||
if (tq.userAnswer !== null && tq.userAnswer !== undefined) {
|
|
||||||
throw conflict(ERROR_CODES.QUESTION_ALREADY_ANSWERED, 'Question already answered');
|
|
||||||
}
|
|
||||||
|
|
||||||
const isCorrect = this.checkAnswer(tq.correctAnswer, userAnswer);
|
|
||||||
|
|
||||||
const [updated] = await this.db
|
|
||||||
.update(testQuestions)
|
|
||||||
.set({
|
|
||||||
userAnswer,
|
|
||||||
isCorrect,
|
|
||||||
answeredAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(testQuestions.id, testQuestionId))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (!updated) {
|
|
||||||
throw notFound('Question not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: updated.id,
|
|
||||||
testId: updated.testId,
|
|
||||||
questionBankId: updated.questionBankId,
|
|
||||||
orderNumber: updated.orderNumber,
|
|
||||||
type: updated.type,
|
|
||||||
questionText: updated.questionText,
|
|
||||||
options: updated.options,
|
|
||||||
correctAnswer: updated.correctAnswer,
|
|
||||||
explanation: updated.explanation,
|
|
||||||
userAnswer: updated.userAnswer,
|
|
||||||
isCorrect: updated.isCorrect,
|
|
||||||
answeredAt: updated.answeredAt?.toISOString() ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private checkAnswer(
|
|
||||||
correct: string | string[],
|
|
||||||
user: string | string[]
|
|
||||||
): boolean {
|
|
||||||
if (Array.isArray(correct) && Array.isArray(user)) {
|
|
||||||
if (correct.length !== user.length) return false;
|
|
||||||
const a = [...correct].sort();
|
|
||||||
const b = [...user].sort();
|
|
||||||
return a.every((v, i) => v === b[i]);
|
|
||||||
}
|
|
||||||
if (typeof correct === 'string' && typeof user === 'string') {
|
|
||||||
return correct.trim().toLowerCase() === user.trim().toLowerCase();
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Finish a test: calculate score, update user_stats.
|
|
||||||
*/
|
|
||||||
async finishTest(userId: string, testId: string): Promise<TestWithQuestions> {
|
|
||||||
const [test] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(tests)
|
|
||||||
.where(and(eq(tests.id, testId), eq(tests.userId, userId)))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!test) {
|
|
||||||
throw notFound('Test not found');
|
|
||||||
}
|
|
||||||
if (test.status !== 'in_progress') {
|
|
||||||
throw conflict(ERROR_CODES.TEST_ALREADY_FINISHED, 'Test is already finished');
|
|
||||||
}
|
|
||||||
|
|
||||||
const questions = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(eq(testQuestions.testId, testId));
|
|
||||||
|
|
||||||
const unanswered = questions.filter(
|
|
||||||
(q) => q.userAnswer === null || q.userAnswer === undefined
|
|
||||||
);
|
|
||||||
if (unanswered.length > 0) {
|
|
||||||
throw new AppError(
|
|
||||||
ERROR_CODES.NO_ANSWERS,
|
|
||||||
`Cannot finish: ${unanswered.length} question(s) not answered`,
|
|
||||||
422
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const correctCount = questions.filter((q) => q.isCorrect === true).length;
|
|
||||||
const score = Math.round((correctCount / questions.length) * 100);
|
|
||||||
|
|
||||||
const [updatedTest] = await this.db
|
|
||||||
.update(tests)
|
|
||||||
.set({
|
|
||||||
status: 'completed',
|
|
||||||
score,
|
|
||||||
finishedAt: new Date(),
|
|
||||||
})
|
|
||||||
.where(eq(tests.id, testId))
|
|
||||||
.returning();
|
|
||||||
|
|
||||||
if (!updatedTest) {
|
|
||||||
throw notFound('Test not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.upsertUserStats(userId, test.stack as Stack, test.level as Level, {
|
|
||||||
totalQuestions: questions.length,
|
|
||||||
correctAnswers: correctCount,
|
|
||||||
testsTaken: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
const questionsRows = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(eq(testQuestions.testId, testId))
|
|
||||||
.orderBy(testQuestions.orderNumber);
|
|
||||||
|
|
||||||
return this.toTestWithQuestions(updatedTest, questionsRows);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async upsertUserStats(
|
|
||||||
userId: string,
|
|
||||||
stack: Stack,
|
|
||||||
level: Level,
|
|
||||||
delta: { totalQuestions: number; correctAnswers: number; testsTaken: number }
|
|
||||||
): Promise<void> {
|
|
||||||
const [existing] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(userStats)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userStats.userId, userId),
|
|
||||||
eq(userStats.stack, stack),
|
|
||||||
eq(userStats.level, level)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
const now = new Date();
|
|
||||||
|
|
||||||
if (existing) {
|
|
||||||
await this.db
|
|
||||||
.update(userStats)
|
|
||||||
.set({
|
|
||||||
totalQuestions: existing.totalQuestions + delta.totalQuestions,
|
|
||||||
correctAnswers: existing.correctAnswers + delta.correctAnswers,
|
|
||||||
testsTaken: existing.testsTaken + delta.testsTaken,
|
|
||||||
lastTestAt: now,
|
|
||||||
})
|
|
||||||
.where(eq(userStats.id, existing.id));
|
|
||||||
} else {
|
|
||||||
await this.db.insert(userStats).values({
|
|
||||||
userId,
|
|
||||||
stack,
|
|
||||||
level,
|
|
||||||
totalQuestions: delta.totalQuestions,
|
|
||||||
correctAnswers: delta.correctAnswers,
|
|
||||||
testsTaken: delta.testsTaken,
|
|
||||||
lastTestAt: now,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a single test by ID (must belong to user).
|
|
||||||
*/
|
|
||||||
async getById(userId: string, testId: string): Promise<TestWithQuestions | null> {
|
|
||||||
const [test] = await this.db
|
|
||||||
.select()
|
|
||||||
.from(tests)
|
|
||||||
.where(and(eq(tests.id, testId), eq(tests.userId, userId)))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!test) return null;
|
|
||||||
|
|
||||||
const questionsRows = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(eq(testQuestions.testId, testId))
|
|
||||||
.orderBy(testQuestions.orderNumber);
|
|
||||||
|
|
||||||
return this.toTestWithQuestions(test, questionsRows);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get test history for a user (most recent first).
|
|
||||||
*/
|
|
||||||
async getHistory(
|
|
||||||
userId: string,
|
|
||||||
options?: { limit?: number; offset?: number }
|
|
||||||
): Promise<{ tests: TestWithQuestions[]; total: number }> {
|
|
||||||
const limit = Math.min(options?.limit ?? 20, 100);
|
|
||||||
const offset = options?.offset ?? 0;
|
|
||||||
|
|
||||||
const all = await this.db
|
|
||||||
.select()
|
|
||||||
.from(tests)
|
|
||||||
.where(eq(tests.userId, userId))
|
|
||||||
.orderBy(desc(tests.startedAt));
|
|
||||||
|
|
||||||
const total = all.length;
|
|
||||||
const page = all.slice(offset, offset + limit);
|
|
||||||
|
|
||||||
const result: TestWithQuestions[] = [];
|
|
||||||
|
|
||||||
for (const test of page) {
|
|
||||||
const questionsRows = await this.db
|
|
||||||
.select()
|
|
||||||
.from(testQuestions)
|
|
||||||
.where(eq(testQuestions.testId, test.id))
|
|
||||||
.orderBy(testQuestions.orderNumber);
|
|
||||||
result.push(this.toTestWithQuestions(test, questionsRows));
|
|
||||||
}
|
|
||||||
|
|
||||||
return { tests: result, total };
|
|
||||||
}
|
|
||||||
|
|
||||||
private toTestWithQuestions(
|
|
||||||
test: (typeof tests.$inferSelect),
|
|
||||||
questionsRows: (typeof testQuestions.$inferSelect)[]
|
|
||||||
): TestWithQuestions {
|
|
||||||
return {
|
|
||||||
id: test.id,
|
|
||||||
userId: test.userId,
|
|
||||||
stack: test.stack,
|
|
||||||
level: test.level,
|
|
||||||
questionCount: test.questionCount,
|
|
||||||
mode: test.mode,
|
|
||||||
status: test.status,
|
|
||||||
score: test.score,
|
|
||||||
startedAt: test.startedAt.toISOString(),
|
|
||||||
finishedAt: test.finishedAt?.toISOString() ?? null,
|
|
||||||
timeLimitSeconds: test.timeLimitSeconds,
|
|
||||||
questions: questionsRows.map((q) => ({
|
|
||||||
id: q.id,
|
|
||||||
testId: q.testId,
|
|
||||||
questionBankId: q.questionBankId,
|
|
||||||
orderNumber: q.orderNumber,
|
|
||||||
type: q.type,
|
|
||||||
questionText: q.questionText,
|
|
||||||
options: q.options,
|
|
||||||
correctAnswer: q.correctAnswer,
|
|
||||||
explanation: q.explanation,
|
|
||||||
userAnswer: q.userAnswer,
|
|
||||||
isCorrect: q.isCorrect,
|
|
||||||
answeredAt: q.answeredAt?.toISOString() ?? null,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,106 +0,0 @@
|
|||||||
import type { Redis } from 'ioredis';
|
|
||||||
|
|
||||||
const WINDOW_15M_SEC = 15 * 60; // 900
|
|
||||||
const WINDOW_1H_SEC = 60 * 60; // 3600
|
|
||||||
const WINDOW_24H_SEC = 24 * 60 * 60; // 86400
|
|
||||||
|
|
||||||
const THRESHOLD_15M = 5;
|
|
||||||
const THRESHOLD_1H = 10;
|
|
||||||
const THRESHOLD_24H = 20;
|
|
||||||
|
|
||||||
const BLOCK_15M_SEC = WINDOW_15M_SEC;
|
|
||||||
const BLOCK_1H_SEC = WINDOW_1H_SEC;
|
|
||||||
const BLOCK_24H_SEC = WINDOW_24H_SEC;
|
|
||||||
|
|
||||||
const KEY_PREFIX = 'lockout';
|
|
||||||
|
|
||||||
function key15m(ip: string): string {
|
|
||||||
return `${KEY_PREFIX}:15m:${ip}`;
|
|
||||||
}
|
|
||||||
function key1h(ip: string): string {
|
|
||||||
return `${KEY_PREFIX}:1h:${ip}`;
|
|
||||||
}
|
|
||||||
function key24h(ip: string): string {
|
|
||||||
return `${KEY_PREFIX}:24h:${ip}`;
|
|
||||||
}
|
|
||||||
function keyBlocked(ip: string): string {
|
|
||||||
return `${KEY_PREFIX}:blocked:${ip}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the IP is currently blocked due to progressive login lockout.
|
|
||||||
* @returns { blocked: true, retryAfter } if blocked, { blocked: false } otherwise
|
|
||||||
*/
|
|
||||||
export async function checkBlocked(
|
|
||||||
redis: Redis,
|
|
||||||
ip: string
|
|
||||||
): Promise<{ blocked: boolean; retryAfter?: number }> {
|
|
||||||
const blockedKey = keyBlocked(ip);
|
|
||||||
const ttl = await redis.ttl(blockedKey);
|
|
||||||
if (ttl > 0) {
|
|
||||||
return { blocked: true, retryAfter: ttl };
|
|
||||||
}
|
|
||||||
return { blocked: false };
|
|
||||||
}
|
|
||||||
|
|
||||||
const RECORD_SCRIPT = `
|
|
||||||
local c15 = redis.call('INCR', KEYS[1])
|
|
||||||
if redis.call('TTL', KEYS[1]) == -1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
|
||||||
local c1h = redis.call('INCR', KEYS[2])
|
|
||||||
if redis.call('TTL', KEYS[2]) == -1 then redis.call('EXPIRE', KEYS[2], ARGV[2]) end
|
|
||||||
local c24 = redis.call('INCR', KEYS[3])
|
|
||||||
if redis.call('TTL', KEYS[3]) == -1 then redis.call('EXPIRE', KEYS[3], ARGV[3]) end
|
|
||||||
return {c15, c1h, c24}
|
|
||||||
`;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Record a failed login attempt. Increments counters and sets blocked key when thresholds are reached.
|
|
||||||
* Thresholds: 5 in 15m -> 15m block; 10 in 1h -> 1h block; 20 in 24h -> 24h block.
|
|
||||||
*/
|
|
||||||
export async function recordFailedAttempt(redis: Redis, ip: string): Promise<void> {
|
|
||||||
const k15 = key15m(ip);
|
|
||||||
const k1h = key1h(ip);
|
|
||||||
const k24 = key24h(ip);
|
|
||||||
const kBlocked = keyBlocked(ip);
|
|
||||||
|
|
||||||
const counts = (await redis.eval(
|
|
||||||
RECORD_SCRIPT,
|
|
||||||
3,
|
|
||||||
k15,
|
|
||||||
k1h,
|
|
||||||
k24,
|
|
||||||
String(WINDOW_15M_SEC),
|
|
||||||
String(WINDOW_1H_SEC),
|
|
||||||
String(WINDOW_24H_SEC)
|
|
||||||
)) as number[];
|
|
||||||
|
|
||||||
const count15m = counts[0] ?? 0;
|
|
||||||
const count1h = counts[1] ?? 0;
|
|
||||||
const count24h = counts[2] ?? 0;
|
|
||||||
|
|
||||||
let blockTtl = 0;
|
|
||||||
if (count24h >= THRESHOLD_24H) {
|
|
||||||
blockTtl = BLOCK_24H_SEC;
|
|
||||||
} else if (count1h >= THRESHOLD_1H) {
|
|
||||||
blockTtl = BLOCK_1H_SEC;
|
|
||||||
} else if (count15m >= THRESHOLD_15M) {
|
|
||||||
blockTtl = BLOCK_15M_SEC;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (blockTtl > 0) {
|
|
||||||
await redis.setex(kBlocked, blockTtl, '1');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear all lockout counters and blocked state on successful login.
|
|
||||||
*/
|
|
||||||
export async function clearOnSuccess(redis: Redis, ip: string): Promise<void> {
|
|
||||||
const keys = [
|
|
||||||
key15m(ip),
|
|
||||||
key1h(ip),
|
|
||||||
key24h(ip),
|
|
||||||
keyBlocked(ip),
|
|
||||||
];
|
|
||||||
await redis.del(...keys);
|
|
||||||
}
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
import Fastify, { FastifyInstance } from 'fastify';
|
|
||||||
import { AppError } from '../../src/utils/errors.js';
|
|
||||||
import { adminQuestionsRoutes } from '../../src/routes/admin/questions.js';
|
|
||||||
import type { MockDb } from '../test-utils.js';
|
|
||||||
import { createMockDb } from '../test-utils.js';
|
|
||||||
|
|
||||||
const mockAdminUser = { id: 'admin-1', email: 'admin@test.com' };
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a minimal Fastify app for admin route integration tests.
|
|
||||||
* Bypasses real auth - preHandlers set req.user to mock admin.
|
|
||||||
*/
|
|
||||||
export async function buildAdminTestApp(mockDb?: MockDb): Promise<FastifyInstance> {
|
|
||||||
const db = mockDb ?? createMockDb();
|
|
||||||
|
|
||||||
const app = Fastify({
|
|
||||||
logger: false,
|
|
||||||
requestIdHeader: 'x-request-id',
|
|
||||||
requestIdLogLabel: 'requestId',
|
|
||||||
});
|
|
||||||
|
|
||||||
app.setErrorHandler((err: unknown, _request, reply) => {
|
|
||||||
const error = err as Error & { statusCode?: number; validation?: unknown };
|
|
||||||
if (err instanceof AppError) {
|
|
||||||
return reply.status(err.statusCode).send(err.toJSON());
|
|
||||||
}
|
|
||||||
if (error.validation) {
|
|
||||||
return reply.status(422).send({
|
|
||||||
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: error.validation },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return reply.status(500).send({ error: { code: 'INTERNAL_ERROR', message: error.message } });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.decorate('db', db);
|
|
||||||
app.decorate('rateLimitOptions', {
|
|
||||||
apiAuthed: { max: 100, timeWindow: '1 minute' },
|
|
||||||
});
|
|
||||||
app.decorateRequest('user', undefined);
|
|
||||||
app.decorate('authenticate', async (req: { user?: { id: string; email: string } }) => {
|
|
||||||
req.user = mockAdminUser;
|
|
||||||
});
|
|
||||||
app.decorate('authenticateAdmin', async (req: { user?: { id: string; email: string } }) => {
|
|
||||||
if (!req.user) req.user = mockAdminUser;
|
|
||||||
(req.user as { role?: string }).role = 'admin';
|
|
||||||
});
|
|
||||||
|
|
||||||
await app.register(adminQuestionsRoutes, { prefix: '/admin' });
|
|
||||||
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
import Fastify, { FastifyInstance } from 'fastify';
|
|
||||||
import { AppError } from '../../src/utils/errors.js';
|
|
||||||
import { authRoutes } from '../../src/routes/auth.js';
|
|
||||||
import type { MockDb } from '../test-utils.js';
|
|
||||||
import { createMockDb } from '../test-utils.js';
|
|
||||||
|
|
||||||
/** Mock Redis for login lockout in auth tests. Implements ttl, setex, del, eval. */
|
|
||||||
const mockRedis = {
|
|
||||||
async ttl(_key: string): Promise<number> {
|
|
||||||
return -2; // key does not exist -> not blocked
|
|
||||||
},
|
|
||||||
async setex(_key: string, _ttl: number, _value: string): Promise<'OK'> {
|
|
||||||
return 'OK';
|
|
||||||
},
|
|
||||||
async del(..._keys: string[]): Promise<number> {
|
|
||||||
return 0;
|
|
||||||
},
|
|
||||||
async eval(
|
|
||||||
_script: string,
|
|
||||||
_keysCount: number,
|
|
||||||
..._keysAndArgs: string[]
|
|
||||||
): Promise<number[]> {
|
|
||||||
return [0, 0, 0]; // counters below threshold
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a minimal Fastify app for auth route integration tests.
|
|
||||||
* Uses mock db, mock Redis for login lockout, and rate limit options (no actual rate limiting).
|
|
||||||
*/
|
|
||||||
export async function buildAuthTestApp(mockDb?: MockDb): Promise<FastifyInstance> {
|
|
||||||
const db = mockDb ?? createMockDb();
|
|
||||||
|
|
||||||
const app = Fastify({
|
|
||||||
logger: false,
|
|
||||||
requestIdHeader: 'x-request-id',
|
|
||||||
requestIdLogLabel: 'requestId',
|
|
||||||
});
|
|
||||||
|
|
||||||
app.setErrorHandler((err: unknown, request, reply) => {
|
|
||||||
const error = err as Error & { statusCode?: number; validation?: unknown };
|
|
||||||
if (err instanceof AppError) {
|
|
||||||
return reply.status(err.statusCode).send(err.toJSON());
|
|
||||||
}
|
|
||||||
if (error.validation) {
|
|
||||||
return reply.status(422).send({
|
|
||||||
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: error.validation },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return reply.status(500).send({ error: { code: 'INTERNAL_ERROR', message: error.message } });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.decorate('db', db);
|
|
||||||
app.decorate('redis', mockRedis);
|
|
||||||
app.decorate('rateLimitOptions', {
|
|
||||||
register: { max: 100, timeWindow: '1 hour' },
|
|
||||||
forgotPassword: { max: 100, timeWindow: '1 hour' },
|
|
||||||
verifyEmail: { max: 100, timeWindow: '15 minutes' },
|
|
||||||
apiAuthed: { max: 100, timeWindow: '1 minute' },
|
|
||||||
apiGuest: { max: 100, timeWindow: '1 minute' },
|
|
||||||
});
|
|
||||||
|
|
||||||
await app.register(authRoutes, { prefix: '/auth' });
|
|
||||||
|
|
||||||
return app;
|
|
||||||
}
|
|
||||||
@@ -1,140 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { buildAdminTestApp } from '../helpers/build-admin-test-app.js';
|
|
||||||
import {
|
|
||||||
createMockDb,
|
|
||||||
selectChainOrderedLimitOffset,
|
|
||||||
selectChainWhere,
|
|
||||||
updateChainReturning,
|
|
||||||
insertChain,
|
|
||||||
} from '../test-utils.js';
|
|
||||||
|
|
||||||
describe('Admin routes integration', () => {
|
|
||||||
let app: Awaited<ReturnType<typeof buildAdminTestApp>>;
|
|
||||||
let mockDb: ReturnType<typeof createMockDb>;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockDb = createMockDb();
|
|
||||||
app = await buildAdminTestApp(mockDb as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('GET /admin/questions/pending', () => {
|
|
||||||
it('returns pending questions list', async () => {
|
|
||||||
const pendingQuestions = [
|
|
||||||
{
|
|
||||||
id: 'q-1',
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
type: 'single_choice',
|
|
||||||
questionText: 'Test question?',
|
|
||||||
options: [{ key: 'a', text: 'A' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Exp',
|
|
||||||
source: 'manual',
|
|
||||||
createdAt: new Date(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChainOrderedLimitOffset(pendingQuestions))
|
|
||||||
.mockReturnValueOnce(selectChainWhere([{ count: 1 }]));
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'GET',
|
|
||||||
url: '/admin/questions/pending',
|
|
||||||
headers: { authorization: 'Bearer any-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.questions).toHaveLength(1);
|
|
||||||
expect(body.questions[0].questionText).toBe('Test question?');
|
|
||||||
expect(body.total).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /admin/questions/:questionId/approve', () => {
|
|
||||||
it('returns 204 on success', async () => {
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChainReturning([{ id: 'q-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/approve',
|
|
||||||
headers: { authorization: 'Bearer any-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(204);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns 404 when question not found', async () => {
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChainReturning([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/approve',
|
|
||||||
headers: { authorization: 'Bearer any-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(404);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /admin/questions/:questionId/reject', () => {
|
|
||||||
it('returns 204 on success', async () => {
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChainReturning([{ id: 'q-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111/reject',
|
|
||||||
headers: { authorization: 'Bearer any-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(204);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('PATCH /admin/questions/:questionId', () => {
|
|
||||||
it('returns updated question', async () => {
|
|
||||||
const updatedQuestion = {
|
|
||||||
id: 'q-1',
|
|
||||||
stack: 'js',
|
|
||||||
level: 'intermediate',
|
|
||||||
type: 'single_choice',
|
|
||||||
questionText: 'Updated?',
|
|
||||||
options: [{ key: 'a', text: 'A' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Updated exp',
|
|
||||||
source: 'manual',
|
|
||||||
createdAt: new Date(),
|
|
||||||
};
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChainReturning([updatedQuestion])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'PATCH',
|
|
||||||
url: '/admin/questions/11111111-1111-1111-1111-111111111111',
|
|
||||||
headers: { authorization: 'Bearer any-token' },
|
|
||||||
payload: { questionText: 'Updated?', explanation: 'Updated exp' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.questionText).toBe('Updated?');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,265 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { buildAuthTestApp } from '../helpers/build-test-app.js';
|
|
||||||
import {
|
|
||||||
createMockDb,
|
|
||||||
selectChain,
|
|
||||||
insertChain,
|
|
||||||
updateChain,
|
|
||||||
deleteChain,
|
|
||||||
} from '../test-utils.js';
|
|
||||||
|
|
||||||
vi.mock('../../src/utils/password.js', () => ({
|
|
||||||
hashPassword: vi.fn().mockResolvedValue('hashed-password'),
|
|
||||||
verifyPassword: vi.fn().mockResolvedValue(true),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../src/utils/jwt.js', () => ({
|
|
||||||
signAccessToken: vi.fn().mockResolvedValue('access-token'),
|
|
||||||
signRefreshToken: vi.fn().mockResolvedValue('refresh-token'),
|
|
||||||
verifyToken: vi.fn(),
|
|
||||||
isRefreshPayload: vi.fn(),
|
|
||||||
hashToken: vi.fn((t: string) => `hash-${t}`),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('node:crypto', () => ({
|
|
||||||
randomBytes: vi.fn(() => ({ toString: () => 'abc123' })),
|
|
||||||
randomUUID: vi.fn(() => 'uuid-session-1'),
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { isRefreshPayload, verifyToken } from '../../src/utils/jwt.js';
|
|
||||||
|
|
||||||
describe('Auth routes integration', () => {
|
|
||||||
let app: Awaited<ReturnType<typeof buildAuthTestApp>>;
|
|
||||||
let mockDb: ReturnType<typeof createMockDb>;
|
|
||||||
|
|
||||||
beforeEach(async () => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockDb = createMockDb();
|
|
||||||
app = await buildAuthTestApp(mockDb as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/register', () => {
|
|
||||||
it('returns 201 with userId and verificationCode when registration succeeds', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([]))
|
|
||||||
.mockReturnValueOnce(selectChain([]));
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(insertChain([{ id: 'user-123' }]))
|
|
||||||
.mockReturnValueOnce(insertChain([]));
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/register',
|
|
||||||
payload: {
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
nickname: 'tester',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(201);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.userId).toBe('user-123');
|
|
||||||
expect(body.message).toContain('verify your email');
|
|
||||||
expect(body.verificationCode).toBeDefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns 409 when email is already taken', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'existing', email: 'test@example.com' }])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/register',
|
|
||||||
payload: {
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
nickname: 'tester',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(409);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.error?.code).toBe('EMAIL_TAKEN');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns 422 when validation fails', async () => {
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/register',
|
|
||||||
payload: {
|
|
||||||
email: 'short',
|
|
||||||
password: '123', // too short
|
|
||||||
nickname: 'x', // too short
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
expect([400, 422]).toContain(res.statusCode);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.error?.code ?? body.error).toBeDefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/login', () => {
|
|
||||||
it('returns tokens when credentials are valid', async () => {
|
|
||||||
const mockUser = {
|
|
||||||
id: 'user-1',
|
|
||||||
email: 'test@example.com',
|
|
||||||
passwordHash: 'hashed',
|
|
||||||
};
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([mockUser])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/login',
|
|
||||||
payload: { email: 'test@example.com', password: 'password123' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.accessToken).toBe('access-token');
|
|
||||||
expect(body.refreshToken).toBe('refresh-token');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns 401 when credentials are invalid', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/login',
|
|
||||||
payload: { email: 'unknown@example.com', password: 'wrong' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(401);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/logout', () => {
|
|
||||||
it('returns 204 on success', async () => {
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/logout',
|
|
||||||
payload: { refreshToken: 'some-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(204);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/refresh', () => {
|
|
||||||
it('returns new tokens when refresh token is valid', async () => {
|
|
||||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
|
||||||
sub: 'user-1',
|
|
||||||
sid: 'sid-1',
|
|
||||||
type: 'refresh',
|
|
||||||
} as never);
|
|
||||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([{ id: 'sess-1', userId: 'user-1' }]))
|
|
||||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', email: 'test@example.com' }]));
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/refresh',
|
|
||||||
payload: { refreshToken: 'valid-refresh-token' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
const body = JSON.parse(res.body);
|
|
||||||
expect(body.accessToken).toBe('access-token');
|
|
||||||
expect(body.refreshToken).toBe('refresh-token');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/verify-email', () => {
|
|
||||||
it('returns success when code is valid', async () => {
|
|
||||||
const mockCode = {
|
|
||||||
id: 'code-1',
|
|
||||||
userId: 'user-1',
|
|
||||||
code: 'ABC123',
|
|
||||||
expiresAt: new Date(Date.now() + 60000),
|
|
||||||
};
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([mockCode]))
|
|
||||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', emailVerifiedAt: null }]));
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChain([{ id: 'user-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/verify-email',
|
|
||||||
payload: { userId: 'user-1', code: 'ABC123' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/forgot-password', () => {
|
|
||||||
it('returns 200 with generic message', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/forgot-password',
|
|
||||||
payload: { email: 'test@example.com' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('POST /auth/reset-password', () => {
|
|
||||||
it('returns 200 when token is valid', async () => {
|
|
||||||
const mockRecord = {
|
|
||||||
id: 'rec-1',
|
|
||||||
userId: 'user-1',
|
|
||||||
expiresAt: new Date(Date.now() + 60000),
|
|
||||||
};
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([mockRecord])
|
|
||||||
);
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChain([{ id: 'user-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
const res = await app.inject({
|
|
||||||
method: 'POST',
|
|
||||||
url: '/auth/reset-password',
|
|
||||||
payload: { token: 'valid-token', newPassword: 'newPassword123' },
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(res.statusCode).toBe(200);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,304 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { AuthService } from '../../src/services/auth/auth.service.js';
|
|
||||||
import {
|
|
||||||
createMockDb,
|
|
||||||
selectChain,
|
|
||||||
insertChain,
|
|
||||||
updateChain,
|
|
||||||
deleteChain,
|
|
||||||
} from '../test-utils.js';
|
|
||||||
|
|
||||||
vi.mock('../../src/utils/password.js', () => ({
|
|
||||||
hashPassword: vi.fn().mockResolvedValue('hashed-password'),
|
|
||||||
verifyPassword: vi.fn().mockResolvedValue(true),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('../../src/utils/jwt.js', () => ({
|
|
||||||
signAccessToken: vi.fn().mockResolvedValue('access-token'),
|
|
||||||
signRefreshToken: vi.fn().mockResolvedValue('refresh-token'),
|
|
||||||
verifyToken: vi.fn(),
|
|
||||||
isRefreshPayload: vi.fn(),
|
|
||||||
hashToken: vi.fn((t: string) => `hash-${t}`),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('node:crypto', () => ({
|
|
||||||
randomBytes: vi.fn(() => ({
|
|
||||||
toString: () => 'abc123',
|
|
||||||
})),
|
|
||||||
randomUUID: vi.fn(() => 'uuid-session-1'),
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { hashPassword, verifyPassword } from '../../src/utils/password.js';
|
|
||||||
import { signAccessToken, signRefreshToken, verifyToken, isRefreshPayload } from '../../src/utils/jwt.js';
|
|
||||||
|
|
||||||
describe('AuthService', () => {
|
|
||||||
let mockDb: ReturnType<typeof createMockDb>;
|
|
||||||
let authService: AuthService;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockDb = createMockDb();
|
|
||||||
authService = new AuthService(mockDb as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('register', () => {
|
|
||||||
it('registers a new user when email and nickname are available', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([]))
|
|
||||||
.mockReturnValueOnce(selectChain([]));
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(insertChain([{ id: 'user-123' }]))
|
|
||||||
.mockReturnValueOnce(insertChain([]));
|
|
||||||
|
|
||||||
const result = await authService.register({
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
nickname: 'tester',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.userId).toBe('user-123');
|
|
||||||
expect(result.verificationCode).toBeDefined();
|
|
||||||
expect(hashPassword).toHaveBeenCalledWith('password123');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when email is already taken', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'existing', email: 'test@example.com' }])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.register({
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
nickname: 'tester',
|
|
||||||
})
|
|
||||||
).rejects.toMatchObject({ code: 'EMAIL_TAKEN' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when nickname is already taken', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([]))
|
|
||||||
.mockReturnValueOnce(selectChain([{ id: 'existing', nickname: 'tester' }]));
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.register({
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
nickname: 'tester',
|
|
||||||
})
|
|
||||||
).rejects.toMatchObject({ code: 'NICKNAME_TAKEN' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('login', () => {
|
|
||||||
it('returns tokens when credentials are valid', async () => {
|
|
||||||
const mockUser = {
|
|
||||||
id: 'user-1',
|
|
||||||
email: 'test@example.com',
|
|
||||||
passwordHash: 'hashed',
|
|
||||||
};
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([mockUser])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await authService.login({
|
|
||||||
email: 'test@example.com',
|
|
||||||
password: 'password123',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.accessToken).toBe('access-token');
|
|
||||||
expect(result.refreshToken).toBe('refresh-token');
|
|
||||||
expect(verifyPassword).toHaveBeenCalledWith('hashed', 'password123');
|
|
||||||
expect(signAccessToken).toHaveBeenCalled();
|
|
||||||
expect(signRefreshToken).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when user not found', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.login({ email: 'nonexistent@example.com', password: 'x' })
|
|
||||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when password is wrong', async () => {
|
|
||||||
vi.mocked(verifyPassword).mockResolvedValueOnce(false);
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'user-1', email: 'test@example.com', passwordHash: 'hashed' }])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.login({ email: 'test@example.com', password: 'wrong' })
|
|
||||||
).rejects.toMatchObject({ code: 'UNAUTHORIZED' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('logout', () => {
|
|
||||||
it('deletes session by refresh token hash', async () => {
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
await authService.logout('some-refresh-token');
|
|
||||||
|
|
||||||
expect(mockDb.delete).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('refresh', () => {
|
|
||||||
it('returns new tokens when refresh token is valid', async () => {
|
|
||||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
|
||||||
sub: 'user-1',
|
|
||||||
sid: 'sid-1',
|
|
||||||
type: 'refresh',
|
|
||||||
} as never);
|
|
||||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'sess-1', userId: 'user-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await authService.refresh({
|
|
||||||
refreshToken: 'valid-refresh-token',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.accessToken).toBe('access-token');
|
|
||||||
expect(result.refreshToken).toBe('refresh-token');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when token is not a refresh payload', async () => {
|
|
||||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
|
||||||
sub: 'user-1',
|
|
||||||
type: 'access',
|
|
||||||
} as never);
|
|
||||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(false);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.refresh({ refreshToken: 'access-token' })
|
|
||||||
).rejects.toMatchObject({ message: expect.stringContaining('Invalid refresh token') });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when session not found', async () => {
|
|
||||||
vi.mocked(verifyToken).mockResolvedValueOnce({
|
|
||||||
sub: 'user-1',
|
|
||||||
sid: 'sid-1',
|
|
||||||
type: 'refresh',
|
|
||||||
} as never);
|
|
||||||
vi.mocked(isRefreshPayload).mockReturnValueOnce(true);
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.refresh({ refreshToken: 'invalid-or-expired' })
|
|
||||||
).rejects.toMatchObject({ code: 'INVALID_REFRESH_TOKEN' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('verifyEmail', () => {
|
|
||||||
it('throws when verification code is invalid', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.verifyEmail('user-1', 'WRONG')
|
|
||||||
).rejects.toMatchObject({ code: 'INVALID_CODE' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('updates user and deletes code when valid', async () => {
|
|
||||||
const mockCode = {
|
|
||||||
id: 'code-1',
|
|
||||||
userId: 'user-1',
|
|
||||||
code: 'ABC123',
|
|
||||||
expiresAt: new Date(Date.now() + 60000),
|
|
||||||
};
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([mockCode]))
|
|
||||||
.mockReturnValueOnce(selectChain([{ id: 'user-1', emailVerifiedAt: null }]));
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChain([{ id: 'user-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
await authService.verifyEmail('user-1', 'ABC123');
|
|
||||||
|
|
||||||
expect(mockDb.update).toHaveBeenCalled();
|
|
||||||
expect(mockDb.delete).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('forgotPassword', () => {
|
|
||||||
it('returns empty token when user not found', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await authService.forgotPassword('unknown@example.com');
|
|
||||||
|
|
||||||
expect(result.token).toBe('');
|
|
||||||
expect(result.expiresAt).toBeInstanceOf(Date);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns token when user exists', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 'user-1', email: 'test@example.com' }])
|
|
||||||
);
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
insertChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await authService.forgotPassword('test@example.com');
|
|
||||||
|
|
||||||
expect(result.token).toBeDefined();
|
|
||||||
expect(result.token).not.toBe('');
|
|
||||||
expect(result.expiresAt).toBeInstanceOf(Date);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('resetPassword', () => {
|
|
||||||
it('throws when token is invalid', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
authService.resetPassword('invalid-token', 'newPassword123')
|
|
||||||
).rejects.toMatchObject({ code: 'INVALID_RESET_TOKEN' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('updates password when token is valid', async () => {
|
|
||||||
const mockRecord = { id: 'rec-1', userId: 'user-1', expiresAt: new Date(Date.now() + 60000) };
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([mockRecord])
|
|
||||||
);
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChain([{ id: 'user-1' }])
|
|
||||||
);
|
|
||||||
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
deleteChain()
|
|
||||||
);
|
|
||||||
|
|
||||||
await authService.resetPassword('valid-token', 'newPassword123');
|
|
||||||
|
|
||||||
expect(hashPassword).toHaveBeenCalledWith('newPassword123');
|
|
||||||
expect(mockDb.update).toHaveBeenCalled();
|
|
||||||
expect(mockDb.delete).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,224 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
|
|
||||||
vi.mock('../../src/config/env.js', () => ({
|
|
||||||
env: {
|
|
||||||
LLM_BASE_URL: 'http://test',
|
|
||||||
LLM_MODEL: 'test-model',
|
|
||||||
LLM_FALLBACK_MODEL: 'fallback-model',
|
|
||||||
LLM_API_KEY: 'key',
|
|
||||||
LLM_TIMEOUT_MS: 5000,
|
|
||||||
LLM_TEMPERATURE: 0.7,
|
|
||||||
LLM_MAX_TOKENS: 2048,
|
|
||||||
LLM_MAX_RETRIES: 1,
|
|
||||||
LLM_RETRY_DELAY_MS: 10,
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { LlmService } from '../../src/services/llm/llm.service.js';
|
|
||||||
|
|
||||||
const mockConfig = {
|
|
||||||
baseUrl: 'http://llm.test/v1',
|
|
||||||
model: 'test-model',
|
|
||||||
fallbackModel: 'fallback-model',
|
|
||||||
apiKey: 'test-key',
|
|
||||||
timeoutMs: 5000,
|
|
||||||
temperature: 0.7,
|
|
||||||
maxTokens: 2048,
|
|
||||||
maxRetries: 1,
|
|
||||||
retryDelayMs: 10,
|
|
||||||
};
|
|
||||||
|
|
||||||
const validQuestionsJson = JSON.stringify({
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
questionText: 'What is 2+2?',
|
|
||||||
type: 'single_choice',
|
|
||||||
options: [{ key: 'a', text: '4' }, { key: 'b', text: '3' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Basic math',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('LlmService', () => {
|
|
||||||
let mockFetch: ReturnType<typeof vi.fn>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockFetch = vi.fn();
|
|
||||||
vi.stubGlobal('fetch', mockFetch);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('chat', () => {
|
|
||||||
it('returns content from LLM response', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: 'Hello!' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
const result = await service.chat([
|
|
||||||
{ role: 'user', content: 'Hi' },
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(result).toBe('Hello!');
|
|
||||||
expect(mockFetch).toHaveBeenCalledWith(
|
|
||||||
'http://llm.test/v1/chat/completions',
|
|
||||||
expect.objectContaining({
|
|
||||||
method: 'POST',
|
|
||||||
headers: expect.objectContaining({
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': 'Bearer test-key',
|
|
||||||
}),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('chatWithMeta', () => {
|
|
||||||
it('returns content and model name', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: 'Response' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
|
||||||
|
|
||||||
expect(result.content).toBe('Response');
|
|
||||||
expect(result.model).toBe('test-model');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries on failure then succeeds', async () => {
|
|
||||||
mockFetch
|
|
||||||
.mockRejectedValueOnce(new Error('Network error'))
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: 'Retry OK' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService({ ...mockConfig, maxRetries: 1 });
|
|
||||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
|
||||||
|
|
||||||
expect(result.content).toBe('Retry OK');
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to fallbackModel when primary fails', async () => {
|
|
||||||
// Primary model: 2 attempts (initial + 1 retry), both fail
|
|
||||||
mockFetch
|
|
||||||
.mockResolvedValueOnce({ ok: false, status: 500, statusText: 'Error', text: () => Promise.resolve('') })
|
|
||||||
.mockResolvedValueOnce({ ok: false, status: 500, statusText: 'Error', text: () => Promise.resolve('') })
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: 'Fallback OK' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
const result = await service.chatWithMeta([{ role: 'user', content: 'Q' }]);
|
|
||||||
|
|
||||||
expect(result.content).toBe('Fallback OK');
|
|
||||||
expect(result.model).toBe('fallback-model');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when all attempts fail', async () => {
|
|
||||||
mockFetch.mockRejectedValue(new Error('Network error'));
|
|
||||||
|
|
||||||
const service = new LlmService({ ...mockConfig, maxRetries: 0 });
|
|
||||||
await expect(
|
|
||||||
service.chatWithMeta([{ role: 'user', content: 'Q' }])
|
|
||||||
).rejects.toThrow();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('generateQuestions', () => {
|
|
||||||
it('returns validated questions with meta', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: validQuestionsJson } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
const result = await service.generateQuestions({
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
count: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.questions).toHaveLength(1);
|
|
||||||
expect(result.questions[0].questionText).toBe('What is 2+2?');
|
|
||||||
expect(result.questions[0].stack).toBe('js');
|
|
||||||
expect(result.questions[0].level).toBe('beginner');
|
|
||||||
expect(result.meta.llmModel).toBe('test-model');
|
|
||||||
expect(result.meta.promptHash).toBeDefined();
|
|
||||||
expect(result.meta.generationTimeMs).toBeGreaterThanOrEqual(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('extracts JSON from markdown code block', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: '```json\n' + validQuestionsJson + '\n```' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
const result = await service.generateQuestions({
|
|
||||||
stack: 'ts',
|
|
||||||
level: 'intermediate',
|
|
||||||
count: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.questions).toHaveLength(1);
|
|
||||||
expect(result.questions[0].type).toBe('single_choice');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when response validation fails', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: '{"invalid": "response"}' } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
await expect(
|
|
||||||
service.generateQuestions({ stack: 'js', level: 'beginner', count: 1 })
|
|
||||||
).rejects.toThrow('LLM response validation failed');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when single_choice has no options', async () => {
|
|
||||||
const invalidJson = JSON.stringify({
|
|
||||||
questions: [
|
|
||||||
{
|
|
||||||
questionText: 'Q?',
|
|
||||||
type: 'single_choice',
|
|
||||||
options: [],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'e',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
});
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
json: () => Promise.resolve({
|
|
||||||
choices: [{ message: { content: invalidJson } }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const service = new LlmService(mockConfig);
|
|
||||||
await expect(
|
|
||||||
service.generateQuestions({ stack: 'js', level: 'beginner', count: 1 })
|
|
||||||
).rejects.toThrow('Question validation failed');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { QuestionService } from '../../src/services/questions/question.service.js';
|
|
||||||
import {
|
|
||||||
createMockDb,
|
|
||||||
selectChainOrdered,
|
|
||||||
selectChainSimple,
|
|
||||||
insertChain,
|
|
||||||
updateChain,
|
|
||||||
} from '../test-utils.js';
|
|
||||||
|
|
||||||
const mockLlmQuestions = [
|
|
||||||
{
|
|
||||||
questionBankId: 'qb-new',
|
|
||||||
type: 'single_choice' as const,
|
|
||||||
questionText: 'New question?',
|
|
||||||
options: [{ key: 'a', text: 'A' }, { key: 'b', text: 'B' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Explanation',
|
|
||||||
stack: 'js' as const,
|
|
||||||
level: 'beginner' as const,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
describe('QuestionService', () => {
|
|
||||||
let mockDb: ReturnType<typeof createMockDb>;
|
|
||||||
let mockLlmService: { generateQuestions: ReturnType<typeof vi.fn> };
|
|
||||||
let questionService: QuestionService;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockDb = createMockDb();
|
|
||||||
mockLlmService = {
|
|
||||||
generateQuestions: vi.fn().mockResolvedValue({
|
|
||||||
questions: mockLlmQuestions,
|
|
||||||
meta: {
|
|
||||||
llmModel: 'test-model',
|
|
||||||
promptHash: 'hash',
|
|
||||||
generationTimeMs: 100,
|
|
||||||
rawResponse: {},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
questionService = new QuestionService(mockDb as never, mockLlmService as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getQuestionsForTest', () => {
|
|
||||||
it('returns questions from bank when enough approved exist', async () => {
|
|
||||||
const approvedRows = [
|
|
||||||
{
|
|
||||||
id: 'qb-1',
|
|
||||||
type: 'single_choice',
|
|
||||||
questionText: 'Q1?',
|
|
||||||
options: [{ key: 'a', text: 'A' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'e',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChainOrdered(approvedRows))
|
|
||||||
.mockReturnValueOnce(selectChainSimple([]));
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>).mockReturnValueOnce(insertChain([]));
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(updateChain([]));
|
|
||||||
|
|
||||||
const result = await questionService.getQuestionsForTest(
|
|
||||||
'user-1',
|
|
||||||
'js',
|
|
||||||
'beginner',
|
|
||||||
1
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toHaveLength(1);
|
|
||||||
expect(result[0].questionBankId).toBe('qb-1');
|
|
||||||
expect(mockLlmService.generateQuestions).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('calls LLM when not enough questions in bank', async () => {
|
|
||||||
const approvedRows: unknown[] = [];
|
|
||||||
const seenIds: unknown[] = [];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChainOrdered(approvedRows))
|
|
||||||
.mockReturnValueOnce(selectChainSimple(seenIds));
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(insertChain([{ id: 'qb-new', ...mockLlmQuestions[0] }]))
|
|
||||||
.mockReturnValueOnce(insertChain([]))
|
|
||||||
.mockReturnValueOnce(insertChain([]));
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(updateChain([]));
|
|
||||||
|
|
||||||
const result = await questionService.getQuestionsForTest(
|
|
||||||
'user-1',
|
|
||||||
'js',
|
|
||||||
'beginner',
|
|
||||||
1
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(result).toHaveLength(1);
|
|
||||||
expect(mockLlmService.generateQuestions).toHaveBeenCalledWith({
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
count: 1,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when not enough questions available', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChainOrdered([]))
|
|
||||||
.mockReturnValueOnce(selectChainSimple([]));
|
|
||||||
mockLlmService.generateQuestions.mockResolvedValueOnce({
|
|
||||||
questions: [],
|
|
||||||
meta: { llmModel: 'x', promptHash: 'y', generationTimeMs: 0, rawResponse: {} },
|
|
||||||
});
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
questionService.getQuestionsForTest('user-1', 'js', 'beginner', 5)
|
|
||||||
).rejects.toMatchObject({ code: 'QUESTIONS_UNAVAILABLE' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,230 +0,0 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
||||||
import { TestsService } from '../../src/services/tests/tests.service.js';
|
|
||||||
import {
|
|
||||||
createMockDb,
|
|
||||||
selectChain,
|
|
||||||
selectChainOrdered,
|
|
||||||
selectChainWhere,
|
|
||||||
insertChain,
|
|
||||||
updateChain,
|
|
||||||
updateChainReturning,
|
|
||||||
} from '../test-utils.js';
|
|
||||||
|
|
||||||
const mockQuestions = [
|
|
||||||
{
|
|
||||||
questionBankId: 'qb-1',
|
|
||||||
type: 'single_choice' as const,
|
|
||||||
questionText: 'What is 2+2?',
|
|
||||||
options: [{ key: 'a', text: '4' }, { key: 'b', text: '3' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Basic math',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
describe('TestsService', () => {
|
|
||||||
let mockDb: ReturnType<typeof createMockDb>;
|
|
||||||
let mockQuestionService: { getQuestionsForTest: ReturnType<typeof vi.fn> };
|
|
||||||
let testsService: TestsService;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.clearAllMocks();
|
|
||||||
mockDb = createMockDb();
|
|
||||||
mockQuestionService = {
|
|
||||||
getQuestionsForTest: vi.fn().mockResolvedValue(mockQuestions),
|
|
||||||
};
|
|
||||||
testsService = new TestsService(mockDb as never, mockQuestionService as never);
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('createTest', () => {
|
|
||||||
it('creates a test with questions from QuestionService', async () => {
|
|
||||||
const mockTest = {
|
|
||||||
id: 'test-1',
|
|
||||||
userId: 'user-1',
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
questionCount: 1,
|
|
||||||
mode: 'fixed',
|
|
||||||
status: 'in_progress',
|
|
||||||
score: null,
|
|
||||||
startedAt: new Date(),
|
|
||||||
finishedAt: null,
|
|
||||||
timeLimitSeconds: null,
|
|
||||||
};
|
|
||||||
const mockTqRows = [
|
|
||||||
{
|
|
||||||
id: 'tq-1',
|
|
||||||
testId: 'test-1',
|
|
||||||
questionBankId: 'qb-1',
|
|
||||||
orderNumber: 1,
|
|
||||||
type: 'single_choice',
|
|
||||||
questionText: 'What is 2+2?',
|
|
||||||
options: [{ key: 'a', text: '4' }],
|
|
||||||
correctAnswer: 'a',
|
|
||||||
explanation: 'Basic math',
|
|
||||||
userAnswer: null,
|
|
||||||
isCorrect: null,
|
|
||||||
answeredAt: null,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
(mockDb.insert as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(insertChain([mockTest]))
|
|
||||||
.mockReturnValueOnce(insertChain([]));
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChainOrdered(mockTqRows)
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await testsService.createTest('user-1', {
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
questionCount: 1,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.id).toBe('test-1');
|
|
||||||
expect(result.questions).toHaveLength(1);
|
|
||||||
expect(mockQuestionService.getQuestionsForTest).toHaveBeenCalledWith(
|
|
||||||
'user-1',
|
|
||||||
'js',
|
|
||||||
'beginner',
|
|
||||||
1
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when questionCount is out of range', async () => {
|
|
||||||
await expect(
|
|
||||||
testsService.createTest('user-1', {
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
questionCount: 0,
|
|
||||||
})
|
|
||||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
testsService.createTest('user-1', {
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
questionCount: 51,
|
|
||||||
})
|
|
||||||
).rejects.toMatchObject({ code: 'BAD_REQUEST' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('answerQuestion', () => {
|
|
||||||
it('returns updated question snapshot when answer is correct', async () => {
|
|
||||||
const mockTest = { id: 't-1', userId: 'user-1', status: 'in_progress' };
|
|
||||||
const mockTq = {
|
|
||||||
id: 'tq-1',
|
|
||||||
testId: 't-1',
|
|
||||||
correctAnswer: 'a',
|
|
||||||
userAnswer: null,
|
|
||||||
questionBankId: 'qb-1',
|
|
||||||
orderNumber: 1,
|
|
||||||
type: 'single_choice',
|
|
||||||
questionText: 'Q?',
|
|
||||||
options: [{ key: 'a', text: 'A' }],
|
|
||||||
explanation: 'exp',
|
|
||||||
};
|
|
||||||
const updatedTq = { ...mockTq, userAnswer: 'a', isCorrect: true, answeredAt: new Date() };
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([mockTest]))
|
|
||||||
.mockReturnValueOnce(selectChain([mockTq]));
|
|
||||||
(mockDb.update as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
updateChainReturning([updatedTq])
|
|
||||||
);
|
|
||||||
|
|
||||||
const result = await testsService.answerQuestion('user-1', 't-1', 'tq-1', 'a');
|
|
||||||
|
|
||||||
expect(result.isCorrect).toBe(true);
|
|
||||||
expect(result.userAnswer).toBe('a');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when test not found', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(selectChain([]));
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
testsService.answerQuestion('user-1', 'bad-id', 'tq-1', 'a')
|
|
||||||
).rejects.toMatchObject({ code: 'NOT_FOUND' });
|
|
||||||
});
|
|
||||||
|
|
||||||
it('throws when test is already finished', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(
|
|
||||||
selectChain([{ id: 't-1', userId: 'user-1', status: 'completed' }])
|
|
||||||
);
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
testsService.answerQuestion('user-1', 't-1', 'tq-1', 'a')
|
|
||||||
).rejects.toMatchObject({ code: 'TEST_ALREADY_FINISHED' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('finishTest', () => {
|
|
||||||
it('throws when there are unanswered questions', async () => {
|
|
||||||
const mockTest = { id: 't-1', userId: 'user-1', status: 'in_progress', stack: 'js', level: 'beginner' };
|
|
||||||
const mockQuestionsWithUnanswered = [
|
|
||||||
{ id: 'tq-1', testId: 't-1', userAnswer: 'a', isCorrect: true },
|
|
||||||
{ id: 'tq-2', testId: 't-1', userAnswer: null, isCorrect: null },
|
|
||||||
];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([mockTest]))
|
|
||||||
.mockReturnValueOnce(selectChainWhere(mockQuestionsWithUnanswered));
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
testsService.finishTest('user-1', 't-1')
|
|
||||||
).rejects.toMatchObject({ code: 'NO_ANSWERS' });
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getById', () => {
|
|
||||||
it('returns null when test not found', async () => {
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>).mockReturnValueOnce(selectChain([]));
|
|
||||||
|
|
||||||
const result = await testsService.getById('user-1', 'bad-id');
|
|
||||||
|
|
||||||
expect(result).toBeNull();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns test with questions when found', async () => {
|
|
||||||
const mockTest = {
|
|
||||||
id: 't-1',
|
|
||||||
userId: 'user-1',
|
|
||||||
stack: 'js',
|
|
||||||
level: 'beginner',
|
|
||||||
questionCount: 2,
|
|
||||||
mode: 'fixed',
|
|
||||||
status: 'in_progress',
|
|
||||||
score: null,
|
|
||||||
startedAt: new Date(),
|
|
||||||
finishedAt: null,
|
|
||||||
timeLimitSeconds: null,
|
|
||||||
};
|
|
||||||
const mockTqRows = [
|
|
||||||
{ id: 'tq-1', testId: 't-1', orderNumber: 1, questionBankId: 'qb-1', type: 'single_choice', questionText: 'Q1', options: [], correctAnswer: 'a', explanation: 'e', userAnswer: null, isCorrect: null, answeredAt: null },
|
|
||||||
];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChain([mockTest]))
|
|
||||||
.mockReturnValueOnce(selectChainOrdered(mockTqRows));
|
|
||||||
|
|
||||||
const result = await testsService.getById('user-1', 't-1');
|
|
||||||
|
|
||||||
expect(result).not.toBeNull();
|
|
||||||
expect(result!.id).toBe('t-1');
|
|
||||||
expect(result!.questions).toHaveLength(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getHistory', () => {
|
|
||||||
it('returns paginated test history', async () => {
|
|
||||||
const mockTests = [
|
|
||||||
{ id: 't-1', userId: 'user-1', stack: 'js', level: 'beginner', questionCount: 1, mode: 'fixed', status: 'completed', score: 100, startedAt: new Date(), finishedAt: new Date(), timeLimitSeconds: null },
|
|
||||||
];
|
|
||||||
const mockTqRows = [];
|
|
||||||
(mockDb.select as ReturnType<typeof vi.fn>)
|
|
||||||
.mockReturnValueOnce(selectChainOrdered(mockTests))
|
|
||||||
.mockReturnValueOnce(selectChainOrdered(mockTqRows));
|
|
||||||
|
|
||||||
const result = await testsService.getHistory('user-1', { limit: 10, offset: 0 });
|
|
||||||
|
|
||||||
expect(result.tests).toHaveLength(1);
|
|
||||||
expect(result.total).toBe(1);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { beforeAll, vi } from 'vitest';
|
|
||||||
|
|
||||||
beforeAll(() => {
|
|
||||||
vi.stubEnv('NODE_ENV', 'test');
|
|
||||||
if (!process.env.DATABASE_URL) {
|
|
||||||
process.env.DATABASE_URL = 'postgresql://test:test@localhost:5432/test';
|
|
||||||
}
|
|
||||||
if (!process.env.JWT_SECRET) {
|
|
||||||
process.env.JWT_SECRET = 'test-secret-min-32-chars-long-for-validation';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
|
||||||
import { createMockDb } from './test-utils.js';
|
|
||||||
|
|
||||||
describe('test-utils', () => {
|
|
||||||
it('createMockDb returns mock with select, insert, update, delete', () => {
|
|
||||||
const db = createMockDb();
|
|
||||||
expect(db.select).toBeDefined();
|
|
||||||
expect(db.insert).toBeDefined();
|
|
||||||
expect(db.update).toBeDefined();
|
|
||||||
expect(db.delete).toBeDefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
import { vi } from 'vitest';
|
|
||||||
import type { FastifyInstance } from 'fastify';
|
|
||||||
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
|
|
||||||
import type * as schema from '../src/db/schema/index.js';
|
|
||||||
|
|
||||||
export type MockDb = {
|
|
||||||
select: ReturnType<NodePgDatabase<typeof schema>['select']>;
|
|
||||||
insert: ReturnType<NodePgDatabase<typeof schema>['insert']>;
|
|
||||||
update: ReturnType<NodePgDatabase<typeof schema>['update']>;
|
|
||||||
delete: ReturnType<NodePgDatabase<typeof schema>['delete']>;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Build a select chain that resolves to the given rows at .limit(n) */
|
|
||||||
export function selectChain(resolveAtLimit: unknown[] = []) {
|
|
||||||
const limitFn = vi.fn().mockResolvedValue(resolveAtLimit);
|
|
||||||
return {
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue({
|
|
||||||
limit: limitFn,
|
|
||||||
orderBy: vi.fn().mockReturnValue({ limit: limitFn }),
|
|
||||||
}),
|
|
||||||
limit: limitFn,
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a select chain for .from().where().orderBy() - orderBy is terminal */
|
|
||||||
export function selectChainOrdered(resolveAtOrderBy: unknown[] = []) {
|
|
||||||
const orderByThenable = {
|
|
||||||
then: (resolve: (v: unknown) => void) => resolve(resolveAtOrderBy),
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue({
|
|
||||||
orderBy: vi.fn().mockReturnValue(orderByThenable),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a select chain for .from().where() with no orderBy - used by select({...}).from() */
|
|
||||||
export function selectChainSimple(resolveRows: unknown[] = []) {
|
|
||||||
const thenable = { then: (resolve: (v: unknown) => void) => resolve(resolveRows) };
|
|
||||||
return {
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue(thenable),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a select chain for .from().where() - where is terminal (no orderBy/limit) */
|
|
||||||
export function selectChainWhere(resolveAtWhere: unknown[] = []) {
|
|
||||||
const thenable = { then: (resolve: (v: unknown) => void) => resolve(resolveAtWhere) };
|
|
||||||
return {
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue(thenable),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a select chain for .from().where().orderBy().limit().offset() */
|
|
||||||
export function selectChainOrderedLimitOffset(resolveRows: unknown[] = []) {
|
|
||||||
const offsetFn = vi.fn().mockResolvedValue(resolveRows);
|
|
||||||
return {
|
|
||||||
from: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue({
|
|
||||||
orderBy: vi.fn().mockReturnValue({
|
|
||||||
limit: vi.fn().mockReturnValue({
|
|
||||||
offset: offsetFn,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build an insert chain that resolves at .returning() or .values() */
|
|
||||||
export function insertChain(resolveAtReturning: unknown[] = []) {
|
|
||||||
const returningFn = vi.fn().mockResolvedValue(resolveAtReturning);
|
|
||||||
const chainFromValues = {
|
|
||||||
returning: returningFn,
|
|
||||||
then: (resolve: (v?: unknown) => void) => resolve(undefined),
|
|
||||||
};
|
|
||||||
return {
|
|
||||||
values: vi.fn().mockReturnValue(chainFromValues),
|
|
||||||
returning: returningFn,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build an update chain that resolves at .where() */
|
|
||||||
export function updateChain(resolveAtWhere: unknown[] = []) {
|
|
||||||
return {
|
|
||||||
set: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockResolvedValue(resolveAtWhere),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build an update chain with .where().returning() */
|
|
||||||
export function updateChainReturning(resolveAtReturning: unknown[] = []) {
|
|
||||||
const returningFn = vi.fn().mockResolvedValue(resolveAtReturning);
|
|
||||||
return {
|
|
||||||
set: vi.fn().mockReturnValue({
|
|
||||||
where: vi.fn().mockReturnValue({
|
|
||||||
returning: returningFn,
|
|
||||||
}),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Build a delete chain that resolves at .where() */
|
|
||||||
export function deleteChain() {
|
|
||||||
return {
|
|
||||||
where: vi.fn().mockResolvedValue(undefined),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a chainable mock for Drizzle DB operations.
|
|
||||||
* Use mockReturnValue with selectChain/insertChain/updateChain/deleteChain.
|
|
||||||
*/
|
|
||||||
export function createMockDb(): MockDb {
|
|
||||||
const chain = {
|
|
||||||
from: vi.fn().mockReturnThis(),
|
|
||||||
where: vi.fn().mockReturnThis(),
|
|
||||||
values: vi.fn().mockReturnThis(),
|
|
||||||
set: vi.fn().mockReturnThis(),
|
|
||||||
orderBy: vi.fn().mockReturnThis(),
|
|
||||||
limit: vi.fn().mockReturnThis(),
|
|
||||||
returning: vi.fn().mockReturnThis(),
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
|
||||||
select: vi.fn().mockReturnValue(chain),
|
|
||||||
insert: vi.fn().mockReturnValue(chain),
|
|
||||||
update: vi.fn().mockReturnValue(chain),
|
|
||||||
delete: vi.fn().mockReturnValue(chain),
|
|
||||||
} as unknown as MockDb;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a minimal mock Fastify app with db for route/integration tests.
|
|
||||||
* Use buildApp() from app.ts for full integration tests.
|
|
||||||
*/
|
|
||||||
export function createMockApp(): FastifyInstance & { db: MockDb } {
|
|
||||||
return {
|
|
||||||
db: createMockDb(),
|
|
||||||
log: {
|
|
||||||
child: () => ({
|
|
||||||
debug: () => {},
|
|
||||||
info: () => {},
|
|
||||||
warn: () => {},
|
|
||||||
error: () => {},
|
|
||||||
trace: () => {},
|
|
||||||
fatal: () => {},
|
|
||||||
}),
|
|
||||||
debug: () => {},
|
|
||||||
info: () => {},
|
|
||||||
warn: () => {},
|
|
||||||
error: () => {},
|
|
||||||
trace: () => {},
|
|
||||||
fatal: () => {},
|
|
||||||
},
|
|
||||||
} as FastifyInstance & { db: MockDb };
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import { defineConfig } from 'vitest/config';
|
|
||||||
import { resolve } from 'path';
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
test: {
|
|
||||||
globals: true,
|
|
||||||
environment: 'node',
|
|
||||||
include: ['tests/**/*.test.ts', 'tests/**/*.spec.ts'],
|
|
||||||
coverage: {
|
|
||||||
provider: 'v8',
|
|
||||||
reporter: ['text', 'json', 'lcov'],
|
|
||||||
include: [
|
|
||||||
'src/services/auth/**/*.ts',
|
|
||||||
'src/services/llm/**/*.ts',
|
|
||||||
'src/services/questions/**/*.ts',
|
|
||||||
'src/services/tests/**/*.ts',
|
|
||||||
'src/services/admin/**/*.ts',
|
|
||||||
],
|
|
||||||
exclude: [
|
|
||||||
'src/services/**/*.d.ts',
|
|
||||||
'**/*.test.ts',
|
|
||||||
'**/*.spec.ts',
|
|
||||||
'**/index.ts',
|
|
||||||
],
|
|
||||||
thresholds: {
|
|
||||||
lines: 70,
|
|
||||||
functions: 70,
|
|
||||||
branches: 68,
|
|
||||||
statements: 70,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
setupFiles: ['tests/setup.ts'],
|
|
||||||
testTimeout: 10000,
|
|
||||||
},
|
|
||||||
resolve: {
|
|
||||||
alias: {
|
|
||||||
'@': resolve(__dirname, 'src'),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
Reference in New Issue
Block a user