8 Commits

Author SHA1 Message Date
Anton
5b0e1aaa46 chore: add server entry and dev docker compose
Made-with: Cursor
2026-03-04 13:46:19 +03:00
Anton
02b7f2f508 feat: add Fastify app with error handler
Made-with: Cursor
2026-03-04 13:45:39 +03:00
Anton
ae642d78b8 chore: add error utils and uuid7 helper
Made-with: Cursor
2026-03-04 13:45:38 +03:00
Anton
8545fd27a2 feat: add rate limit plugin with Redis
Made-with: Cursor
2026-03-04 13:45:38 +03:00
Anton
8940ab6ce9 feat: add security plugin
Made-with: Cursor
2026-03-04 13:45:37 +03:00
Anton
8e550b54a9 feat: add database plugin with Drizzle
Made-with: Cursor
2026-03-04 13:45:37 +03:00
Anton
019bf875ff feat: add Redis plugin
Made-with: Cursor
2026-03-04 13:39:56 +03:00
Anton
9ffd59eb3e chore: add env config with validation
Made-with: Cursor
2026-03-04 13:39:56 +03:00
62 changed files with 8 additions and 8465 deletions

View File

@@ -1,366 +0,0 @@
---
name: Документация vs Реализация
overview: "Подробный отчёт о соответствии бэкенда документации samreshu_docs: выявлены расхождения в API контрактах, схеме БД, аутентификации, тестах и других компонентах."
todos: []
isProject: false
---
# Отчёт: Соответствие бэкенда документации Samreshu
## 1. Базовый URL и структура API
**Документация** ([contracts.md](samreshu_docs/api/contracts.md)):
- Базовый URL: `/api/v1`
- Все эндпоинты: `/api/v1/auth/`*, `/api/v1/profile/`*, `/api/v1/tests/*`, `/api/v1/admin/*`
**Реализация** ([app.ts](src/app.ts)):
- Префикс `/api/v1` отсутствует. Маршруты зарегистрированы как `/auth`, `/profile`, `/tests`, `/admin`
- Фактические URL: `/auth/`*, `/profile/`*, `/tests/*`, `/admin/*`
**Вывод:** Критическое расхождение. Клиент, следующий документации, будет отправлять запросы на несуществующие эндпоинты.
---
## 2. Аутентификация (Auth)
### 2.1 POST /auth/register
| Аспект | Документация | Реализация |
| -------------- | ------------------------------------------------- | --------------------------------------------------------------------- |
| Response 201 | `{ user, accessToken }` + Set-Cookie refreshToken | `{ userId, message, verificationCode }` |
| Логика | Сразу выдаёт токены, отправляет письмо | Требует верификацию email; не выдаёт токены; возвращает код (для dev) |
| NICKNAME_TAKEN | — | Есть в коде; в документации не описан |
**Вывод:** Разный flow. Документация описывает выдачу токенов сразу после регистрации; реализация ожидает верификацию email.
### 2.2 POST /auth/login
| Аспект | Документация | Реализация |
| ----------------------- | ------------------------------------ | ------------------------------------------------------- |
| Response | `{ user, accessToken }` + Set-Cookie | `{ accessToken, refreshToken, expiresIn }` — без `user` |
| Lockout при brute force | 403 `ACCOUNT_LOCKED` | 429 `RATE_LIMIT_EXCEEDED` |
| Ошибка неверных данных | 401 `INVALID_CREDENTIALS` | 401 `UNAUTHORIZED` (общий код) |
**Вывод:** Расхождения в формате ответа, коде ошибки и семантике блокировки (403 vs 429).
### 2.3 POST /auth/logout
| Аспект | Документация | Реализация |
| ------------ | ------------------------ | -------------------------- |
| Авторизация | Bearer token | refreshToken в теле |
| Request body | Пустое | `{ refreshToken: string }` |
| Response | 200 `{ message: "..." }` | 204 (без тела) |
**Вывод:** Другой механизм авторизации и формат ответа.
### 2.4 POST /auth/refresh
| Аспект | Документация | Реализация |
| ------------ | --------------- | -------------------------- |
| Токен | httpOnly cookie | `{ refreshToken }` в body |
| Request body | Пустое | `{ refreshToken: string }` |
**Вывод:** Документация предполагает cookie; реализация использует body.
### 2.5 POST /auth/verify-email
| Аспект | Документация | Реализация |
| ----------- | ------------ | ------------------ |
| Request | `{ code }` | `{ userId, code }` |
| Авторизация | Bearer token | Не требуется |
**Вывод:** Документация — только `code` с Bearer; реализация — `userId` и `code` без Bearer.
### 2.6 POST /auth/reset-password
| Аспект | Документация | Реализация |
| ----------- | ------------ | ------------- |
| Поле пароля | `password` | `newPassword` |
**Вывод:** Разные имена полей в теле запроса.
### 2.7 Set-Cookie для refresh token
**Документация:** RefreshToken в httpOnly cookie (`Path=/api/v1/auth`, `Max-Age=604800`).
**Реализация:** Cookie не устанавливаются; refresh token возвращается только в JSON.
---
## 3. Profile
### 3.1 GET /profile
**Документация:** Ответ включает `role`, `plan` (из subscriptions).
**Реализация** ([user.service.ts](src/services/user/user.service.ts)): `getPrivateProfile` возвращает `id`, `nickname`, `avatarUrl`, `country`, `city`, `selfLevel`, `isPublic`, `email`, `emailVerifiedAt`, `createdAt`, `updatedAt`, `stats`. Поля `role` и `plan` отсутствуют.
**Вывод:** В ответе нет полей, указанных в документации.
### 3.2 GET /profile/:username
**Документация:** `stats: { testsCompleted, averageScore }`.
**Реализация:** `stats: { byStack, totalTestsTaken, totalQuestions, correctAnswers, accuracy }` — другая структура.
**Вывод:** Формат статистики не совпадает.
### 3.3 PATCH /profile
**Документация:** Поле `avatarUrl` не описано.
**Реализация:** Поддерживается `avatarUrl`.
**Вывод:** Документация неполная (расхождение в пользу реализации).
---
## 4. Tests
### 4.1 POST /tests (создание)
| Аспект | Документация | Реализация |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------- |
| questionCount | enum: 10 / 20 | integer 150 |
| stack/level (MVP 0) | html, css / basic, beginner | Все значения enum |
| Response структура | `{ id, stack, level, questionCount, status, currentQuestion, startedAt, timeLimitSeconds, question: {...} }` — только текущий вопрос | `{ ...test, questions: [...] }` — все вопросы |
**Вывод:** Разная структура ответа и валидация параметров.
### 4.2 POST /tests/:id/answer
**Документация:** `{ answered: {...}, progress: {...}, nextQuestion: {...} }`.
**Реализация:** Возвращает полный `TestSnapshot` отвеченного вопроса, без `progress` и `nextQuestion`.
**Вывод:** Формат ответа не совпадает с документацией.
### 4.3 POST /tests/:id/finish
| Аспект | Документация | Реализация |
| -------------- | --------------------------------------- | ----------------------- |
| score | Количество правильных ответов (8 из 10) | Процент (0100) |
| totalQuestions | В ответе | Нет в ответе |
| percentage | В ответе | Нет (score как процент) |
**Реализация** ([tests.service.ts](src/services/tests/tests.service.ts) 239241):
```ts
const score = Math.round((correctCount / questions.length) * 100);
```
**Вывод:** Критическое расхождение: `score` в документации — количество, в реализации — процент.
### 4.4 GET /tests/:id/results
**Документация:** Детальные результаты с `questions`, `userAnswer`, `correctAnswer`, `isCorrect`, `explanation`.
**Реализация:** Эндпоинт отсутствует.
**Вывод:** Критическое расхождение: описанный эндпоинт не реализован.
### 4.5 GET /tests/history
| Аспект | Документация | Реализация |
| ------------- | ------------------------------------------------------ | ------------------------------ |
| Путь | GET /tests/history | GET /tests (то же для истории) |
| Пагинация | cursor-based (limit, cursor) | offset-based (limit, offset) |
| Формат ответа | `{ data: [...], pagination: { nextCursor, hasMore } }` | `{ tests: [...], total }` |
| Параметры | stack, status фильтры | Нет фильтров |
**Вывод:** Другая схема пагинации и структура ответа.
### 4.6 Параметр теста
**Документация:** `:id`.
**Реализация:** `:testId` в params.
**Вывод:** Незначительное расхождение в именовании.
---
## 5. Admin
### 5.1 Список вопросов
| Аспект | Документация | Реализация |
| -------------- | ----------------------------- | ---------------------------- |
| Эндпоинт | GET /admin/questions/queue | GET /admin/questions/pending |
| Пагинация | cursor (limit, cursor) | offset (limit, offset) |
| status в query | pending / approved / rejected | — |
### 5.2 Редактирование
**Документация:** PATCH /admin/questions/:id с `status: approved | rejected` и полями для правок.
**Реализация:**
- POST /admin/questions/:questionId/approve
- POST /admin/questions/:questionId/reject
- PATCH /admin/questions/:questionId — для редактирования
**Вывод:** Другая схема: отдельные approve/reject вместо смены статуса через PATCH.
---
## 6. База данных
### 6.1 Таблицы
**Документация** ([schema.md](samreshu_docs/database/schema.md)): `verification_tokens` (обобщённо).
**Реализация:** Отдельные таблицы `email_verification_codes` и `password_reset_tokens` (в [verificationTokens.ts](src/db/schema/verificationTokens.ts)).
**Вывод:** Расхождение в модели хранения токенов.
### 6.2 Отсутствующие таблицы (Phase 2+)
В документации есть таблицы, которых нет в текущем коде: `oauth_accounts`, `totp_secrets`, `payments`, `payment_events`, `notifications_log`, `promo_codes`, `user_achievements`. Это ожидаемо для Phase 2+.
---
## 7. Безопасность
### 7.1 Argon2
**Документация:** argon2id, 19 MiB, 2 iterations.
**Реализация** ([password.ts](src/utils/password.ts)): `memoryCost: 19456` (KiB), `timeCost: 2`.
**Вывод:** Совпадение.
### 7.2 JWT
**Документация:** Access 15 мин, Refresh 7 дней, HS256.
**Реализация:** `JWT_ACCESS_TTL=15m`, `JWT_REFRESH_TTL=7d`.
**Вывод:** Совпадение.
### 7.3 Login lockout
**Документация:** 5/15 мин, 10/1 ч, 20/24 ч.
**Реализация** ([loginLockout.ts](src/utils/loginLockout.ts)): Те же пороги (5, 10, 20).
**Вывод:** Совпадение.
### 7.4 Rate limits
**Документация:** RATE_LIMIT_LOGIN, RATE_LIMIT_REGISTER, RATE_LIMIT_FORGOT_PASSWORD, RATE_LIMIT_VERIFY_EMAIL, RATE_LIMIT_API_AUTHED, RATE_LIMIT_API_GUEST.
**Реализация** ([env.ts](src/config/env.ts)): RATE_LIMIT_LOGIN отсутствует (используется progressive lockout). Остальные переменные есть.
**Вывод:** Незначительное расхождение; security.md упоминает RATE_LIMIT_LOGIN, но логика lockout иная.
### 7.5 CORS
**Документация:** `http://localhost:5173`, `https://samreshu.ru`, `credentials: true`, методы GET, POST, PATCH, DELETE.
**Реализация:** Origins из `CORS_ORIGINS`, `credentials: true`, методы включают PUT и OPTIONS.
**Вывод:** Реализация шире, расхождение несущественное.
### 7.6 Helmet
**Документация:** Полный набор заголовков, включая CSP.
**Реализация:** `contentSecurityPolicy: false`, `crossOriginEmbedderPolicy: false`.
**Вывод:** CSP и COEP отключены.
---
## 8. LLM
### 8.1 Конфигурация
**Документация:** LLM_BASE_URL, LLM_MODEL, LLM_API_KEY, LLM_TIMEOUT_MS, LLM_MAX_RETRIES, LLM_TEMPERATURE, LLM_MAX_TOKENS.
**Реализация:** Дополнительно `LLM_FALLBACK_MODEL`, `LLM_RETRY_DELAY_MS`.
**Вывод:** Реализация расширяет документацию.
### 8.2 question_cache_meta
**Документация:** model, generation_time_ms, prompt_hash. Также упоминаются valid, retry_count, questions_generated.
**Реализация:** Нужно проверить сохранение этих полей в [questionCacheMeta](src/db/schema/questionCacheMeta.ts) и связанных сервисах.
---
## 9. Код и инфраструктура
### 9.1 Onboarding / setup
**Документация:** docker-compose.dev.yml с postgres и redis.
**Реализация:** Соответствует.
### 9.2 .env.example
**Документация:** Полный перечень переменных.
**Реализация:** Совпадает, включая rate limits и LLM. JWT_SECRET требует не менее 32 символов — в примере выполнено.
---
## 10. Сводка расхождений
### Критические
1. Отсутствие префикса `/api/v1`
2. Auth: другой flow (verify-email до токенов, refresh/logout через body вместо cookie)
3. Tests: `score` как процент вместо количества
4. Отсутствует GET /tests/:id/results
5. Формат ответов create/answer/finish/history не совпадает с документацией
### Значительные
1. Login lockout: 429 вместо 403 ACCOUNT_LOCKED
2. Login: нет поля `user` в ответе
3. Profile: нет `role`, `plan`; другая структура `stats`
4. Admin: другой набор эндпоинтов и логика approve/reject
5. Пагинация: offset вместо cursor
### Незначительные
1. Имена полей (testId vs id, newPassword vs password)
2. verify-email: userId + code вместо только code
3. Эндпоинт admin: /pending вместо /queue
---
## Рекомендации
1. **Привести маршрутизацию к документации:** добавить префикс `/api/v1` при регистрации роутов.
2. **Унифицировать auth:** реализовать cookie для refresh token и обновить logout/refresh под документацию, либо явно зафиксировать в документации текущий подход (body).
3. **Исправить score в тестах:** хранить и возвращать количество правильных ответов, а процент считать отдельно.
4. **Реализовать GET /tests/:id/results** по описанному в документации формату.
5. **Привести ответы create/answer/finish/history** к формату из contracts.md.
6. **Обновить документацию** под уже реализованные отличия (offset, admin approve/reject и т.д.), если менять реализацию не планируется.
7. **Расширить getPrivateProfile** полями `role` и `plan` из subscription middleware.

