CLT-2: Postgres, миграции, учётные записи, сессии, CSRF, rate-limit, удаление аккаунта
All checks were successful
All checks were successful
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
804ca46d5b
commit
4acc7f5ea6
@ -8,9 +8,11 @@
|
||||
## Грабли
|
||||
- Sentry v11: опции `sendDefaultPii` нет, её заменил `dataCollection`, который по умолчанию собирает всё. Используй `PRIVACY_DATA_COLLECTION` из src/sentry.ts. TypeScript держим на ~6.0: typescript-eslint 8 не поддерживает TS 7.
|
||||
- На CI-раннере нет pnpm: в checks install = `npx --yes pnpm@12.18.0 install --frozen-lockfile`, остальные шаги через `npm run`. Не возвращай голый `pnpm` в checks.
|
||||
- tsconfig erasableSyntaxOnly: нет parameter properties в классах; Fastify trustProxy принимает только boolean/строку/функцию (не число). Compose стенда: POSTGRES_PASSWORD из secrets, только буквы/цифры (идёт в URL).
|
||||
|
||||
## Соглашения
|
||||
- Модули продукта — Fastify-плагины в src/modules/<имя>, регистрируются в buildApp() (src/app.ts). Тесты через app.inject(), названия тестов совпадают со сценариями спеки. Ошибки наружу — только `{"error":"<код>"}`. В логах — только метод и путь, без IP и query. HTML выводить через escapeHtml.
|
||||
- БД: интерфейс Db/TxDb (src/db/db.ts), миграции migrations/NNNN_*.sql через node dist/db/migrate.js (deploy.migrate); тесты на PGlite (test/helpers/db.ts), без DATABASE_URL модуль accounts не регистрируется. Пароли argon2id (@node-rs/argon2), сессии — SHA-256 токена в БД, CSRF через X-CSRF-Token.
|
||||
|
||||
## Решения
|
||||
- CLT-1: стек Node 22 + TS + Fastify одобрен PM. Порядок: CLT-2 (БД/учётки) → CLT-4 (биллинг) → CLT-5 (комплекты); AI-модули CLT-6..8 ждут CLT-3 (политика ПДн, 152-ФЗ). Платёжный провайдер не выбран — вопрос к PM в CLT-4.
|
||||
|
||||
@ -14,6 +14,7 @@
|
||||
"compose": "deploy/compose.yml",
|
||||
"service": "web",
|
||||
"port": 3000,
|
||||
"health": "/healthz"
|
||||
"health": "/healthz",
|
||||
"migrate": "node dist/db/migrate.js"
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ ENV NODE_ENV=production PORT=3000
|
||||
COPY --from=build --chown=node:node /app/package.json ./
|
||||
COPY --from=build --chown=node:node /app/node_modules ./node_modules
|
||||
COPY --from=build --chown=node:node /app/dist ./dist
|
||||
COPY --chown=node:node migrations ./migrations
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
|
||||
|
||||
@ -12,14 +12,38 @@ services:
|
||||
SENTRY_DSN: "${SENTRY_DSN:-}"
|
||||
SENTRY_RELEASE: "${PEPPA_SHA:-}"
|
||||
SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-dev}"
|
||||
# Postgres стенда. POSTGRES_PASSWORD — из secrets Actions (запросить у PM); не из репозитория.
|
||||
DATABASE_URL: "postgres://app:${POSTGRES_PASSWORD:-app}@db:5432/app"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- traefik_default
|
||||
- default
|
||||
labels:
|
||||
- traefik.enable=true
|
||||
- traefik.docker.network=traefik_default
|
||||
- traefik.http.routers.${ROUTER}.rule=Host(`${HOST}`)
|
||||
- traefik.http.routers.${ROUTER}.entrypoints=web
|
||||
- traefik.http.services.${ROUTER}.loadbalancer.server.port=${APP_PORT:-3000}
|
||||
db:
|
||||
image: postgres:17-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_USER: app
|
||||
POSTGRES_DB: app
|
||||
POSTGRES_PASSWORD: "${POSTGRES_PASSWORD:-app}"
|
||||
volumes:
|
||||
- db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U app -d app"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
networks:
|
||||
- default
|
||||
volumes:
|
||||
db-data:
|
||||
networks:
|
||||
traefik_default:
|
||||
external: true
|
||||
|
||||
27
migrations/0001_accounts.sql
Normal file
27
migrations/0001_accounts.sql
Normal file
@ -0,0 +1,27 @@
|
||||
CREATE TABLE organizations (
|
||||
id uuid PRIMARY KEY,
|
||||
name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
email text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
role text NOT NULL CHECK (role IN ('buyer', 'org_admin', 'operator')),
|
||||
org_id uuid REFERENCES organizations (id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK ((role = 'buyer') = (org_id IS NULL))
|
||||
);
|
||||
CREATE UNIQUE INDEX users_email_lower_idx ON users (lower(email));
|
||||
CREATE INDEX users_org_id_idx ON users (org_id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
csrf_token text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX sessions_user_id_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expires_at_idx ON sessions (expires_at);
|
||||
@ -1,18 +1,18 @@
|
||||
# Tasks
|
||||
|
||||
## 1. База данных
|
||||
- [ ] 1.1 Зависимости `pg`, `@node-rs/argon2`, dev `@electric-sql/pglite`, `@types/pg`; `src/db/` (интерфейс `Db`, `createPool` из `DATABASE_URL`). Проверка: typecheck.
|
||||
- [ ] 1.2 Раннер миграций `src/db/migrate.ts` + `migrations/0001_accounts.sql`. Проверка: тесты «Первое применение», «Повторный запуск», «Ошибка в миграции».
|
||||
- [ ] 1.3 Подключение в `buildApp()`/`index.ts`: без `DATABASE_URL` модуль не регистрируется. Проверка: тесты «БД не настроена», «БД настроена».
|
||||
- [x] 1.1 Зависимости `pg`, `@node-rs/argon2`, dev `@electric-sql/pglite`, `@types/pg`; `src/db/` (интерфейс `Db`, `createPool` из `DATABASE_URL`). Проверка: typecheck.
|
||||
- [x] 1.2 Раннер миграций `src/db/migrate.ts` + `migrations/0001_accounts.sql`. Проверка: тесты «Первое применение», «Повторный запуск», «Ошибка в миграции».
|
||||
- [x] 1.3 Подключение в `buildApp()`/`index.ts`: без `DATABASE_URL` модуль не регистрируется. Проверка: тесты «БД не настроена», «БД настроена».
|
||||
|
||||
## 2. Учётные записи
|
||||
- [ ] 2.1 Пароли (argon2id), сессии (хэш токена, cookie), нормализация email. Проверка: тесты регистрации (покупатель, организация, дубликат, невалидные данные).
|
||||
- [ ] 2.2 Вход/выход/`GET /api/session`. Проверка: тесты «Успешный вход», «Неверный пароль и неизвестный email», «Выход», «Истёкшая сессия».
|
||||
- [ ] 2.3 CSRF и проверка Origin. Проверка: «Нет CSRF-токена», «Чужой Origin».
|
||||
- [ ] 2.4 Rate-limit в памяти. Проверка: «Перебор пароля».
|
||||
- [ ] 2.5 Операторы организации и роли. Проверка: «Админ заводит оператора», «Покупатель не может создавать операторов».
|
||||
- [ ] 2.6 Удаление аккаунта и очистка сессий (таймер раз в час, `unref`). Проверка: четыре сценария удаления/очистки.
|
||||
- [x] 2.1 Пароли (argon2id), сессии (хэш токена, cookie), нормализация email. Проверка: тесты регистрации (покупатель, организация, дубликат, невалидные данные).
|
||||
- [x] 2.2 Вход/выход/`GET /api/session`. Проверка: тесты «Успешный вход», «Неверный пароль и неизвестный email», «Выход», «Истёкшая сессия».
|
||||
- [x] 2.3 CSRF и проверка Origin. Проверка: «Нет CSRF-токена», «Чужой Origin».
|
||||
- [x] 2.4 Rate-limit в памяти. Проверка: «Перебор пароля».
|
||||
- [x] 2.5 Операторы организации и роли. Проверка: «Админ заводит оператора», «Покупатель не может создавать операторов».
|
||||
- [x] 2.6 Удаление аккаунта и очистка сессий (таймер раз в час, `unref`). Проверка: четыре сценария удаления/очистки.
|
||||
|
||||
## 3. Деплой и завершение
|
||||
- [ ] 3.1 `Dockerfile` копирует `migrations/`; `deploy/compose.yml` — сервис postgres с volume, `DATABASE_URL`; `deploy.migrate` в `.peppa/project.json`. Проверка: `docker build`, миграция и `/healthz` локально, если docker доступен.
|
||||
- [ ] 3.2 Все проверки `bash .gitea/peppa-check.sh <проверка>`; память проекта; archive; PR.
|
||||
- [x] 3.1 `Dockerfile` копирует `migrations/`; `deploy/compose.yml` — сервис postgres с volume, `DATABASE_URL`; `deploy.migrate` в `.peppa/project.json`. Проверка: `docker build`, миграция и `/healthz` локально, если docker доступен.
|
||||
- [x] 3.2 Все проверки `bash .gitea/peppa-check.sh <проверка>`; память проекта; archive; PR.
|
||||
140
openspec/specs/accounts/spec.md
Normal file
140
openspec/specs/accounts/spec.md
Normal file
@ -0,0 +1,140 @@
|
||||
# accounts Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change clt-2-accounts-and-database. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Модель ролей
|
||||
Пользователь SHALL иметь ровно одну роль: `buyer`, `org_admin` или `operator`. `buyer` SHALL
|
||||
NOT принадлежать организации; `org_admin` и `operator` SHALL принадлежать ровно одной.
|
||||
Email SHALL быть уникален без учёта регистра.
|
||||
|
||||
#### Scenario: Дубликат email
|
||||
- **GIVEN** зарегистрирован пользователь «anna@example.com»
|
||||
- **WHEN** посетитель регистрируется с email «Anna@Example.com»
|
||||
- **THEN** ответ — 409 `{"error":"email_taken"}`
|
||||
|
||||
### Requirement: Регистрация
|
||||
`POST /api/auth/register` (JSON `email`, `password`) SHALL создавать `buyer` и сессию.
|
||||
`POST /api/auth/register-org` (`orgName`, `email`, `password`) SHALL создавать организацию и
|
||||
`org_admin` и сессию. Пароль SHALL быть длиной 10..128 символов, email — валидным адресом.
|
||||
Пароль SHALL храниться только как хэш argon2id.
|
||||
|
||||
#### Scenario: Регистрация покупателя
|
||||
- **GIVEN** email «anna@example.com» не зарегистрирован
|
||||
- **WHEN** посетитель отправляет `POST /api/auth/register` с этим email и паролем «correct-horse-9»
|
||||
- **THEN** ответ — 201 с ролью «buyer» и CSRF-токеном
|
||||
- **AND** выставлена cookie «sid» с флагами HttpOnly и SameSite=Lax
|
||||
- **AND** в БД `password_hash` начинается с «$argon2id$»
|
||||
|
||||
#### Scenario: Регистрация организации
|
||||
- **GIVEN** email «boss@corp.ru» не зарегистрирован
|
||||
- **WHEN** посетитель отправляет `POST /api/auth/register-org` с `orgName` «Корп» и этим email
|
||||
- **THEN** ответ — 201 с ролью «org_admin»
|
||||
- **AND** создана организация «Корп», к которой привязан пользователь
|
||||
|
||||
#### Scenario Outline: Невалидные данные регистрации
|
||||
- **WHEN** посетитель отправляет `POST /api/auth/register` с email «<email>» и паролем «<password>»
|
||||
- **THEN** ответ — 400 `{"error":"invalid_input"}`
|
||||
|
||||
| email | password |
|
||||
| not-an-email | correct-horse-9 |
|
||||
| anna@example.com | short |
|
||||
|
||||
### Requirement: Вход и выход
|
||||
`POST /api/auth/login` SHALL проверять пароль и создавать сессию на 30 суток. Для неизвестного
|
||||
email и неверного пароля SHALL возвращаться одинаковый ответ 401 `invalid_credentials`.
|
||||
`POST /api/auth/logout` SHALL удалять сессию и cookie. В БД SHALL храниться только SHA-256
|
||||
токена сессии.
|
||||
|
||||
#### Scenario: Успешный вход
|
||||
- **GIVEN** зарегистрирован «anna@example.com» с паролем «correct-horse-9»
|
||||
- **WHEN** она отправляет `POST /api/auth/login` с этими данными
|
||||
- **THEN** ответ — 200 с ролью и CSRF-токеном
|
||||
- **AND** `GET /api/session` с выданной cookie возвращает её email
|
||||
|
||||
#### Scenario: Неверный пароль и неизвестный email
|
||||
- **WHEN** посетитель входит с неверным паролем, а затем с незарегистрированным email
|
||||
- **THEN** оба ответа — 401 `{"error":"invalid_credentials"}` с одинаковым телом
|
||||
|
||||
#### Scenario: Выход
|
||||
- **GIVEN** пользователь вошёл
|
||||
- **WHEN** он отправляет `POST /api/auth/logout` с верным CSRF-токеном
|
||||
- **THEN** `GET /api/session` со старой cookie возвращает 401
|
||||
|
||||
#### Scenario: Истёкшая сессия
|
||||
- **GIVEN** сессия пользователя истекла
|
||||
- **WHEN** он запрашивает `GET /api/session`
|
||||
- **THEN** ответ — 401 `{"error":"unauthenticated"}`
|
||||
|
||||
### Requirement: CSRF-защита
|
||||
Изменяющие запросы (POST, DELETE) с сессионной cookie SHALL требовать заголовок
|
||||
`X-CSRF-Token`, равный токену сессии, иначе 403 `csrf_failed`. Запросы без сессии на
|
||||
регистрацию и вход SHALL принимать только `Content-Type: application/json` и отклонять
|
||||
`Origin`, не совпадающий с `Host`, ответом 403 `csrf_failed`.
|
||||
|
||||
#### Scenario: Нет CSRF-токена
|
||||
- **GIVEN** пользователь вошёл
|
||||
- **WHEN** он отправляет `POST /api/auth/logout` без заголовка `X-CSRF-Token`
|
||||
- **THEN** ответ — 403 `{"error":"csrf_failed"}`
|
||||
- **AND** сессия осталась действительной
|
||||
|
||||
#### Scenario: Чужой Origin
|
||||
- **WHEN** посетитель отправляет `POST /api/auth/login` с `Origin: https://evil.example`
|
||||
- **THEN** ответ — 403 `{"error":"csrf_failed"}`
|
||||
|
||||
### Requirement: Ограничение частоты
|
||||
Вход SHALL блокироваться ответом 429 `rate_limited` после 5 неудачных попыток на один email
|
||||
за 15 минут и после 20 на один IP; регистрация — после 10 запросов на IP за 15 минут.
|
||||
Успешный вход SHALL сбрасывать счётчик email.
|
||||
|
||||
#### Scenario: Перебор пароля
|
||||
- **GIVEN** зарегистрирован «anna@example.com»
|
||||
- **WHEN** посетитель делает 5 входов с неверным паролем, затем шестой с верным
|
||||
- **THEN** шестой ответ — 429 `{"error":"rate_limited"}`
|
||||
|
||||
### Requirement: Операторы организации
|
||||
`org_admin` SHALL создавать операторов своей организации через `POST /api/org/operators`
|
||||
(`email`, `password`). Другие роли SHALL получать 403 `forbidden`; без сессии — 401.
|
||||
|
||||
#### Scenario: Админ заводит оператора
|
||||
- **GIVEN** вошёл `org_admin` организации «Корп»
|
||||
- **WHEN** он отправляет `POST /api/org/operators` с email «op@corp.ru» и верным CSRF-токеном
|
||||
- **THEN** ответ — 201
|
||||
- **AND** пользователь «op@corp.ru» имеет роль «operator» в организации «Корп»
|
||||
|
||||
#### Scenario: Покупатель не может создавать операторов
|
||||
- **GIVEN** вошёл `buyer`
|
||||
- **WHEN** он отправляет `POST /api/org/operators`
|
||||
- **THEN** ответ — 403 `{"error":"forbidden"}`
|
||||
|
||||
### Requirement: Минимизация ПДн и удаление аккаунта
|
||||
Система SHALL хранить только email, хэш пароля, роль, организацию и даты; IP и User-Agent SHALL
|
||||
NOT сохраняться в БД и логах. Истёкшие сессии SHALL удаляться. `DELETE /api/account`
|
||||
(`password`, CSRF) SHALL жёстко удалять пользователя и его сессии; `org_admin` с оставшимися
|
||||
операторами SHALL получать 409 `org_has_members`. Если удалённый пользователь был
|
||||
единственным членом организации, организация SHALL удаляться.
|
||||
|
||||
#### Scenario: Удаление аккаунта
|
||||
- **GIVEN** вошёл `buyer` «anna@example.com»
|
||||
- **WHEN** он отправляет `DELETE /api/account` с верным паролем и CSRF-токеном
|
||||
- **THEN** ответ — 204
|
||||
- **AND** в БД нет ни пользователя, ни его сессий
|
||||
- **AND** вход с его данными даёт 401
|
||||
|
||||
#### Scenario: Неверный пароль при удалении
|
||||
- **GIVEN** вошёл `buyer`
|
||||
- **WHEN** он отправляет `DELETE /api/account` с неверным паролем
|
||||
- **THEN** ответ — 401 `{"error":"invalid_credentials"}`
|
||||
- **AND** аккаунт остался
|
||||
|
||||
#### Scenario: Админ с операторами не удаляется
|
||||
- **GIVEN** `org_admin` организации «Корп» с оператором «op@corp.ru»
|
||||
- **WHEN** он удаляет свой аккаунт с верным паролем
|
||||
- **THEN** ответ — 409 `{"error":"org_has_members"}`
|
||||
|
||||
#### Scenario: Очистка истёкших сессий
|
||||
- **GIVEN** в БД есть сессия с истёкшим `expires_at`
|
||||
- **WHEN** выполняется очистка сессий
|
||||
- **THEN** эта сессия удалена, действующие остались
|
||||
46
openspec/specs/database/spec.md
Normal file
46
openspec/specs/database/spec.md
Normal file
@ -0,0 +1,46 @@
|
||||
# database Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change clt-2-accounts-and-database. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Подключение к Postgres из окружения
|
||||
Сервис SHALL подключаться к Postgres по `DATABASE_URL`. Строка подключения SHALL NOT попадать
|
||||
в логи, ответы и Sentry. Если `DATABASE_URL` не задан, сервис SHALL запускаться без модуля
|
||||
учётных записей, а `GET /healthz` SHALL по-прежнему отвечать 200 без обращения к БД.
|
||||
|
||||
#### Scenario: БД не настроена
|
||||
- **GIVEN** переменная `DATABASE_URL` не задана
|
||||
- **WHEN** посетитель запрашивает `POST /api/auth/login`
|
||||
- **THEN** ответ — 404 `{"error":"not_found"}`
|
||||
- **AND** `GET /healthz` возвращает 200
|
||||
|
||||
#### Scenario: БД настроена
|
||||
- **GIVEN** `DATABASE_URL` указывает на доступный Postgres с применёнными миграциями
|
||||
- **WHEN** посетитель запрашивает `GET /api/session` без cookie
|
||||
- **THEN** ответ — 401 `{"error":"unauthenticated"}`
|
||||
|
||||
### Requirement: Миграции
|
||||
Схема БД SHALL меняться только SQL-миграциями из `migrations/`, применяемыми командой
|
||||
`node dist/db/migrate.js` по порядку имён. Применённые миграции SHALL фиксироваться в
|
||||
`schema_migrations`; повторный запуск SHALL NOT менять схему. Неудачная миграция SHALL
|
||||
откатываться целиком, а команда — завершаться с ненулевым кодом.
|
||||
|
||||
#### Scenario: Первое применение
|
||||
- **GIVEN** пустая БД
|
||||
- **WHEN** запускается раннер миграций
|
||||
- **THEN** созданы таблицы `organizations`, `users`, `sessions`
|
||||
- **AND** в `schema_migrations` есть запись «0001_accounts»
|
||||
|
||||
#### Scenario: Повторный запуск
|
||||
- **GIVEN** все миграции уже применены
|
||||
- **WHEN** раннер запускается снова
|
||||
- **THEN** новых записей в `schema_migrations` нет
|
||||
- **AND** код завершения 0
|
||||
|
||||
#### Scenario: Ошибка в миграции
|
||||
- **GIVEN** миграция «0002_broken» содержит некорректный SQL
|
||||
- **WHEN** запускается раннер миграций
|
||||
- **THEN** изменения «0002_broken» откатены
|
||||
- **AND** код завершения ненулевой
|
||||
@ -16,13 +16,17 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/helmet": "^13.2.0",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@sentry/node": "^11.12.0",
|
||||
"fastify": "^5.12.8"
|
||||
"fastify": "^5.12.8",
|
||||
"pg": "^8.23.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electric-sql/pglite": "^0.5.16",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@sentry/core": "11.12.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"@types/pg": "^8.23.1",
|
||||
"eslint": "^10.14.0",
|
||||
"globals": "^17.14.0",
|
||||
"typescript": "~6.0.3",
|
||||
|
||||
268
pnpm-lock.yaml
generated
268
pnpm-lock.yaml
generated
@ -169,13 +169,22 @@ importers:
|
||||
'@fastify/helmet':
|
||||
specifier: ^13.2.0
|
||||
version: 13.2.0
|
||||
'@node-rs/argon2':
|
||||
specifier: ^2.2.2
|
||||
version: 2.2.2
|
||||
'@sentry/node':
|
||||
specifier: ^11.12.0
|
||||
version: 11.12.0
|
||||
fastify:
|
||||
specifier: ^5.12.8
|
||||
version: 5.12.8
|
||||
pg:
|
||||
specifier: ^8.23.1
|
||||
version: 8.23.1
|
||||
devDependencies:
|
||||
'@electric-sql/pglite':
|
||||
specifier: ^0.5.16
|
||||
version: 0.5.16
|
||||
'@eslint/js':
|
||||
specifier: ^10.0.1
|
||||
version: 10.0.1(eslint@10.14.0)
|
||||
@ -185,6 +194,9 @@ importers:
|
||||
'@types/node':
|
||||
specifier: ^26.6.6
|
||||
version: 26.6.6
|
||||
'@types/pg':
|
||||
specifier: ^8.23.1
|
||||
version: 8.23.1
|
||||
eslint:
|
||||
specifier: ^10.14.0
|
||||
version: 10.14.0
|
||||
@ -209,6 +221,9 @@ packages:
|
||||
'@cacheable/utils@2.5.0':
|
||||
resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}
|
||||
|
||||
'@electric-sql/pglite@0.5.16':
|
||||
resolution: {integrity: sha512-Nj8KcIsJL748W408U2N8q4+9IlONdpRIU8MJypIAAINMJ5nqKyqpX7Mgg/5XKkXiAib3AoZGR6hnJFlrlLBrcg==}
|
||||
|
||||
'@emnapi/core@2.0.0-beta.2':
|
||||
resolution: {integrity: sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==}
|
||||
|
||||
@ -330,6 +345,92 @@ packages:
|
||||
'@emnapi/core': ^1.7.1 || 2.0.0-beta.2
|
||||
'@emnapi/runtime': ^1.7.1 || 2.0.0-beta.2
|
||||
|
||||
'@node-rs/argon2-android-arm-eabi@2.2.2':
|
||||
resolution: {integrity: sha512-c11BOrPLBWNC1cDyzGB+Bil+flmxfZbB2hv8EhcobmAsFKMyqkHPNhUY4qhcjv1U+4+Vmw4G8H+l224iO2g/Dw==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
|
||||
'@node-rs/argon2-android-arm64@2.2.2':
|
||||
resolution: {integrity: sha512-dpMYIoxhN/wY6hFH+3MM5kQErcH3luMekkszbkDF3NKqhB1kFRntkOLDpFY87oItBSHJrsoYkXC3vBRhjYoCjQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@node-rs/argon2-darwin-arm64@2.2.2':
|
||||
resolution: {integrity: sha512-vxVAXcIG0iiHizkCuImmzVhOFsRnU4Z79xiOxdISLyI+QhOAWbbTaVSXw0PNfThB3zAdkzzDJ/WWu52Hs/qHGg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@node-rs/argon2-darwin-x64@2.2.2':
|
||||
resolution: {integrity: sha512-r7GbSFpFZZ9EAV9cvIm9prUjOupK7QQXTyP+FJ6bWSMq0h+qRDBlUOXQXduDIIrLEGoBVelixKUtf4ksZ0ljoQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@node-rs/argon2-freebsd-x64@2.2.2':
|
||||
resolution: {integrity: sha512-AmWxDSmQgprilD6NX3jmxCgcDvWAW7kGJnnWQo+0qav6nfMXdPZYgSezK/skmw1GBWipr4yZMIUzpeNHnVpMxg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
|
||||
'@node-rs/argon2-linux-arm-gnueabihf@2.2.2':
|
||||
resolution: {integrity: sha512-M1gnPBTr9GFeEUWkQ53qCJeTsX03C3kcUeHnDbN7dU2xkI58wMP4Z1sEBN7WmKJ/fTHYEgti4truz7r4A82DLg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
|
||||
'@node-rs/argon2-linux-arm64-gnu@2.2.2':
|
||||
resolution: {integrity: sha512-4CYDlIdITlLSVcAXYUtEoGUahRaayPXM+4Rcfg3BZx9WGi6UB8HUycs6GNMTPYXV5kVXCpyE2u1HmYUpgmIzOQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@node-rs/argon2-linux-arm64-musl@2.2.2':
|
||||
resolution: {integrity: sha512-FYlfj3XgQ1xrx6HzQbKbUcKiYMG/3iSi/X81KyhHaItTJ7vZlMwrbVLl9yqDmvotKUF6VjrhrlZ8KRbbzchseA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@node-rs/argon2-linux-x64-gnu@2.2.2':
|
||||
resolution: {integrity: sha512-ULXLs8UFYZANlwiROM7AeccxZndr2Xk3IstADq3jAUhnwV2W75mxMBTABUZ+7AdKRhPLOrxU77OgnMWlDkYJQg==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@node-rs/argon2-linux-x64-musl@2.2.2':
|
||||
resolution: {integrity: sha512-zgjIwc9TyGodn62vGc+36DGwFqVV5e7L8Ptd2FQWuBxe5aFrcFxvtDGn1/qfYwoHLv09utgtR+RBAPCXepWG3Q==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@node-rs/argon2-win32-arm64-msvc@2.2.2':
|
||||
resolution: {integrity: sha512-3nLhvLie/ec5xfxUBXXqGMb7oGeqF+YXrcGckqaTaGkPtOBozho0Kh2IuP/zi9BcOriirTG2LW3gtIOfpuh+mQ==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@node-rs/argon2-win32-ia32-msvc@2.2.2':
|
||||
resolution: {integrity: sha512-6RJKD6cFl7UeiYJLjRsXPywVXSFSaSDdr6xGpztNDV31QHCEecWnsnNmKxzi4gVpln2F9XeWEtIgM4Nqw1hLbA==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
|
||||
'@node-rs/argon2-win32-x64-msvc@2.2.2':
|
||||
resolution: {integrity: sha512-dQOO9S4QKBaVul0Uyk/2quJc/OBeHNZRJP+GZZTy1A5kYIaAfIJGHUYLY6oFoAlcuLIkdFouLaHX3fCl8tZm/w==}
|
||||
engines: {node: '>= 10'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@node-rs/argon2@2.2.2':
|
||||
resolution: {integrity: sha512-NtdlPPWtR5U4BxX5EGJYza+UklNaoWORmkaKCMqf/nyKeXWKVwNt8KfQoRpNT7OB1DcEwmePafO4wZyW+sbfCQ==}
|
||||
engines: {node: '>= 10'}
|
||||
|
||||
'@opentelemetry/api@1.10.0':
|
||||
resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
@ -628,6 +729,9 @@ packages:
|
||||
'@types/node@26.6.6':
|
||||
resolution: {integrity: sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==}
|
||||
|
||||
'@types/pg@8.23.1':
|
||||
resolution: {integrity: sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==}
|
||||
|
||||
'@typescript-eslint/eslint-plugin@8.72.2':
|
||||
resolution: {integrity: sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==}
|
||||
engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}
|
||||
@ -1125,6 +1229,40 @@ packages:
|
||||
resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==}
|
||||
engines: {node: 18 || 20 || >=22}
|
||||
|
||||
pg-cloudflare@1.4.1:
|
||||
resolution: {integrity: sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==}
|
||||
|
||||
pg-connection-string@2.14.1:
|
||||
resolution: {integrity: sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==}
|
||||
|
||||
pg-int8@1.0.1:
|
||||
resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==}
|
||||
engines: {node: '>=4.0.0'}
|
||||
|
||||
pg-pool@3.14.0:
|
||||
resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==}
|
||||
peerDependencies:
|
||||
pg: '>=8.0'
|
||||
|
||||
pg-protocol@1.16.1:
|
||||
resolution: {integrity: sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==}
|
||||
|
||||
pg-types@2.2.0:
|
||||
resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
pg@8.23.1:
|
||||
resolution: {integrity: sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==}
|
||||
engines: {node: '>= 16.0.0'}
|
||||
peerDependencies:
|
||||
pg-native: '>=3.0.1'
|
||||
peerDependenciesMeta:
|
||||
pg-native:
|
||||
optional: true
|
||||
|
||||
pgpass@1.0.5:
|
||||
resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==}
|
||||
|
||||
picocolors@1.1.1:
|
||||
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
|
||||
|
||||
@ -1146,6 +1284,22 @@ packages:
|
||||
resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
|
||||
postgres-array@2.0.0:
|
||||
resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==}
|
||||
engines: {node: '>=4'}
|
||||
|
||||
postgres-bytea@1.0.1:
|
||||
resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
postgres-date@1.0.7:
|
||||
resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
postgres-interval@1.2.0:
|
||||
resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
prelude-ls@1.2.1:
|
||||
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
|
||||
engines: {node: '>= 0.8.0'}
|
||||
@ -1382,6 +1536,10 @@ packages:
|
||||
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
xtend@4.0.2:
|
||||
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
|
||||
engines: {node: '>=0.4'}
|
||||
|
||||
yocto-queue@0.1.0:
|
||||
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
|
||||
engines: {node: '>=10'}
|
||||
@ -1400,6 +1558,8 @@ snapshots:
|
||||
hashery: 1.5.1
|
||||
keyv: 5.6.0
|
||||
|
||||
'@electric-sql/pglite@0.5.16': {}
|
||||
|
||||
'@emnapi/core@2.0.0-beta.2':
|
||||
dependencies:
|
||||
'@emnapi/wasi-threads': 2.2.0
|
||||
@ -1522,6 +1682,61 @@ snapshots:
|
||||
'@tybys/wasm-util': 0.10.4
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-android-arm-eabi@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-android-arm64@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-darwin-arm64@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-darwin-x64@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-freebsd-x64@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-linux-arm-gnueabihf@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-linux-arm64-gnu@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-linux-arm64-musl@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-linux-x64-gnu@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-linux-x64-musl@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-win32-arm64-msvc@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-win32-ia32-msvc@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2-win32-x64-msvc@2.2.2':
|
||||
optional: true
|
||||
|
||||
'@node-rs/argon2@2.2.2':
|
||||
optionalDependencies:
|
||||
'@node-rs/argon2-android-arm-eabi': 2.2.2
|
||||
'@node-rs/argon2-android-arm64': 2.2.2
|
||||
'@node-rs/argon2-darwin-arm64': 2.2.2
|
||||
'@node-rs/argon2-darwin-x64': 2.2.2
|
||||
'@node-rs/argon2-freebsd-x64': 2.2.2
|
||||
'@node-rs/argon2-linux-arm-gnueabihf': 2.2.2
|
||||
'@node-rs/argon2-linux-arm64-gnu': 2.2.2
|
||||
'@node-rs/argon2-linux-arm64-musl': 2.2.2
|
||||
'@node-rs/argon2-linux-x64-gnu': 2.2.2
|
||||
'@node-rs/argon2-linux-x64-musl': 2.2.2
|
||||
'@node-rs/argon2-win32-arm64-msvc': 2.2.2
|
||||
'@node-rs/argon2-win32-ia32-msvc': 2.2.2
|
||||
'@node-rs/argon2-win32-x64-msvc': 2.2.2
|
||||
|
||||
'@opentelemetry/api@1.10.0': {}
|
||||
|
||||
'@oxc-parser/binding-android-arm-eabi@0.152.0':
|
||||
@ -1708,6 +1923,12 @@ snapshots:
|
||||
dependencies:
|
||||
undici-types: 8.9.0
|
||||
|
||||
'@types/pg@8.23.1':
|
||||
dependencies:
|
||||
'@types/node': 26.6.6
|
||||
pg-protocol: 1.16.1
|
||||
pg-types: 2.2.0
|
||||
|
||||
'@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@10.14.0)(typescript@6.0.3))(eslint@10.14.0)(typescript@6.0.3)':
|
||||
dependencies:
|
||||
'@eslint-community/regexpp': 4.12.3
|
||||
@ -2228,6 +2449,41 @@ snapshots:
|
||||
lru-cache: 11.5.3
|
||||
minipass: 7.1.3
|
||||
|
||||
pg-cloudflare@1.4.1:
|
||||
optional: true
|
||||
|
||||
pg-connection-string@2.14.1: {}
|
||||
|
||||
pg-int8@1.0.1: {}
|
||||
|
||||
pg-pool@3.14.0(pg@8.23.1):
|
||||
dependencies:
|
||||
pg: 8.23.1
|
||||
|
||||
pg-protocol@1.16.1: {}
|
||||
|
||||
pg-types@2.2.0:
|
||||
dependencies:
|
||||
pg-int8: 1.0.1
|
||||
postgres-array: 2.0.0
|
||||
postgres-bytea: 1.0.1
|
||||
postgres-date: 1.0.7
|
||||
postgres-interval: 1.2.0
|
||||
|
||||
pg@8.23.1:
|
||||
dependencies:
|
||||
pg-connection-string: 2.14.1
|
||||
pg-pool: 3.14.0(pg@8.23.1)
|
||||
pg-protocol: 1.16.1
|
||||
pg-types: 2.2.0
|
||||
pgpass: 1.0.5
|
||||
optionalDependencies:
|
||||
pg-cloudflare: 1.4.1
|
||||
|
||||
pgpass@1.0.5:
|
||||
dependencies:
|
||||
split2: 4.2.0
|
||||
|
||||
picocolors@1.1.1: {}
|
||||
|
||||
picomatch@4.0.7: {}
|
||||
@ -2258,6 +2514,16 @@ snapshots:
|
||||
picocolors: 1.1.1
|
||||
source-map-js: 1.2.2
|
||||
|
||||
postgres-array@2.0.0: {}
|
||||
|
||||
postgres-bytea@1.0.1: {}
|
||||
|
||||
postgres-date@1.0.7: {}
|
||||
|
||||
postgres-interval@1.2.0:
|
||||
dependencies:
|
||||
xtend: 4.0.2
|
||||
|
||||
prelude-ls@1.2.1: {}
|
||||
|
||||
process-warning@5.1.1: {}
|
||||
@ -2418,4 +2684,6 @@ snapshots:
|
||||
|
||||
word-wrap@1.2.5: {}
|
||||
|
||||
xtend@4.0.2: {}
|
||||
|
||||
yocto-queue@0.1.0: {}
|
||||
|
||||
11
src/app.ts
11
src/app.ts
@ -1,6 +1,8 @@
|
||||
import Fastify, { type FastifyError, type FastifyInstance, type FastifyServerOptions } from "fastify";
|
||||
import helmet from "@fastify/helmet";
|
||||
import { captureError } from "./sentry.ts";
|
||||
import type { TxDb } from "./db/db.ts";
|
||||
import { accountsModule, type AccountsOptions } from "./modules/accounts/index.ts";
|
||||
import { catalogModule, type CatalogOptions } from "./modules/catalog/index.ts";
|
||||
|
||||
export const BODY_LIMIT = 1024 * 1024;
|
||||
@ -8,6 +10,9 @@ export const BODY_LIMIT = 1024 * 1024;
|
||||
export interface AppOptions {
|
||||
logger?: FastifyServerOptions["logger"];
|
||||
catalog?: CatalogOptions;
|
||||
/** БД; без неё модуль учётных записей не регистрируется. */
|
||||
db?: TxDb;
|
||||
accounts?: Omit<AccountsOptions, "db">;
|
||||
}
|
||||
|
||||
const CLIENT_ERROR_CODES: Record<number, string> = {
|
||||
@ -22,6 +27,8 @@ export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance>
|
||||
const app = Fastify({
|
||||
logger: opts.logger ?? false,
|
||||
bodyLimit: BODY_LIMIT,
|
||||
// За Traefik: клиентский IP (только для счётчиков rate-limit в памяти) — из X-Forwarded-For одного прокси.
|
||||
trustProxy: (_address: string, hop: number) => hop < 1,
|
||||
});
|
||||
|
||||
await app.register(helmet, {
|
||||
@ -66,5 +73,9 @@ export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance>
|
||||
|
||||
await app.register(catalogModule, opts.catalog ?? {});
|
||||
|
||||
if (opts.db) {
|
||||
await app.register(accountsModule, { ...opts.accounts, db: opts.db });
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
37
src/db/db.ts
Normal file
37
src/db/db.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import pg from "pg";
|
||||
|
||||
/** Минимальный интерфейс БД: его реализуют pg.Pool и PGlite (в тестах). */
|
||||
export interface Db {
|
||||
query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<{ rows: T[]; rowCount: number | null }>;
|
||||
}
|
||||
|
||||
/** Db с транзакциями: `tx` выполняет функцию в BEGIN/COMMIT, при ошибке — ROLLBACK. */
|
||||
export interface TxDb extends Db {
|
||||
tx<R>(fn: (db: Db) => Promise<R>): Promise<R>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Пул Postgres из DATABASE_URL. Строка подключения не логируется и не попадает в ошибки. */
|
||||
export function createPool(databaseUrl: string): TxDb {
|
||||
const pool = new pg.Pool({ connectionString: databaseUrl, max: 10 });
|
||||
// Ошибки idle-клиентов не должны ронять процесс.
|
||||
pool.on("error", () => undefined);
|
||||
return {
|
||||
query: (sql, params) => pool.query(sql, params as unknown[]) as never,
|
||||
async tx(fn) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query("BEGIN");
|
||||
const result = await fn({ query: (sql, params) => client.query(sql, params as unknown[]) as never });
|
||||
await client.query("COMMIT");
|
||||
return result;
|
||||
} catch (err) {
|
||||
await client.query("ROLLBACK").catch(() => undefined);
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
},
|
||||
close: () => pool.end(),
|
||||
};
|
||||
}
|
||||
50
src/db/migrate.ts
Normal file
50
src/db/migrate.ts
Normal file
@ -0,0 +1,50 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createPool, type Db, type TxDb } from "./db.ts";
|
||||
|
||||
export const MIGRATIONS_DIR = fileURLToPath(new URL("../../migrations/", import.meta.url));
|
||||
const LOCK_ID = 727_001;
|
||||
|
||||
/** Применяет по порядку имён миграции, которых ещё нет в schema_migrations. Возвращает применённые. */
|
||||
export async function runMigrations(db: TxDb, dir: string = MIGRATIONS_DIR): Promise<string[]> {
|
||||
const files = (await readdir(dir)).filter((f) => f.endsWith(".sql")).sort();
|
||||
return db.tx(async (tx: Db) => {
|
||||
// Блокировка до конца транзакции: параллельный запуск ждёт.
|
||||
await tx.query("SELECT pg_advisory_xact_lock($1)", [LOCK_ID]);
|
||||
await tx.query(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())",
|
||||
);
|
||||
const done = new Set((await tx.query<{ name: string }>("SELECT name FROM schema_migrations")).rows.map((r) => r.name));
|
||||
const applied: string[] = [];
|
||||
for (const file of files) {
|
||||
const name = file.replace(/\.sql$/, "");
|
||||
if (done.has(name)) continue;
|
||||
await tx.query(await readFile(dir + file, "utf8"));
|
||||
await tx.query("INSERT INTO schema_migrations (name) VALUES ($1)", [name]);
|
||||
applied.push(name);
|
||||
}
|
||||
return applied;
|
||||
});
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) {
|
||||
console.error("DATABASE_URL is not set");
|
||||
process.exit(1);
|
||||
}
|
||||
const db = createPool(url);
|
||||
try {
|
||||
const applied = await runMigrations(db);
|
||||
console.log(applied.length ? `Applied: ${applied.join(", ")}` : "No pending migrations");
|
||||
} finally {
|
||||
await db.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
|
||||
main().catch((err: unknown) => {
|
||||
console.error("Migration failed:", err instanceof Error ? err.message : "unknown error");
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
import { initSentry, flushSentry } from "./sentry.ts";
|
||||
import { buildApp } from "./app.ts";
|
||||
import { createPool } from "./db/db.ts";
|
||||
import { parsePort } from "./config.ts";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
@ -12,7 +13,10 @@ async function main(): Promise<void> {
|
||||
}
|
||||
|
||||
initSentry();
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
const db = databaseUrl ? createPool(databaseUrl) : undefined;
|
||||
const app = await buildApp({
|
||||
db,
|
||||
logger: {
|
||||
level: process.env.LOG_LEVEL ?? "info",
|
||||
// В логах — только метод и путь: без IP клиента, query и заголовков (ПДн).
|
||||
@ -25,6 +29,7 @@ async function main(): Promise<void> {
|
||||
const shutdown = async (signal: string): Promise<void> => {
|
||||
app.log.info({ signal }, "shutting down");
|
||||
await app.close();
|
||||
await db?.close();
|
||||
await flushSentry();
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
256
src/modules/accounts/index.ts
Normal file
256
src/modules/accounts/index.ts
Normal file
@ -0,0 +1,256 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import type { Db, TxDb } from "../../db/db.ts";
|
||||
import { RateLimiter } from "./rate-limit.ts";
|
||||
import {
|
||||
checkPassword,
|
||||
hashPassword,
|
||||
hashToken,
|
||||
newToken,
|
||||
normalizeEmail,
|
||||
validEmail,
|
||||
validPassword,
|
||||
} from "./security.ts";
|
||||
|
||||
export const SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
const COOKIE = "sid";
|
||||
|
||||
export interface AccountsOptions {
|
||||
db: TxDb;
|
||||
/** Secure-флаг cookie; по умолчанию — NODE_ENV=production. */
|
||||
secureCookie?: boolean;
|
||||
now?: () => number;
|
||||
}
|
||||
|
||||
type Role = "buyer" | "org_admin" | "operator";
|
||||
interface SessionUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: Role;
|
||||
orgId: string | null;
|
||||
csrf: string;
|
||||
}
|
||||
|
||||
const fail = (reply: FastifyReply, code: number, error: string) => reply.code(code).send({ error });
|
||||
|
||||
function parseCookies(header: string | undefined): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of (header ?? "").split(";")) {
|
||||
const i = part.indexOf("=");
|
||||
if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Удаляет истёкшие сессии; возвращает их число. */
|
||||
export async function purgeExpiredSessions(db: Db): Promise<number> {
|
||||
const r = await db.query("DELETE FROM sessions WHERE expires_at <= now()");
|
||||
return r.rowCount ?? 0;
|
||||
}
|
||||
|
||||
export async function accountsModule(app: FastifyInstance, opts: AccountsOptions): Promise<void> {
|
||||
const { db } = opts;
|
||||
const secure = opts.secureCookie ?? process.env.NODE_ENV === "production";
|
||||
const now = opts.now ?? Date.now;
|
||||
const loginByEmail = new RateLimiter(5, undefined, now);
|
||||
const loginByIp = new RateLimiter(20, undefined, now);
|
||||
const registerByIp = new RateLimiter(10, undefined, now);
|
||||
|
||||
const timer = setInterval(() => void purgeExpiredSessions(db).catch(() => undefined), 60 * 60 * 1000);
|
||||
timer.unref();
|
||||
app.addHook("onClose", async () => clearInterval(timer));
|
||||
|
||||
const cookieHeader = (value: string, maxAgeSec: number): string =>
|
||||
`${COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSec}${secure ? "; Secure" : ""}`;
|
||||
|
||||
async function createSession(reply: FastifyReply, userId: string): Promise<string> {
|
||||
const token = newToken();
|
||||
const csrf = newToken();
|
||||
await db.query("INSERT INTO sessions (token_hash, user_id, csrf_token, expires_at) VALUES ($1, $2, $3, $4)", [
|
||||
hashToken(token),
|
||||
userId,
|
||||
csrf,
|
||||
new Date(now() + SESSION_TTL_MS),
|
||||
]);
|
||||
reply.header("set-cookie", cookieHeader(token, SESSION_TTL_MS / 1000));
|
||||
return csrf;
|
||||
}
|
||||
|
||||
async function loadSession(req: FastifyRequest): Promise<SessionUser | null> {
|
||||
const token = parseCookies(req.headers.cookie)[COOKIE];
|
||||
if (!token) return null;
|
||||
const r = await db.query<{ id: string; email: string; role: Role; org_id: string | null; csrf_token: string }>(
|
||||
`SELECT u.id, u.email, u.role, u.org_id, s.csrf_token FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > $2`,
|
||||
[hashToken(token), new Date(now())],
|
||||
);
|
||||
const row = r.rows[0];
|
||||
return row ? { id: row.id, email: row.email, role: row.role, orgId: row.org_id, csrf: row.csrf_token } : null;
|
||||
}
|
||||
|
||||
/** Требует сессию и CSRF-токен; при отказе отвечает сам и возвращает null. */
|
||||
async function authed(req: FastifyRequest, reply: FastifyReply, csrf: boolean): Promise<SessionUser | null> {
|
||||
const user = await loadSession(req);
|
||||
if (!user) {
|
||||
await fail(reply, 401, "unauthenticated");
|
||||
return null;
|
||||
}
|
||||
if (csrf && req.headers["x-csrf-token"] !== user.csrf) {
|
||||
await fail(reply, 403, "csrf_failed");
|
||||
return null;
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
/** Запросы без сессии: только JSON и свой Origin. */
|
||||
function anonymousGuard(req: FastifyRequest, reply: FastifyReply): boolean {
|
||||
const origin = req.headers.origin;
|
||||
const ctype = req.headers["content-type"] ?? "";
|
||||
let originOk = true;
|
||||
if (origin !== undefined) {
|
||||
try {
|
||||
originOk = new URL(origin).host === req.headers.host;
|
||||
} catch {
|
||||
originOk = false;
|
||||
}
|
||||
}
|
||||
if (!originOk || !ctype.toLowerCase().startsWith("application/json")) {
|
||||
void fail(reply, 403, "csrf_failed");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const body = (req: FastifyRequest): Record<string, unknown> =>
|
||||
req.body && typeof req.body === "object" ? (req.body as Record<string, unknown>) : {};
|
||||
|
||||
const isUniqueViolation = (err: unknown): boolean => (err as { code?: string })?.code === "23505";
|
||||
|
||||
async function register(
|
||||
req: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
kind: "buyer" | "org",
|
||||
): Promise<FastifyReply> {
|
||||
if (!anonymousGuard(req, reply)) return reply;
|
||||
if (registerByIp.blocked(req.ip)) return fail(reply, 429, "rate_limited");
|
||||
registerByIp.hit(req.ip);
|
||||
const b = body(req);
|
||||
const email = typeof b.email === "string" ? normalizeEmail(b.email) : "";
|
||||
const orgName = typeof b.orgName === "string" ? b.orgName.trim() : "";
|
||||
if (!validEmail(email) || !validPassword(b.password) || (kind === "org" && (orgName.length < 1 || orgName.length > 200))) {
|
||||
return fail(reply, 400, "invalid_input");
|
||||
}
|
||||
const passwordHash = await hashPassword(b.password);
|
||||
const userId = randomUUID();
|
||||
const role: Role = kind === "org" ? "org_admin" : "buyer";
|
||||
try {
|
||||
await db.tx(async (tx) => {
|
||||
let orgId: string | null = null;
|
||||
if (kind === "org") {
|
||||
orgId = randomUUID();
|
||||
await tx.query("INSERT INTO organizations (id, name) VALUES ($1, $2)", [orgId, orgName]);
|
||||
}
|
||||
await tx.query("INSERT INTO users (id, email, password_hash, role, org_id) VALUES ($1, $2, $3, $4, $5)", [
|
||||
userId,
|
||||
email,
|
||||
passwordHash,
|
||||
role,
|
||||
orgId,
|
||||
]);
|
||||
});
|
||||
} catch (err) {
|
||||
if (isUniqueViolation(err)) return fail(reply, 409, "email_taken");
|
||||
throw err;
|
||||
}
|
||||
const csrf = await createSession(reply, userId);
|
||||
return reply.code(201).send({ role, email, csrfToken: csrf });
|
||||
}
|
||||
|
||||
app.post("/api/auth/register", (req, reply) => register(req, reply, "buyer"));
|
||||
app.post("/api/auth/register-org", (req, reply) => register(req, reply, "org"));
|
||||
|
||||
app.post("/api/auth/login", async (req, reply) => {
|
||||
if (!anonymousGuard(req, reply)) return reply;
|
||||
const b = body(req);
|
||||
const email = typeof b.email === "string" ? normalizeEmail(b.email) : "";
|
||||
if (loginByEmail.blocked(email) || loginByIp.blocked(req.ip)) return fail(reply, 429, "rate_limited");
|
||||
const password = typeof b.password === "string" ? b.password : "";
|
||||
const r = await db.query<{ id: string; password_hash: string; role: Role }>(
|
||||
"SELECT id, password_hash, role FROM users WHERE lower(email) = $1",
|
||||
[email],
|
||||
);
|
||||
const user = r.rows[0];
|
||||
if (!(await checkPassword(user?.password_hash ?? null, password)) || !user) {
|
||||
loginByEmail.hit(email);
|
||||
loginByIp.hit(req.ip);
|
||||
return fail(reply, 401, "invalid_credentials");
|
||||
}
|
||||
loginByEmail.reset(email);
|
||||
await purgeExpiredSessions(db);
|
||||
const csrf = await createSession(reply, user.id);
|
||||
return reply.send({ role: user.role, email, csrfToken: csrf });
|
||||
});
|
||||
|
||||
app.post("/api/auth/logout", async (req, reply) => {
|
||||
const user = await authed(req, reply, true);
|
||||
if (!user) return reply;
|
||||
const token = parseCookies(req.headers.cookie)[COOKIE] ?? "";
|
||||
await db.query("DELETE FROM sessions WHERE token_hash = $1", [hashToken(token)]);
|
||||
reply.header("set-cookie", cookieHeader("", 0));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
app.get("/api/session", async (req, reply) => {
|
||||
const user = await authed(req, reply, false);
|
||||
if (!user) return reply;
|
||||
return reply.send({ email: user.email, role: user.role, orgId: user.orgId, csrfToken: user.csrf });
|
||||
});
|
||||
|
||||
app.post("/api/org/operators", async (req, reply) => {
|
||||
const user = await authed(req, reply, true);
|
||||
if (!user) return reply;
|
||||
if (user.role !== "org_admin" || !user.orgId) return fail(reply, 403, "forbidden");
|
||||
const b = body(req);
|
||||
const email = typeof b.email === "string" ? normalizeEmail(b.email) : "";
|
||||
if (!validEmail(email) || !validPassword(b.password)) return fail(reply, 400, "invalid_input");
|
||||
try {
|
||||
await db.query("INSERT INTO users (id, email, password_hash, role, org_id) VALUES ($1, $2, $3, 'operator', $4)", [
|
||||
randomUUID(),
|
||||
email,
|
||||
await hashPassword(b.password),
|
||||
user.orgId,
|
||||
]);
|
||||
} catch (err) {
|
||||
if (isUniqueViolation(err)) return fail(reply, 409, "email_taken");
|
||||
throw err;
|
||||
}
|
||||
return reply.code(201).send({ email, role: "operator" });
|
||||
});
|
||||
|
||||
app.delete("/api/account", async (req, reply) => {
|
||||
const user = await authed(req, reply, true);
|
||||
if (!user) return reply;
|
||||
const password = typeof body(req).password === "string" ? (body(req).password as string) : "";
|
||||
const r = await db.query<{ password_hash: string }>("SELECT password_hash FROM users WHERE id = $1", [user.id]);
|
||||
if (!(await checkPassword(r.rows[0]?.password_hash ?? null, password))) {
|
||||
return fail(reply, 401, "invalid_credentials");
|
||||
}
|
||||
const result = await db.tx(async (tx) => {
|
||||
if (user.orgId) {
|
||||
const others = await tx.query<{ role: Role }>("SELECT role FROM users WHERE org_id = $1 AND id <> $2", [
|
||||
user.orgId,
|
||||
user.id,
|
||||
]);
|
||||
if (user.role === "org_admin" && others.rows.length > 0) return "org_has_members" as const;
|
||||
await tx.query("DELETE FROM users WHERE id = $1", [user.id]);
|
||||
if (others.rows.length === 0) await tx.query("DELETE FROM organizations WHERE id = $1", [user.orgId]);
|
||||
} else {
|
||||
await tx.query("DELETE FROM users WHERE id = $1", [user.id]);
|
||||
}
|
||||
return "ok" as const;
|
||||
});
|
||||
if (result === "org_has_members") return fail(reply, 409, "org_has_members");
|
||||
reply.header("set-cookie", cookieHeader("", 0));
|
||||
return reply.code(204).send();
|
||||
});
|
||||
}
|
||||
34
src/modules/accounts/rate-limit.ts
Normal file
34
src/modules/accounts/rate-limit.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/** Счётчики в памяти процесса: окно windowMs, ключи не пишутся ни в БД, ни в логи. */
|
||||
export class RateLimiter {
|
||||
private readonly hits = new Map<string, number[]>();
|
||||
private readonly max: number;
|
||||
private readonly windowMs: number;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(max: number, windowMs = 15 * 60 * 1000, now: () => number = Date.now) {
|
||||
this.max = max;
|
||||
this.windowMs = windowMs;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
private recent(key: string): number[] {
|
||||
const cutoff = this.now() - this.windowMs;
|
||||
const list = (this.hits.get(key) ?? []).filter((t) => t > cutoff);
|
||||
if (list.length) this.hits.set(key, list);
|
||||
else this.hits.delete(key);
|
||||
return list;
|
||||
}
|
||||
|
||||
/** true, если лимит уже исчерпан. */
|
||||
blocked(key: string): boolean {
|
||||
return this.recent(key).length >= this.max;
|
||||
}
|
||||
|
||||
hit(key: string): void {
|
||||
this.hits.set(key, [...this.recent(key), this.now()]);
|
||||
}
|
||||
|
||||
reset(key: string): void {
|
||||
this.hits.delete(key);
|
||||
}
|
||||
}
|
||||
28
src/modules/accounts/security.ts
Normal file
28
src/modules/accounts/security.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { hash, verify } from "@node-rs/argon2";
|
||||
|
||||
// argon2id (algorithm: 2), параметры OWASP: m=19 МиБ, t=2, p=1.
|
||||
const ARGON = { algorithm: 2, memoryCost: 19456, timeCost: 2, parallelism: 1 } as const;
|
||||
|
||||
export const hashPassword = (password: string): Promise<string> => hash(password, ARGON);
|
||||
|
||||
let dummyHash: Promise<string> | undefined;
|
||||
/** Проверка пароля; для несуществующего пользователя (hash=null) тратит то же время на фиктивном хэше. */
|
||||
export async function checkPassword(storedHash: string | null, password: string): Promise<boolean> {
|
||||
dummyHash ??= hashPassword("dummy-password-for-timing");
|
||||
const h = storedHash ?? (await dummyHash);
|
||||
try {
|
||||
const ok = await verify(h, password);
|
||||
return ok && storedHash !== null;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export const newToken = (): string => randomBytes(32).toString("base64url");
|
||||
export const hashToken = (token: string): Buffer => createHash("sha256").update(token).digest();
|
||||
|
||||
export const EMAIL_RE = /^[^\s@]{1,64}@[^\s@.]+(\.[^\s@.]+)+$/;
|
||||
export const normalizeEmail = (raw: string): string => raw.trim().toLowerCase();
|
||||
export const validEmail = (email: string): boolean => email.length <= 254 && EMAIL_RE.test(email);
|
||||
export const validPassword = (p: unknown): p is string => typeof p === "string" && p.length >= 10 && p.length <= 128;
|
||||
225
test/accounts.test.ts
Normal file
225
test/accounts.test.ts
Normal file
@ -0,0 +1,225 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.ts";
|
||||
import { purgeExpiredSessions, SESSION_TTL_MS } from "../src/modules/accounts/index.ts";
|
||||
import { createTestDb } from "./helpers/db.ts";
|
||||
|
||||
type TestDb = Awaited<ReturnType<typeof createTestDb>>;
|
||||
let app: FastifyInstance;
|
||||
let db: TestDb;
|
||||
let clock = Date.now();
|
||||
|
||||
beforeEach(async () => {
|
||||
clock = Date.now();
|
||||
db = await createTestDb();
|
||||
app = await buildApp({ db, accounts: { now: () => clock } });
|
||||
});
|
||||
afterEach(async () => app.close());
|
||||
|
||||
const PASS = "correct-horse-9";
|
||||
const JSON_H = { "content-type": "application/json" };
|
||||
|
||||
const post = (url: string, payload: unknown, headers: Record<string, string> = {}) =>
|
||||
app.inject({ method: "POST", url, payload: payload as object, headers: { ...JSON_H, ...headers } });
|
||||
|
||||
interface Auth { cookie: string; csrf: string }
|
||||
function authOf(res: Awaited<ReturnType<typeof post>>): Auth {
|
||||
const raw = String(res.headers["set-cookie"]);
|
||||
return { cookie: raw.split(";")[0] ?? "", csrf: (res.json() as { csrfToken: string }).csrfToken };
|
||||
}
|
||||
const authHeaders = (a: Auth) => ({ cookie: a.cookie, "x-csrf-token": a.csrf });
|
||||
|
||||
async function registerBuyer(email = "anna@example.com"): Promise<Auth> {
|
||||
const res = await post("/api/auth/register", { email, password: PASS });
|
||||
expect(res.statusCode).toBe(201);
|
||||
return authOf(res);
|
||||
}
|
||||
async function registerOrg(email = "boss@corp.ru"): Promise<Auth> {
|
||||
const res = await post("/api/auth/register-org", { orgName: "Корп", email, password: PASS });
|
||||
expect(res.statusCode).toBe(201);
|
||||
return authOf(res);
|
||||
}
|
||||
const count = async (sql: string, params: unknown[] = []) => (await db.query(sql, params)).rows.length;
|
||||
|
||||
describe("Requirement: Модель ролей", () => {
|
||||
it("Scenario: Дубликат email", async () => {
|
||||
await registerBuyer("anna@example.com");
|
||||
const res = await post("/api/auth/register", { email: "Anna@Example.com", password: PASS });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toEqual({ error: "email_taken" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Регистрация", () => {
|
||||
it("Scenario: Регистрация покупателя", async () => {
|
||||
const res = await post("/api/auth/register", { email: "anna@example.com", password: PASS });
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json()).toMatchObject({ role: "buyer", csrfToken: expect.any(String) });
|
||||
const cookie = String(res.headers["set-cookie"]);
|
||||
expect(cookie).toMatch(/^sid=/);
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
expect(cookie).toContain("SameSite=Lax");
|
||||
const u = await db.query<{ password_hash: string }>("SELECT password_hash FROM users");
|
||||
expect(u.rows[0]?.password_hash.startsWith("$argon2id$")).toBe(true);
|
||||
});
|
||||
|
||||
it("Scenario: Регистрация организации", async () => {
|
||||
const res = await post("/api/auth/register-org", { orgName: "Корп", email: "boss@corp.ru", password: PASS });
|
||||
expect(res.statusCode).toBe(201);
|
||||
expect(res.json()).toMatchObject({ role: "org_admin" });
|
||||
const r = await db.query<{ name: string; role: string }>(
|
||||
"SELECT o.name, u.role FROM users u JOIN organizations o ON o.id = u.org_id",
|
||||
);
|
||||
expect(r.rows).toEqual([{ name: "Корп", role: "org_admin" }]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["not-an-email", "correct-horse-9"],
|
||||
["anna@example.com", "short"],
|
||||
])("Scenario Outline: Невалидные данные регистрации (%s / %s)", async (email, password) => {
|
||||
const res = await post("/api/auth/register", { email, password });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json()).toEqual({ error: "invalid_input" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Вход и выход", () => {
|
||||
it("Scenario: Успешный вход", async () => {
|
||||
await registerBuyer();
|
||||
const res = await post("/api/auth/login", { email: "anna@example.com", password: PASS });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toMatchObject({ role: "buyer", csrfToken: expect.any(String) });
|
||||
const session = await app.inject({ method: "GET", url: "/api/session", headers: { cookie: authOf(res).cookie } });
|
||||
expect(session.json()).toMatchObject({ email: "anna@example.com" });
|
||||
const stored = await db.query<{ token_hash: Uint8Array }>("SELECT token_hash FROM sessions");
|
||||
const token = authOf(res).cookie.slice("sid=".length);
|
||||
expect(stored.rows.some((r) => Buffer.from(r.token_hash).equals(createHash("sha256").update(token).digest()))).toBe(true);
|
||||
});
|
||||
|
||||
it("Scenario: Неверный пароль и неизвестный email", async () => {
|
||||
await registerBuyer();
|
||||
const a = await post("/api/auth/login", { email: "anna@example.com", password: "wrong-password-1" });
|
||||
const b = await post("/api/auth/login", { email: "nobody@example.com", password: "wrong-password-1" });
|
||||
expect(a.statusCode).toBe(401);
|
||||
expect(b.statusCode).toBe(401);
|
||||
expect(a.body).toBe(b.body);
|
||||
expect(a.json()).toEqual({ error: "invalid_credentials" });
|
||||
});
|
||||
|
||||
it("Scenario: Выход", async () => {
|
||||
const auth = await registerBuyer();
|
||||
const out = await app.inject({ method: "POST", url: "/api/auth/logout", headers: authHeaders(auth) });
|
||||
expect(out.statusCode).toBe(204);
|
||||
const session = await app.inject({ method: "GET", url: "/api/session", headers: { cookie: auth.cookie } });
|
||||
expect(session.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("Scenario: Истёкшая сессия", async () => {
|
||||
const auth = await registerBuyer();
|
||||
clock += SESSION_TTL_MS + 1000;
|
||||
const session = await app.inject({ method: "GET", url: "/api/session", headers: { cookie: auth.cookie } });
|
||||
expect(session.statusCode).toBe(401);
|
||||
expect(session.json()).toEqual({ error: "unauthenticated" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: CSRF-защита", () => {
|
||||
it("Scenario: Нет CSRF-токена", async () => {
|
||||
const auth = await registerBuyer();
|
||||
const res = await app.inject({ method: "POST", url: "/api/auth/logout", headers: { cookie: auth.cookie } });
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json()).toEqual({ error: "csrf_failed" });
|
||||
const session = await app.inject({ method: "GET", url: "/api/session", headers: { cookie: auth.cookie } });
|
||||
expect(session.statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("Scenario: Чужой Origin", async () => {
|
||||
await registerBuyer();
|
||||
const res = await post(
|
||||
"/api/auth/login",
|
||||
{ email: "anna@example.com", password: PASS },
|
||||
{ origin: "https://evil.example", host: "app.example" },
|
||||
);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json()).toEqual({ error: "csrf_failed" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Ограничение частоты", () => {
|
||||
it("Scenario: Перебор пароля", async () => {
|
||||
await registerBuyer();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const bad = await post("/api/auth/login", { email: "anna@example.com", password: "wrong-password-1" });
|
||||
expect(bad.statusCode).toBe(401);
|
||||
}
|
||||
const res = await post("/api/auth/login", { email: "anna@example.com", password: PASS });
|
||||
expect(res.statusCode).toBe(429);
|
||||
expect(res.json()).toEqual({ error: "rate_limited" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Операторы организации", () => {
|
||||
it("Scenario: Админ заводит оператора", async () => {
|
||||
const admin = await registerOrg();
|
||||
const res = await post("/api/org/operators", { email: "op@corp.ru", password: PASS }, authHeaders(admin));
|
||||
expect(res.statusCode).toBe(201);
|
||||
const r = await db.query<{ role: string; name: string }>(
|
||||
"SELECT u.role, o.name FROM users u JOIN organizations o ON o.id = u.org_id WHERE u.email = 'op@corp.ru'",
|
||||
);
|
||||
expect(r.rows).toEqual([{ role: "operator", name: "Корп" }]);
|
||||
});
|
||||
|
||||
it("Scenario: Покупатель не может создавать операторов", async () => {
|
||||
const buyer = await registerBuyer();
|
||||
const res = await post("/api/org/operators", { email: "op@corp.ru", password: PASS }, authHeaders(buyer));
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json()).toEqual({ error: "forbidden" });
|
||||
});
|
||||
});
|
||||
|
||||
const del = (auth: Auth, password: string) =>
|
||||
app.inject({ method: "DELETE", url: "/api/account", payload: { password }, headers: { ...JSON_H, ...authHeaders(auth) } });
|
||||
|
||||
describe("Requirement: Минимизация ПДн и удаление аккаунта", () => {
|
||||
it("Scenario: Удаление аккаунта", async () => {
|
||||
const auth = await registerBuyer();
|
||||
const res = await del(auth, PASS);
|
||||
expect(res.statusCode).toBe(204);
|
||||
expect(await count("SELECT 1 FROM users")).toBe(0);
|
||||
expect(await count("SELECT 1 FROM sessions")).toBe(0);
|
||||
const login = await post("/api/auth/login", { email: "anna@example.com", password: PASS });
|
||||
expect(login.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("Scenario: Неверный пароль при удалении", async () => {
|
||||
const auth = await registerBuyer();
|
||||
const res = await del(auth, "wrong-password-1");
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toEqual({ error: "invalid_credentials" });
|
||||
expect(await count("SELECT 1 FROM users")).toBe(1);
|
||||
});
|
||||
|
||||
it("Scenario: Админ с операторами не удаляется", async () => {
|
||||
const admin = await registerOrg();
|
||||
await post("/api/org/operators", { email: "op@corp.ru", password: PASS }, authHeaders(admin));
|
||||
const res = await del(admin, PASS);
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toEqual({ error: "org_has_members" });
|
||||
expect(await count("SELECT 1 FROM users")).toBe(2);
|
||||
});
|
||||
|
||||
it("Scenario: Единственный член организации удаляет и организацию", async () => {
|
||||
const admin = await registerOrg();
|
||||
expect((await del(admin, PASS)).statusCode).toBe(204);
|
||||
expect(await count("SELECT 1 FROM organizations")).toBe(0);
|
||||
});
|
||||
|
||||
it("Scenario: Очистка истёкших сессий", async () => {
|
||||
await registerBuyer();
|
||||
await db.query("UPDATE sessions SET expires_at = now() - interval '1 day'");
|
||||
await registerBuyer("bob@example.com");
|
||||
expect(await purgeExpiredSessions(db)).toBe(1);
|
||||
expect(await count("SELECT 1 FROM sessions")).toBe(1);
|
||||
});
|
||||
});
|
||||
61
test/database.test.ts
Normal file
61
test/database.test.ts
Normal file
@ -0,0 +1,61 @@
|
||||
import { mkdtemp, writeFile, cp } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.ts";
|
||||
import { MIGRATIONS_DIR, runMigrations } from "../src/db/migrate.ts";
|
||||
import { createTestDb } from "./helpers/db.ts";
|
||||
|
||||
let app: FastifyInstance | undefined;
|
||||
afterEach(async () => app?.close());
|
||||
|
||||
const names = async (db: Awaited<ReturnType<typeof createTestDb>>) =>
|
||||
(await db.query<{ name: string }>("SELECT name FROM schema_migrations ORDER BY name")).rows.map((r) => r.name);
|
||||
|
||||
describe("Requirement: Подключение к Postgres из окружения", () => {
|
||||
it("Scenario: БД не настроена", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "POST", url: "/api/auth/login", payload: {} });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.json()).toEqual({ error: "not_found" });
|
||||
expect((await app.inject({ method: "GET", url: "/healthz" })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("Scenario: БД настроена", async () => {
|
||||
app = await buildApp({ db: await createTestDb() });
|
||||
const res = await app.inject({ method: "GET", url: "/api/session" });
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.json()).toEqual({ error: "unauthenticated" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Миграции", () => {
|
||||
it("Scenario: Первое применение", async () => {
|
||||
const db = await createTestDb();
|
||||
const tables = (
|
||||
await db.query<{ table_name: string }>(
|
||||
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'",
|
||||
)
|
||||
).rows.map((r) => r.table_name);
|
||||
expect(tables).toEqual(expect.arrayContaining(["organizations", "users", "sessions"]));
|
||||
expect(await names(db)).toContain("0001_accounts");
|
||||
});
|
||||
|
||||
it("Scenario: Повторный запуск", async () => {
|
||||
const db = await createTestDb();
|
||||
expect(await runMigrations(db)).toEqual([]);
|
||||
expect(await names(db)).toEqual(["0001_accounts"]);
|
||||
});
|
||||
|
||||
it("Scenario: Ошибка в миграции", async () => {
|
||||
const db = await createTestDb();
|
||||
const dir = await mkdtemp(join(tmpdir(), "mig-"));
|
||||
await cp(MIGRATIONS_DIR, dir, { recursive: true });
|
||||
await writeFile(join(dir, "0002_broken.sql"), "CREATE TABLE ok_table (id int); SELECT * FROM no_such_table;");
|
||||
await expect(runMigrations(db, dir + "/")).rejects.toThrow();
|
||||
expect(await names(db)).toEqual(["0001_accounts"]);
|
||||
const r = await db.query("SELECT 1 FROM information_schema.tables WHERE table_name = 'ok_table'");
|
||||
expect(r.rows).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
28
test/helpers/db.ts
Normal file
28
test/helpers/db.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { PGlite } from "@electric-sql/pglite";
|
||||
import type { Db, TxDb } from "../../src/db/db.ts";
|
||||
import { runMigrations } from "../../src/db/migrate.ts";
|
||||
|
||||
/** Настоящий Postgres (WASM) в памяти: те же миграции, что на проде. */
|
||||
export async function createTestDb(migrate = true): Promise<TxDb & { pg: PGlite }> {
|
||||
const pg = new PGlite();
|
||||
const wrap = (c: { query: PGlite["query"]; exec: PGlite["exec"] }): Db => ({
|
||||
query: async (sql, params) => {
|
||||
// Без параметров допустим многооператорный SQL (миграции), как у настоящего pg.
|
||||
if (!params || params.length === 0) {
|
||||
const rs = await c.exec(sql);
|
||||
const last = rs[rs.length - 1];
|
||||
return { rows: (last?.rows ?? []) as never[], rowCount: last?.affectedRows ?? last?.rows.length ?? 0 };
|
||||
}
|
||||
const r = await c.query(sql, params as unknown[]);
|
||||
return { rows: r.rows as never[], rowCount: r.affectedRows ?? r.rows.length };
|
||||
},
|
||||
});
|
||||
const db: TxDb & { pg: PGlite } = {
|
||||
pg,
|
||||
...wrap(pg),
|
||||
tx: (fn) => pg.transaction((t) => fn(wrap(t as never))),
|
||||
close: () => pg.close(),
|
||||
};
|
||||
if (migrate) await runMigrations(db);
|
||||
return db;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user