diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 6bed56b..8eeae14 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -4,9 +4,9 @@ Целевая оценка (3/4/5): 4 Трек 5, если заявлен: не заявлен -Что реализовано и что перенесено: из lab1 перенесены NestJS + Fastify API, валидация, формат ошибок, курсоры, Dockerfile и e2e-тесты. Хранилище заменено на PostgreSQL 17 через Prisma 6.1 (2 версионируемые миграции, PK/FK/UNIQUE/CHECK, индекс истории `(chat_id, created_at, id)`, keyset-пагинация через `$queryRaw`, атомарное создание чата в `$transaction`). Аутентификация: Argon2id-пароли, вход по Basic, opaque Bearer-токен (256 бит, в БД — sha256), TTL `SESSION_TTL_SECONDS`, logout. Redis 7.4 — read-through кэш сессий (TTL ≤ 60 с, tombstone при logout, обход при отказе), источник истины — PostgreSQL. Compose со secrets-init, migrate, именованными volumes, restart-hook и сервисом tools для проверок только через Docker. Собственные тесты: 63 (в т. ч. expiry, отказ Redis/БД, гонка регистрации, rollback). +Что реализовано и что перенесено: из lab1 перенесены NestJS + Fastify API, валидация, формат ошибок, курсоры, Dockerfile и e2e-тесты. Хранилище заменено на PostgreSQL 17 через Prisma 6.1 (2 версионируемые миграции, PK/FK/UNIQUE/CHECK, индекс истории `(chat_id, created_at, id)`, keyset-пагинация через `$queryRaw`, атомарное создание чата в `$transaction`). Аутентификация: Argon2id-пароли, вход по Basic, opaque Bearer-токен (256 бит, в БД — sha256), TTL `SESSION_TTL_SECONDS`, logout. Redis 7.4 — read-through кэш сессий (TTL ≤ 60 с, tombstone при logout, обход при отказе), источник истины — PostgreSQL. Compose со secrets-init, migrate, именованными volumes, restart-hook и сервисом tools для проверок только через Docker. Собственные тесты: 65 (в т. ч. expiry, отказ Redis/БД, гонка регистрации, rollback, валидность примеров Swagger). Swagger UI на `/docs` по контракту с примерами. Команды запуска из чистого clone: `docker compose up -d --build --wait`, затем `docker compose run --rm tools make test`, `docker compose run --rm tools make test-persistence ACTION_SCRIPT=scripts/restart.sh`, `docker compose -f compose.test.yaml run --rm --build tests`. Подробности в REPORT.md. -Результаты проверок и ссылка на REPORT.md: `make check`, `make test`, `make test-persistence`, 63 собственных теста — PASS; EXPLAIN на 50 000 сообщений; вывод в `evidence/`, таблица критериев в [REPORT.md](../REPORT.md). +Результаты проверок и ссылка на REPORT.md: `make check`, `make test`, `make test-persistence`, 65 собственных тестов — PASS; EXPLAIN на 50 000 сообщений; вывод в `evidence/`, таблица критериев в [REPORT.md](../REPORT.md). Ограничения / известные ошибки: нет репликации и backup PostgreSQL; logout и tombstone в Redis не атомарны (окно до 60 с только при сетевом разрыве с Redis); порядок `created_at` при конкурентной записи описан в REPORT.md; нет rate limiting входа; HTTP без TLS. Источники и использование ИИ: документация NestJS, Fastify, Prisma, PostgreSQL, Redis, OWASP Password Storage, RFC 7617; библиотеки `@prisma/client`, `argon2`, `ioredis`, `class-validator`, `jest`/`supertest`. ИИ-ассистент использовался как парный программист: генерация кода, тестов и отчёта по моим архитектурным решениям с последующим ревью и переработкой; выбор стека, модель данных, роль Redis и границы транзакций определены мной; все проверки воспроизведены мной на своём стенде. diff --git a/Dockerfile b/Dockerfile index afbfd17..e433a41 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,6 +18,7 @@ COPY src ./src RUN npm run build FROM build AS test +COPY contracts/openapi.json ./contracts/openapi.json COPY test ./test CMD ["npm", "test"] @@ -32,6 +33,7 @@ ENV NODE_ENV=production COPY package.json ./ COPY --from=prod-deps /app/node_modules ./node_modules COPY --from=build /app/dist ./dist +COPY contracts/openapi.json ./contracts/openapi.json USER node EXPOSE 8080 diff --git a/REPORT.md b/REPORT.md index 08ed05d..5e8bffc 100644 --- a/REPORT.md +++ b/REPORT.md @@ -43,6 +43,7 @@ docker compose down -v - **Секреты** создаёт one-shot сервис `secrets-init` при первом запуске: случайные пароли PostgreSQL и Redis (24 байта из `/dev/urandom`) и строки подключения кладутся в именованный volume `secrets`, который монтируется read-only в `/run/secrets`. Уже созданные пароли не перезаписываются. Действий оператора не требуется; секреты не попадают в Git, образы и логи. - **Миграции**: сервис `migrate` выполняет `prisma migrate deploy` при каждом `up`. Повторный запуск безопасен — применённые миграции записаны в `_prisma_migrations` (`docker compose run --rm migrate` → `No pending migrations to apply`). - API опубликован только на `127.0.0.1:8080`; PostgreSQL и Redis наружу не публикуются. +- **Swagger UI**: http://localhost:8080/docs (документ — http://localhost:8080/docs-json). Это обязательный контракт `contracts/openapi.json` без изменений, который при старте API дополняется в памяти пошаговой инструкцией и 57 именованными примерами запросов и ответов (`src/docs/examples.ts`); Authorize поддерживает basicAuth (вход) и bearerAuth (остальное). Все примеры проверяются по JSON Schema контракта в `test/docs.e2e-spec.ts`, поэтому документация не может разойтись с контрактом. ## Архитектура и решения @@ -133,7 +134,7 @@ CHECK-ограничения дописаны в SQL миграции вручн | **4**: автотесты logout и неверного пароля | `auth.e2e-spec.ts` | `204` → `401`; неверный пароль и неизвестный пользователь — одинаковый `401` с `WWW-Authenticate: Basic` | [evidence/tests.txt](evidence/tests.txt) | | **4**: недоступность Redis | автотест с `redis://127.0.0.1:1`; стенд: `docker compose stop redis` + smoke | вход, Bearer, logout работают через PostgreSQL; smoke `PASS` | [evidence/tests.txt](evidence/tests.txt), [evidence/failures.txt](evidence/failures.txt) §1 | | **4**: недоступность БД | автотест с недостижимым `DATABASE_URL`; стенд: `docker compose stop postgres` | `/health/ready` и `/chats` с токеном → `503 unavailable` без деталей; аноним → `401` | [evidence/tests.txt](evidence/tests.txt), [evidence/failures.txt](evidence/failures.txt) §2 | -| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | `Tests: 63 passed, 63 total` | [evidence/tests.txt](evidence/tests.txt) | +| Собственные тесты | `docker compose -f compose.test.yaml run --rm --build tests` | `Tests: 65 passed, 65 total` | [evidence/tests.txt](evidence/tests.txt) | ## Эксперименты и отказы diff --git a/package-lock.json b/package-lock.json index 48ce183..5bfc603 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,11 @@ "version": "1.0.0", "license": "UNLICENSED", "dependencies": { + "@fastify/static": "7.0.4", "@nestjs/common": "^10.4.15", "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", + "@nestjs/swagger": "7.4.2", "@prisma/client": "6.1.0", "argon2": "0.41.1", "class-transformer": "^0.5.1", @@ -29,6 +31,7 @@ "@types/supertest": "^6.0.2", "@typescript-eslint/eslint-plugin": "^8.18.1", "@typescript-eslint/parser": "^8.18.1", + "ajv": "8.12.0", "eslint": "^8.57.1", "jest": "^29.7.0", "prisma": "6.1.0", @@ -890,6 +893,15 @@ "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, + "node_modules/@fastify/accept-negotiator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@fastify/accept-negotiator/-/accept-negotiator-1.1.0.tgz", + "integrity": "sha512-OIHZrb2ImZ7XG85HXOONLcJWGosv7sIvM2ifAPQVhg9Lv7qdmMBNVaai4QTdyuaqbKM5eO6sLSQOYI7wEQeCJQ==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, "node_modules/@fastify/ajv-compiler": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/@fastify/ajv-compiler/-/ajv-compiler-3.6.0.tgz", @@ -963,6 +975,45 @@ "integrity": "sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==", "license": "MIT" }, + "node_modules/@fastify/send": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/send/-/send-2.1.0.tgz", + "integrity": "sha512-yNYiY6sDkexoJR0D8IDy3aRP3+L4wdqCpvx5WP+VtEU58sn7USmKynBzDQex5X42Zzvw2gNzzYgP90UfWShLFA==", + "license": "MIT", + "dependencies": { + "@lukeed/ms": "^2.0.1", + "escape-html": "~1.0.3", + "fast-decode-uri-component": "^1.0.1", + "http-errors": "2.0.0", + "mime": "^3.0.0" + } + }, + "node_modules/@fastify/send/node_modules/mime": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-3.0.0.tgz", + "integrity": "sha512-jSCU7/VB1loIWBZe14aEYHU/+1UMEHoaO7qxCOVJOw9GgH72VAWppxNcjU+x9a2k3GSIBXNKxXQFqRvvZ7vr3A==", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@fastify/static": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/@fastify/static/-/static-7.0.4.tgz", + "integrity": "sha512-p2uKtaf8BMOZWLs6wu+Ihg7bWNBdjNgCwDza4MJtTqg+5ovKmcbgbR9Xs5/smZ1YISfzKOCNYmZV8LaCj+eJ1Q==", + "license": "MIT", + "dependencies": { + "@fastify/accept-negotiator": "^1.0.0", + "@fastify/send": "^2.0.0", + "content-disposition": "^0.5.3", + "fastify-plugin": "^4.0.0", + "fastq": "^1.17.0", + "glob": "^10.3.4" + } + }, "node_modules/@humanwhocodes/config-array": { "version": "0.13.0", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", @@ -1042,7 +1093,6 @@ "version": "8.0.2", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "dev": true, "license": "ISC", "dependencies": { "string-width": "^5.1.2", @@ -1060,7 +1110,6 @@ "version": "6.3.0", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz", "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -1073,7 +1122,6 @@ "version": "6.2.3", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, "license": "MIT", "engines": { "node": ">=12" @@ -1086,14 +1134,12 @@ "version": "9.2.2", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, "license": "MIT" }, "node_modules/@isaacs/cliui/node_modules/string-width": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, "license": "MIT", "dependencies": { "eastasianwidth": "^0.2.0", @@ -1111,7 +1157,6 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^6.2.2" @@ -1127,7 +1172,6 @@ "version": "8.1.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^6.1.0", @@ -1686,6 +1730,21 @@ "node": ">=8" } }, + "node_modules/@lukeed/ms": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@lukeed/ms/-/ms-2.0.2.tgz", + "integrity": "sha512-9I2Zn6+NJLfaGoz9jN3lpwDgAYvfGeNYdbAIjJOqzs4Tpc+VU3Jqq4IofSUBKajiDS8k9fZIg18/z13mpk1bsA==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/@microsoft/tsdoc": { + "version": "0.15.1", + "resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.15.1.tgz", + "integrity": "sha512-4aErSrCR/On/e5G2hDP0wjooqDdauzEbIq8hIkIe5pXV0rtWJZvdCEKL0ykZxex+IxIwBp0eGeV48hQN07dXtw==", + "license": "MIT" + }, "node_modules/@nestjs/cli": { "version": "10.4.9", "resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-10.4.9.tgz", @@ -1892,6 +1951,26 @@ } } }, + "node_modules/@nestjs/mapped-types": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.0.5.tgz", + "integrity": "sha512-bSJv4pd6EY99NX9CjBIyn4TVDoSit82DUZlL4I3bqNfy5Gt+gXTa86i3I/i0iIV9P4hntcGM5GyO+FhZAhxtyg==", + "license": "MIT", + "peerDependencies": { + "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0", + "class-transformer": "^0.4.0 || ^0.5.0", + "class-validator": "^0.13.0 || ^0.14.0", + "reflect-metadata": "^0.1.12 || ^0.2.0" + }, + "peerDependenciesMeta": { + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, "node_modules/@nestjs/platform-fastify": { "version": "10.4.22", "resolved": "https://registry.npmjs.org/@nestjs/platform-fastify/-/platform-fastify-10.4.22.tgz", @@ -1949,6 +2028,57 @@ "dev": true, "license": "MIT" }, + "node_modules/@nestjs/swagger": { + "version": "7.4.2", + "resolved": "https://registry.npmjs.org/@nestjs/swagger/-/swagger-7.4.2.tgz", + "integrity": "sha512-Mu6TEn1M/owIvAx2B4DUQObQXqo2028R2s9rSZ/hJEgBK95+doTwS0DjmVA2wTeZTyVtXOoN7CsoM5pONBzvKQ==", + "license": "MIT", + "dependencies": { + "@microsoft/tsdoc": "^0.15.0", + "@nestjs/mapped-types": "2.0.5", + "js-yaml": "4.1.0", + "lodash": "4.17.21", + "path-to-regexp": "3.3.0", + "swagger-ui-dist": "5.17.14" + }, + "peerDependencies": { + "@fastify/static": "^6.0.0 || ^7.0.0", + "@nestjs/common": "^9.0.0 || ^10.0.0", + "@nestjs/core": "^9.0.0 || ^10.0.0", + "class-transformer": "*", + "class-validator": "*", + "reflect-metadata": "^0.1.12 || ^0.2.0" + }, + "peerDependenciesMeta": { + "@fastify/static": { + "optional": true + }, + "class-transformer": { + "optional": true + }, + "class-validator": { + "optional": true + } + } + }, + "node_modules/@nestjs/swagger/node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/@nestjs/swagger/node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "license": "MIT" + }, "node_modules/@nestjs/testing": { "version": "10.4.22", "resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-10.4.22.tgz", @@ -2075,7 +2205,6 @@ "version": "0.11.0", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", - "dev": true, "license": "MIT", "optional": true, "engines": { @@ -2982,7 +3111,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -3056,7 +3184,6 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, "license": "Python-2.0" }, "node_modules/array-timsort": { @@ -3811,6 +3938,18 @@ "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==", "license": "MIT" }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/convert-source-map": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", @@ -3915,7 +4054,6 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -4025,6 +4163,15 @@ "node": ">=0.10" } }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -4098,7 +4245,6 @@ "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "dev": true, "license": "MIT" }, "node_modules/electron-to-chromium": { @@ -4125,7 +4271,6 @@ "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, "license": "MIT" }, "node_modules/enhanced-resolve": { @@ -4219,6 +4364,12 @@ "node": ">=6" } }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, "node_modules/escape-string-regexp": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", @@ -4872,7 +5023,6 @@ "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", - "dev": true, "license": "ISC", "dependencies": { "cross-spawn": "^7.0.6", @@ -5130,7 +5280,6 @@ "resolved": "https://registry.npmjs.org/glob/-/glob-10.4.5.tgz", "integrity": "sha512-7Bv8RF0k6xjo7d4A/PxYLbUCfb6c+Vpd2/mB2yRDlew7Jb5hEXiCD9ibfO7wpk8i4sevK6DFny9h7EYbM3/sHg==", "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, "license": "ISC", "dependencies": { "foreground-child": "^3.1.0", @@ -5171,14 +5320,12 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, "license": "MIT" }, "node_modules/glob/node_modules/brace-expansion": { "version": "2.1.7", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", - "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" @@ -5188,7 +5335,6 @@ "version": "9.0.9", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "dev": true, "license": "ISC", "dependencies": { "brace-expansion": "^2.0.2" @@ -5356,6 +5502,22 @@ "dev": true, "license": "MIT" }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -5472,7 +5634,6 @@ "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, "license": "ISC" }, "node_modules/inquirer": { @@ -5585,7 +5746,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -5674,7 +5834,6 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, "license": "ISC" }, "node_modules/istanbul-lib-coverage": { @@ -5771,7 +5930,6 @@ "version": "3.4.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz", "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==", - "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "@isaacs/cliui": "^8.0.2" @@ -7164,7 +7322,6 @@ "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" @@ -7455,7 +7612,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", - "dev": true, "license": "BlueOak-1.0.0" }, "node_modules/parent-module": { @@ -7514,7 +7670,6 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -7531,7 +7686,6 @@ "version": "1.11.1", "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz", "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==", - "dev": true, "license": "BlueOak-1.0.0", "dependencies": { "lru-cache": "^10.2.0", @@ -7548,7 +7702,6 @@ "version": "10.4.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, "license": "ISC" }, "node_modules/path-to-regexp": { @@ -8235,7 +8388,6 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, "funding": [ { "type": "github", @@ -8372,11 +8524,16 @@ "node": ">= 0.4" } }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -8389,7 +8546,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -8475,7 +8631,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, "license": "ISC", "engines": { "node": ">=14" @@ -8586,6 +8741,15 @@ "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", "license": "MIT" }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -8614,7 +8778,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -8630,7 +8793,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, "license": "MIT", "dependencies": { "emoji-regex": "^8.0.0", @@ -8645,7 +8807,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -8659,7 +8820,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, "license": "MIT", "dependencies": { "ansi-regex": "^5.0.1" @@ -8778,6 +8938,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/swagger-ui-dist": { + "version": "5.17.14", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.17.14.tgz", + "integrity": "sha512-CVbSfaLpstV65OnSjbXfVd6Sta3q3F7Cj/yYuvHMp1P90LztOLs6PfUnKEVAeiIVQt9u2SaPwv0LiH/OyMjHRw==", + "license": "Apache-2.0" + }, "node_modules/symbol-observable": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-4.0.0.tgz", @@ -9155,6 +9321,15 @@ "node": ">=20" } }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, "node_modules/token-types": { "version": "6.1.2", "resolved": "https://registry.npmjs.org/token-types/-/token-types-6.1.2.tgz", @@ -9769,7 +9944,6 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -9818,7 +9992,6 @@ "version": "7.0.0", "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, "license": "MIT", "dependencies": { "ansi-styles": "^4.0.0", diff --git a/package.json b/package.json index f1c0aad..d3f972d 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,11 @@ "test:watch": "jest --config ./test/jest-e2e.json --watch" }, "dependencies": { + "@fastify/static": "7.0.4", "@nestjs/common": "^10.4.15", "@nestjs/core": "^10.4.15", "@nestjs/platform-fastify": "^10.4.15", + "@nestjs/swagger": "7.4.2", "@prisma/client": "6.1.0", "argon2": "0.41.1", "class-transformer": "^0.5.1", @@ -33,6 +35,7 @@ "@types/supertest": "^6.0.2", "@typescript-eslint/eslint-plugin": "^8.18.1", "@typescript-eslint/parser": "^8.18.1", + "ajv": "8.12.0", "eslint": "^8.57.1", "jest": "^29.7.0", "prisma": "6.1.0", diff --git a/scripts/probe.py b/scripts/probe.py index 05c18e1..4882453 100644 --- a/scripts/probe.py +++ b/scripts/probe.py @@ -16,7 +16,7 @@ def call(method, path, body=None, headers=None): content_type = {'Content-Type': 'application/json'} if data else {} request = urllib.request.Request(BASE + path, data=data, method=method, headers={**content_type, **(headers or {})}) try: - with urllib.request.urlopen(request, timeout=5) as response: + with urllib.request.urlopen(request, timeout=15) as response: return response.status, json.loads(response.read() or b'null') except urllib.error.HTTPError as error: return error.code, json.loads(error.read() or b'null') diff --git a/src/docs/examples.ts b/src/docs/examples.ts new file mode 100644 index 0000000..39a3baa --- /dev/null +++ b/src/docs/examples.ts @@ -0,0 +1,327 @@ +const ALICE_ID = '11111111-1111-4111-8111-111111111111'; +const BOB_ID = '22222222-2222-4222-8222-222222222222'; +const CHAT_ID = '33333333-3333-4333-8333-333333333333'; +const MESSAGE_ID = '44444444-4444-4444-8444-444444444444'; +const CURSOR = + 'eyJjaGF0SWQiOiIzMzMzMzMzMy0zMzMzLTQzMzMtODMzMy0zMzMzMzMzMzMzMzMiLCJpZCI6IjQ0NDQ0NDQ0LTQ0NDQtNDQ0NC04NDQ0LTQ0NDQ0NDQ0NDQ0NCJ9'; + +const ALICE = { + id: ALICE_ID, + username: 'alice', + display_name: 'Алиса', + created_at: '2026-09-01T12:00:00.000Z', +}; + +const CHAT = { + id: CHAT_ID, + title: 'Проект по ВНП', + member_ids: [ALICE_ID, BOB_ID], + created_at: '2026-09-01T12:01:00.000Z', +}; + +const MESSAGE = { + id: MESSAGE_ID, + chat_id: CHAT_ID, + sender_id: ALICE_ID, + text: 'Привет, Боб! 👋', + created_at: '2026-09-01T12:02:00.000Z', +}; + +export interface Example { + summary: string; + value: unknown; +} + +export interface OperationExamples { + request?: Record; + responses: Record>; +} + +function example(summary: string, value: unknown): Example { + return { summary, value }; +} + +function error(code: string, message: string): unknown { + return { + error: { + code, + message, + request_id: '9b2c6f1e-5d4a-4c3b-8a2f-1e0d9c8b7a6f', + }, + }; +} + +const UNAUTHORIZED = { + missing: example( + 'Нет/неверный/истёкший/отозванный Bearer-токен', + error('unauthorized', 'missing or invalid session'), + ), +}; + +const UNAVAILABLE = { + database: example( + 'PostgreSQL недоступен', + error('unavailable', 'database unavailable'), + ), +}; + +const CHAT_NOT_FOUND = { + notFound: example( + 'Чата нет или вызывающий не участник (не 403)', + error('not_found', 'chat not found'), + ), +}; + +const INVALID_CHAT_ID = example( + 'chat_id не UUID', + error('invalid_request', 'chatId must be a valid UUID'), +); + +export const GUIDE = ` +Учебный мессенджер, лабораторная 2: PostgreSQL, сессии, Redis-кэш сессий. +Документ — обязательный контракт \`contracts/openapi.json\`, дополненный примерами запросов и ответов. + +**Как пройти сценарий в Swagger UI** + +1. \`POST /api/v1/users\` — зарегистрируйте пользователей (примеры alice, bob, eve в списке Examples). Повторная регистрация того же username — 409, меняйте username. +2. **Authorize → basicAuth**: username и password из шага 1 → \`POST /api/v1/auth/sessions\` → скопируйте \`token\`. +3. **Authorize → bearerAuth**: вставьте token (без слова Bearer). Basic отправляется только на вход, остальные запросы идут с Bearer. +4. \`GET /api/v1/users/me\` — свой id; id второго участника — из ответа его регистрации. +5. \`POST /api/v1/chats\` с \`member_ids\` = [свой id, id собеседника] → \`chat_id\`. +6. \`POST /api/v1/chats/{chat_id}/messages\`, затем \`GET …/messages?limit=1\` и следующая страница с \`cursor\` = \`next_cursor\`. +7. Чтобы действовать от другого пользователя: Logout в Authorize, вход им и новый token. +8. \`DELETE /api/v1/auth/sessions/current\` — logout; тот же token дальше даёт 401. + +Сессия живёт \`SESSION_TTL_SECONDS\` (по умолчанию 3600 с). Пароль — 12–128 символов Unicode, двоеточие допустимо. +`; + +export const OPERATION_EXAMPLES: Record = { + 'GET /health/live': { + responses: { + '200': { ok: example('Процесс жив', { status: 'ok' }) }, + }, + }, + 'GET /health/ready': { + responses: { + '200': { + ok: example('PostgreSQL доступен (Redis не критичен)', { + status: 'ok', + }), + }, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/users': { + request: { + alice: example('Алиса', { + username: 'alice', + display_name: 'Алиса', + password: 'Alice-password-123', + }), + bob: example('Боб', { + username: 'bob', + display_name: 'Боб', + password: 'Bob-password-123', + }), + eve: example('Ева (посторонняя)', { + username: 'eve', + display_name: 'Ева', + password: 'Eve-password-123', + }), + colon: example('Пароль с двоеточием и эмодзи', { + username: 'carol', + display_name: 'Кэрол 🌸', + password: 'пароль:с:двоеточием🔑', + }), + }, + responses: { + '201': { created: example('Пользователь создан', ALICE) }, + '400': { + username: example( + 'username не соответствует [a-z0-9_]{3,32}', + error('invalid_request', 'username must match [a-z0-9_]{3,32}'), + ), + password: example( + 'password короче 12 символов', + error( + 'invalid_request', + 'password must be between 12 and 128 Unicode code points', + ), + ), + extra: example( + 'Лишнее поле в JSON', + error('invalid_request', 'property extra should not exist'), + ), + }, + '409': { + taken: example( + 'username уже занят', + error('conflict', 'username is already taken'), + ), + }, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/auth/sessions': { + responses: { + '201': { + created: example('Сессия создана', { + token: 'q8Hn3vXl0ZbJ7mWcY2sRkT5uPaE9dFgVhN1oLxI4w6A', + token_type: 'Bearer', + expires_at: '2026-09-01T13:00:00.000Z', + user: ALICE, + }), + }, + '401': { + invalid: example( + 'Неверный пароль, неизвестный пользователь или нет Basic — ответ одинаковый', + error('unauthorized', 'invalid credentials'), + ), + }, + '503': UNAVAILABLE, + }, + }, + 'DELETE /api/v1/auth/sessions/current': { + responses: { + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/users/me': { + responses: { + '200': { me: example('Текущий пользователь из сессии', ALICE) }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/chats': { + request: { + pair: example('Чат Алисы и Боба', { + title: CHAT.title, + member_ids: CHAT.member_ids, + }), + solo: example('Чат только с собой', { + title: 'Заметки', + member_ids: [ALICE_ID], + }), + }, + responses: { + '201': { created: example('Чат создан атомарно', CHAT) }, + '400': { + noCaller: example( + 'Вызывающий не в member_ids', + error('invalid_request', 'member_ids must include the caller'), + ), + unknown: example( + 'Неизвестный участник — транзакция откатывается', + error('invalid_request', 'member_ids contain an unknown user'), + ), + duplicate: example( + 'Дубликаты в member_ids', + error( + 'invalid_request', + "All member_ids's elements must be unique", + ), + ), + }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats': { + responses: { + '200': { + page: example('Страница чатов с продолжением', { + items: [CHAT], + next_cursor: 'eyJpZCI6IjMzMzMzMzMzLTMzMzMtNDMzMy04MzMzLTMzMzMzMzMzMzMzMyJ9', + }), + last: example('Последняя страница', { + items: [CHAT], + next_cursor: null, + }), + }, + '400': { + limit: example( + 'limit вне 1–100', + error('invalid_request', 'limit must be between 1 and 100'), + ), + cursor: example( + 'Испорченный или чужой cursor', + error('invalid_request', 'invalid cursor'), + ), + }, + '401': UNAUTHORIZED, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats/{chat_id}': { + responses: { + '200': { chat: example('Чат, где вызывающий — участник', CHAT) }, + '400': { chatId: INVALID_CHAT_ID }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '503': UNAVAILABLE, + }, + }, + 'POST /api/v1/chats/{chat_id}/messages': { + request: { + text: example('Обычное сообщение', { text: MESSAGE.text }), + long: example('Максимум — 4000 символов Unicode', { + text: 'Длинный текст…', + }), + }, + responses: { + '201': { + created: example('Отправитель берётся из сессии', MESSAGE), + }, + '400': { + blank: example( + 'Пустой или пробельный текст', + error( + 'invalid_request', + 'text must not be empty or whitespace-only', + ), + ), + sender: example( + 'sender_id в теле не принимается', + error('invalid_request', 'property sender_id should not exist'), + ), + chatId: INVALID_CHAT_ID, + }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '503': UNAVAILABLE, + }, + }, + 'GET /api/v1/chats/{chat_id}/messages': { + responses: { + '200': { + page: example('Страница истории (limit=1) с cursor', { + items: [MESSAGE], + next_cursor: CURSOR, + }), + last: example('Последняя страница', { + items: [MESSAGE], + next_cursor: null, + }), + }, + '400': { + otherChat: example( + 'cursor от другого чата', + error('invalid_request', 'cursor belongs to a different chat'), + ), + cursor: example( + 'Испорченный cursor или cursor несуществующего сообщения', + error('invalid_request', 'invalid cursor'), + ), + limit: example( + 'limit вне 1–100', + error('invalid_request', 'limit must be between 1 and 100'), + ), + }, + '401': UNAUTHORIZED, + '404': CHAT_NOT_FOUND, + '503': UNAVAILABLE, + }, + }, +}; diff --git a/src/docs/swagger.ts b/src/docs/swagger.ts new file mode 100644 index 0000000..e433fd9 --- /dev/null +++ b/src/docs/swagger.ts @@ -0,0 +1,43 @@ +import { NestFastifyApplication } from '@nestjs/platform-fastify'; +import { OpenAPIObject, SwaggerModule } from '@nestjs/swagger'; +import { readFileSync } from 'fs'; +import { join } from 'path'; +import { GUIDE, OPERATION_EXAMPLES } from './examples'; + +const CONTRACT_PATH = join(process.cwd(), 'contracts', 'openapi.json'); + +export function setupSwagger(app: NestFastifyApplication): void { + SwaggerModule.setup('docs', app, loadDocument(), { + customSiteTitle: 'Messenger lab2 API', + swaggerOptions: { + persistAuthorization: true, + displayRequestDuration: true, + tryItOutEnabled: true, + }, + }); +} + +export function loadDocument(): OpenAPIObject { + const document = JSON.parse(readFileSync(CONTRACT_PATH, 'utf8')); + document.info.description = GUIDE; + document.servers = [{ url: '/', description: 'Этот экземпляр API' }]; + for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) { + const [method, path] = key.split(' '); + const operation = document.paths[path]?.[method.toLowerCase()]; + if (!operation) { + throw new Error(`examples for unknown operation ${key}`); + } + if (examples.request) { + operation.requestBody.content['application/json'].examples = + examples.request; + } + for (const [status, named] of Object.entries(examples.responses)) { + const content = operation.responses[status]?.content; + if (!content) { + throw new Error(`examples for unknown response ${key} ${status}`); + } + content['application/json'].examples = named; + } + } + return document; +} diff --git a/src/main.ts b/src/main.ts index ddee64c..a71214b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -6,6 +6,7 @@ import { } from '@nestjs/platform-fastify'; import { AppModule } from './app.module'; import { configureApp } from './configure-app'; +import { setupSwagger } from './docs/swagger'; async function bootstrap(): Promise { const app = await NestFactory.create( @@ -17,6 +18,7 @@ async function bootstrap(): Promise { ); configureApp(app); + setupSwagger(app); app.enableShutdownHooks(); const host = process.env.APP_HOST ?? '0.0.0.0'; diff --git a/test/docs.e2e-spec.ts b/test/docs.e2e-spec.ts new file mode 100644 index 0000000..3066219 --- /dev/null +++ b/test/docs.e2e-spec.ts @@ -0,0 +1,69 @@ +import { INestApplication } from '@nestjs/common'; +import Ajv2020 from 'ajv/dist/2020'; +import request from 'supertest'; +import { OPERATION_EXAMPLES } from '../src/docs/examples'; +import { loadDocument, setupSwagger } from '../src/docs/swagger'; +import { createTestApp } from './helpers'; + +const CONTRACT_ID = 'https://contract.local/openapi.json'; + +describe('Swagger UI и примеры (e2e)', () => { + let app: INestApplication; + let server: any; + + beforeAll(async () => { + ({ app, server } = await createTestApp({}, setupSwagger)); + }); + + afterAll(async () => { + await app.close(); + }); + + it('отдаёт Swagger UI и документ контракта со всеми путями', async () => { + await request(server).get('/docs').expect(200); + const res = await request(server).get('/docs-json').expect(200); + expect(res.body.openapi).toBe('3.1.0'); + expect(Object.keys(res.body.paths)).toEqual( + Object.keys(loadDocument().paths), + ); + expect(res.body.components.securitySchemes).toHaveProperty('basicAuth'); + expect(res.body.components.securitySchemes).toHaveProperty('bearerAuth'); + }); + + it('каждый пример запроса и ответа проходит JSON Schema контракта', () => { + const document: any = loadDocument(); + const ajv = new Ajv2020({ strict: false, validateFormats: false }); + ajv.addSchema(document, CONTRACT_ID); + let checked = 0; + for (const [key, examples] of Object.entries(OPERATION_EXAMPLES)) { + const [method, path] = key.split(' '); + const operation = document.paths[path][method.toLowerCase()]; + const targets: [string, any, Record][] = []; + if (examples.request) { + targets.push([ + 'request', + operation.requestBody.content['application/json'].schema, + examples.request, + ]); + } + for (const [status, named] of Object.entries(examples.responses)) { + targets.push([ + status, + operation.responses[status].content['application/json'].schema, + named, + ]); + } + for (const [where, schema, named] of targets) { + const validate = ajv.compile({ $ref: CONTRACT_ID + schema.$ref }); + for (const [name, example] of Object.entries(named)) { + const valid = validate(example.value); + expect({ key, where, name, valid, errors: validate.errors }).toEqual( + { key, where, name, valid: true, errors: null }, + ); + checked++; + } + } + } + expect(checked).toBeGreaterThan(40); + }); +}); diff --git a/test/helpers.ts b/test/helpers.ts index 676d6be..9278e86 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -17,7 +17,10 @@ export interface TestUser { token: string; } -export async function createTestApp(env: Record = {}): Promise<{ +export async function createTestApp( + env: Record = {}, + setup: (app: NestFastifyApplication) => void = () => undefined, +): Promise<{ app: INestApplication; server: any; }> { @@ -35,6 +38,7 @@ export async function createTestApp(env: Record = {}): Promise<{ process.env = saved; } configureApp(app); + setup(app); await app.listen(0, '127.0.0.1'); return { app, server: app.getHttpServer() }; }