View File

@@ -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

3
.gitmodules vendored
View File

@@ -1,3 +0,0 @@
[submodule "samreshu_docs"]
path = samreshu_docs
url = https://git.vakanaut.ru/admin/samreshu_docs.git

View File

@@ -1,385 +0,0 @@
# Распределение задач по агентам (MVP 0)
Документ для параллельной работы нескольких агентов. Каждый агент работает в **отдельной сессии Cursor** (отдельное окно чата). После выполнения **каждой задачи** — отдельный коммит по conventional commits.
## Как запустить агента
1. Открыть **новую сессию чата** (новое окно Composer/Chat в Cursor)
2. Скопировать промпт для нужного агента из раздела ниже
3. Агент выполнит свои задачи и сделает коммиты
4. Повторить для следующего агента
### Промпты для запуска агентов
**Agent A (Infrastructure):**
```text
Implement Agent A tasks from AGENT_TASKS.md. Work in branch feat/infra-core.
Do tasks A1A9 in order. After EACH task, run: git add -A && git commit -m "<message from table>".
Use conventional commits. Do not touch schema or auth/tests/profile/llm/admin code.
```
**Agent B (DB Schema):**
```text
Implement Agent B tasks from AGENT_TASKS.md. Work in branch feat/db-schema.
Do tasks B1B7. After EACH task, commit with the message from the table.
Assume Agent A has created plugins. Generate migrations with npm run db:generate.
```
**Agent C (Auth):**
```text
Implement Agent C tasks from AGENT_TASKS.md. Work in branch feat/auth.
Merge or rebase from dev first. Do tasks C1C7, commit after each.
```
**Agent D (Profile):**
```text
Implement Agent D tasks from AGENT_TASKS.md. Work in branch feat/profile-subscription.
Merge dev first. Do tasks D1D5, commit after each.
```
**Agent E (Tests & Questions):**
```text
Implement Agent E tasks from AGENT_TASKS.md. Work in branch feat/tests-questions.
Requires Auth, Profile, LLM done. Do E1E5, commit after each.
```
**Agent F (LLM):**
```text
Implement Agent F tasks from AGENT_TASKS.md. Work in branch feat/llm-service.
Do F1F5, commit after each. Export LlmService interface for QuestionService.
```
**Agent G (Admin):**
```text
Implement Agent G tasks from AGENT_TASKS.md. Work in branch feat/admin-qa.
Do G1G4, commit after each.
```
**Agent H (Testing):**
```text
Implement Agent H tasks from AGENT_TASKS.md. Work in branch feat/testing.
Do H1H7, 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.
```
## Текущее состояние репозитория
Часть работы уже выполнена одним агентом:
- **Infra (A):** package.json, config, plugins (database, redis, security, rateLimit), app.ts, server.ts, utils/errors, utils/uuid, docker-compose, .env.example
- **Schema (B):** все схемы в src/db/schema, drizzle.config, migrate.ts. Миграции ещё не сгенерированы (нужен `npm run db:generate`)
Агентам BH при старте: проверить, что уже есть, и дописать недостающее. Не дублировать сделанное. Коммитить только свои изменения.
---
## Формат коммитов
Использовать [conventional commits](samreshu_docs/principles/git-workflow.md):
- `feat:` — новый функционал
- `fix:` — исправление бага
- `refactor:` — рефакторинг
- `chore:` — инфраструктура, зависимости, конфиг
- `test:` — тесты
Примеры: `feat: add auth register endpoint`, `chore: add database plugin`, `test: add auth service unit tests`.
---
## Волны запуска и зависимости
```text
Волна 1 (старт сразу, параллельно):
Agent A ────────────────────────────►
Agent B ────────────────────────────►
Волна 2 (после завершения A + B):
Agent C ────────────────────────────►
Agent D ────────────────────────────►
Agent F ────────────────────────────►
Волна 3 (после C, D, F):
Agent E ────────────────────────────►
Agent G ────────────────────────────►
Agent H ────────────────────────────► (может стартовать частично после C)
```
---
## Agent A: Infrastructure & Core Backend
**Зависимости:** нет (запускать первым)
**Ветка:** `feat/infra-core` (создать от `main`/`dev`)
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| A1 | package.json, tsconfig, .nvmrc, .gitignore | `chore: init project with Fastify and TypeScript` |
| A2 | src/config/env.ts с Zod-валидацией | `chore: add env config with validation` |
| A3 | src/plugins/redis.ts | `feat: add Redis plugin` |
| A4 | src/plugins/database.ts | `feat: add database plugin with Drizzle` |
| A5 | src/plugins/security.ts (helmet + cors) | `feat: add security plugin` |
| A6 | src/plugins/rateLimit.ts | `feat: add rate limit plugin with Redis` |
| A7 | src/utils/errors.ts, src/utils/uuid.ts | `chore: add error utils and uuid7 helper` |
| A8 | src/app.ts — error handler, логирование | `feat: add Fastify app with error handler` |
| A9 | src/server.ts, docker-compose.dev.yml, .env.example | `chore: add server entry and dev docker compose` |
**Итого:** 9 коммитов. После завершения — PR в `dev`.
---
## 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 A (нужен database plugin). Может стартовать после A4.
**Ветка:** `feat/db-schema`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| B1 | src/db/schema/enums.ts | `feat: add Drizzle enums for schema` |
| B2 | src/db/schema/users.ts, sessions.ts, subscriptions.ts | `feat: add users and auth tables schema` |
| B3 | src/db/schema/tests.ts, testQuestions.ts | `feat: add tests and test_questions schema` |
| B4 | src/db/schema/questionBank.ts, questionCacheMeta.ts, questionReports.ts | `feat: add question bank schema` |
| B5 | src/db/schema/userStats.ts, auditLogs.ts, userQuestionLog.ts, verificationTokens.ts | `feat: add user_stats, audit_logs and verification tokens schema` |
| B6 | src/db/schema/index.ts, drizzle.config.ts, migrate.ts | `chore: wire schema and migrations` |
| B7 | Генерация миграций (npm run db:generate), seed скрипт | `chore: add initial migration and seed script` |
**Итого:** 7 коммитов. После завершения — PR в `dev`.
---
## Agent C: Auth & Sessions Service
**Зависимости:** A, B завершены.
**Ветка:** `feat/auth`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| C1 | src/utils/password.ts (argon2id), src/utils/jwt.ts | `feat: add password hashing and JWT utils` |
| C2 | src/services/auth/auth.service.ts | `feat: add AuthService` |
| C3 | src/plugins/auth.ts (JWT verify, request.user) | `feat: add auth plugin` |
| C4 | src/routes/auth.ts — register, login, logout, refresh | `feat: add auth routes` |
| C5 | verify-email, forgot-password, reset-password | `feat: add email verification and password reset` |
| C6 | Rate limiting на auth-роуты | `feat: add rate limiting to auth endpoints` |
| C7 | Регистрация auth routes в app | `feat: register auth routes in app` |
**Итого:** 7 коммитов. После завершения — PR в `dev`.
---
## Agent D: Profile & Subscription Middleware
**Зависимости:** A, B, C.
**Ветка:** `feat/profile-subscription`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| D1 | src/plugins/subscription.ts | `feat: add subscription middleware` |
| D2 | src/services/user/user.service.ts | `feat: add UserService` |
| D3 | src/routes/profile.ts — GET, PATCH, GET :username | `feat: add profile routes` |
| D4 | Интеграция user_stats в профиль | `feat: add stats to profile response` |
| D5 | Регистрация profile routes в app | `feat: register profile routes` |
**Итого:** 5 коммитов. После завершения — PR в `dev`.
---
## Agent E: Question Bank & Tests Service
**Зависимости:** A, B, C, D, F (контракт LlmService).
**Ветка:** `feat/tests-questions`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| E1 | src/services/questions/question.service.ts | `feat: add QuestionService` |
| E2 | src/services/tests/tests.service.ts — создание теста, снепшот | `feat: add TestsService create flow` |
| E3 | tests.service — answer, finish, history | `feat: add test answer and finish flow` |
| E4 | src/routes/tests.ts | `feat: add tests routes` |
| E5 | Регистрация tests routes | `feat: register tests routes` |
**Итого:** 5 коммитов. После завершения — PR в `dev`.
---
## Agent F: LLM Service & Fallback Logic
**Зависимости:** A, B.
**Ветка:** `feat/llm-service`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| F1 | src/services/llm/llm.service.ts — конфиг, HTTP client | `feat: add LlmService base` |
| F2 | generateQuestions с JSON Schema валидацией | `feat: add LLM question generation` |
| F3 | Retry и fallback логика | `feat: add LLM retry and fallback` |
| F4 | Интеграция question_cache_meta | `feat: log LLM metadata to question_cache_meta` |
| F5 | Экспорт интерфейса для QuestionService | `feat: export LlmService interface` |
**Итого:** 5 коммитов. После завершения — PR в `dev`.
---
## Agent G: Admin QA for Questions
**Зависимости:** A, B, C, E (модель question_bank).
**Ветка:** `feat/admin-qa`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| G1 | src/services/admin/admin-question.service.ts | `feat: add AdminQuestionService` |
| G2 | src/routes/admin/questions.ts | `feat: add admin questions routes` |
| G3 | audit_logs при approve/reject/edit | `feat: add audit logging to admin actions` |
| G4 | Регистрация admin routes | `feat: register admin routes` |
**Итого:** 4 коммита. После завершения — PR в `dev`.
---
## Agent H: Tests & Quality
**Зависимости:** Может стартовать после C (auth), наращивать по мере готовности других агентов.
**Ветка:** `feat/testing`
**Задачи и коммиты:**
| # | Задача | Коммит |
| - | - | - |
| H1 | Vitest config, test-utils | `test: add Vitest config and test utils` |
| H2 | AuthService unit tests | `test: add auth service tests` |
| H3 | Auth routes integration tests | `test: add auth routes integration tests` |
| H4 | TestsService и QuestionService tests | `test: add tests and questions service tests` |
| H5 | LlmService unit tests (с моком) | `test: add LLM service tests` |
| H6 | Admin routes integration tests | `test: add admin routes tests` |
| H7 | Coverage ≥70%, npm script | `test: add coverage config` |
**Итого:** 7 коммитов. После завершения — PR в `dev`.
---
## Рекомендуемый порядок запуска
1. **Сразу:** Agent A и Agent B (в двух отдельных сессиях Cursor)
2. **После A и B:** Agent C, D, F (три сессии)
3. **После C, D, F:** Agent E, G (две сессии)
4. **Параллельно волне 23:** Agent H (тесты по мере готовности API)
---
## Чеклист для каждого агента
Перед каждым коммитом:
- [ ] `npm run typecheck` проходит
- [ ] Сообщение коммита по conventional commits
- [ ] Нет `console.log`, только `logger`
- [ ] Нет `any` без необходимости
После завершения всех задач агента:
- [ ] Создать PR в `dev`
- [ ] Проверить, что не сломаны существующие тесты (если есть)

View File

