CLT-1: каркас сервиса, каталог, Sentry без ПДн, CI-проверки и Dockerfile
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
995b558c5d
commit
e8f1344af7
10
.dockerignore
Normal file
10
.dockerignore
Normal file
@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
dist
|
||||
coverage
|
||||
.git
|
||||
.env
|
||||
.env.*
|
||||
.claude
|
||||
.agents
|
||||
openspec
|
||||
test
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@ -1,4 +1,6 @@
|
||||
node_modules/
|
||||
.env
|
||||
.env.local
|
||||
.DS_Store
|
||||
node_modules/
|
||||
dist/
|
||||
coverage/
|
||||
|
||||
@ -1 +1,19 @@
|
||||
{"slug":"customer","key":"CLT","name":"Клиентология SaaS & Content Engine","peppaUrl":"https://peppa.telecom.quest"}
|
||||
{
|
||||
"slug": "customer",
|
||||
"key": "CLT",
|
||||
"name": "Клиентология SaaS & Content Engine",
|
||||
"peppaUrl": "https://peppa.telecom.quest",
|
||||
"checks": {
|
||||
"install": "pnpm install --frozen-lockfile",
|
||||
"lint": "pnpm lint",
|
||||
"typecheck": "pnpm typecheck",
|
||||
"test": "pnpm test",
|
||||
"build": "pnpm build"
|
||||
},
|
||||
"deploy": {
|
||||
"compose": "deploy/compose.yml",
|
||||
"service": "web",
|
||||
"port": 3000,
|
||||
"health": "/healthz"
|
||||
}
|
||||
}
|
||||
|
||||
21
Dockerfile
Normal file
21
Dockerfile
Normal file
@ -0,0 +1,21 @@
|
||||
# Клиентология: Node.js 22 + pnpm. Слушает $PORT, GET /healthz → 200.
|
||||
FROM node:22-bookworm-slim AS build
|
||||
WORKDIR /app
|
||||
RUN corepack enable
|
||||
COPY package.json pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
COPY tsconfig.json tsconfig.build.json ./
|
||||
COPY src ./src
|
||||
RUN pnpm build && pnpm prune --prod
|
||||
|
||||
FROM node:22-bookworm-slim
|
||||
WORKDIR /app
|
||||
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
|
||||
USER node
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s \
|
||||
CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/healthz').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"
|
||||
CMD ["node", "dist/index.js"]
|
||||
@ -8,6 +8,10 @@ services:
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
PORT: "${APP_PORT:-3000}"
|
||||
# Bugsink (SDK Sentry): без SENTRY_DSN отправки нет. DSN — из secrets Actions, не из репозитория.
|
||||
SENTRY_DSN: "${SENTRY_DSN:-}"
|
||||
SENTRY_RELEASE: "${PEPPA_SHA:-}"
|
||||
SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-dev}"
|
||||
networks:
|
||||
- traefik_default
|
||||
labels:
|
||||
|
||||
10
eslint.config.js
Normal file
10
eslint.config.js
Normal file
@ -0,0 +1,10 @@
|
||||
import js from "@eslint/js";
|
||||
import globals from "globals";
|
||||
import tseslint from "typescript-eslint";
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ["dist/", "node_modules/", "openspec/", ".claude/", ".agents/"] },
|
||||
js.configs.recommended,
|
||||
...tseslint.configs.strict,
|
||||
{ languageOptions: { globals: globals.node } },
|
||||
);
|
||||
@ -35,7 +35,7 @@ Next.js (лишний фронтенд-слой для B2B-API и ботов); P
|
||||
src/
|
||||
index.ts — чтение env, валидация PORT, запуск
|
||||
app.ts — buildApp(): Fastify, helmet, обработчики ошибок, регистрация модулей
|
||||
sentry.ts — init Sentry из env, sendDefaultPii: false, beforeSend чистит request
|
||||
sentry.ts — init Sentry из env, запрещающий dataCollection, beforeSend чистит request
|
||||
modules/catalog/ — данные каталога, маршруты /api/products, рендер /
|
||||
test/ — vitest, fastify.inject(), имена тестов = имена сценариев
|
||||
```
|
||||
@ -77,6 +77,22 @@ test `pnpm test` (vitest run), build `pnpm build` (tsc → `dist/`).
|
||||
7. Контент-агент (модуль 2) — Telegram-канал/блог, ссылки на воронку.
|
||||
8. Политика ПДн (152-ФЗ): обезличивание перед LLM, сроки хранения, согласия — блокирует 4–6.
|
||||
|
||||
### D8. Уточнения при реализации
|
||||
- **Sentry v11** удалил `sendDefaultPii`; его заменил `dataCollection`, который по умолчанию
|
||||
собирает всё (заголовки, cookies, тела, query, переменные стека). Включён запрещающий
|
||||
`dataCollection` (всё `false`) плюс `beforeSend`-очистка. Это эквивалент
|
||||
`sendDefaultPii: false` из правил Пеппы.
|
||||
- **TypeScript 6.0**, не 7.x: typescript-eslint 8 поддерживает TS < 6.1.
|
||||
- Исходники импортируются с расширением `.ts` (`rewriteRelativeImportExtensions`):
|
||||
тесты запускают `src/index.ts` напрямую через node без сборки.
|
||||
- Логи запросов: только метод и путь, без IP, query и заголовков.
|
||||
- `trustProxy` выключен: `req.ip` пока не используется; включать с конкретным списком
|
||||
доверенных прокси (Traefik), когда понадобится rate-limit.
|
||||
- Лимит тела проверяется в `onRequest` по `Content-Length` (413 и для несуществующих
|
||||
маршрутов); для chunked-тел действует `bodyLimit` Fastify.
|
||||
- `deploy/compose.yml`: `SENTRY_DSN`, `SENTRY_ENVIRONMENT` из окружения раннера,
|
||||
`SENTRY_RELEASE` = `PEPPA_SHA`. Без DSN в secrets Actions отправки нет.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- [Стори CLT-1 описывает весь продукт, а change делает только каркас] → явное
|
||||
|
||||
@ -2,24 +2,24 @@
|
||||
|
||||
## 1. Каркас проекта и проверки
|
||||
|
||||
- [ ] 1.1 `package.json` (pnpm, Node 22), TypeScript strict, eslint flat config + typescript-eslint, vitest; скрипты `lint`, `typecheck`, `test`, `build`, `start`. Проверка: `pnpm install && pnpm lint && pnpm typecheck` — зелёные.
|
||||
- [ ] 1.2 Заполнить `.peppa/project.json → checks` и `deploy`. Проверка: `bash .gitea/peppa-check.sh <check>` для install, lint, typecheck, test, build — код 0.
|
||||
- [x] 1.1 `package.json` (pnpm, Node 22), TypeScript strict, eslint flat config + typescript-eslint, vitest; скрипты `lint`, `typecheck`, `test`, `build`, `start`. Проверка: `pnpm install && pnpm lint && pnpm typecheck` — зелёные.
|
||||
- [x] 1.2 Заполнить `.peppa/project.json → checks` и `deploy`. Проверка: `bash .gitea/peppa-check.sh <check>` для install, lint, typecheck, test, build — код 0.
|
||||
|
||||
## 2. service-runtime
|
||||
|
||||
- [ ] 2.1 `src/index.ts`, `src/app.ts`: валидация `PORT`, `GET /healthz`, обработчики 404/500 без утечек, `bodyLimit` 1 МБ. Проверка: тесты по сценариям «Запуск на заданном порту», «Некорректный порт», «Сервис здоров», «Неподдерживаемый метод», «Неизвестный маршрут», «Необработанное исключение», «Слишком большое тело».
|
||||
- [ ] 2.2 `@fastify/helmet` с CSP, без `X-Powered-By`. Проверка: тест «Заголовки на главной».
|
||||
- [ ] 2.3 `src/sentry.ts`: init из env, `sendDefaultPii: false`, `beforeSend` удаляет IP/cookies/authorization. Проверка: тесты «DSN не задан» и «Ошибка уходит в Bugsink без ПДн» (транспорт Sentry подменён `mockSentryTransport`).
|
||||
- [x] 2.1 `src/index.ts`, `src/app.ts`: валидация `PORT`, `GET /healthz`, обработчики 404/500 без утечек, `bodyLimit` 1 МБ. Проверка: тесты по сценариям «Запуск на заданном порту», «Некорректный порт», «Сервис здоров», «Неподдерживаемый метод», «Неизвестный маршрут», «Необработанное исключение», «Слишком большое тело».
|
||||
- [x] 2.2 `@fastify/helmet` с CSP, без `X-Powered-By`. Проверка: тест «Заголовки на главной».
|
||||
- [x] 2.3 `src/sentry.ts`: init из env, `sendDefaultPii: false`, `beforeSend` удаляет IP/cookies/authorization. Проверка: тесты «DSN не задан» и «Ошибка уходит в Bugsink без ПДн» (транспорт Sentry подменён `mockSentryTransport`).
|
||||
|
||||
## 3. product-catalog
|
||||
|
||||
- [ ] 3.1 Модуль каталога: данные 6 продуктов, `GET /api/products`, `GET /api/products/:id`. Проверка: тесты «Получение каталога», «Неизвестный продукт», «Карточка продукта» (outline).
|
||||
- [ ] 3.2 Лендинг `GET /` с `escapeHtml`. Проверка: тесты «Посетитель открывает главную», «Экранирование HTML в данных каталога».
|
||||
- [x] 3.1 Модуль каталога: данные 6 продуктов, `GET /api/products`, `GET /api/products/:id`. Проверка: тесты «Получение каталога», «Неизвестный продукт», «Карточка продукта» (outline).
|
||||
- [x] 3.2 Лендинг `GET /` с `escapeHtml`. Проверка: тесты «Посетитель открывает главную», «Экранирование HTML в данных каталога».
|
||||
|
||||
## 4. Деплой и проверка
|
||||
|
||||
- [ ] 4.1 `Dockerfile` из заготовки: multi-stage, prod-зависимости, `USER node`. Проверка: `docker build .`, запуск с `PORT=3000`, `curl /healthz` → 200.
|
||||
- [ ] 4.2 Все проверки через `bash .gitea/peppa-check.sh` зелёные; `openspec validate clt-1-platform-foundation` проходит.
|
||||
- [x] 4.1 `Dockerfile` из заготовки: multi-stage, prod-зависимости, `USER node`. Проверка: `docker build .`, запуск с `PORT=3000`, `curl /healthz` → 200.
|
||||
- [x] 4.2 Все проверки через `bash .gitea/peppa-check.sh` зелёные; `openspec validate clt-1-platform-foundation` проходит.
|
||||
|
||||
## 5. Декомпозиция
|
||||
|
||||
|
||||
32
package.json
Normal file
32
package.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "clientology",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"packageManager": "pnpm@12.18.0",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node dist/index.js",
|
||||
"lint": "eslint .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/helmet": "^13.2.0",
|
||||
"@sentry/node": "^11.12.0",
|
||||
"fastify": "^5.12.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@sentry/core": "11.12.0",
|
||||
"@types/node": "^26.6.6",
|
||||
"eslint": "^10.14.0",
|
||||
"globals": "^17.14.0",
|
||||
"typescript": "~6.0.3",
|
||||
"typescript-eslint": "^8.72.2",
|
||||
"vitest": "^5.1.0"
|
||||
}
|
||||
}
|
||||
2421
pnpm-lock.yaml
generated
Normal file
2421
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
70
src/app.ts
Normal file
70
src/app.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import Fastify, { type FastifyError, type FastifyInstance, type FastifyServerOptions } from "fastify";
|
||||
import helmet from "@fastify/helmet";
|
||||
import { captureError } from "./sentry.ts";
|
||||
import { catalogModule, type CatalogOptions } from "./modules/catalog/index.ts";
|
||||
|
||||
export const BODY_LIMIT = 1024 * 1024;
|
||||
|
||||
export interface AppOptions {
|
||||
logger?: FastifyServerOptions["logger"];
|
||||
catalog?: CatalogOptions;
|
||||
}
|
||||
|
||||
const CLIENT_ERROR_CODES: Record<number, string> = {
|
||||
400: "bad_request",
|
||||
404: "not_found",
|
||||
405: "method_not_allowed",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
};
|
||||
|
||||
export async function buildApp(opts: AppOptions = {}): Promise<FastifyInstance> {
|
||||
const app = Fastify({
|
||||
logger: opts.logger ?? false,
|
||||
bodyLimit: BODY_LIMIT,
|
||||
});
|
||||
|
||||
await app.register(helmet, {
|
||||
contentSecurityPolicy: {
|
||||
useDefaults: false,
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
baseUri: ["'self'"],
|
||||
formAction: ["'self'"],
|
||||
frameAncestors: ["'none'"],
|
||||
objectSrc: ["'none'"],
|
||||
imgSrc: ["'self'", "data:"],
|
||||
styleSrc: ["'self'"],
|
||||
scriptSrc: ["'self'"],
|
||||
},
|
||||
},
|
||||
xFrameOptions: { action: "deny" },
|
||||
referrerPolicy: { policy: "strict-origin-when-cross-origin" },
|
||||
});
|
||||
|
||||
// Тело больше лимита отклоняем до маршрутизации — и для несуществующих маршрутов тоже.
|
||||
app.addHook("onRequest", async (req, reply) => {
|
||||
const len = Number(req.headers["content-length"] ?? 0);
|
||||
if (Number.isFinite(len) && len > BODY_LIMIT) {
|
||||
return reply.code(413).send({ error: "payload_too_large" });
|
||||
}
|
||||
});
|
||||
|
||||
app.setNotFoundHandler(async (_req, reply) => reply.code(404).send({ error: "not_found" }));
|
||||
|
||||
app.setErrorHandler(async (err: FastifyError, req, reply) => {
|
||||
const status = err.statusCode ?? 500;
|
||||
if (status >= 400 && status < 500) {
|
||||
return reply.code(status).send({ error: CLIENT_ERROR_CODES[status] ?? "client_error" });
|
||||
}
|
||||
req.log.error({ err }, "unhandled error");
|
||||
captureError(err, { method: req.method, url: req.url });
|
||||
return reply.code(500).send({ error: "internal_error" });
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => ({ status: "ok" }));
|
||||
|
||||
await app.register(catalogModule, opts.catalog ?? {});
|
||||
|
||||
return app;
|
||||
}
|
||||
10
src/config.ts
Normal file
10
src/config.ts
Normal file
@ -0,0 +1,10 @@
|
||||
export const DEFAULT_PORT = 3000;
|
||||
|
||||
/** Порт из env: только десятичное целое 1..65535, иначе ошибка (сервис не стартует). */
|
||||
export function parsePort(raw: string | undefined): number {
|
||||
if (raw === undefined || raw === "") return DEFAULT_PORT;
|
||||
if (!/^\d{1,5}$/.test(raw)) throw new Error(`Invalid PORT: ${JSON.stringify(raw)}`);
|
||||
const port = Number(raw);
|
||||
if (port < 1 || port > 65535) throw new Error(`Invalid PORT: ${JSON.stringify(raw)}`);
|
||||
return port;
|
||||
}
|
||||
12
src/html.ts
Normal file
12
src/html.ts
Normal file
@ -0,0 +1,12 @@
|
||||
const HTML_ESCAPES: Record<string, string> = {
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
};
|
||||
|
||||
/** Экранирует строку для текста и значений атрибутов HTML. */
|
||||
export function escapeHtml(value: string): string {
|
||||
return value.replace(/[&<>"']/g, (ch) => HTML_ESCAPES[ch] ?? ch);
|
||||
}
|
||||
40
src/index.ts
Normal file
40
src/index.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import { initSentry, flushSentry } from "./sentry.ts";
|
||||
import { buildApp } from "./app.ts";
|
||||
import { parsePort } from "./config.ts";
|
||||
|
||||
async function main(): Promise<void> {
|
||||
let port: number;
|
||||
try {
|
||||
port = parsePort(process.env.PORT);
|
||||
} catch (err) {
|
||||
console.error((err as Error).message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
initSentry();
|
||||
const app = await buildApp({
|
||||
logger: {
|
||||
level: process.env.LOG_LEVEL ?? "info",
|
||||
// В логах — только метод и путь: без IP клиента, query и заголовков (ПДн).
|
||||
serializers: {
|
||||
req: (req: { method: string; url: string }) => ({ method: req.method, path: req.url.split("?")[0] }),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const shutdown = async (signal: string): Promise<void> => {
|
||||
app.log.info({ signal }, "shutting down");
|
||||
await app.close();
|
||||
await flushSentry();
|
||||
process.exit(0);
|
||||
};
|
||||
process.once("SIGTERM", () => void shutdown("SIGTERM"));
|
||||
process.once("SIGINT", () => void shutdown("SIGINT"));
|
||||
|
||||
await app.listen({ port, host: "0.0.0.0" });
|
||||
}
|
||||
|
||||
main().catch((err: unknown) => {
|
||||
console.error("Failed to start:", err instanceof Error ? err.message : err);
|
||||
process.exit(1);
|
||||
});
|
||||
73
src/modules/catalog/index.ts
Normal file
73
src/modules/catalog/index.ts
Normal file
@ -0,0 +1,73 @@
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { escapeHtml } from "../../html.ts";
|
||||
import { PRODUCTS, type Product } from "./products.ts";
|
||||
|
||||
export interface CatalogOptions {
|
||||
products?: readonly Product[];
|
||||
}
|
||||
|
||||
const STYLES = `
|
||||
:root{--bg:#f7f6f2;--fg:#1d1d1b;--muted:#5d5d58;--card:#fff;--line:#e2e0d8;--accent:#2f5d50}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#141413;--fg:#ecebe6;--muted:#a3a29b;--card:#1e1e1c;--line:#33332f;--accent:#8cc1b0}}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
|
||||
main{max-width:960px;margin:0 auto;padding:48px 16px}
|
||||
h1{font-size:2.25rem;margin:0 0 8px}
|
||||
.lead{color:var(--muted);margin:0 0 32px;max-width:60ch}
|
||||
.grid{display:grid;gap:16px;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));list-style:none;padding:0;margin:0}
|
||||
.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:20px}
|
||||
.card h2{font-size:1.125rem;margin:0 0 8px}
|
||||
.card p{margin:0 0 12px;color:var(--muted)}
|
||||
.price{font-size:.875rem;color:var(--fg)}
|
||||
.badge{display:inline-block;font-size:.75rem;padding:2px 8px;border-radius:999px;border:1px solid var(--accent);color:var(--accent);margin-left:8px;vertical-align:middle}
|
||||
`;
|
||||
|
||||
function renderCard(p: Product): string {
|
||||
const badge = p.status === "coming_soon" ? `<span class="badge">Скоро</span>` : "";
|
||||
return `<li class="card" id="${escapeHtml(p.id)}">
|
||||
<h2>${escapeHtml(p.title)}${badge}</h2>
|
||||
<p>${escapeHtml(p.summary)}</p>
|
||||
<div class="price">${escapeHtml(p.pricing)}</div>
|
||||
</li>`;
|
||||
}
|
||||
|
||||
export function renderLanding(products: readonly Product[]): string {
|
||||
return `<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Клиентология</title>
|
||||
<link rel="stylesheet" href="/assets/site.css">
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>Клиентология</h1>
|
||||
<p class="lead">Инструменты для контакт-центров и отделов продаж по методологии «Клиентологии»: цифровые комплекты, автоматические аудиты, тренажёры и тестирование кандидатов.</p>
|
||||
<ul class="grid">
|
||||
${products.map(renderCard).join("\n")}
|
||||
</ul>
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
export async function catalogModule(app: FastifyInstance, opts: CatalogOptions): Promise<void> {
|
||||
const products = opts.products ?? PRODUCTS;
|
||||
const byId = new Map(products.map((p) => [p.id, p]));
|
||||
const landing = renderLanding(products);
|
||||
|
||||
app.get("/api/products", async () => products);
|
||||
|
||||
app.get<{ Params: { id: string } }>("/api/products/:id", async (req, reply) => {
|
||||
const product = byId.get(req.params.id);
|
||||
if (!product) return reply.code(404).send({ error: "not_found" });
|
||||
return product;
|
||||
});
|
||||
|
||||
app.get("/", async (_req, reply) => reply.type("text/html; charset=utf-8").send(landing));
|
||||
|
||||
app.get("/assets/site.css", async (_req, reply) =>
|
||||
reply.type("text/css; charset=utf-8").header("cache-control", "public, max-age=3600").send(STYLES),
|
||||
);
|
||||
}
|
||||
59
src/modules/catalog/products.ts
Normal file
59
src/modules/catalog/products.ts
Normal file
@ -0,0 +1,59 @@
|
||||
export type ProductStatus = "available" | "coming_soon";
|
||||
|
||||
export interface Product {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
pricing: string;
|
||||
status: ProductStatus;
|
||||
}
|
||||
|
||||
export const PRODUCTS: readonly Product[] = [
|
||||
{
|
||||
id: "digital-toolkits",
|
||||
title: "Цифровые комплекты",
|
||||
summary:
|
||||
"Электронные книги, PDF-гайды и чек-листы по ISO 18295 / COPC, матрицы навыков и WFM-калькуляторы.",
|
||||
pricing: "Разовая покупка комплекта",
|
||||
status: "coming_soon",
|
||||
},
|
||||
{
|
||||
id: "content-hub",
|
||||
title: "Экспертный контент",
|
||||
summary:
|
||||
"Telegram-канал и блог: кейсы, разборы ошибок в сервисе, эмпатия и речевая аналитика.",
|
||||
pricing: "Бесплатно",
|
||||
status: "coming_soon",
|
||||
},
|
||||
{
|
||||
id: "express-audit",
|
||||
title: "Экспресс-аудит диалогов",
|
||||
summary:
|
||||
"Проверка диалога оператора или скрипта по критериям COPC с PDF-отчётом о найденных ошибках.",
|
||||
pricing: "Оплата за отчёт или пакет отчётов",
|
||||
status: "coming_soon",
|
||||
},
|
||||
{
|
||||
id: "skill-coach",
|
||||
title: "AI-тренажёр диалогов",
|
||||
summary:
|
||||
"Тренировка разговора с «трудным» клиентом: «Метод 3 шагов», «Свойство-Связка-Выгода», «хвостатые вопросы».",
|
||||
pricing: "Ежемесячная подписка за оператора",
|
||||
status: "coming_soon",
|
||||
},
|
||||
{
|
||||
id: "hr-screening",
|
||||
title: "Тестирование кандидатов",
|
||||
summary:
|
||||
"Автоматические тесты соискателей на позиции операторов и продавцов со скоринговым отчётом.",
|
||||
pricing: "Пакеты проверок",
|
||||
status: "coming_soon",
|
||||
},
|
||||
{
|
||||
id: "billing",
|
||||
title: "Подписки и оплата",
|
||||
summary: "Оплата, выдача доступов и продление подписок без участия менеджера.",
|
||||
pricing: "Входит в продукты",
|
||||
status: "coming_soon",
|
||||
},
|
||||
];
|
||||
89
src/sentry.ts
Normal file
89
src/sentry.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import * as Sentry from "@sentry/node";
|
||||
import type { ErrorEvent, NodeOptions } from "@sentry/node";
|
||||
import type { DataCollection } from "@sentry/core";
|
||||
|
||||
const SENSITIVE_HEADERS = new Set([
|
||||
"authorization",
|
||||
"cookie",
|
||||
"set-cookie",
|
||||
"proxy-authorization",
|
||||
"x-forwarded-for",
|
||||
"x-real-ip",
|
||||
"forwarded",
|
||||
]);
|
||||
|
||||
/** Удаляет из события ПДн: IP, cookies, заголовки авторизации, query и тело запроса. */
|
||||
export function scrubEvent(event: ErrorEvent): ErrorEvent {
|
||||
if (event.user) {
|
||||
delete event.user.ip_address;
|
||||
delete event.user.email;
|
||||
delete event.user.username;
|
||||
}
|
||||
const req = event.request;
|
||||
if (req) {
|
||||
delete req.cookies;
|
||||
delete req.data;
|
||||
delete req.query_string;
|
||||
delete req.env;
|
||||
if (req.url) req.url = req.url.split("?")[0];
|
||||
if (req.headers) {
|
||||
req.headers = Object.fromEntries(
|
||||
Object.entries(req.headers).filter(([name]) => !SENSITIVE_HEADERS.has(name.toLowerCase())),
|
||||
);
|
||||
}
|
||||
}
|
||||
return event;
|
||||
}
|
||||
|
||||
/** Не собирать ПДн автоматически: пользователь, cookies, заголовки, тела, query, переменные стека. */
|
||||
export const PRIVACY_DATA_COLLECTION: DataCollection = {
|
||||
userInfo: false,
|
||||
cookies: false,
|
||||
httpHeaders: false,
|
||||
httpBodies: [],
|
||||
urlQueryParams: false,
|
||||
graphQL: { document: false, variables: false },
|
||||
genAI: { inputs: false, outputs: false },
|
||||
mcp: { inputs: false, outputs: false },
|
||||
databaseQueryData: false,
|
||||
queues: false,
|
||||
stackFrameVariables: false,
|
||||
};
|
||||
|
||||
let enabled = false;
|
||||
|
||||
/** Инициализирует SDK Sentry (Bugsink), только если задан SENTRY_DSN. */
|
||||
export function initSentry(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
extra: Partial<NodeOptions> = {},
|
||||
): boolean {
|
||||
const dsn = env.SENTRY_DSN;
|
||||
if (!dsn) return false;
|
||||
Sentry.init({
|
||||
dsn,
|
||||
release: env.SENTRY_RELEASE || undefined,
|
||||
environment: env.SENTRY_ENVIRONMENT || "dev",
|
||||
// Sentry v11: вместо sendDefaultPii — dataCollection, по умолчанию собирает всё. Запрещаем ПДн.
|
||||
dataCollection: PRIVACY_DATA_COLLECTION,
|
||||
tracesSampleRate: 0,
|
||||
beforeSend: scrubEvent,
|
||||
...extra,
|
||||
});
|
||||
enabled = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function captureError(err: unknown, request?: { method: string; url: string }): void {
|
||||
if (!enabled) return;
|
||||
Sentry.withScope((scope) => {
|
||||
if (request) {
|
||||
// Только метод и путь: без query, заголовков и тела.
|
||||
scope.setContext("request", { method: request.method, path: request.url.split("?")[0] });
|
||||
}
|
||||
Sentry.captureException(err);
|
||||
});
|
||||
}
|
||||
|
||||
export async function flushSentry(timeoutMs = 2000): Promise<void> {
|
||||
if (enabled) await Sentry.flush(timeoutMs);
|
||||
}
|
||||
98
test/product-catalog.test.ts
Normal file
98
test/product-catalog.test.ts
Normal file
@ -0,0 +1,98 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.ts";
|
||||
import { PRODUCTS } from "../src/modules/catalog/products.ts";
|
||||
|
||||
let app: FastifyInstance;
|
||||
afterEach(async () => app?.close());
|
||||
|
||||
describe("Requirement: Каталог продуктов в JSON", () => {
|
||||
it("Scenario: Получение каталога", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/api/products" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers["content-type"]).toContain("application/json");
|
||||
const items = res.json() as { id: string; status: string }[];
|
||||
expect(items).toHaveLength(6);
|
||||
expect(items.map((p) => p.id)).toEqual([
|
||||
"digital-toolkits",
|
||||
"content-hub",
|
||||
"express-audit",
|
||||
"skill-coach",
|
||||
"hr-screening",
|
||||
"billing",
|
||||
]);
|
||||
expect(items.find((p) => p.id === "express-audit")?.status).toBe("coming_soon");
|
||||
for (const p of items) {
|
||||
expect(Object.keys(p).sort()).toEqual(["id", "pricing", "status", "summary", "title"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("Scenario: Неизвестный продукт", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/api/products/unknown" });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.json()).toEqual({ error: "not_found" });
|
||||
});
|
||||
|
||||
it.each(["__proto__", "constructor", "toString"])("служебное имя %s — 404", async (id) => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: `/api/products/${id}` });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["digital-toolkits", "Цифровые комплекты"],
|
||||
["express-audit", "Экспресс-аудит диалогов"],
|
||||
["skill-coach", "AI-тренажёр диалогов"],
|
||||
["hr-screening", "Тестирование кандидатов"],
|
||||
])("Scenario Outline: Карточка продукта (%s)", async (id, title) => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: `/api/products/${id}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().title).toBe(title);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Лендинг со списком продуктов", () => {
|
||||
it("Scenario: Посетитель открывает главную", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers["content-type"]).toContain("text/html");
|
||||
expect(res.body).toContain("Клиентология");
|
||||
expect(res.body).toContain("Экспресс-аудит диалогов");
|
||||
expect(res.body).toContain("Скоро");
|
||||
expect(res.body).not.toMatch(/<form/i);
|
||||
expect(res.body).not.toMatch(/<input/i);
|
||||
for (const p of PRODUCTS) expect(res.body).toContain(p.title);
|
||||
});
|
||||
|
||||
it("Scenario: Экранирование HTML в данных каталога", async () => {
|
||||
app = await buildApp({
|
||||
catalog: {
|
||||
products: [
|
||||
{
|
||||
id: "x\"><img src=x>",
|
||||
title: "<script>alert(1)</script>",
|
||||
summary: "a & b",
|
||||
pricing: "'q'",
|
||||
status: "available",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const res = await app.inject({ method: "GET", url: "/" });
|
||||
expect(res.body).toContain("<script>");
|
||||
expect(res.body).not.toContain("<script>alert(1)");
|
||||
expect(res.body).not.toContain("<img src=x>");
|
||||
expect(res.body).toContain("a & b");
|
||||
});
|
||||
|
||||
it("стили отдаются своим маршрутом (CSP style-src 'self')", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/assets/site.css" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers["content-type"]).toContain("text/css");
|
||||
});
|
||||
});
|
||||
102
test/sentry.test.ts
Normal file
102
test/sentry.test.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import type { Envelope, Transport, TransportMakeRequestResponse } from "@sentry/core";
|
||||
import type { ErrorEvent } from "@sentry/node";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.ts";
|
||||
import { flushSentry, initSentry, scrubEvent } from "../src/sentry.ts";
|
||||
|
||||
/** Мок транспорта Sentry: собирает конверты вместо отправки в Bugsink. */
|
||||
const mockSentryEnvelopes: Envelope[] = [];
|
||||
function mockSentryTransport(): Transport {
|
||||
return {
|
||||
send(envelope: Envelope): PromiseLike<TransportMakeRequestResponse> {
|
||||
mockSentryEnvelopes.push(envelope);
|
||||
return Promise.resolve({ statusCode: 200 });
|
||||
},
|
||||
flush: () => Promise.resolve(true),
|
||||
};
|
||||
}
|
||||
|
||||
function sentEvents(): Record<string, unknown>[] {
|
||||
return mockSentryEnvelopes.flatMap((env) =>
|
||||
env[1]
|
||||
.filter(([header]) => header.type === "event")
|
||||
.map(([, payload]) => payload as Record<string, unknown>),
|
||||
);
|
||||
}
|
||||
|
||||
describe("Requirement: Отчёт об ошибках в Bugsink", () => {
|
||||
it("Scenario: DSN не задан", async () => {
|
||||
expect(initSentry({})).toBe(false);
|
||||
const app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/healthz" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
await flushSentry();
|
||||
expect(mockSentryEnvelopes).toHaveLength(0);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe("с DSN", () => {
|
||||
let app: FastifyInstance;
|
||||
beforeAll(async () => {
|
||||
initSentry(
|
||||
{
|
||||
SENTRY_DSN: "https://mockpublickey@mock-bugsink.invalid/1",
|
||||
SENTRY_ENVIRONMENT: "staging",
|
||||
SENTRY_RELEASE: "abc123",
|
||||
},
|
||||
{ transport: mockSentryTransport, defaultIntegrations: false },
|
||||
);
|
||||
app = await buildApp();
|
||||
app.get("/boom", async () => {
|
||||
throw new Error("boom for bugsink");
|
||||
});
|
||||
});
|
||||
afterAll(async () => app.close());
|
||||
|
||||
it("Scenario: Ошибка уходит в Bugsink без ПДн", async () => {
|
||||
const res = await app.inject({
|
||||
method: "GET",
|
||||
url: "/boom?email=anna@example.com",
|
||||
headers: {
|
||||
cookie: "session=mock-session-cookie",
|
||||
authorization: "Bearer mock-token",
|
||||
"x-forwarded-for": "203.0.113.7",
|
||||
},
|
||||
remoteAddress: "203.0.113.7",
|
||||
});
|
||||
expect(res.statusCode).toBe(500);
|
||||
await flushSentry();
|
||||
|
||||
const events = sentEvents();
|
||||
expect(events).toHaveLength(1);
|
||||
const event = events[0];
|
||||
expect(event?.environment).toBe("staging");
|
||||
expect(event?.release).toBe("abc123");
|
||||
const raw = JSON.stringify(event);
|
||||
expect(raw).toContain("boom for bugsink");
|
||||
for (const leak of ["203.0.113.7", "mock-session-cookie", "mock-token", "anna@example.com"]) {
|
||||
expect(raw).not.toContain(leak);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("scrubEvent", () => {
|
||||
it("удаляет IP, cookies, заголовки авторизации и query", () => {
|
||||
const event = {
|
||||
type: undefined,
|
||||
user: { ip_address: "203.0.113.7", id: "u1" },
|
||||
request: {
|
||||
url: "https://x.test/a?token=1",
|
||||
query_string: "token=1",
|
||||
cookies: { s: "1" },
|
||||
data: { password: "p" },
|
||||
headers: { Cookie: "s=1", Authorization: "Bearer t", "X-Forwarded-For": "1.2.3.4", Accept: "*/*" },
|
||||
},
|
||||
} as unknown as ErrorEvent;
|
||||
const out = scrubEvent(event);
|
||||
expect(out.user).toEqual({ id: "u1" });
|
||||
expect(out.request).toEqual({ url: "https://x.test/a", headers: { Accept: "*/*" } });
|
||||
});
|
||||
});
|
||||
162
test/service-runtime.test.ts
Normal file
162
test/service-runtime.test.ts
Normal file
@ -0,0 +1,162 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.ts";
|
||||
import { parsePort } from "../src/config.ts";
|
||||
|
||||
const ENTRY = fileURLToPath(new URL("../src/index.ts", import.meta.url));
|
||||
|
||||
function runServer(env: Record<string, string>) {
|
||||
const child = spawn(process.execPath, [ENTRY], {
|
||||
env: { PATH: process.env.PATH ?? "", ...env },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let stderr = "";
|
||||
let stdout = "";
|
||||
child.stderr.on("data", (d: Buffer) => (stderr += d.toString()));
|
||||
child.stdout.on("data", (d: Buffer) => (stdout += d.toString()));
|
||||
return { child, out: () => stdout, err: () => stderr };
|
||||
}
|
||||
|
||||
async function waitFor(fn: () => boolean, timeoutMs = 10_000): Promise<void> {
|
||||
const start = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - start > timeoutMs) throw new Error("timeout");
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
|
||||
describe("Requirement: Порт из окружения", () => {
|
||||
it("Scenario: Запуск на заданном порту", async () => {
|
||||
const port = String(41000 + Math.floor(Math.random() * 1000));
|
||||
const srv = runServer({ PORT: port, LOG_LEVEL: "info" });
|
||||
try {
|
||||
await waitFor(() => srv.out().includes("Server listening"));
|
||||
const res = await fetch(`http://127.0.0.1:${port}/healthz`);
|
||||
expect(res.status).toBe(200);
|
||||
} finally {
|
||||
srv.child.kill("SIGTERM");
|
||||
await once(srv.child, "exit");
|
||||
}
|
||||
});
|
||||
|
||||
it("Scenario: Некорректный порт", async () => {
|
||||
const srv = runServer({ PORT: "abc" });
|
||||
const [code] = (await once(srv.child, "exit")) as [number | null];
|
||||
expect(code).not.toBe(0);
|
||||
expect(srv.err()).toContain("Invalid PORT");
|
||||
});
|
||||
|
||||
it.each(["0", "65536", "-1", "3000.5", " 3000", "1e3"])("отклоняет PORT=%j", (raw) => {
|
||||
expect(() => parsePort(raw)).toThrow("Invalid PORT");
|
||||
});
|
||||
|
||||
it("без PORT использует 3000", () => {
|
||||
expect(parsePort(undefined)).toBe(3000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Проверка здоровья", () => {
|
||||
let app: FastifyInstance;
|
||||
afterEach(async () => app?.close());
|
||||
|
||||
it("Scenario: Сервис здоров", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/healthz" });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ status: "ok" });
|
||||
});
|
||||
|
||||
it("Scenario: Неподдерживаемый метод", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "POST", url: "/healthz", payload: { a: 1 } });
|
||||
expect([404, 405]).toContain(res.statusCode);
|
||||
expect(res.body).not.toContain(" at ");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Безопасные ответы об ошибках", () => {
|
||||
let app: FastifyInstance;
|
||||
afterEach(async () => app?.close());
|
||||
|
||||
it("Scenario: Неизвестный маршрут", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/no-such-page" });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.json()).toEqual({ error: "not_found" });
|
||||
});
|
||||
|
||||
it("Scenario: Необработанное исключение", async () => {
|
||||
app = await buildApp();
|
||||
app.get("/boom", async () => {
|
||||
throw new Error("db password=secret");
|
||||
});
|
||||
const res = await app.inject({ method: "GET", url: "/boom" });
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.json()).toEqual({ error: "internal_error" });
|
||||
expect(res.body).not.toContain("secret");
|
||||
expect(res.body).not.toContain("at ");
|
||||
});
|
||||
|
||||
it("битый JSON — 400 без деталей парсера", async () => {
|
||||
app = await buildApp();
|
||||
app.post("/echo", async (req) => req.body);
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/echo",
|
||||
headers: { "content-type": "application/json" },
|
||||
payload: '{"a":',
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json()).toEqual({ error: "bad_request" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Заголовки безопасности и лимит тела", () => {
|
||||
let app: FastifyInstance;
|
||||
afterEach(async () => app?.close());
|
||||
|
||||
it("Scenario: Заголовки на главной", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/" });
|
||||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||||
expect(res.headers["content-security-policy"]).toContain("default-src 'self'");
|
||||
expect(res.headers["content-security-policy"]).toContain("frame-ancestors 'none'");
|
||||
expect(res.headers["x-frame-options"]).toBe("DENY");
|
||||
expect(res.headers["referrer-policy"]).toBeDefined();
|
||||
expect(res.headers["x-powered-by"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("заголовки есть и на ответах об ошибках", async () => {
|
||||
app = await buildApp();
|
||||
const res = await app.inject({ method: "GET", url: "/no-such-page" });
|
||||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||||
});
|
||||
|
||||
it("Scenario: Слишком большое тело", async () => {
|
||||
app = await buildApp();
|
||||
const payload = JSON.stringify({ data: "x".repeat(2 * 1024 * 1024) });
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/healthz",
|
||||
headers: { "content-type": "application/json" },
|
||||
payload,
|
||||
});
|
||||
expect(res.statusCode).toBe(413);
|
||||
});
|
||||
|
||||
it("слишком большое тело на существующем POST-маршруте — 413", async () => {
|
||||
app = await buildApp();
|
||||
app.post("/echo", async () => ({ ok: true }));
|
||||
const res = await app.inject({
|
||||
method: "POST",
|
||||
url: "/echo",
|
||||
headers: { "content-type": "application/json" },
|
||||
payload: JSON.stringify({ data: "x".repeat(2 * 1024 * 1024) }),
|
||||
});
|
||||
expect(res.statusCode).toBe(413);
|
||||
expect(res.json()).toEqual({ error: "payload_too_large" });
|
||||
});
|
||||
});
|
||||
5
tsconfig.build.json
Normal file
5
tsconfig.build.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"]
|
||||
}
|
||||
23
tsconfig.json
Normal file
23
tsconfig.json
Normal file
@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist",
|
||||
"rootDir": ".",
|
||||
"types": [
|
||||
"node"
|
||||
],
|
||||
"rewriteRelativeImportExtensions": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"test"
|
||||
]
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user