feat: add Drizzle enums for schema
Made-with: Cursor
This commit is contained in:
45
.env.example
Normal file
45
.env.example
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
# Server
|
||||||
|
PORT=3000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
NODE_ENV=development
|
||||||
|
|
||||||
|
# Database
|
||||||
|
DATABASE_URL=postgresql://samreshu:samreshu_dev@localhost:5432/samreshu
|
||||||
|
|
||||||
|
# Redis
|
||||||
|
REDIS_URL=redis://localhost:6379
|
||||||
|
|
||||||
|
# Auth
|
||||||
|
JWT_SECRET=dev-secret-change-in-production-min-32-chars
|
||||||
|
JWT_ACCESS_TTL=15m
|
||||||
|
JWT_REFRESH_TTL=7d
|
||||||
|
|
||||||
|
# LLM
|
||||||
|
LLM_BASE_URL=http://localhost:11434/v1
|
||||||
|
LLM_MODEL=qwen2.5:14b
|
||||||
|
LLM_API_KEY=
|
||||||
|
LLM_TIMEOUT_MS=15000
|
||||||
|
LLM_MAX_RETRIES=1
|
||||||
|
LLM_TEMPERATURE=0.7
|
||||||
|
LLM_MAX_TOKENS=2048
|
||||||
|
|
||||||
|
# Rate limits
|
||||||
|
RATE_LIMIT_LOGIN=5
|
||||||
|
RATE_LIMIT_REGISTER=3
|
||||||
|
RATE_LIMIT_FORGOT_PASSWORD=3
|
||||||
|
RATE_LIMIT_VERIFY_EMAIL=5
|
||||||
|
RATE_LIMIT_API_AUTHED=100
|
||||||
|
RATE_LIMIT_API_GUEST=30
|
||||||
|
|
||||||
|
# CORS (comma-separated origins)
|
||||||
|
CORS_ORIGINS=http://localhost:5173,http://localhost:3000
|
||||||
|
|
||||||
|
# Email (dev — mailpit / mailtrap)
|
||||||
|
SMTP_HOST=localhost
|
||||||
|
SMTP_PORT=1025
|
||||||
|
SMTP_USER=
|
||||||
|
SMTP_PASS=
|
||||||
|
EMAIL_FROM=noreply@samreshu.dev
|
||||||
|
|
||||||
|
# Sentry (optional for dev)
|
||||||
|
SENTRY_DSN=
|
||||||
307
AGENT_TASKS.md
Normal file
307
AGENT_TASKS.md
Normal file
@@ -0,0 +1,307 @@
|
|||||||
|
# Распределение задач по агентам (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 A1–A9 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 B1–B7. 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 C1–C7, 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 D1–D5, 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 E1–E5, commit after each.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Agent F (LLM):**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Agent F tasks from AGENT_TASKS.md. Work in branch feat/llm-service.
|
||||||
|
Do F1–F5, 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 G1–G4, commit after each.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Agent H (Testing):**
|
||||||
|
|
||||||
|
```text
|
||||||
|
Implement Agent H tasks from AGENT_TASKS.md. Work in branch feat/testing.
|
||||||
|
Do H1–H7, commit after each. Target ≥70% coverage on services.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Текущее состояние репозитория
|
||||||
|
|
||||||
|
Часть работы уже выполнена одним агентом:
|
||||||
|
|
||||||
|
- **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`)
|
||||||
|
|
||||||
|
Агентам B–H при старте: проверить, что уже есть, и дописать недостающее. Не дублировать сделанное. Коммитить только свои изменения.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Формат коммитов
|
||||||
|
|
||||||
|
Использовать [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 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. **Параллельно волне 2–3:** Agent H (тесты по мере готовности API)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Чеклист для каждого агента
|
||||||
|
|
||||||
|
Перед каждым коммитом:
|
||||||
|
|
||||||
|
- [ ] `npm run typecheck` проходит
|
||||||
|
- [ ] Сообщение коммита по conventional commits
|
||||||
|
- [ ] Нет `console.log`, только `logger`
|
||||||
|
- [ ] Нет `any` без необходимости
|
||||||
|
|
||||||
|
После завершения всех задач агента:
|
||||||
|
|
||||||
|
- [ ] Создать PR в `dev`
|
||||||
|
- [ ] Проверить, что не сломаны существующие тесты (если есть)
|
||||||
29
docker-compose.dev.yml
Normal file
29
docker-compose.dev.yml
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: samreshu
|
||||||
|
POSTGRES_PASSWORD: samreshu_dev
|
||||||
|
POSTGRES_DB: samreshu
|
||||||
|
ports:
|
||||||
|
- "5432:5432"
|
||||||
|
volumes:
|
||||||
|
- pgdata:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U samreshu -d samreshu"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
redis:
|
||||||
|
image: redis:7-alpine
|
||||||
|
ports:
|
||||||
|
- "6379:6379"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "redis-cli", "ping"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
pgdata:
|
||||||
76
src/app.ts
Normal file
76
src/app.ts
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
import Fastify, { FastifyInstance } from 'fastify';
|
||||||
|
import { AppError } from './utils/errors.js';
|
||||||
|
import databasePlugin from './plugins/database.js';
|
||||||
|
import redisPlugin from './plugins/redis.js';
|
||||||
|
import securityPlugin from './plugins/security.js';
|
||||||
|
import rateLimitPlugin from './plugins/rateLimit.js';
|
||||||
|
import { env } from './config/env.js';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
|
||||||
|
export async function buildApp(): Promise<FastifyInstance> {
|
||||||
|
const isDev = env.NODE_ENV === 'development';
|
||||||
|
|
||||||
|
const app = Fastify({
|
||||||
|
logger: {
|
||||||
|
level: isDev ? 'debug' : 'info',
|
||||||
|
transport:
|
||||||
|
isDev
|
||||||
|
? {
|
||||||
|
target: 'pino-pretty',
|
||||||
|
options: {
|
||||||
|
translateTime: 'HH:MM:ss Z',
|
||||||
|
ignore: 'pid,hostname',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
},
|
||||||
|
requestIdHeader: 'x-request-id',
|
||||||
|
requestIdLogLabel: 'requestId',
|
||||||
|
genReqId: () => randomUUID(),
|
||||||
|
});
|
||||||
|
|
||||||
|
app.setErrorHandler((err: unknown, request, reply) => {
|
||||||
|
const error = err as Error & { statusCode?: number; validation?: unknown };
|
||||||
|
request.log.error({ err }, error.message);
|
||||||
|
|
||||||
|
if (err instanceof AppError) {
|
||||||
|
const statusCode = err.statusCode;
|
||||||
|
const payload = err.toJSON();
|
||||||
|
if (err.code === 'RATE_LIMIT_EXCEEDED' && 'retryAfter' in err) {
|
||||||
|
reply.header('Retry-After', String((err as AppError & { retryAfter?: number }).retryAfter ?? 60));
|
||||||
|
}
|
||||||
|
return reply.status(statusCode).send(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error.validation) {
|
||||||
|
return reply.status(422).send({
|
||||||
|
error: {
|
||||||
|
code: 'VALIDATION_ERROR',
|
||||||
|
message: 'Validation failed',
|
||||||
|
details: error.validation,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusCode = error.statusCode ?? 500;
|
||||||
|
return reply.status(statusCode).send({
|
||||||
|
error: {
|
||||||
|
code: 'INTERNAL_ERROR',
|
||||||
|
message: env.NODE_ENV === 'production' ? 'Internal server error' : error.message,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
app.addHook('onRequest', async (request, reply) => {
|
||||||
|
reply.header('x-request-id', request.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(redisPlugin);
|
||||||
|
await app.register(databasePlugin);
|
||||||
|
await app.register(securityPlugin);
|
||||||
|
await app.register(rateLimitPlugin);
|
||||||
|
|
||||||
|
app.get('/health', async () => ({ status: 'ok', timestamp: new Date().toISOString() }));
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
27
src/db/schema/enums.ts
Normal file
27
src/db/schema/enums.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
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];
|
||||||
1
src/db/schema/index.ts
Normal file
1
src/db/schema/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './enums.js';
|
||||||
33
src/plugins/database.ts
Normal file
33
src/plugins/database.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||||
|
import { drizzle } from 'drizzle-orm/node-postgres';
|
||||||
|
import pg from 'pg';
|
||||||
|
import fp from 'fastify-plugin';
|
||||||
|
import { env } from '../config/env.js';
|
||||||
|
import * as schema from '../db/schema/index.js';
|
||||||
|
|
||||||
|
const { Pool } = pg;
|
||||||
|
|
||||||
|
declare module 'fastify' {
|
||||||
|
interface FastifyInstance {
|
||||||
|
db: ReturnType<typeof drizzle<typeof schema>>;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const databasePlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
|
||||||
|
const pool = new Pool({
|
||||||
|
connectionString: env.DATABASE_URL,
|
||||||
|
max: 10,
|
||||||
|
idleTimeoutMillis: 30000,
|
||||||
|
connectionTimeoutMillis: 5000,
|
||||||
|
});
|
||||||
|
|
||||||
|
const db = drizzle(pool, { schema });
|
||||||
|
|
||||||
|
app.decorate('db', db);
|
||||||
|
|
||||||
|
app.addHook('onClose', async () => {
|
||||||
|
await pool.end();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export default fp(databasePlugin, { name: 'database' });
|
||||||
59
src/plugins/rateLimit.ts
Normal file
59
src/plugins/rateLimit.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||||
|
import rateLimit from '@fastify/rate-limit';
|
||||||
|
import fp from 'fastify-plugin';
|
||||||
|
import { env } from '../config/env.js';
|
||||||
|
|
||||||
|
declare module 'fastify' {
|
||||||
|
interface FastifyInstance {
|
||||||
|
rateLimitOptions: {
|
||||||
|
login: { max: number; timeWindow: string };
|
||||||
|
register: { max: number; timeWindow: string };
|
||||||
|
forgotPassword: { max: number; timeWindow: string };
|
||||||
|
verifyEmail: { max: number; timeWindow: string };
|
||||||
|
apiAuthed: { max: number; timeWindow: string };
|
||||||
|
apiGuest: { max: number; timeWindow: string };
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const rateLimitPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
|
||||||
|
const options = {
|
||||||
|
login: { max: env.RATE_LIMIT_LOGIN, timeWindow: '15 minutes' },
|
||||||
|
register: { max: env.RATE_LIMIT_REGISTER, timeWindow: '1 hour' },
|
||||||
|
forgotPassword: { max: env.RATE_LIMIT_FORGOT_PASSWORD, timeWindow: '1 hour' },
|
||||||
|
verifyEmail: { max: env.RATE_LIMIT_VERIFY_EMAIL, timeWindow: '15 minutes' },
|
||||||
|
apiAuthed: { max: env.RATE_LIMIT_API_AUTHED, timeWindow: '1 minute' },
|
||||||
|
apiGuest: { max: env.RATE_LIMIT_API_GUEST, timeWindow: '1 minute' },
|
||||||
|
};
|
||||||
|
|
||||||
|
app.decorate('rateLimitOptions', options);
|
||||||
|
|
||||||
|
await app.register(rateLimit, {
|
||||||
|
max: options.apiGuest.max,
|
||||||
|
timeWindow: options.apiGuest.timeWindow,
|
||||||
|
keyGenerator: (req) => {
|
||||||
|
return (req.ip ?? 'unknown') as string;
|
||||||
|
},
|
||||||
|
redis: app.redis,
|
||||||
|
addHeadersOnExceeding: {
|
||||||
|
'x-ratelimit-limit': true,
|
||||||
|
'x-ratelimit-remaining': true,
|
||||||
|
'x-ratelimit-reset': true,
|
||||||
|
},
|
||||||
|
addHeaders: {
|
||||||
|
'x-ratelimit-limit': true,
|
||||||
|
'x-ratelimit-remaining': true,
|
||||||
|
'x-ratelimit-reset': true,
|
||||||
|
'retry-after': true,
|
||||||
|
},
|
||||||
|
errorResponseBuilder: (_req, context) => ({
|
||||||
|
error: {
|
||||||
|
code: 'RATE_LIMIT_EXCEEDED',
|
||||||
|
message: 'Too many requests, please try again later',
|
||||||
|
retryAfter: context.ttl,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export default fp(rateLimitPlugin, { name: 'rateLimit', dependencies: ['redis'] });
|
||||||
21
src/plugins/security.ts
Normal file
21
src/plugins/security.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||||
|
import helmet from '@fastify/helmet';
|
||||||
|
import cors from '@fastify/cors';
|
||||||
|
import fp from 'fastify-plugin';
|
||||||
|
import { getCorsOrigins } from '../config/env.js';
|
||||||
|
|
||||||
|
const securityPlugin: FastifyPluginAsync = async (app: FastifyInstance) => {
|
||||||
|
await app.register(helmet, {
|
||||||
|
contentSecurityPolicy: false,
|
||||||
|
crossOriginEmbedderPolicy: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: getCorsOrigins(),
|
||||||
|
credentials: true,
|
||||||
|
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'PUT', 'OPTIONS'],
|
||||||
|
allowedHeaders: ['Content-Type', 'Authorization'],
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export default fp(securityPlugin, { name: 'security' });
|
||||||
26
src/server.ts
Normal file
26
src/server.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import 'dotenv/config';
|
||||||
|
import { buildApp } from './app.js';
|
||||||
|
import { env } from './config/env.js';
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const app = await buildApp();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await app.listen({ port: env.PORT, host: env.HOST });
|
||||||
|
app.log.info({ port: env.PORT }, 'Server started');
|
||||||
|
} catch (err) {
|
||||||
|
app.log.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const shutdown = async () => {
|
||||||
|
app.log.info('Shutting down...');
|
||||||
|
await app.close();
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
|
||||||
|
process.on('SIGINT', shutdown);
|
||||||
|
process.on('SIGTERM', shutdown);
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
88
src/utils/errors.ts
Normal file
88
src/utils/errors.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
export const ERROR_CODES = {
|
||||||
|
BAD_REQUEST: 'BAD_REQUEST',
|
||||||
|
UNAUTHORIZED: 'UNAUTHORIZED',
|
||||||
|
FORBIDDEN: 'FORBIDDEN',
|
||||||
|
NOT_FOUND: 'NOT_FOUND',
|
||||||
|
CONFLICT: 'CONFLICT',
|
||||||
|
VALIDATION_ERROR: 'VALIDATION_ERROR',
|
||||||
|
RATE_LIMIT_EXCEEDED: 'RATE_LIMIT_EXCEEDED',
|
||||||
|
INTERNAL_ERROR: 'INTERNAL_ERROR',
|
||||||
|
INVALID_CREDENTIALS: 'INVALID_CREDENTIALS',
|
||||||
|
ACCOUNT_LOCKED: 'ACCOUNT_LOCKED',
|
||||||
|
EMAIL_TAKEN: 'EMAIL_TAKEN',
|
||||||
|
INVALID_REFRESH_TOKEN: 'INVALID_REFRESH_TOKEN',
|
||||||
|
TOKEN_REUSE_DETECTED: 'TOKEN_REUSE_DETECTED',
|
||||||
|
INVALID_CODE: 'INVALID_CODE',
|
||||||
|
ALREADY_VERIFIED: 'ALREADY_VERIFIED',
|
||||||
|
INVALID_RESET_TOKEN: 'INVALID_RESET_TOKEN',
|
||||||
|
NICKNAME_TAKEN: 'NICKNAME_TAKEN',
|
||||||
|
DAILY_LIMIT_REACHED: 'DAILY_LIMIT_REACHED',
|
||||||
|
EMAIL_NOT_VERIFIED: 'EMAIL_NOT_VERIFIED',
|
||||||
|
QUESTIONS_UNAVAILABLE: 'QUESTIONS_UNAVAILABLE',
|
||||||
|
QUESTION_ALREADY_ANSWERED: 'QUESTION_ALREADY_ANSWERED',
|
||||||
|
WRONG_QUESTION: 'WRONG_QUESTION',
|
||||||
|
TEST_ALREADY_FINISHED: 'TEST_ALREADY_FINISHED',
|
||||||
|
NO_ANSWERS: 'NO_ANSWERS',
|
||||||
|
TEST_NOT_FINISHED: 'TEST_NOT_FINISHED',
|
||||||
|
USER_NOT_FOUND: 'USER_NOT_FOUND',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
||||||
|
|
||||||
|
export class AppError extends Error {
|
||||||
|
constructor(
|
||||||
|
public readonly code: ErrorCode,
|
||||||
|
public readonly message: string,
|
||||||
|
public readonly statusCode: number = 500,
|
||||||
|
public readonly details?: unknown
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'AppError';
|
||||||
|
Object.setPrototypeOf(this, AppError.prototype);
|
||||||
|
}
|
||||||
|
|
||||||
|
toJSON() {
|
||||||
|
const err: { code: string; message: string; details?: unknown } = {
|
||||||
|
code: this.code,
|
||||||
|
message: this.message,
|
||||||
|
};
|
||||||
|
if (this.details !== undefined) err.details = this.details;
|
||||||
|
return { error: err };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function badRequest(message: string, details?: unknown): AppError {
|
||||||
|
return new AppError(ERROR_CODES.BAD_REQUEST, message, 400, details);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unauthorized(message: string): AppError {
|
||||||
|
return new AppError(ERROR_CODES.UNAUTHORIZED, message, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function forbidden(message: string): AppError {
|
||||||
|
return new AppError(ERROR_CODES.FORBIDDEN, message, 403);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function notFound(message: string): AppError {
|
||||||
|
return new AppError(ERROR_CODES.NOT_FOUND, message, 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function conflict(code: ErrorCode, message: string): AppError {
|
||||||
|
return new AppError(code, message, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function validationError(message: string, details?: unknown): AppError {
|
||||||
|
return new AppError(ERROR_CODES.VALIDATION_ERROR, message, 422, details);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function rateLimitExceeded(message: string, retryAfter?: number): AppError {
|
||||||
|
const err = new AppError(ERROR_CODES.RATE_LIMIT_EXCEEDED, message, 429);
|
||||||
|
if (retryAfter !== undefined) {
|
||||||
|
(err as AppError & { retryAfter: number }).retryAfter = retryAfter;
|
||||||
|
}
|
||||||
|
return err;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function internalError(message: string, cause?: unknown): AppError {
|
||||||
|
return new AppError(ERROR_CODES.INTERNAL_ERROR, message, 500, cause);
|
||||||
|
}
|
||||||
37
src/utils/uuid.ts
Normal file
37
src/utils/uuid.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate UUID v7 (time-ordered, sortable).
|
||||||
|
* Simplified implementation: timestamp (48 bit) + random (74 bit).
|
||||||
|
*/
|
||||||
|
export function uuid7(): string {
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const random = randomBytes(10);
|
||||||
|
|
||||||
|
const high = (timestamp / 0x100000000) >>> 0;
|
||||||
|
const low = timestamp >>> 0;
|
||||||
|
|
||||||
|
const b = new Uint8Array(16);
|
||||||
|
b[0] = (high >> 24) & 0xff;
|
||||||
|
b[1] = (high >> 16) & 0xff;
|
||||||
|
b[2] = (high >> 8) & 0xff;
|
||||||
|
b[3] = high & 0xff;
|
||||||
|
b[4] = (low >> 24) & 0xff;
|
||||||
|
b[5] = (low >> 16) & 0xff;
|
||||||
|
b[6] = ((low >> 8) & 0x3f) | 0x70;
|
||||||
|
b[7] = low & 0xff;
|
||||||
|
b[8] = 0x80 | (random[0] & 0x3f);
|
||||||
|
b[9] = random[1];
|
||||||
|
b[10] = random[2];
|
||||||
|
b[11] = random[3];
|
||||||
|
b[12] = random[4];
|
||||||
|
b[13] = random[5];
|
||||||
|
b[14] = random[6];
|
||||||
|
b[15] = random[7];
|
||||||
|
|
||||||
|
const hex = Array.from(b)
|
||||||
|
.map((x) => x.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
|
||||||
|
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user