@@ -1,221 +0,0 @@
# Задача: Синхронизация бэкенда с документацией
## Контекст
По итогам аудита документации vs кода приняты решения. Данная задача — изменения в backend-репозитории.
---
## 0. Настройка Cookie в Fastify
Cookie нужны для хранения refresh token (httpOnly). Без этого разделы 3, 4 и 5 (logout, refresh, login Set-Cookie) не реализуемы.
### 0.1 Установка плагина
```bash
npm install @fastify/cookie
```
### 0.2 Регистрация в app.ts
Зарегистрировать **до** auth-роутов (cookie должны быть доступны в onRequest):
```ts
import cookie from '@fastify/cookie';
// После securityPlugin, до authPlugin
await app.register(cookie, {
secret: env.JWT_SECRET, // для подписанных cookie (опционально)
parseOptions: {}, // опции для парсинга входящих cookie
});
```
Порядок плагинов: `redis``database``security``cookie``rateLimit``auth``subscription` → routes.
### 0.3 Чтение cookie в роуте
```ts
const refreshToken = req.cookies.refreshToken; // string | undefined
```
Если cookie не передан, `refreshToken` будет `undefined`.
### 0.4 Установка cookie в ответе
```ts
reply.setCookie('refreshToken', token, {
httpOnly: true,
secure: env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/api/v1/auth',
maxAge: 604800, // 7 дней в секундах
signed: false, // если не используем подпись
});
```
Для production: `secure: true` (только HTTPS). Для development: `secure: false`, иначе cookie не установится на localhost:3000 (если без HTTPS).
### 0.5 Очистка cookie (logout)
```ts
reply.clearCookie('refreshToken', {
path: '/api/v1/auth',
httpOnly: true,
secure: env.NODE_ENV === 'production',
sameSite: 'strict',
});
```
Либо `reply.setCookie('refreshToken', '', { ... same opts ..., maxAge: 0 })`.
### 0.6 CORS и credentials
Убедиться, что CORS настроен с `credentials: true` (уже есть в `@fastify/cors`), иначе браузер не будет отправлять cookie с cross-origin запросами. Origin фронтенда должен быть в whitelist `CORS_ORIGINS`.
### 0.7 Согласование пути cookie и роутов
Cookie с `path: '/api/v1/auth'` отправляется только на запросы к `/api/v1/auth/*`. Refresh и logout должны вызываться по этим путям.
---
## 1. Префикс /api/v1
**Файл:** `src/app.ts`
При регистрации роутов добавить префикс `/api/v1`:
```ts
await app.register(authRoutes, { prefix: '/api/v1/auth' });
await app.register(profileRoutes, { prefix: '/api/v1/profile' });
await app.register(testsRoutes, { prefix: '/api/v1/tests' });
await app.register(adminQuestionsRoutes, { prefix: '/api/v1/admin' });
```
Health check оставить без префикса (например `/health`) или перенести по необходимости.
---
## 2. Auth: Login — вернуть объект user в ответ
**Файлы:** `src/routes/auth.ts`, `src/services/auth/auth.service.ts`
- `AuthService.login()` должен возвращать `{ user, accessToken, refreshToken, expiresIn }`.
- `user`: `{ id, email, nickname, avatarUrl, role, emailVerified }` — нужно подтянуть из БД.
- Фронтенду нужны id, nickname, avatarUrl для стейта (шапка, Redux/Pinia).
---
## 3. Auth: Logout — по документации (cookie, Bearer)
**Файлы:** `src/routes/auth.ts`, `src/services/auth/auth.service.ts`
- **Авторизация:** Bearer token в заголовке.
- **Request:** пустое тело (refresh token читается из cookie).
- **Response:** 200 с `{ message: "Logged out successfully" }`.
- Set-Cookie: `refreshToken=; ... Max-Age=0` для очистки cookie.
Требуется:
- Читать refresh token из cookie `refreshToken` (httpOnly cookie).
- Удалять сессию по хешу refresh token.
- Очищать cookie в ответе.
---
## 4. Auth: Refresh — по документации (cookie)
**Файлы:** `src/routes/auth.ts`, `src/services/auth/auth.service.ts`
- **Request:** пустое тело (refresh token из cookie).
- **Response:** 200 с `{ accessToken }`.
- Set-Cookie: новый refreshToken (ротация).
Требуется:
- Читать refresh token из cookie.
- Убрать `refreshToken` из body в schema и коде.
- Устанавливать httpOnly cookie с новым refresh token в ответе.
---
## 5. Auth: Login — установка cookie при успехе
При успешном login устанавливать refresh token в httpOnly cookie:
```text
Set-Cookie: refreshToken=<token>; HttpOnly; Secure; SameSite=Strict; Path=/api/v1/auth; Max-Age=604800
```
В development (`NODE_ENV=development`) Secure можно опустить, если используется HTTP.
---
## 6. Profile: добавить role и plan в getPrivateProfile
**Файлы:** `src/services/user/user.service.ts`, `src/routes/profile.ts`
- Расширить `PrivateProfile`: добавить `role`, `plan`.
- `role` — из `users.role`.
- `plan` — из `subscriptions` через subscription middleware (уже загружается в `req.subscription` для GET /profile).
- В route GET /profile после `getPrivateProfile` добавить в ответ `role: req.user` (из users) и `plan: req.subscription?.plan ?? 'free'`.
Либо загружать subscription в UserService при запросе профиля и включать plan/role в ответ.
---
## 7. Tests: score — хранить и отдавать количество правильных
**Файлы:** `src/services/tests/tests.service.ts`, `src/db/schema/tests.ts` (если нужно)
- `score` в БД и API = количество правильных ответов (integer), не процент.
- В `finishTest`: `score = correctCount` (не `Math.round((correctCount / questions.length) * 100)`).
- В ответе finish и results: `{ score, totalQuestions, percentage }`, где `percentage = (score / totalQuestions) * 100`.
---
## 8. question_cache_meta: привести схему к документации
**Файлы:** `src/db/schema/questionCacheMeta.ts`, миграция, `src/services/llm/llm.service.ts`, `src/services/questions/question.service.ts`
Документация (llm/strategy.md) требует:
| Поле | Тип | Описание |
| - | - | - |
| model | varchar | Уже есть как llm_model |
| generation_time_ms | integer | Есть |
| prompt_hash | varchar | Есть |
| valid | boolean | Прошёл ли валидацию с первого раза |
| retry_count | integer | Сколько retry потребовалось |
| questions_generated | integer | Сколько вопросов вернул LLM |
Действия:
1. Добавить в схему `questionCacheMeta`: `valid` (boolean), `retryCount` (integer), `questionsGenerated` (integer).
2. Создать миграцию Drizzle.
3. Расширить `LlmGenerationMeta` в llm.service: `valid`, `retryCount`, `questionsGenerated`.
4. В `LlmService.generateQuestions` и `chatWithMeta`: при необходимости возвращать retry count.
5. В `QuestionService.generateAndPersistQuestions`: при вставке в `questionCacheMeta` передавать новые поля.
---
## 9. Cookie-настройки
- Путь для cookie: `/api/v1/auth` (совпадает с префиксом auth-роутов).
- Max-Age для refresh: 604800 (7 дней).
- Secure: только в production (NODE_ENV=production).
- SameSite=Strict.
---
## Чеклист
- [x] @fastify/cookie установлен и зарегистрирован (раздел 0)
- [x] Префикс /api/v1 для роутов
- [x] Login: user в ответе (id, nickname, avatarUrl, role, emailVerified)
- [x] Login: Set-Cookie refreshToken
- [x] Logout: Bearer + cookie, пустое тело, 200 + message
- [x] Refresh: cookie, пустое тело, 200 + accessToken + Set-Cookie
- [x] getPrivateProfile: role, plan
- [x] Tests finish: score = correctCount, возвращать score, totalQuestions, percentage
- [x] question_cache_meta: valid, retryCount, questionsGenerated
- [x] Обновить тесты под новые контракты

View File

@@ -1,157 +0,0 @@
# Задача: Синхронизация документации с реализацией
## Контекст
По итогам аудита документация должна быть приведена в соответствие с текущей реализацией backend. Данная задача — правки в samreshu_docs (submodule или основной репо с документацией).
---
## 1. API: Базовый URL
Убедиться, что базовый URL `/api/v1` соответствует backend (после внесения префикса агентом backend). Если в docs есть примеры с другим базовым путём — исправить.
---
## 2. Auth: Register
**Файл:** `samreshu_docs/api/contracts.md`
- Регистрация **не выдаёт токены** до подтверждения email.
- Response 201: `{ userId, message, verificationCode }` (verificationCode — для dev/тестов, в prod не отдаётся).
- Добавить ошибку `NICKNAME_TAKEN` (409), если в коде она есть.
---
## 3. Auth: Login
- Ошибка при блокировке (lockout): **429** `RATE_LIMIT_EXCEEDED` (не 403 ACCOUNT_LOCKED).
- Response 200 должен включать объект `user`: `{ id, email, nickname, avatarUrl, role, emailVerified }`.
- Set-Cookie: refreshToken (httpOnly, Secure, SameSite=Strict, Path=/api/v1/auth).
---
## 4. Auth: Verify-email
- **Request:** `{ userId, code }` (не только code).
- **Авторизация:** не требуется (Bearer не нужен).
---
## 5. Auth: Reset-password
- **Request:** поле `newPassword` (не `password`).
---
## 6. Profile: GET /profile
- В ответе: `role`, `plan` (из subscriptions).
---
## 7. Profile: GET /profile/:username (публичный профиль)
- Структура `stats`: `{ byStack, totalTestsTaken, totalQuestions, correctAnswers, accuracy }` (а не только testsCompleted, averageScore).
- Описать формат `byStack` и остальных полей.
---
## 8. Tests: POST /tests (создание)
- Response: тест со списком **всех** вопросов в `questions` (не только текущий в `question`).
- Структура ответа: `{ id, stack, level, questionCount, status, startedAt, timeLimitSeconds, questions: [...] }`.
---
## 9. Tests: POST /tests/:id/answer
- Response: полный snapshot отвеченного вопроса (формат из реализации).
- Указать, что структура может отличаться от минимальной "answered + progress + nextQuestion".
---
## 10. Tests: POST /tests/:id/finish
- `score` — количество правильных ответов (integer).
- В ответе: `score`, `totalQuestions`, `percentage` (процент считает фронтенд или он приходит с бэка).
---
## 11. Tests: GET /tests/history (или GET /tests для истории)
- **Пагинация:** offset-based: `limit`, `offset` (не cursor).
- Формат: `{ tests: [...], total }` (не `{ data, pagination }`).
- Указать параметры `limit`, `offset`.
---
## 12. Admin
- Эндпоинт списка: **GET /admin/questions/pending** (не /queue).
- Отдельные эндпоинты: **POST /admin/questions/:id/approve**, **POST /admin/questions/:id/reject**.
- **PATCH /admin/questions/:id** — для редактирования контента (без смены статуса).
- Пагинация: limit/offset.
---
## 13. Database: Токены верификации
**Файл:** `samreshu_docs/database/schema.md`
- Вместо общей таблицы `verification_tokens` описать:
- `email_verification_codes` (userId, code, expiresAt)
- `password_reset_tokens` (userId, tokenHash, expiresAt)
---
## 14. Security: CORS
**Файл:** `samreshu_docs/principles/security.md`
- Origins задаются через переменную окружения **CORS_ORIGINS** (не хардкод localhost/prod).
- Методы: **GET, POST, PATCH, DELETE, PUT, OPTIONS** (OPTIONS нужен для preflight, PUT — для идемпотентных обновлений).
---
## 15. Security: Helmet (CSP, COEP)
- **CSP и COEP отключены** — бэкенд отдаёт только JSON API.
- Эти заголовки предназначены для HTML-страниц; для REST API они не нужны и могут мешать Swagger UI.
---
## 16. LLM: Переменные окружения
**Файлы:** `samreshu_docs/llm/strategy.md`, `samreshu_docs/onboarding/setup.md`
Добавить в документацию:
- **LLM_FALLBACK_MODEL** — запасная модель при падении основной.
- **LLM_RETRY_DELAY_MS** — задержка между retry при ошибках API.
---
## 17. LLM: Логирование в question_cache_meta
**Файл:** `samreshu_docs/llm/strategy.md`
- Актуальная структура: `llm_model`, `prompt_hash`, `generation_time_ms`, `valid`, `retry_count`, `questions_generated`, `raw_response` (опционально).
---
## 18. Onboarding: .env.example
- Закрепить правило: `.env.example` обновляется при добавлении новых фич (новые переменные, rate limits, LLM и т.д.).
- Упомянуть требование JWT_SECRET >= 32 символа.
---
## Чеклист
- [ ] api/contracts.md: register, login, verify-email, reset-password, logout, refresh
- [ ] api/contracts.md: profile (role, plan, stats)
- [ ] api/contracts.md: tests (create, answer, finish, history)
- [ ] api/contracts.md: admin (pending, approve, reject, PATCH)
- [ ] database/schema.md: email_verification_codes, password_reset_tokens
- [ ] principles/security.md: CORS, Helmet
- [ ] llm/strategy.md: LLM_FALLBACK_MODEL, LLM_RETRY_DELAY_MS, question_cache_meta
- [ ] onboarding/setup.md: правило .env.example

View File

@@ -1,13 +0,0 @@
import 'dotenv/config';
import { defineConfig } from 'drizzle-kit';
const databaseUrl = process.env.DATABASE_URL ?? 'postgresql://samreshu:samreshu_dev@localhost:5432/samreshu';
export default defineConfig({
schema: './src/db/schema/*.ts',
out: './src/db/migrations',
dialect: 'postgresql',
dbCredentials: {
url: databaseUrl,
},
});

37
package-lock.json generated
View File

@@ -8,7 +8,6 @@
"name": "samreshu-backend", "name": "samreshu-backend",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^10.0.0", "@fastify/cors": "^10.0.0",
"@fastify/helmet": "^12.0.0", "@fastify/helmet": "^12.0.0",
"@fastify/rate-limit": "^10.0.0", "@fastify/rate-limit": "^10.0.0",
@@ -1181,42 +1180,6 @@
"integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@fastify/cookie": {
"version": "11.0.2",
"resolved": "https://registry.npmjs.org/@fastify/cookie/-/cookie-11.0.2.tgz",
"integrity": "sha512-GWdwdGlgJxyvNv+QcKiGNevSspMQXncjMZ1J8IvuDQk0jvkzgWWZFNC2En3s+nHndZBGV8IbLwOI/sxCZw/mzA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT",
"dependencies": {
"cookie": "^1.0.0",
"fastify-plugin": "^5.0.0"
}
},
"node_modules/@fastify/cookie/node_modules/fastify-plugin": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/fastify-plugin/-/fastify-plugin-5.1.0.tgz",
"integrity": "sha512-FAIDA8eovSt5qcDgcBvDuX/v0Cjz0ohGhENZ/wpc3y+oZCY2afZ9Baqql3g/lC+OHRnciQol4ww7tuthOb9idw==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT"
},
"node_modules/@fastify/cors": { "node_modules/@fastify/cors": {
"version": "10.1.0", "version": "10.1.0",
"resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-10.1.0.tgz", "resolved": "https://registry.npmjs.org/@fastify/cors/-/cors-10.1.0.tgz",

View File

@@ -8,7 +8,7 @@
"build": "tsc", "build": "tsc",
"dev": "tsx watch src/server.ts", "dev": "tsx watch src/server.ts",
"start": "node dist/server.js", "start": "node dist/server.js",
"db:generate": "tsx node_modules/drizzle-kit/bin.cjs generate --config=drizzle.config.ts", "db:generate": "drizzle-kit generate --config=drizzle.config.ts",
"db:migrate": "tsx src/db/migrate.ts", "db:migrate": "tsx src/db/migrate.ts",
"db:studio": "drizzle-kit studio", "db:studio": "drizzle-kit studio",
"db:seed": "tsx src/db/seed.ts", "db:seed": "tsx src/db/seed.ts",
@@ -20,7 +20,6 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@fastify/cookie": "^11.0.2",
"@fastify/cors": "^10.0.0", "@fastify/cors": "^10.0.0",
"@fastify/helmet": "^12.0.0", "@fastify/helmet": "^12.0.0",
"@fastify/rate-limit": "^10.0.0", "@fastify/rate-limit": "^10.0.0",

Submodule samreshu_docs deleted from 99cd8ae727

View File

@@ -1,16 +1,9 @@
import Fastify, { FastifyInstance } from 'fastify'; import Fastify, { FastifyInstance } from 'fastify';
import cookie from '@fastify/cookie';
import { AppError } from './utils/errors.js'; import { AppError } from './utils/errors.js';
import databasePlugin from './plugins/database.js'; import databasePlugin from './plugins/database.js';
import redisPlugin from './plugins/redis.js'; import redisPlugin from './plugins/redis.js';
import securityPlugin from './plugins/security.js'; import securityPlugin from './plugins/security.js';
import rateLimitPlugin from './plugins/rateLimit.js'; import rateLimitPlugin from './plugins/rateLimit.js';
import authPlugin from './plugins/auth.js';
import subscriptionPlugin from './plugins/subscription.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';
@@ -75,17 +68,7 @@ export async function buildApp(): Promise<FastifyInstance> {
await app.register(redisPlugin); await app.register(redisPlugin);
await app.register(databasePlugin); await app.register(databasePlugin);
await app.register(securityPlugin); await app.register(securityPlugin);
await app.register(cookie, {
secret: env.JWT_SECRET,
parseOptions: {},
});
await app.register(rateLimitPlugin); await app.register(rateLimitPlugin);
await app.register(authPlugin);
await app.register(subscriptionPlugin);
await app.register(authRoutes, { prefix: '/api/v1/auth' });
await app.register(profileRoutes, { prefix: '/api/v1/profile' });
await app.register(testsRoutes, { prefix: '/api/v1/tests' });
await app.register(adminQuestionsRoutes, { prefix: '/api/v1/admin' });
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() })); app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));

View File

@@ -14,14 +14,13 @@ const envSchema = z.object({
LLM_BASE_URL: z.string().url().default('http://localhost:11434/v1'), LLM_BASE_URL: z.string().url().default('http://localhost:11434/v1'),
LLM_MODEL: z.string().default('qwen2.5:14b'), LLM_MODEL: z.string().default('qwen2.5:14b'),
LLM_FALLBACK_MODEL: z.string().optional(),
LLM_API_KEY: z.string().optional(), LLM_API_KEY: z.string().optional(),
LLM_TIMEOUT_MS: z.coerce.number().default(15000), LLM_TIMEOUT_MS: z.coerce.number().default(15000),
LLM_MAX_RETRIES: z.coerce.number().min(0).default(1), LLM_MAX_RETRIES: z.coerce.number().min(0).default(1),
LLM_RETRY_DELAY_MS: z.coerce.number().min(0).default(1000),
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),

View File

@@ -1,19 +0,0 @@
import { drizzle } from 'drizzle-orm/node-postgres';
import { migrate } from 'drizzle-orm/node-postgres/migrator';
import pg from 'pg';
import { env } from '../config/env.js';
const { Pool } = pg;
async function runMigrations() {
const pool = new Pool({ connectionString: env.DATABASE_URL });
const db = drizzle(pool);
await migrate(db, { migrationsFolder: './src/db/migrations' });
await pool.end();
}
runMigrations().catch((err) => {
console.error('Migration failed:', err);
process.exit(1);
});

View File

@@ -1,246 +0,0 @@
CREATE TYPE "public"."level" AS ENUM('basic', 'beginner', 'intermediate', 'advanced', 'expert');--> statement-breakpoint
CREATE TYPE "public"."plan" AS ENUM('free', 'pro');--> statement-breakpoint
CREATE TYPE "public"."question_source" AS ENUM('llm_generated', 'manual');--> statement-breakpoint
CREATE TYPE "public"."question_status" AS ENUM('pending', 'approved', 'rejected');--> statement-breakpoint
CREATE TYPE "public"."question_type" AS ENUM('single_choice', 'multiple_select', 'true_false', 'short_text');--> statement-breakpoint
CREATE TYPE "public"."report_status" AS ENUM('open', 'resolved', 'dismissed');--> statement-breakpoint
CREATE TYPE "public"."self_level" AS ENUM('jun', 'mid', 'sen');--> statement-breakpoint
CREATE TYPE "public"."stack" AS ENUM('html', 'css', 'js', 'ts', 'react', 'vue', 'nodejs', 'git', 'web_basics');--> statement-breakpoint
CREATE TYPE "public"."subscription_status" AS ENUM('active', 'trialing', 'cancelled', 'expired');--> statement-breakpoint
CREATE TYPE "public"."test_mode" AS ENUM('fixed', 'infinite', 'marathon');--> statement-breakpoint
CREATE TYPE "public"."test_status" AS ENUM('in_progress', 'completed', 'abandoned');--> statement-breakpoint
CREATE TYPE "public"."user_role" AS ENUM('guest', 'free', 'pro', 'admin');--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "users" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"email" varchar(255) NOT NULL,
"password_hash" varchar(255) NOT NULL,
"nickname" varchar(30) NOT NULL,
"avatar_url" varchar(500),
"country" varchar(100),
"city" varchar(100),
"self_level" "self_level",
"is_public" boolean DEFAULT true NOT NULL,
"role" "user_role" DEFAULT 'free' NOT NULL,
"email_verified_at" timestamp with time zone,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
CONSTRAINT "users_email_unique" UNIQUE("email")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "sessions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"refresh_token_hash" varchar(255) NOT NULL,
"user_agent" varchar(500),
"ip_address" varchar(45),
"last_active_at" timestamp with time zone DEFAULT now() NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "subscriptions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"plan" "plan" NOT NULL,
"status" "subscription_status" NOT NULL,
"started_at" timestamp with time zone NOT NULL,
"expires_at" timestamp with time zone,
"cancelled_at" timestamp with time zone,
"payment_provider" varchar(50),
"external_id" varchar(255),
CONSTRAINT "subscriptions_user_id_unique" UNIQUE("user_id")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "tests" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"stack" "stack" NOT NULL,
"level" "level" NOT NULL,
"question_count" integer NOT NULL,
"mode" "test_mode" DEFAULT 'fixed' NOT NULL,
"status" "test_status" DEFAULT 'in_progress' NOT NULL,
"score" integer,
"started_at" timestamp with time zone DEFAULT now() NOT NULL,
"finished_at" timestamp with time zone,
"time_limit_seconds" integer
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "test_questions" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"test_id" uuid NOT NULL,
"question_bank_id" uuid,
"order_number" integer NOT NULL,
"type" "question_type" NOT NULL,
"question_text" text NOT NULL,
"options" jsonb,
"correct_answer" jsonb NOT NULL,
"explanation" text NOT NULL,
"user_answer" jsonb,
"is_correct" boolean,
"answered_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "question_bank" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"stack" "stack" NOT NULL,
"level" "level" NOT NULL,
"type" "question_type" NOT NULL,
"question_text" text NOT NULL,
"options" jsonb,
"correct_answer" jsonb NOT NULL,
"explanation" text NOT NULL,
"status" "question_status" DEFAULT 'pending' NOT NULL,
"source" "question_source" NOT NULL,
"usage_count" integer DEFAULT 0 NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"approved_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "question_cache_meta" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"question_bank_id" uuid NOT NULL,
"llm_model" varchar(100) NOT NULL,
"prompt_hash" varchar(64) NOT NULL,
"generation_time_ms" integer NOT NULL,
"raw_response" jsonb,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "question_reports" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"question_bank_id" uuid NOT NULL,
"user_id" uuid NOT NULL,
"reason" text NOT NULL,
"status" "report_status" DEFAULT 'open' NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"resolved_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "user_stats" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"stack" "stack" NOT NULL,
"level" "level" NOT NULL,
"total_questions" integer DEFAULT 0 NOT NULL,
"correct_answers" integer DEFAULT 0 NOT NULL,
"tests_taken" integer DEFAULT 0 NOT NULL,
"last_test_at" timestamp with time zone,
CONSTRAINT "user_stats_user_id_stack_level_unique" UNIQUE("user_id","stack","level")
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "audit_logs" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"admin_id" uuid NOT NULL,
"action" varchar(100) NOT NULL,
"target_type" varchar(50) NOT NULL,
"target_id" uuid NOT NULL,
"details" jsonb,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "user_question_log" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"question_bank_id" uuid NOT NULL,
"seen_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "email_verification_codes" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"code" varchar(10) NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "password_reset_tokens" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"user_id" uuid NOT NULL,
"token_hash" varchar(255) NOT NULL,
"expires_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "subscriptions" ADD CONSTRAINT "subscriptions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "tests" ADD CONSTRAINT "tests_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "test_questions" ADD CONSTRAINT "test_questions_test_id_tests_id_fk" FOREIGN KEY ("test_id") REFERENCES "public"."tests"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "test_questions" ADD CONSTRAINT "test_questions_question_bank_id_question_bank_id_fk" FOREIGN KEY ("question_bank_id") REFERENCES "public"."question_bank"("id") ON DELETE set null ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "question_cache_meta" ADD CONSTRAINT "question_cache_meta_question_bank_id_question_bank_id_fk" FOREIGN KEY ("question_bank_id") REFERENCES "public"."question_bank"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "question_reports" ADD CONSTRAINT "question_reports_question_bank_id_question_bank_id_fk" FOREIGN KEY ("question_bank_id") REFERENCES "public"."question_bank"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "question_reports" ADD CONSTRAINT "question_reports_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "user_stats" ADD CONSTRAINT "user_stats_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "audit_logs" ADD CONSTRAINT "audit_logs_admin_id_users_id_fk" FOREIGN KEY ("admin_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "user_question_log" ADD CONSTRAINT "user_question_log_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "user_question_log" ADD CONSTRAINT "user_question_log_question_bank_id_question_bank_id_fk" FOREIGN KEY ("question_bank_id") REFERENCES "public"."question_bank"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "email_verification_codes" ADD CONSTRAINT "email_verification_codes_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
--> statement-breakpoint
DO $$ BEGIN
ALTER TABLE "password_reset_tokens" ADD CONSTRAINT "password_reset_tokens_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;
EXCEPTION
WHEN duplicate_object THEN null;
END $$;

View File

@@ -1,3 +0,0 @@
ALTER TABLE "question_cache_meta" ADD COLUMN "valid" boolean DEFAULT true NOT NULL;--> statement-breakpoint
ALTER TABLE "question_cache_meta" ADD COLUMN "retry_count" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
ALTER TABLE "question_cache_meta" ADD COLUMN "questions_generated" integer DEFAULT 0 NOT NULL;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,20 +0,0 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1772620981431,
"tag": "0000_fearless_salo",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1772792192122,
"tag": "0001_fluffy_yellowjacket",
"breakpoints": true
}
]
}

View File

@@ -1,18 +0,0 @@
import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';
import { jsonb } from 'drizzle-orm/pg-core';
import { users } from './users.js';
export const auditLogs = pgTable('audit_logs', {
id: uuid('id').primaryKey().defaultRandom(),
adminId: uuid('admin_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
action: varchar('action', { length: 100 }).notNull(),
targetType: varchar('target_type', { length: 50 }).notNull(),
targetId: uuid('target_id').notNull(),
details: jsonb('details').$type<Record<string, unknown>>(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});
export type AuditLog = typeof auditLogs.$inferSelect;
export type NewAuditLog = typeof auditLogs.$inferInsert;

View File

@@ -1,27 +0,0 @@
import { pgEnum } from 'drizzle-orm/pg-core';
export const userRoleEnum = pgEnum('user_role', ['guest', 'free', 'pro', 'admin']);
export const planEnum = pgEnum('plan', ['free', 'pro']);
export const subscriptionStatusEnum = pgEnum('subscription_status', ['active', 'trialing', 'cancelled', 'expired']);
export const stackEnum = pgEnum('stack', ['html', 'css', 'js', 'ts', 'react', 'vue', 'nodejs', 'git', 'web_basics']);
export const levelEnum = pgEnum('level', ['basic', 'beginner', 'intermediate', 'advanced', 'expert']);
export const testModeEnum = pgEnum('test_mode', ['fixed', 'infinite', 'marathon']);
export const testStatusEnum = pgEnum('test_status', ['in_progress', 'completed', 'abandoned']);
export const questionTypeEnum = pgEnum('question_type', ['single_choice', 'multiple_select', 'true_false', 'short_text']);
export const questionStatusEnum = pgEnum('question_status', ['pending', 'approved', 'rejected']);
export const questionSourceEnum = pgEnum('question_source', ['llm_generated', 'manual']);
export const reportStatusEnum = pgEnum('report_status', ['open', 'resolved', 'dismissed']);
export const selfLevelEnum = pgEnum('self_level', ['jun', 'mid', 'sen']);
export type UserRole = (typeof userRoleEnum.enumValues)[number];
export type Plan = (typeof planEnum.enumValues)[number];
export type SubscriptionStatus = (typeof subscriptionStatusEnum.enumValues)[number];
export type Stack = (typeof stackEnum.enumValues)[number];
export type Level = (typeof levelEnum.enumValues)[number];
export type TestMode = (typeof testModeEnum.enumValues)[number];
export type TestStatus = (typeof testStatusEnum.enumValues)[number];
export type QuestionType = (typeof questionTypeEnum.enumValues)[number];
export type QuestionStatus = (typeof questionStatusEnum.enumValues)[number];
export type QuestionSource = (typeof questionSourceEnum.enumValues)[number];
export type ReportStatus = (typeof reportStatusEnum.enumValues)[number];
export type SelfLevel = (typeof selfLevelEnum.enumValues)[number];

View File

@@ -1,13 +0,0 @@
export * from './enums.js';
export * from './users.js';
export * from './sessions.js';
export * from './subscriptions.js';
export * from './tests.js';
export * from './testQuestions.js';
export * from './questionBank.js';
export * from './questionCacheMeta.js';
export * from './questionReports.js';
export * from './userStats.js';
export * from './auditLogs.js';
export * from './userQuestionLog.js';
export * from './verificationTokens.js';

View File

@@ -1,22 +0,0 @@
import { pgTable, uuid, text, integer, timestamp } from 'drizzle-orm/pg-core';
import { jsonb } from 'drizzle-orm/pg-core';
import { stackEnum, levelEnum, questionTypeEnum, questionStatusEnum, questionSourceEnum } from './enums.js';
export const questionBank = pgTable('question_bank', {
id: uuid('id').primaryKey().defaultRandom(),
stack: stackEnum('stack').notNull(),
level: levelEnum('level').notNull(),
type: questionTypeEnum('type').notNull(),
questionText: text('question_text').notNull(),
options: jsonb('options').$type<Array<{ key: string; text: string }>>(),
correctAnswer: jsonb('correct_answer').$type<string | string[]>().notNull(),
explanation: text('explanation').notNull(),
status: questionStatusEnum('status').notNull().default('pending'),
source: questionSourceEnum('source').notNull(),
usageCount: integer('usage_count').notNull().default(0),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
approvedAt: timestamp('approved_at', { withTimezone: true }),
});
export type QuestionBank = typeof questionBank.$inferSelect;
export type NewQuestionBank = typeof questionBank.$inferInsert;

View File

@@ -1,21 +0,0 @@
import { pgTable, uuid, varchar, integer, timestamp, boolean } from 'drizzle-orm/pg-core';
import { jsonb } from 'drizzle-orm/pg-core';
import { questionBank } from './questionBank.js';
export const questionCacheMeta = pgTable('question_cache_meta', {
id: uuid('id').primaryKey().defaultRandom(),
questionBankId: uuid('question_bank_id')
.notNull()
.references(() => questionBank.id, { onDelete: 'cascade' }),
llmModel: varchar('llm_model', { length: 100 }).notNull(),
promptHash: varchar('prompt_hash', { length: 64 }).notNull(),
generationTimeMs: integer('generation_time_ms').notNull(),
rawResponse: jsonb('raw_response').$type<unknown>(),
valid: boolean('valid').notNull().default(true),
retryCount: integer('retry_count').notNull().default(0),
questionsGenerated: integer('questions_generated').notNull().default(0),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});
export type QuestionCacheMeta = typeof questionCacheMeta.$inferSelect;
export type NewQuestionCacheMeta = typeof questionCacheMeta.$inferInsert;

View File

@@ -1,21 +0,0 @@
import { pgTable, uuid, text, timestamp } from 'drizzle-orm/pg-core';
import { reportStatusEnum } from './enums.js';
import { questionBank } from './questionBank.js';
import { users } from './users.js';
export const questionReports = pgTable('question_reports', {
id: uuid('id').primaryKey().defaultRandom(),
questionBankId: uuid('question_bank_id')
.notNull()
.references(() => questionBank.id, { onDelete: 'cascade' }),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
reason: text('reason').notNull(),
status: reportStatusEnum('status').notNull().default('open'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
resolvedAt: timestamp('resolved_at', { withTimezone: true }),
});
export type QuestionReport = typeof questionReports.$inferSelect;
export type NewQuestionReport = typeof questionReports.$inferInsert;

View File

@@ -1,18 +0,0 @@
import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';
import { users } from './users.js';
export const sessions = pgTable('sessions', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
refreshTokenHash: varchar('refresh_token_hash', { length: 255 }).notNull(),
userAgent: varchar('user_agent', { length: 500 }),
ipAddress: varchar('ip_address', { length: 45 }),
lastActiveAt: timestamp('last_active_at', { withTimezone: true }).notNull().defaultNow(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});
export type Session = typeof sessions.$inferSelect;
export type NewSession = typeof sessions.$inferInsert;

View File

@@ -1,21 +0,0 @@
import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';
import { planEnum, subscriptionStatusEnum } from './enums.js';
import { users } from './users.js';
export const subscriptions = pgTable('subscriptions', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' })
.unique(),
plan: planEnum('plan').notNull(),
status: subscriptionStatusEnum('status').notNull(),
startedAt: timestamp('started_at', { withTimezone: true }).notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }),
cancelledAt: timestamp('cancelled_at', { withTimezone: true }),
paymentProvider: varchar('payment_provider', { length: 50 }),
externalId: varchar('external_id', { length: 255 }),
});
export type Subscription = typeof subscriptions.$inferSelect;
export type NewSubscription = typeof subscriptions.$inferInsert;

View File

@@ -1,25 +0,0 @@
import { pgTable, uuid, text, integer, boolean, timestamp } from 'drizzle-orm/pg-core';
import { jsonb } from 'drizzle-orm/pg-core';
import { questionTypeEnum } from './enums.js';
import { tests } from './tests.js';
import { questionBank } from './questionBank.js';
export const testQuestions = pgTable('test_questions', {
id: uuid('id').primaryKey().defaultRandom(),
testId: uuid('test_id')
.notNull()
.references(() => tests.id, { onDelete: 'cascade' }),
questionBankId: uuid('question_bank_id').references(() => questionBank.id, { onDelete: 'set null' }),
orderNumber: integer('order_number').notNull(),
type: questionTypeEnum('type').notNull(),
questionText: text('question_text').notNull(),
options: jsonb('options').$type<Array<{ key: string; text: string }>>(),
correctAnswer: jsonb('correct_answer').$type<string | string[]>().notNull(),
explanation: text('explanation').notNull(),
userAnswer: jsonb('user_answer').$type<string | string[]>(),
isCorrect: boolean('is_correct'),
answeredAt: timestamp('answered_at', { withTimezone: true }),
});
export type TestQuestion = typeof testQuestions.$inferSelect;
export type NewTestQuestion = typeof testQuestions.$inferInsert;

View File

@@ -1,22 +0,0 @@
import { pgTable, uuid, integer, timestamp } from 'drizzle-orm/pg-core';
import { stackEnum, levelEnum, testModeEnum, testStatusEnum } from './enums.js';
import { users } from './users.js';
export const tests = pgTable('tests', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
stack: stackEnum('stack').notNull(),
level: levelEnum('level').notNull(),
questionCount: integer('question_count').notNull(),
mode: testModeEnum('mode').notNull().default('fixed'),
status: testStatusEnum('status').notNull().default('in_progress'),
score: integer('score'),
startedAt: timestamp('started_at', { withTimezone: true }).notNull().defaultNow(),
finishedAt: timestamp('finished_at', { withTimezone: true }),
timeLimitSeconds: integer('time_limit_seconds'),
});
export type Test = typeof tests.$inferSelect;
export type NewTest = typeof tests.$inferInsert;

View File

@@ -1,17 +0,0 @@
import { pgTable, uuid, timestamp } from 'drizzle-orm/pg-core';
import { users } from './users.js';
import { questionBank } from './questionBank.js';
export const userQuestionLog = pgTable('user_question_log', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
questionBankId: uuid('question_bank_id')
.notNull()
.references(() => questionBank.id, { onDelete: 'cascade' }),
seenAt: timestamp('seen_at', { withTimezone: true }).notNull().defaultNow(),
});
export type UserQuestionLog = typeof userQuestionLog.$inferSelect;
export type NewUserQuestionLog = typeof userQuestionLog.$inferInsert;

View File

@@ -1,26 +0,0 @@
import { pgTable, uuid, integer, timestamp } from 'drizzle-orm/pg-core';
import { unique } from 'drizzle-orm/pg-core';
import { stackEnum, levelEnum } from './enums.js';
import { users } from './users.js';
export const userStats = pgTable(
'user_stats',
{
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
stack: stackEnum('stack').notNull(),
level: levelEnum('level').notNull(),
totalQuestions: integer('total_questions').notNull().default(0),
correctAnswers: integer('correct_answers').notNull().default(0),
testsTaken: integer('tests_taken').notNull().default(0),
lastTestAt: timestamp('last_test_at', { withTimezone: true }),
},
(t) => ({
userStackLevelUnique: unique().on(t.userId, t.stack, t.level),
})
);
export type UserStat = typeof userStats.$inferSelect;
export type NewUserStat = typeof userStats.$inferInsert;

View File

@@ -1,21 +0,0 @@
import { pgTable, uuid, varchar, timestamp, boolean } from 'drizzle-orm/pg-core';
import { userRoleEnum, selfLevelEnum } from './enums.js';
export const users = pgTable('users', {
id: uuid('id').primaryKey().defaultRandom(),
email: varchar('email', { length: 255 }).notNull().unique(),
passwordHash: varchar('password_hash', { length: 255 }).notNull(),
nickname: varchar('nickname', { length: 30 }).notNull(),
avatarUrl: varchar('avatar_url', { length: 500 }),
country: varchar('country', { length: 100 }),
city: varchar('city', { length: 100 }),
selfLevel: selfLevelEnum('self_level'),
isPublic: boolean('is_public').notNull().default(true),
role: userRoleEnum('role').notNull().default('free'),
emailVerifiedAt: timestamp('email_verified_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
});
export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;

View File

@@ -1,22 +0,0 @@
import { pgTable, uuid, varchar, timestamp } from 'drizzle-orm/pg-core';
import { users } from './users.js';
export const emailVerificationCodes = pgTable('email_verification_codes', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
code: varchar('code', { length: 10 }).notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});
export const passwordResetTokens = pgTable('password_reset_tokens', {
id: uuid('id').primaryKey().defaultRandom(),
userId: uuid('user_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
tokenHash: varchar('token_hash', { length: 255 }).notNull(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
});

View File

@@ -1,47 +0,0 @@
import 'dotenv/config';
import { drizzle } from 'drizzle-orm/node-postgres';
import { eq } from 'drizzle-orm';
import pg from 'pg';
import argon2 from 'argon2';
import { env } from '../config/env.js';
import { users } from './schema/index.js';
const { Pool } = pg;
const TEST_USER = {
email: 'test@example.com',
password: 'TestPassword123!',
nickname: 'TestUser',
};
async function runSeed() {
const pool = new Pool({ connectionString: env.DATABASE_URL });
const db = drizzle(pool);
if (env.NODE_ENV !== 'development') {
await pool.end();
return;
}
const existing = await db.select().from(users).where(eq(users.email, TEST_USER.email)).limit(1);
if (existing.length > 0) {
await pool.end();
return;
}
const passwordHash = await argon2.hash(TEST_USER.password);
await db.insert(users).values({
email: TEST_USER.email,
passwordHash,
nickname: TEST_USER.nickname,
role: 'free',
emailVerifiedAt: new Date(),
});
await pool.end();
}
runSeed().catch((err) => {
console.error('Seed failed:', err);
process.exit(1);
});

View File

@@ -1,58 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fp from 'fastify-plugin';
import { eq } from 'drizzle-orm';
import { verifyToken, isAccessPayload } from '../utils/jwt.js';
import { unauthorized, forbidden } from '../utils/errors.js';
import { users } from '../db/schema/users.js';
declare module 'fastify' {
interface FastifyInstance {
authenticate: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
authenticateAdmin: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
interface FastifyRequest {
user?: { id: string; email: string };
}
}
export async function authenticate(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
throw unauthorized('Missing or invalid authorization header');
}
const token = authHeader.slice(7);
try {
const payload = await verifyToken(token);
if (!isAccessPayload(payload)) {
throw unauthorized('Invalid token type');
}
req.user = { id: payload.sub, email: payload.email };
} catch {
throw unauthorized('Invalid or expired token');
}
}
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) => {
app.decorateRequest('user', undefined);
app.decorate('authenticate', authenticate);
app.decorate('authenticateAdmin', authenticateAdmin);
};
export default fp(authPlugin, { name: 'auth', dependencies: ['database'] });

View File

@@ -3,13 +3,12 @@ import { drizzle } from 'drizzle-orm/node-postgres';
import pg from 'pg'; import pg from 'pg';
import fp from 'fastify-plugin'; import fp from 'fastify-plugin';
import { env } from '../config/env.js'; import { env } from '../config/env.js';
import * as schema from '../db/schema/index.js';
const { Pool } = pg; const { Pool } = pg;
declare module 'fastify' { declare module 'fastify' {
interface FastifyInstance { interface FastifyInstance {
db: ReturnType<typeof drizzle<typeof schema>>; db: ReturnType<typeof drizzle>;
} }
} }
@@ -21,7 +20,7 @@ const databasePlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
connectionTimeoutMillis: 5000, connectionTimeoutMillis: 5000,
}); });
const db = drizzle(pool, { schema }); const db = drizzle(pool);
app.decorate('db', db); app.decorate('db', db);

View File

@@ -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' },
@@ -27,7 +29,6 @@ const rateLimitPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
app.decorate('rateLimitOptions', options); app.decorate('rateLimitOptions', options);
await app.register(rateLimit, { await app.register(rateLimit, {
global: false,
max: options.apiGuest.max, max: options.apiGuest.max,
timeWindow: options.apiGuest.timeWindow, timeWindow: options.apiGuest.timeWindow,
keyGenerator: (req) => { keyGenerator: (req) => {

View File

@@ -1,71 +0,0 @@
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import fp from 'fastify-plugin';
import { eq } from 'drizzle-orm';
import { subscriptions } from '../db/schema/subscriptions.js';
import { forbidden } from '../utils/errors.js';
export type SubscriptionInfo = {
plan: 'free' | 'pro';
status: 'active' | 'trialing' | 'cancelled' | 'expired';
isPro: boolean;
expiresAt: Date | null;
};
declare module 'fastify' {
interface FastifyRequest {
subscription?: SubscriptionInfo | null;
}
interface FastifyInstance {
withSubscription: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
requirePro: (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
}
}
async function loadSubscription(db: FastifyInstance['db'], userId: string): Promise<SubscriptionInfo | null> {
const [sub] = await db
.select()
.from(subscriptions)
.where(eq(subscriptions.userId, userId))
.limit(1);
if (!sub) return null;
const now = new Date();
const isExpired = sub.expiresAt && sub.expiresAt < now;
const isPro =
sub.plan === 'pro' &&
(sub.status === 'active' || sub.status === 'trialing') &&
!isExpired;
return {
plan: sub.plan as 'free' | 'pro',
status: sub.status as SubscriptionInfo['status'],
isPro,
expiresAt: sub.expiresAt,
};
}
export async function requirePro(req: FastifyRequest, _reply: FastifyReply): Promise<void> {
const sub = req.subscription;
if (!sub?.isPro) {
throw forbidden('Pro subscription required');
}
}
const subscriptionPlugin = async (app: FastifyInstance) => {
app.decorateRequest('subscription', undefined);
app.decorate('withSubscription', async (req: FastifyRequest, _reply: FastifyReply) => {
if (!req.user?.id) return;
const sub = await loadSubscription(app.db, req.user.id);
req.subscription = sub;
});
app.decorate('requirePro', requirePro);
};
export default fp(subscriptionPlugin, {
name: 'subscription',
dependencies: ['database', 'auth'],
});

View File

@@ -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);
},
);
}

View File

@@ -1,213 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { AuthService } from '../services/auth/auth.service.js';
import { checkBlocked, clearOnSuccess, recordFailedAttempt } from '../utils/loginLockout.js';
import { env } from '../config/env.js';
const COOKIE_PATH = '/api/v1/auth';
const REFRESH_MAX_AGE = 604800; // 7 days
function getRefreshCookieOptions() {
return {
httpOnly: true,
secure: env.NODE_ENV === 'production',
sameSite: 'strict' as const,
path: COOKIE_PATH,
maxAge: REFRESH_MAX_AGE,
signed: false,
};
}
const registerSchema = {
body: {
type: 'object',
required: ['email', 'password', 'nickname'],
properties: {
email: { type: 'string', minLength: 1 },
password: { type: 'string', minLength: 8 },
nickname: { type: 'string', minLength: 2, maxLength: 30 },
},
},
};
const loginSchema = {
body: {
type: 'object',
required: ['email', 'password'],
properties: {
email: { type: 'string', minLength: 1 },
password: { type: 'string' },
},
},
};
/** Refresh: empty body, token from cookie */
const refreshSchema = { body: { type: 'object', properties: {} } };
/** Logout: Bearer + cookie, empty body */
const logoutSchema = { body: { type: 'object', properties: {} } };
const verifyEmailSchema = {
body: {
type: 'object',
required: ['userId', 'code'],
properties: {
userId: { type: 'string', minLength: 1 },
code: { type: 'string', minLength: 1, maxLength: 10 },
},
},
};
const forgotPasswordSchema = {
body: {
type: 'object',
required: ['email'],
properties: {
email: { type: 'string', minLength: 1 },
},
},
};
const resetPasswordSchema = {
body: {
type: 'object',
required: ['token', 'newPassword'],
properties: {
token: { type: 'string' },
newPassword: { type: 'string', minLength: 8 },
},
},
};
export async function authRoutes(app: FastifyInstance) {
const authService = new AuthService(app.db);
const { rateLimitOptions } = app;
app.post(
'/register',
{ schema: registerSchema, config: { rateLimit: rateLimitOptions.register } },
async (req, reply) => {
const body = req.body as { email: string; password: string; nickname: string };
const { userId, verificationCode } = await authService.register(body);
return reply.status(201).send({
userId,
message: 'Registration successful. Please verify your email.',
verificationCode,
});
},
);
app.post(
'/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) => {
const body = req.body as { email: string; password: string };
const userAgent = req.headers['user-agent'];
const ip = req.ip ?? 'unknown';
try {
const result = await authService.login({
email: body.email,
password: body.password,
userAgent,
ipAddress: ip,
});
await clearOnSuccess(app.redis, ip);
reply.setCookie('refreshToken', result.refreshToken, getRefreshCookieOptions());
return reply.send(result);
} catch (err) {
await recordFailedAttempt(app.redis, ip);
throw err;
}
},
);
app.post(
'/logout',
{
schema: logoutSchema,
config: { rateLimit: rateLimitOptions.apiGuest },
preHandler: [app.authenticate],
},
async (req, reply) => {
const refreshToken = req.cookies?.refreshToken;
await authService.logout(refreshToken);
reply.clearCookie('refreshToken', {
path: COOKIE_PATH,
httpOnly: true,
secure: env.NODE_ENV === 'production',
sameSite: 'strict',
});
return reply.status(200).send({ message: 'Logged out successfully' });
},
);
app.post(
'/refresh',
{ schema: refreshSchema, config: { rateLimit: rateLimitOptions.apiGuest } },
async (req, reply) => {
const refreshToken = req.cookies?.refreshToken;
const userAgent = req.headers['user-agent'];
const ipAddress = req.ip;
const result = await authService.refresh({
refreshToken,
userAgent,
ipAddress,
});
reply.setCookie('refreshToken', result.refreshToken, getRefreshCookieOptions());
return reply.send({ accessToken: result.accessToken });
},
);
app.post(
'/verify-email',
{ schema: verifyEmailSchema, config: { rateLimit: rateLimitOptions.verifyEmail } },
async (req, reply) => {
const body = req.body as { userId: string; code: string };
await authService.verifyEmail(body.userId, body.code);
return reply.send({ message: 'Email verified successfully' });
},
);
app.post(
'/forgot-password',
{ schema: forgotPasswordSchema, config: { rateLimit: rateLimitOptions.forgotPassword } },
async (req, reply) => {
const body = req.body as { email: string };
await authService.forgotPassword(body.email);
return reply.send({
message: 'If the email exists, a reset link has been sent.',
});
},
);
app.post(
'/reset-password',
{ schema: resetPasswordSchema, config: { rateLimit: rateLimitOptions.forgotPassword } },
async (req, reply) => {
const body = req.body as { token: string; newPassword: string };
await authService.resetPassword(body.token, body.newPassword);
return reply.send({ message: 'Password reset successfully' });
},
);
}

View File

@@ -1,74 +0,0 @@
import type { FastifyInstance } from 'fastify';
import { UserService } from '../services/user/user.service.js';
const patchProfileSchema = {
body: {
type: 'object',
properties: {
nickname: { type: 'string', minLength: 2, maxLength: 30 },
avatarUrl: { type: ['string', 'null'], maxLength: 500 },
country: { type: ['string', 'null'], maxLength: 100 },
city: { type: ['string', 'null'], maxLength: 100 },
selfLevel: { type: ['string', 'null'], enum: ['jun', 'mid', 'sen'] },
isPublic: { type: 'boolean' },
},
additionalProperties: false,
},
};
const usernameParamsSchema = {
params: {
type: 'object',
required: ['username'],
properties: {
username: { type: 'string', minLength: 2, maxLength: 30 },
},
},
};
export async function profileRoutes(app: FastifyInstance) {
const userService = new UserService(app.db);
const { rateLimitOptions } = app;
app.get(
'/',
{
config: { rateLimit: rateLimitOptions.apiAuthed },
preHandler: [app.authenticate, app.withSubscription],
},
async (req, reply) => {
const userId = req.user!.id;
const plan = req.subscription?.plan ?? 'free';
const profile = await userService.getPrivateProfile(userId, plan);
return reply.send(profile);
},
);
app.patch(
'/',
{
schema: patchProfileSchema,
config: { rateLimit: rateLimitOptions.apiAuthed },
preHandler: [app.authenticate],
},
async (req, reply) => {
const userId = req.user!.id;
const body = req.body as Parameters<UserService['updateProfile']>[1];
const profile = await userService.updateProfile(userId, body);
return reply.send(profile);
},
);
app.get(
'/:username',
{
schema: usernameParamsSchema,
config: { rateLimit: rateLimitOptions.apiGuest },
},
async (req, reply) => {
const { username } = req.params as { username: string };
const profile = await userService.getPublicProfile(username);
return reply.send(profile);
},
);
}

View File

@@ -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);
}
);
}

View File

@@ -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,
};
}
}

View File

@@ -1,326 +0,0 @@
import { eq, and, gt } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type * as schema from '../../db/schema/index.js';
import { users, sessions, emailVerificationCodes, passwordResetTokens } from '../../db/schema/index.js';
import { hashPassword, verifyPassword } from '../../utils/password.js';
import {
signAccessToken,
signRefreshToken,
verifyToken,
isRefreshPayload,
hashToken,
} from '../../utils/jwt.js';
import {
AppError,
conflict,
unauthorized,
notFound,
ERROR_CODES,
} from '../../utils/errors.js';
import { randomBytes, randomUUID } from 'node:crypto';
type Db = NodePgDatabase<typeof schema>;
export interface RegisterInput {
email: string;
password: string;
nickname: string;
}
export interface LoginInput {
email: string;
password: string;
userAgent?: string;
ipAddress?: string;
}
export interface LoginUser {
id: string;
email: string;
nickname: string;
avatarUrl: string | null;
role: string;
emailVerified: boolean;
}
export interface LoginResult {
user: LoginUser;
accessToken: string;
refreshToken: string;
expiresIn: number;
}
export interface RefreshInput {
refreshToken: string | undefined;
userAgent?: string;
ipAddress?: string;
}
export interface ForgotPasswordResult {
token: string;
expiresAt: Date;
}
const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const VERIFICATION_CODE_LENGTH = 6;
const VERIFICATION_CODE_TTL_MS = 15 * 60 * 1000;
const RESET_TOKEN_TTL_MS = 60 * 60 * 1000;
export class AuthService {
constructor(private readonly db: Db) {}
async register(input: RegisterInput): Promise<{ userId: string; verificationCode: string }> {
const [existing] = await this.db
.select()
.from(users)
.where(eq(users.email, input.email.toLowerCase().trim()))
.limit(1);
if (existing) {
throw conflict(ERROR_CODES.EMAIL_TAKEN, 'Email already registered');
}
const [nicknameConflict] = await this.db
.select()
.from(users)
.where(eq(users.nickname, input.nickname.trim()))
.limit(1);
if (nicknameConflict) {
throw conflict(ERROR_CODES.NICKNAME_TAKEN, 'Nickname already taken');
}
const passwordHash = await hashPassword(input.password);
const [user] = await this.db
.insert(users)
.values({
email: input.email.toLowerCase().trim(),
passwordHash,
nickname: input.nickname.trim(),
})
.returning({ id: users.id });
if (!user) {
throw new AppError(ERROR_CODES.INTERNAL_ERROR, 'Failed to create user', 500);
}
const code = randomBytes(VERIFICATION_CODE_LENGTH)
.toString('hex')
.slice(0, VERIFICATION_CODE_LENGTH)
.toUpperCase();
const expiresAt = new Date(Date.now() + VERIFICATION_CODE_TTL_MS);
await this.db.insert(emailVerificationCodes).values({
userId: user.id,
code,
expiresAt,
});
return { userId: user.id, verificationCode: code };
}
async login(input: LoginInput): Promise<LoginResult> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.email, input.email.toLowerCase().trim()))
.limit(1);
if (!user || !(await verifyPassword(user.passwordHash, input.password))) {
throw unauthorized('Invalid email or password');
}
const [accessToken, refreshToken] = await Promise.all([
signAccessToken({ sub: user.id, email: user.email }),
signRefreshToken({ sub: user.id, sid: randomUUID() }),
]);
const refreshHash = hashToken(refreshToken);
const expiresAt = new Date(Date.now() + REFRESH_TTL_MS);
await this.db.insert(sessions).values({
userId: user.id,
refreshTokenHash: refreshHash,
userAgent: input.userAgent ?? null,
ipAddress: input.ipAddress ?? null,
expiresAt,
});
return {
user: {
id: user.id,
email: user.email,
nickname: user.nickname,
avatarUrl: user.avatarUrl ?? null,
role: user.role,
emailVerified: !!user.emailVerifiedAt,
},
accessToken,
refreshToken,
expiresIn: Math.floor(REFRESH_TTL_MS / 1000),
};
}
async refresh(input: RefreshInput): Promise<{ accessToken: string; refreshToken: string; expiresIn: number }> {
if (!input.refreshToken) {
throw new AppError(ERROR_CODES.INVALID_REFRESH_TOKEN, 'Refresh token required (cookie)', 401);
}
const payload = await verifyToken(input.refreshToken);
if (!isRefreshPayload(payload)) {
throw unauthorized('Invalid refresh token');
}
const hash = hashToken(input.refreshToken);
const [session] = await this.db
.select()
.from(sessions)
.where(and(eq(sessions.refreshTokenHash, hash), gt(sessions.expiresAt, new Date())))
.limit(1);
if (!session) {
throw new AppError(ERROR_CODES.INVALID_REFRESH_TOKEN, 'Invalid or expired refresh token', 401);
}
await this.db.delete(sessions).where(eq(sessions.id, session.id));
const [user] = await this.db.select().from(users).where(eq(users.id, session.userId)).limit(1);
if (!user) {
throw notFound('User not found');
}
const [accessToken, newRefreshToken] = await Promise.all([
signAccessToken({ sub: user.id, email: user.email }),
signRefreshToken({ sub: user.id, sid: randomUUID() }),
]);
const newHash = hashToken(newRefreshToken);
const expiresAt = new Date(Date.now() + REFRESH_TTL_MS);
await this.db.insert(sessions).values({
userId: user.id,
refreshTokenHash: newHash,
userAgent: input.userAgent ?? session.userAgent,
ipAddress: input.ipAddress ?? session.ipAddress,
expiresAt,
});
return {
accessToken,
refreshToken: newRefreshToken,
expiresIn: Math.floor(REFRESH_TTL_MS / 1000),
};
}
async logout(refreshToken: string | undefined): Promise<void> {
if (!refreshToken) return;
const hash = hashToken(refreshToken);
await this.db.delete(sessions).where(eq(sessions.refreshTokenHash, hash));
}
async verifyEmail(userId: string, verificationCode: string): Promise<void> {
const codeUpper = verificationCode.toUpperCase();
const [record] = await this.db
.select()
.from(emailVerificationCodes)
.where(
and(
eq(emailVerificationCodes.userId, userId),
eq(emailVerificationCodes.code, codeUpper),
),
)
.limit(1);
if (!record) {
throw new AppError(ERROR_CODES.INVALID_CODE, 'Invalid or expired verification code', 400);
}
if (record.expiresAt < new Date()) {
await this.db
.delete(emailVerificationCodes)
.where(eq(emailVerificationCodes.id, record.id));
throw new AppError(ERROR_CODES.INVALID_CODE, 'Verification code expired', 400);
}
const [user] = await this.db.select().from(users).where(eq(users.id, userId)).limit(1);
if (!user) {
throw notFound('User not found');
}
if (user.emailVerifiedAt) {
throw new AppError(ERROR_CODES.ALREADY_VERIFIED, 'Email already verified', 400);
}
await this.db
.update(users)
.set({ emailVerifiedAt: new Date(), updatedAt: new Date() })
.where(eq(users.id, userId));
await this.db
.delete(emailVerificationCodes)
.where(eq(emailVerificationCodes.userId, userId));
}
async forgotPassword(email: string): Promise<ForgotPasswordResult> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.email, email.toLowerCase().trim()))
.limit(1);
if (!user) {
return {
token: '',
expiresAt: new Date(Date.now() + RESET_TOKEN_TTL_MS),
};
}
const token = randomBytes(32).toString('hex');
const tokenHash = hashToken(token);
const expiresAt = new Date(Date.now() + RESET_TOKEN_TTL_MS);
await this.db.insert(passwordResetTokens).values({
userId: user.id,
tokenHash,
expiresAt,
});
return { token, expiresAt };
}
async resetPassword(token: string, newPassword: string): Promise<void> {
const tokenHash = hashToken(token);
const [record] = await this.db
.select()
.from(passwordResetTokens)
.where(eq(passwordResetTokens.tokenHash, tokenHash))
.limit(1);
if (!record) {
throw new AppError(ERROR_CODES.INVALID_RESET_TOKEN, 'Invalid or expired reset token', 400);
}
if (record.expiresAt < new Date()) {
await this.db
.delete(passwordResetTokens)
.where(eq(passwordResetTokens.id, record.id));
throw new AppError(ERROR_CODES.INVALID_RESET_TOKEN, 'Reset token expired', 400);
}
const passwordHash = await hashPassword(newPassword);
await this.db
.update(users)
.set({ passwordHash, updatedAt: new Date() })
.where(eq(users.id, record.userId));
await this.db
.delete(passwordResetTokens)
.where(eq(passwordResetTokens.id, record.id));
}
}

View File

@@ -1,245 +0,0 @@
import { z } from 'zod';
import { createHash } from 'node:crypto';
import { env } from '../../config/env.js';
import type { Stack, Level, QuestionType } from '../../db/schema/enums.js';
export interface LlmConfig {
baseUrl: string;
model: string;
fallbackModel?: string;
apiKey?: string;
timeoutMs: number;
temperature: number;
maxTokens: number;
maxRetries: number;
retryDelayMs: number;
}
export interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface ChatCompletionResponse {
choices: Array<{
message?: { content: string };
text?: string;
}>;
}
const QUESTION_TYPES: QuestionType[] = ['single_choice', 'multiple_select', 'true_false', 'short_text'];
const optionSchema = z.object({
key: z.string().min(1),
text: z.string().min(1),
});
const generatedQuestionSchema = z.object({
questionText: z.string().min(1),
type: z.enum(QUESTION_TYPES as [string, ...string[]]),
options: z.array(optionSchema).optional(),
correctAnswer: z.union([z.string(), z.array(z.string())]),
explanation: z.string().min(1),
});
const generateQuestionsResponseSchema = z.object({
questions: z.array(generatedQuestionSchema),
});
export type GeneratedQuestion = z.infer<typeof generatedQuestionSchema> & {
stack: Stack;
level: Level;
};
export interface GenerateQuestionsInput {
stack: Stack;
level: Level;
count: number;
types?: QuestionType[];
}
/** Metadata for persisting to question_cache_meta (used by QuestionService) */
export interface LlmGenerationMeta {
llmModel: string;
promptHash: string;
generationTimeMs: number;
rawResponse: unknown;
valid: boolean;
retryCount: number;
questionsGenerated: number;
}
export interface GenerateQuestionsResult {
questions: GeneratedQuestion[];
meta: LlmGenerationMeta;
}
export class LlmService {
private readonly config: LlmConfig;
constructor(config?: Partial<LlmConfig>) {
this.config = {
baseUrl: config?.baseUrl ?? env.LLM_BASE_URL,
model: config?.model ?? env.LLM_MODEL,
fallbackModel: config?.fallbackModel ?? env.LLM_FALLBACK_MODEL,
apiKey: config?.apiKey ?? env.LLM_API_KEY,
timeoutMs: config?.timeoutMs ?? env.LLM_TIMEOUT_MS,
temperature: config?.temperature ?? env.LLM_TEMPERATURE,
maxTokens: config?.maxTokens ?? env.LLM_MAX_TOKENS,
maxRetries: config?.maxRetries ?? env.LLM_MAX_RETRIES,
retryDelayMs: config?.retryDelayMs ?? env.LLM_RETRY_DELAY_MS,
};
}
async chat(messages: ChatMessage[]): Promise<string> {
const { content } = await this.chatWithMeta(messages);
return content;
}
/** Returns content, model, and retry count (for logging to question_cache_meta) */
async chatWithMeta(
messages: ChatMessage[]
): Promise<{ content: string; model: string; retryCount: number }> {
let lastError: Error | null = null;
const modelsToTry = [this.config.model];
if (this.config.fallbackModel) {
modelsToTry.push(this.config.fallbackModel);
}
for (const model of modelsToTry) {
for (let attempt = 0; attempt <= this.config.maxRetries; attempt++) {
try {
const content = await this.executeChat(messages, model);
return { content, model, retryCount: attempt };
} catch (err) {
lastError = err instanceof Error ? err : new Error('LLM request failed');
if (attempt < this.config.maxRetries) {
const delayMs = this.config.retryDelayMs * Math.pow(2, attempt);
await sleep(delayMs);
}
}
}
}
throw lastError ?? new Error('LLM request failed');
}
private async executeChat(messages: ChatMessage[], model: string): Promise<string> {
const url = `${this.config.baseUrl.replace(/\/$/, '')}/chat/completions`;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
};
if (this.config.apiKey) {
headers['Authorization'] = `Bearer ${this.config.apiKey}`;
}
const body = {
model,
messages: messages.map((m) => ({ role: m.role, content: m.content })),
temperature: this.config.temperature,
max_tokens: this.config.maxTokens,
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.config.timeoutMs);
try {
const res = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(body),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!res.ok) {
const text = await res.text();
throw new Error(`LLM request failed: ${res.status} ${res.statusText} - ${text}`);
}
const data = (await res.json()) as ChatCompletionResponse;
const choice = data.choices?.[0];
const content = choice?.message?.content ?? choice?.text ?? '';
return content.trim();
} catch (err) {
clearTimeout(timeoutId);
if (err instanceof Error) {
throw err;
}
throw new Error('LLM request failed');
}
}
async generateQuestions(input: GenerateQuestionsInput): Promise<GenerateQuestionsResult> {
const { stack, level, count, types = QUESTION_TYPES } = input;
const typeList = types.join(', ');
const systemPrompt = `You are a technical interview question generator. Generate exactly ${count} programming/tech questions.
Return ONLY valid JSON in this exact format (no markdown, no code blocks):
{"questions":[{"questionText":"...","type":"single_choice|multiple_select|true_false|short_text","options":[{"key":"a","text":"..."}],"correctAnswer":"a" or ["a","b"],"explanation":"..."}]}
Rules: type must be one of: ${typeList}. For single_choice/multiple_select: options array required with key (a,b,c,d). For true_false: options [{"key":"true","text":"True"},{"key":"false","text":"False"}]. For short_text: options omitted, correctAnswer is string.`;
const userPrompt = `Generate ${count} questions for stack="${stack}", level="${level}". Use types: ${typeList}.`;
const promptForHash = systemPrompt + '\n---\n' + userPrompt;
const promptHash = createHash('sha256').update(promptForHash).digest('hex');
const start = Date.now();
const { content: raw, model, retryCount } = await this.chatWithMeta([
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userPrompt },
]);
const generationTimeMs = Date.now() - start;
const jsonStr = extractJson(raw);
const parsed = JSON.parse(jsonStr) as unknown;
const result = generateQuestionsResponseSchema.safeParse(parsed);
if (!result.success) {
throw new Error(`LLM response validation failed: ${result.error.message}`);
}
const questions: GeneratedQuestion[] = result.data.questions.map((q) => ({
...q,
stack,
level,
}));
for (const q of questions) {
if ((q.type === 'single_choice' || q.type === 'multiple_select') && (!q.options || q.options.length === 0)) {
throw new Error(`Question validation failed: ${q.type} requires options`);
}
if (q.type === 'true_false' && (!q.options || q.options.length < 2)) {
throw new Error(`Question validation failed: true_false requires true/false options`);
}
}
return {
questions,
meta: {
llmModel: model,
promptHash,
generationTimeMs,
rawResponse: parsed,
valid: retryCount === 0,
retryCount,
questionsGenerated: questions.length,
},
};
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function extractJson(text: string): string {
const trimmed = text.trim();
const match = trimmed.match(/\{[\s\S]*\}/);
return match ? match[0]! : trimmed;
}

View File

@@ -1,200 +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,
valid: meta.valid,
retryCount: meta.retryCount,
questionsGenerated: meta.questionsGenerated,
});
inserted.push({
questionBankId: row.id,
type: row.type,
questionText: row.questionText,
options: row.options,
correctAnswer: row.correctAnswer,
explanation: row.explanation,
});
}
}
return inserted;
}
}

View File

@@ -1,408 +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;
totalQuestions: number;
percentage: 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 = correctCount; // score = count of correct answers, not percentage
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 {
const totalQuestions = questionsRows.length;
const percentage =
test.score !== null && totalQuestions > 0
? (test.score / totalQuestions) * 100
: null;
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,
totalQuestions,
percentage,
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,
})),
};
}
}

View File

@@ -1,198 +0,0 @@
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import type * as schema from '../../db/schema/index.js';
import { users, userStats, subscriptions } from '../../db/schema/index.js';
import { notFound, conflict, ERROR_CODES } from '../../utils/errors.js';
import type { User } from '../../db/schema/users.js';
import type { SelfLevel } from '../../db/schema/index.js';
type Db = NodePgDatabase<typeof schema>;
export type UserStatItem = {
stack: string;
level: string;
totalQuestions: number;
correctAnswers: number;
testsTaken: number;
lastTestAt: string | null;
};
export type ProfileStats = {
byStack: UserStatItem[];
totalTestsTaken: number;
totalQuestions: number;
correctAnswers: number;
accuracy: number | null;
};
export type ProfileUpdateInput = {
nickname?: string;
avatarUrl?: string | null;
country?: string | null;
city?: string | null;
selfLevel?: SelfLevel | null;
isPublic?: boolean;
};
export type PublicProfile = {
id: string;
nickname: string;
avatarUrl: string | null;
country: string | null;
city: string | null;
selfLevel: string | null;
isPublic: boolean;
stats: ProfileStats;
};
export type PrivateProfile = PublicProfile & {
email: string;
emailVerifiedAt: string | null;
createdAt: string;
updatedAt: string;
role: string;
plan: 'free' | 'pro';
};
async function getStatsForUser(db: Db, userId: string): Promise<ProfileStats> {
const rows = await db
.select()
.from(userStats)
.where(eq(userStats.userId, userId));
const byStack: UserStatItem[] = rows.map((r) => ({
stack: r.stack,
level: r.level,
totalQuestions: r.totalQuestions,
correctAnswers: r.correctAnswers,
testsTaken: r.testsTaken,
lastTestAt: r.lastTestAt?.toISOString() ?? null,
}));
const totalTestsTaken = rows.reduce((sum, r) => sum + r.testsTaken, 0);
const totalQuestions = rows.reduce((sum, r) => sum + r.totalQuestions, 0);
const correctAnswers = rows.reduce((sum, r) => sum + r.correctAnswers, 0);
const accuracy = totalQuestions > 0 ? correctAnswers / totalQuestions : null;
return { byStack, totalTestsTaken, totalQuestions, correctAnswers, accuracy };
}
function toPublicProfile(user: User, stats: ProfileStats): PublicProfile {
return {
id: user.id,
nickname: user.nickname,
avatarUrl: user.avatarUrl,
country: user.country,
city: user.city,
selfLevel: user.selfLevel,
isPublic: user.isPublic,
stats,
};
}
function toPrivateProfile(
user: User,
stats: ProfileStats,
plan: 'free' | 'pro' = 'free'
): PrivateProfile {
return {
...toPublicProfile(user, stats),
email: user.email,
emailVerifiedAt: user.emailVerifiedAt?.toISOString() ?? null,
createdAt: user.createdAt.toISOString(),
updatedAt: user.updatedAt.toISOString(),
role: user.role,
plan,
};
}
export class UserService {
constructor(private readonly db: Db) {}
async getById(userId: string): Promise<User | null> {
const [user] = await this.db.select().from(users).where(eq(users.id, userId)).limit(1);
return user ?? null;
}
async getByNickname(nickname: string): Promise<User | null> {
const [user] = await this.db
.select()
.from(users)
.where(eq(users.nickname, nickname.trim()))
.limit(1);
return user ?? null;
}
async getPrivateProfile(
userId: string,
plan: 'free' | 'pro' = 'free'
): Promise<PrivateProfile> {
const [user, stats] = await Promise.all([this.getById(userId), getStatsForUser(this.db, userId)]);
if (!user) {
throw notFound('User not found');
}
return toPrivateProfile(user, stats, plan);
}
async getPublicProfile(username: string): Promise<PublicProfile> {
const user = await this.getByNickname(username);
if (!user) {
throw notFound('User not found');
}
if (!user.isPublic) {
throw notFound('User not found');
}
const stats = await getStatsForUser(this.db, user.id);
return toPublicProfile(user, stats);
}
async updateProfile(userId: string, input: ProfileUpdateInput): Promise<PrivateProfile> {
const updateData: Partial<typeof users.$inferInsert> = {
updatedAt: new Date(),
};
if (input.nickname !== undefined) {
const trimmed = input.nickname.trim();
const [existing] = await this.db
.select({ id: users.id })
.from(users)
.where(eq(users.nickname, trimmed))
.limit(1);
if (existing && existing.id !== userId) {
throw conflict(ERROR_CODES.NICKNAME_TAKEN, 'Nickname already taken');
}
updateData.nickname = trimmed;
}
if (input.avatarUrl !== undefined) updateData.avatarUrl = input.avatarUrl;
if (input.country !== undefined) updateData.country = input.country;
if (input.city !== undefined) updateData.city = input.city;
if (input.selfLevel !== undefined) updateData.selfLevel = input.selfLevel;
if (input.isPublic !== undefined) updateData.isPublic = input.isPublic;
const [updated] = await this.db
.update(users)
.set(updateData)
.where(eq(users.id, userId))
.returning();
if (!updated) {
throw notFound('User not found');
}
const stats = await getStatsForUser(this.db, userId);
const plan = await this.getPlanForUser(userId);
return toPrivateProfile(updated, stats, plan);
}
async getPlanForUser(userId: string): Promise<'free' | 'pro'> {
const [sub] = await this.db
.select()
.from(subscriptions)
.where(eq(subscriptions.userId, userId))
.limit(1);
if (!sub || (sub.expiresAt && sub.expiresAt < new Date())) return 'free';
if (sub.plan === 'pro' && (sub.status === 'active' || sub.status === 'trialing')) return 'pro';
return 'free';
}
}

View File

@@ -1,52 +0,0 @@
import { createHash } from 'node:crypto';
import * as jose from 'jose';
import { env } from '../config/env.js';
export function hashToken(token: string): string {
return createHash('sha256').update(token).digest('hex');
}
export interface AccessPayload {
sub: string;
email: string;
type: 'access';
}
export interface RefreshPayload {
sub: string;
sid: string;
type: 'refresh';
}
type JwtPayload = AccessPayload | RefreshPayload;
const secret = new TextEncoder().encode(env.JWT_SECRET);
export async function signAccessToken(payload: Omit<AccessPayload, 'type'>): Promise<string> {
return new jose.SignJWT({ ...payload, type: 'access' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(env.JWT_ACCESS_TTL)
.sign(secret);
}
export async function signRefreshToken(payload: Omit<RefreshPayload, 'type'>): Promise<string> {
return new jose.SignJWT({ ...payload, type: 'refresh' })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(env.JWT_REFRESH_TTL)
.sign(secret);
}
export async function verifyToken(token: string): Promise<JwtPayload> {
const { payload } = await jose.jwtVerify(token, secret);
return payload as unknown as JwtPayload;
}
export function isAccessPayload(p: JwtPayload): p is AccessPayload {
return p.type === 'access';
}
export function isRefreshPayload(p: JwtPayload): p is RefreshPayload {
return p.type === 'refresh';
}

View File

@@ -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);
}

View File

@@ -1,15 +0,0 @@
import * as argon2 from 'argon2';
const HASH_OPTIONS: argon2.Options = {
type: argon2.argon2id,
memoryCost: 19456,
timeCost: 2,
};
export async function hashPassword(plain: string): Promise<string> {
return argon2.hash(plain, HASH_OPTIONS);
}
export async function verifyPassword(hash: string, plain: string): Promise<boolean> {
return argon2.verify(hash, plain);
}

View File

@@ -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;
}

View File

@@ -1,76 +0,0 @@
import Fastify, { FastifyInstance } from 'fastify';
import cookie from '@fastify/cookie';
import fp from 'fastify-plugin';
import { AppError } from '../../src/utils/errors.js';
import authPlugin from '../../src/plugins/auth.js';
import { authRoutes } from '../../src/routes/auth.js';
import type { MockDb } from '../test-utils.js';
import { createMockDb } from '../test-utils.js';
const mockDatabasePlugin = (db: MockDb) =>
fp(async (app) => {
app.decorate('db', db);
}, { name: 'database' });
/** 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('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(mockDatabasePlugin(db));
await app.register(cookie, { secret: 'test-secret-at-least-32-characters-long' });
await app.register(authPlugin);
await app.register(authRoutes, { prefix: '/api/v1/auth' });
return app;
}

View File

@@ -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?');
});
});
});

View File

@@ -1,291 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
vi.mock('../../src/config/env.js', () => ({
env: {
NODE_ENV: 'test',
JWT_SECRET: 'test-secret',
},
}));
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(),
isAccessPayload: vi.fn((p: { type?: string }) => p?.type === 'access'),
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: '/api/v1/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: '/api/v1/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: '/api/v1/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 user and tokens when credentials are valid', async () => {
const mockUser = {
id: 'user-1',
email: 'test@example.com',
nickname: 'tester',
avatarUrl: null,
role: 'free',
emailVerifiedAt: null,
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: '/api/v1/auth/login',
payload: { email: 'test@example.com', password: 'password123' },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.user).toBeDefined();
expect(body.user.id).toBe('user-1');
expect(body.user.email).toBe('test@example.com');
expect(body.user.nickname).toBeDefined();
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: '/api/v1/auth/login',
payload: { email: 'unknown@example.com', password: 'wrong' },
});
expect(res.statusCode).toBe(401);
});
});
describe('POST /auth/logout', () => {
it('returns 200 with message on success (Bearer + cookie)', async () => {
vi.mocked(verifyToken).mockResolvedValueOnce({
sub: 'user-1',
email: 'test@example.com',
type: 'access',
} as never);
(mockDb.delete as ReturnType<typeof vi.fn>).mockReturnValueOnce(
deleteChain()
);
const res = await app.inject({
method: 'POST',
url: '/api/v1/auth/logout',
headers: { authorization: 'Bearer valid-access-token' },
payload: {},
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.message).toBe('Logged out successfully');
});
});
describe('POST /auth/refresh', () => {
it('returns accessToken when refresh token from cookie 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: '/api/v1/auth/refresh',
payload: {},
headers: { cookie: 'refreshToken=valid-refresh-token' },
});
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.accessToken).toBe('access-token');
expect(body.refreshToken).toBeUndefined();
});
});
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: '/api/v1/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: '/api/v1/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: '/api/v1/auth/reset-password',
payload: { token: 'valid-token', newPassword: 'newPassword123' },
});
expect(res.statusCode).toBe(200);
});
});
});

View File

@@ -1,311 +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 user and tokens when credentials are valid', async () => {
const mockUser = {
id: 'user-1',
email: 'test@example.com',
nickname: 'tester',
avatarUrl: null,
role: 'free',
emailVerifiedAt: null,
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.user).toBeDefined();
expect(result.user.id).toBe('user-1');
expect(result.user.email).toBe('test@example.com');
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();
});
});
});

View File

@@ -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');
});
});
});

View File

@@ -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' });
});
});
});

View File

@@ -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: 1, 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);
});
});
});

View File

@@ -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';
}
});

View File

@@ -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();
});
});

View File

@@ -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 };
}

View File

@@ -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'),
},
},
});