diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a7efdd1 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +node_modules +dist +.git +.env +.env.local +openspec +.agents +.claude diff --git a/.gitignore b/.gitignore index 8f85d90..ae3897d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules/ +dist/ .env .env.local .DS_Store diff --git a/.peppa/memory.md b/.peppa/memory.md index 716626b..ee4546e 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -3,7 +3,19 @@ Пишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения. ## Команды -- Проверки: `npm run lint`, `npm test` (node:test, без зависимостей; если в окружении NODE_TEST_CONTEXT — запускать через `env -u NODE_TEST_CONTEXT`). Новый пользователь: `node scripts/add-user.js <логин> <пароль>`. + +- Каркас на TypeScript (TR-1): `npm ci`, `npm run lint` (Biome; `npm run format` чинит), `npm run typecheck`, `npm test` (Vitest), `npm run build` (tsc → dist/), `npm run dev`. Перед PR: `bash .gitea/peppa-check.sh `. +- Новый пользователь или смена пароля: `npm run build && node scripts/add-user.js <логин> <пароль>` (пишет в data/users.json, путь меняется через USERS_FILE). ## Решения -- TR-2: пользователи в data/users.json (scrypt), блокировка 5 ошибок/15 мин по логину в памяти процесса (src/auth.js); страница входа минимальная — при слиянии с TR-1 взять вид из TR-1. + +- TR-1: сервер на node:http без фреймворка и без клиентского JS; маршруты в src/app.ts, HTML/CSS в src/views.ts, тексты только в src/locales/{ru,kk,en}.json (тест сверяет их со словарём docs/glossary.md). Страница входа — /login, страница после входа — /. Отметка о входе — подписанная cookie `session` до закрытия браузера (ключ SESSION_SECRET или случайный на запуск). +- TR-2 (перенесена в каркас TR-1 при rebase): пользователи в data/users.json (scrypt, src/users.ts), проверка и блокировка 5 ошибок/15 мин по логину в памяти процесса — src/auth.ts. Тестовые пользователи: anna / Anna-pass-2026, boris / Boris-pass-2026. Старых src/*.js, AUTH_LOGIN/AUTH_PASSWORD и пробного входа demo больше нет. + +## Грабли + +- @sentry/node 11: опции `sendDefaultPii` нет, вместо неё `dataCollection`, где всё включено по умолчанию — выключать явно (httpBodies: [], cookies, httpHeaders, urlQueryParams, stackFrameVariables), иначе в отчёт уйдёт пароль из формы входа. +- Свежие версии пакетов (моложе суток) pnpm 12 отклоняет в Docker по minimumReleaseAge и молча дописывает исключения в pnpm-workspace.yaml — не коммить их, бери версию постарше. Проект на npm. chrome-devtools MCP бывает занят другим агентом — экраны можно проверить headless Chrome через CDP. +- В общей папке проекта могут одновременно работать несколько агентов на разных ветках: не переключай ветку там, заведи свою копию — `git worktree add -b task/<ключ>-<номер> ../-<номер>-wt origin/main`. `remember` пишет в .peppa/memory.md общей папки — перенеси строки в свою копию перед коммитом. +- Biome 2.6 форматирует и Markdown: линтер ограничен src/, test/ и корневыми *.json, иначе он переверстает таблицу docs/glossary.md и .peppa/memory.md. +- Две стори с каркасом параллельно = конфликт: при rebase на main, где уже принята чужая стори, её поведение и спецификацию нужно сохранить (перенести в свой код), а не затереть своей версией. diff --git a/.peppa/project.json b/.peppa/project.json index 85dbd34..ae2ac46 100644 --- a/.peppa/project.json +++ b/.peppa/project.json @@ -1 +1,20 @@ -{"slug":"testirovanie-robot","key":"TR","name":"тестирование робот","peppaUrl":"https://peppa.telecom.quest","checks":{"lint":"npm run lint","test":"npm test"},"deploy":{"compose":"deploy/compose.yml","service":"web","port":3000,"health":"/healthz"}} +{ + "slug": "testirovanie-robot", + "key": "TR", + "name": "тестирование робот", + "peppaUrl": "https://peppa.telecom.quest", + "checks": { + "install": "npm ci", + "lint": "npm run lint", + "typecheck": "npm run typecheck", + "test": "npm test", + "build": "npm run build" + }, + "deploy": { + "compose": "deploy/compose.yml", + "service": "web", + "port": 3000, + "health": "/healthz", + "screenshots": ["/login"] + } +} diff --git a/AGENTS.md b/AGENTS.md index 3be88e3..ce6ace4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,4 +12,22 @@ ## Проект - +Веб-приложение со входом по логину и паролю. Требования — `openspec/specs/user-login/` +(страницы) и `openspec/specs/auth/` (список пользователей, блокировка). + +- **Стек:** Node.js 22+, TypeScript, встроенный `node:http` (без фреймворка и без клиентского + JavaScript), npm, Vitest, Biome. Страницы отрисовываются на сервере. +- **Команды:** `npm run dev` (запуск с перезагрузкой, http://localhost:3000), `npm test`, + `npm run lint` (`npm run format` — автоисправление), `npm run typecheck`, `npm run build` (в `dist/`). +- **Код:** `src/app.ts` — все маршруты; `src/views.ts` — HTML и CSS; `src/auth.ts` — проверка + по списку пользователей и блокировка после 5 ошибок; `src/users.ts` — файл пользователей и + хеши паролей (scrypt); `src/session.ts` — подписанная cookie; `src/config.ts` — окружение. +- **Пользователи:** `data/users.json`, паролей в открытом виде там нет. Добавить или сменить + пароль: `npm run build && node scripts/add-user.js <логин> <пароль>`. +- **Тексты:** только в `src/locales/{ru,kk,en}.json`, в коде строк для пользователя нет. Тест + `test/units.test.ts` сверяет ключи трёх языков и слова из колонки «Нельзя» `docs/glossary.md`. +- **Тесты** называются по сценариям спецификации (`Requirement: …` / `Scenario: …`) и ходят в + приложение по HTTP (`test/helpers.ts`, часы подменяются через `now`). +- **Окружение:** `USERS_FILE` (по умолчанию `data/users.json`), `SESSION_SECRET` (без него + после перезапуска нужно войти заново), `COOKIE_SECURE=false` — для запуска production-сборки + по http, `SENTRY_DSN` / `SENTRY_RELEASE` / `SENTRY_ENVIRONMENT`. diff --git a/Dockerfile b/Dockerfile index 8f1ec77..148317e 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,20 @@ +# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health). +FROM node:22-bookworm-slim AS build +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci +COPY tsconfig.json tsconfig.build.json ./ +COPY src ./src +RUN npm run build && npm prune --omit=dev + FROM node:22-bookworm-slim WORKDIR /app ENV NODE_ENV=production PORT=3000 -COPY package.json ./ -COPY src ./src +COPY --from=build /app/package.json ./ +COPY --from=build /app/node_modules ./node_modules +COPY --from=build /app/dist ./dist COPY scripts ./scripts COPY data ./data +USER node EXPOSE 3000 -CMD ["node", "src/server.js"] +CMD ["node", "dist/index.js"] diff --git a/biome.json b/biome.json new file mode 100644 index 0000000..5233378 --- /dev/null +++ b/biome.json @@ -0,0 +1,7 @@ +{ + "$schema": "https://biomejs.dev/schemas/2.6.7/schema.json", + "vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true }, + "files": { "includes": ["src/**", "test/**", "*.json", "!package-lock.json"] }, + "formatter": { "indentStyle": "space", "lineWidth": 100 }, + "linter": { "enabled": true, "rules": { "preset": "recommended" } } +} diff --git a/deploy/compose.yml b/deploy/compose.yml index 01936ba..3443b0f 100644 --- a/deploy/compose.yml +++ b/deploy/compose.yml @@ -8,6 +8,13 @@ services: restart: unless-stopped environment: PORT: "${APP_PORT:-3000}" + APP_HOST: "${HOST:-}" + # Ключ подписи отметки о входе; без него после перезапуска нужно войти заново. + SESSION_SECRET: "${SESSION_SECRET:-}" + # Ошибки продукта: без SENTRY_DSN отправка выключена; release — образ с SHA деплоя. + SENTRY_DSN: "${SENTRY_DSN:-}" + SENTRY_RELEASE: "${SENTRY_RELEASE:-${IMAGE}}" + SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-}" networks: - traefik_default labels: diff --git a/docs/glossary.md b/docs/glossary.md index 5fa372f..9cdedfa 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -32,3 +32,7 @@ | Вернуть работу | поправить | реджект, вернуть в бэклог, change request | Кнопка «Поправить» | | Список задач | доска, бэклог | канбан-борд, backlog | «Бэклог» допустим как название колонки | | Ошибки продукта | баги | инциденты, Bugsink, Sentry | Вкладка «Баги» | +| Попадание в продукт | вход, войти | авторизация, аутентификация, залогиниться, логиниться | Страница «Вход», кнопка «Войти» | +| Имя для входа | логин | юзернейм, username, имя пользователя, учётка | Поле «Логин» | +| Секретное слово для входа | пароль | пассворд, кодовое слово | Поле «Пароль»; на экране никогда не показывается | +| Первая страница после входа | главная, главная страница | дашборд, dashboard, хоум | «Вернитесь на главную» | diff --git a/openspec/changes/archive/2026-11-16-tr-1-login-window/.openspec.yaml b/openspec/changes/archive/2026-11-16-tr-1-login-window/.openspec.yaml new file mode 100644 index 0000000..90080a9 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tr-1-login-window/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-16 diff --git a/openspec/changes/archive/2026-11-16-tr-1-login-window/design.md b/openspec/changes/archive/2026-11-16-tr-1-login-window/design.md new file mode 100644 index 0000000..ae3445a --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tr-1-login-window/design.md @@ -0,0 +1,78 @@ +# Design + +## Context + +Репозиторий — пустой шаблон Пеппы: кода приложения, `checks` и `deploy` нет. Стенд: один +контейнер за Traefik (перед ним Cloudflare), слушает `$PORT`, отвечает на `/healthz`. +Постановку TR-1 уточнили уже в ходе работы: выход и защита страниц ушли в TR-3, хранение +пользователей и блокировка попыток — в TR-2; первая версия этого дизайна их включала, из +кода и спецификации они убраны. +Мотивация — в proposal.md, требования — в specs/user-login/spec.md. + +## Goals / Non-Goals + +**Goals:** рабочий вход с серверной отрисовкой страниц; минимум зависимостей; проверки и +деплой настроены, чтобы следующие стори начинали с готового каркаса. + +**Non-Goals:** база данных, фронтенд-фреймворк, клиентский JavaScript, хранение сессий на +сервере, выход, блокировка попыток (TR-2, TR-3). + +## Decisions + +1. **Стек: Node.js 22 + TypeScript, встроенный `node:http`, без веб-фреймворка.** Пять + маршрутов и две страницы не оправдывают Express/Next. Альтернатива — Next.js: тяжёлая + сборка и клиентский рантайм ради одной формы. Когда появятся настоящие разделы, фреймворк + можно ввести отдельной стори: маршруты собраны в одном файле `src/app.ts`. +2. **Инструменты:** npm (как в параллельной TR-2 и заведомо есть на раннере проверок; + от pnpm отказался), `tsc` (сборка в `dist/` и typecheck), Vitest (тесты), Biome (линт + + формат одной командой). +3. **Страницы — HTML с сервера, обычная форма `POST /login`.** Работает без JavaScript; CSS + отдаётся отдельным адресом `/static/style.css`, чтобы CSP был строгим + (`default-src 'none'; style-src 'self'; form-action 'self'`). +4. **Пользователь — один, из окружения: `AUTH_LOGIN` + `AUTH_PASSWORD`** (секреты проекта + Пеппы) — так решено в постановке. TR-2 заменит источник: меняется только `src/auth.ts`. Базы нет, поэтому пароль сравнивается с секретом из окружения: SHA-256 от + обеих сторон + `timingSafeEqual` (без утечки длины и времени). +5. **Мок, пока секретов нет: `mockAccount` (`demo` / `demo`).** Включается, только если не + заданы оба секрета; страница входа прямо показывает пробные логин и пароль. Задан только + один секрет — считаем, что не задано (в журнале предупреждение). +6. **Состояние «вошёл» — подписанная cookie без состояния на сервере:** + `session=.`, в payload логин. `HttpOnly`, `SameSite=Lax`, `Secure` в + production (`COOKIE_SECURE=false` отключает для локального запуска по http), без `Max-Age` — + живёт, пока открыт браузер (так же предполагает TR-3; «запомнить меня» вне scope). Внутри + отметки есть технический предел в 7 дней на случай утечки. Ключ подписи: `SESSION_SECRET`, + иначе производный от `AUTH_PASSWORD` (смена пароля сбрасывает все входы), иначе случайный + на процесс (пробный режим). Без cookie страницу «Вы вошли как …» не показать, поэтому + минимальная проверка отметки на `/` входит в TR-1; выход и защита остальных адресов — TR-3. +7. **CSRF:** `SameSite=Lax`; изменяющее действие одно — сам вход. +8. **Пустые поля проверяет сервер, а не браузер** (`novalidate`, без `required`): сообщение + показывается над формой на языке страницы, а не всплывающей подсказкой на языке браузера. +9. **Тексты — только в `src/locales/{ru,kk,en}.json`.** Язык: `?lang=` (запоминается в + cookie `lang`) → cookie → `Accept-Language` → русский. Тест сверяет набор ключей во всех + трёх файлах и ищет в текстах слова из колонки «Нельзя» словаря `docs/glossary.md`. +10. **Ошибки продукта — `@sentry/node` 11**, включается только при `SENTRY_DSN`; + `release` = `SENTRY_RELEASE` (в compose по умолчанию — имя образа с SHA), `environment` = + `SENTRY_ENVIRONMENT`, иначе выводится из адреса стенда (`APP_HOST`). В 11-й версии + `sendDefaultPii` заменён на `dataCollection`, где всё включено по умолчанию — выключаем + явно: тела запросов (в них пароль), cookie, заголовки, параметры адреса, локальные переменные. +11. **Деплой:** `Dockerfile` из заготовки `deploy/Dockerfile.node` (npm, `npm prune --omit=dev`, + пользователь `node`); `deploy.screenshots: ["/login"]`, чтобы PM видел экран входа. + +## Risks / Trade-offs + +- [Пробный вход `demo`/`demo` открыт, пока владелец не задал секреты] → за входом пока нет + данных; подсказка видна на странице; потребность объявлена владельцу (`declare_needs`). +- [Пароль хранится в секрете в открытом виде, не хэшем] → временное решение для одной + учётной записи; хранение в защищённом виде — TR-2. +- [Нет ограничения числа попыток] → вне scope TR-1, делает TR-2. +- [TR-2 в ревью построена на другом каркасе (чистый JS, свой `src/server.js`)] → при слиянии + она переносится поверх этого кода: источник пользователей и блокировка встают в + `src/auth.ts`, страницы и тексты остаются из TR-1. + +## После слияния с TR-2 (rebase на main) + +TR-2 приняли раньше TR-1, поэтому при rebase её поведение перенесено в этот каркас, а решения +4 и 5 выше больше не действуют: единственной учётной записи из `AUTH_LOGIN` / `AUTH_PASSWORD` +и мока `mockAccount` нет. Пользователи — в `data/users.json` (scrypt, `src/users.ts`), проверка +и блокировка 5 ошибок / 15 минут по логину — в `src/auth.ts` (спецификация `auth`). Ключ подписи +отметки о входе — `SESSION_SECRET` или случайный на запуск. Требование «Пробный вход» из +спецификации `user-login` удалено. Страницы, тексты, адреса (`/login`, `/`) — из TR-1. diff --git a/openspec/changes/archive/2026-11-16-tr-1-login-window/proposal.md b/openspec/changes/archive/2026-11-16-tr-1-login-window/proposal.md new file mode 100644 index 0000000..dfb8185 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tr-1-login-window/proposal.md @@ -0,0 +1,59 @@ +# Proposal + +Задача Пеппы: **TR-1 «вход»** — «сделай окно входа логин пароль». Цель: у продукта появляется +страница входа, и без входа в него не попасть. + +## Why + +В проекте пока нет ни одного экрана и ни строчки кода приложения. Вход по логину и паролю — +первый экран продукта и основа для всех следующих: остальные страницы будут доступны только +вошедшему пользователю. + +## What Changes + +- Страница входа с полями «Логин» и «Пароль» и кнопкой «Войти»; вход работает и по Enter. +- Проверка логина и пароля; сообщение «Неверный логин или пароль», если они не подошли, и + просьба заполнить поля, если они пустые. Введённый логин остаётся в поле, пароль очищается. +- После входа — простая страница «Вы вошли как <логин>». Без входа она ведёт на страницу входа. +- Учётная запись одна; её логин и пароль владелец задаёт в настройках проекта. Пока они не + заданы, работает пробный вход (`demo` / `demo`), о чём написано на странице входа. +- Тексты экранов на русском, казахском и английском, переключатель языка (правило Пеппы №6; + основной язык — русский). +- Каркас проекта, без которого страницу не показать: веб-сервер, проверки (`checks`), + сборка образа и настройки показа версии для проверки (`deploy`), отправка ошибок продукта. + +Вне scope (по уточнённой постановке TR-1): + +- хранение пользователей и проверка паролей по хранилищу, блокировка после неудачных + попыток — TR-2; +- выход, защита остальных страниц, сохранение входа между визитами — TR-3; +- регистрация, роли, восстановление и смена пароля, «запомнить меня», вход через сторонние + сервисы, капча; +- содержательная страница после входа — только заглушка. + +## Capabilities + +### New Capabilities + +- `user-login`: страница входа, проверка логина и пароля, страница после входа, пробный + вход, язык экранов. + +### Modified Capabilities + +Нет. + +## Impact + +- Новый код: веб-приложение на Node.js + TypeScript (`src/`, `test/`), `Dockerfile`. +- `.peppa/project.json`: заполняются `checks` и `deploy` (первая стори проекта). +- `deploy/compose.yml`: в окружение сервиса передаются `AUTH_LOGIN`, `AUTH_PASSWORD`, + `SESSION_SECRET`, `SENTRY_*`. +- `docs/glossary.md`: новые понятия (вход, логин, пароль, пробный вход, главная). +- Параллельная стори TR-2 (в ревью) завела свой каркас на чистом JS; TR-2 и TR-3 должны + лечь поверх этого изменения (так указано в их постановках). +- От владельца нужны секреты `AUTH_LOGIN` и `AUTH_PASSWORD`; до этого вход работает на моке. + +## Открытые вопросы к PM + +Нет. Вопрос №379 («кто входит») снят уточнённой постановкой: одна учётная запись из настроек +проекта, хранение пользователей — в TR-2. diff --git a/openspec/changes/archive/2026-11-16-tr-1-login-window/specs/user-login/spec.md b/openspec/changes/archive/2026-11-16-tr-1-login-window/specs/user-login/spec.md new file mode 100644 index 0000000..26d3f95 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tr-1-login-window/specs/user-login/spec.md @@ -0,0 +1,140 @@ +# Spec Delta + +## Purpose + +Вход в продукт по логину и паролю: посетитель вводит их на странице входа и, если они верны, +попадает на страницу после входа, где указан его логин. + +## ADDED Requirements + +### Requirement: Страница входа +Система SHALL показывать по адресу `/login` страницу входа с заголовком, пояснением, что +нужно сделать и что будет дальше, полями «Логин» и «Пароль» и кнопкой «Войти». Поле пароля +SHALL скрывать вводимые символы. Форма SHALL отправляться и кнопкой, и клавишей Enter в +любом из полей. + +#### Scenario: Страница входа открывается +- **GIVEN** посетитель не вошёл +- **WHEN** он открывает `/login` +- **THEN** он видит заголовок «Вход», поля «Логин» и «Пароль» и кнопку «Войти» +- **AND** символы в поле «Пароль» показаны точками +- **AND** над формой написано «Введите логин и пароль. После входа откроется главная страница.» + +#### Scenario: Вход нажатием Enter +- **GIVEN** владелец задал логин «anna» и пароль «s3cret-pass» +- **AND** посетитель ввёл на странице входа логин «anna» и пароль «s3cret-pass» +- **WHEN** он нажимает Enter в поле «Пароль», не трогая кнопку +- **THEN** открывается страница после входа `/` + +### Requirement: Вход по логину и паролю +Система SHALL пускать пользователя, если логин и пароль совпали с единственной учётной +записью, заданной владельцем в настройках проекта, и открывать страницу после входа. Логин SHALL сравниваться без учёта +регистра и пробелов по краям, пароль — точно. При ошибке система SHALL оставлять +пользователя на странице входа, сохранять введённый логин и не сообщать, что именно не подошло. + +#### Scenario: Успешный вход +- **GIVEN** владелец задал логин «anna» и пароль «s3cret-pass» +- **WHEN** посетитель вводит логин «anna», пароль «s3cret-pass» и нажимает «Войти» +- **THEN** открывается страница после входа `/` +- **AND** на ней написано «Вы вошли как anna» + +#### Scenario: Логин набран в другом регистре +- **GIVEN** владелец задал логин «anna» и пароль «s3cret-pass» +- **WHEN** посетитель вводит логин « Anna », пароль «s3cret-pass» и нажимает «Войти» +- **THEN** открывается страница после входа `/` + +#### Scenario Outline: Неверный логин или пароль +- **GIVEN** владелец задал логин «anna» и пароль «s3cret-pass» +- **WHEN** посетитель вводит логин «<логин>», пароль «<пароль>» и нажимает «Войти» +- **THEN** он остаётся на странице входа и видит «Неверный логин или пароль. Проверьте их и попробуйте ещё раз.» +- **AND** в поле «Логин» осталось «<логин>», поле «Пароль» пустое + +| логин | пароль | +|---|---| +| anna | wrong | +| boris | s3cret-pass | +| anna | S3CRET-PASS | + +#### Scenario Outline: Поле не заполнено +- **GIVEN** посетитель на странице входа +- **WHEN** он вводит логин «<логин>», пароль «<пароль>» и нажимает «Войти» +- **THEN** вход не происходит и над формой написано «Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти».» + +| логин | пароль | +|---|---| +| | s3cret-pass | +| anna | | +| | | + +### Requirement: Страница после входа +Система SHALL показывать вошедшему пользователю по адресу `/` страницу, где написано, что +вход выполнен, и указан его логин. Посетителя без входа, а также с подделанной или +испорченной отметкой о входе система SHALL перенаправлять с `/` на страницу входа. + +#### Scenario: Страница после входа +- **GIVEN** пользователь «anna» вошёл +- **WHEN** он открывает `/` +- **THEN** он видит «Вы вошли как anna» и «Вход выполнен.» + +#### Scenario: Страница после входа без входа +- **GIVEN** посетитель не вошёл +- **WHEN** он открывает `/` +- **THEN** его перенаправляет на `/login` + +#### Scenario: Подделанная отметка о входе +- **GIVEN** посетитель изменил в браузере сохранённую отметку о входе, подставив логин «admin» +- **WHEN** он открывает `/` +- **THEN** его перенаправляет на `/login` + +### Requirement: Пробный вход, пока логин и пароль не заданы +Пока владелец не задал и логин, и пароль, система SHALL пускать по пробным логину «demo» и +паролю «demo» и показывать их на странице входа. Когда логин и пароль заданы, пробный вход +SHALL быть отключён, подсказка — скрыта, а заданные логин и пароль SHALL не появляться в +тексте страницы. + +#### Scenario: Пробный вход работает +- **GIVEN** владелец не задал логин и пароль +- **WHEN** посетитель открывает `/login` +- **THEN** он видит подсказку «Пробный вход: логин demo, пароль demo.» +- **AND** вход с логином «demo» и паролем «demo» открывает страницу после входа + +#### Scenario: Пробный вход отключён +- **GIVEN** владелец задал логин «anna» и пароль «s3cret-pass» +- **WHEN** посетитель вводит логин «demo» и пароль «demo» +- **THEN** он видит «Неверный логин или пароль. Проверьте их и попробуйте ещё раз.» +- **AND** подсказки о пробном входе на странице нет +- **AND** в тексте страницы нет ни «anna», ни «s3cret-pass» + +### Requirement: Язык экранов +Система SHALL показывать экраны на русском, казахском или английском: по выбору пользователя +в переключателе языка, иначе по языку браузера, иначе на русском. Выбор SHALL запоминаться. + +#### Scenario Outline: Язык выбран в переключателе +- **GIVEN** посетитель на странице входа +- **WHEN** он выбирает в переключателе язык «<язык>» +- **THEN** кнопка входа называется «<кнопка>» +- **AND** при следующем открытии `/login` язык остаётся «<язык>» + +| язык | кнопка | +|---|---| +| Русский | Войти | +| Қазақша | Кіру | +| English | Sign in | + +#### Scenario: Язык браузера не поддерживается +- **GIVEN** в браузере посетителя выбран немецкий язык и он ничего не выбирал в переключателе +- **WHEN** он открывает `/login` +- **THEN** страница показана на русском + +### Requirement: Проверка работоспособности +Система SHALL отвечать на `GET /healthz` кодом 200 без входа. + +#### Scenario: Сервис работает +- **GIVEN** приложение запущено +- **WHEN** приходит запрос `GET /healthz` без отметки о входе +- **THEN** ответ имеет код 200 + +#### Scenario: Неизвестный адрес +- **GIVEN** приложение запущено +- **WHEN** посетитель открывает `/no-such-page` +- **THEN** ответ имеет код 404 и текст «Такой страницы нет. Вернитесь на главную.» diff --git a/openspec/changes/archive/2026-11-16-tr-1-login-window/tasks.md b/openspec/changes/archive/2026-11-16-tr-1-login-window/tasks.md new file mode 100644 index 0000000..be8a9b1 --- /dev/null +++ b/openspec/changes/archive/2026-11-16-tr-1-login-window/tasks.md @@ -0,0 +1,33 @@ +# Tasks + +## 1. Каркас проекта + +- [x] 1.1 Создать `package.json`, `tsconfig*.json`, `biome.json`, заполнить `checks` в `.peppa/project.json`; проверка: `bash .gitea/peppa-check.sh install` и `lint` проходят +- [x] 1.2 Поднять HTTP-сервер на `$PORT` с `GET /healthz`, страницей 404 и заголовками безопасности; проверка: тесты сценариев «Сервис работает» и «Неизвестный адрес» + +## 2. Тексты и язык + +- [x] 2.1 Добавить понятия входа в `docs/glossary.md` и тексты в `src/locales/{ru,kk,en}.json`; проверка: тест на одинаковые ключи и на слова из колонки «Нельзя» +- [x] 2.2 Реализовать выбор языка (`?lang=`, cookie, `Accept-Language`) и переключатель; проверка: тесты сценариев требования «Язык экранов» + +## 3. Вход + +- [x] 3.1 Реализовать проверку логина и пароля из `AUTH_LOGIN`/`AUTH_PASSWORD` и `mockAccount`; проверка: модульные тесты `auth` и `config` +- [x] 3.2 Реализовать подписанную cookie с отметкой о входе; проверка: тесты на подделку и просрочку +- [x] 3.3 Сделать страницу входа, `POST /login` и страницу после входа; проверка: тесты сценариев требований «Страница входа», «Вход по логину и паролю», «Страница после входа», «Пробный вход» +- [x] 3.4 Привести scope к уточнённой постановке TR-1: убрать выход и блокировку попыток (TR-3, TR-2), текст ошибки «Неверный логин или пароль»; проверка: тесты и `openspec validate` + +## 4. Запуск и деплой + +- [x] 4.1 Подключить `@sentry/node` (только при `SENTRY_DSN`, без персональных данных); проверка: тест конфигурации, приложение стартует без DSN +- [x] 4.2 Добавить `Dockerfile`, `deploy` в `.peppa/project.json`, переменные в `deploy/compose.yml`; проверка: `docker build .`, запуск с `PORT=3000`, `curl /healthz` → 200 +- [x] 4.3 Описать стек и команды в `AGENTS.md` + +## 5. Итоговая проверка + +- [x] 5.1 Открыть страницу входа и страницу после входа в браузере на трёх языках, сверить видимые тексты со словарём +- [x] 5.2 Прогнать `install`, `lint`, `typecheck`, `test`, `build` через `.gitea/peppa-check.sh` и `openspec validate tr-1-login-window --strict` + +## Workflow follow-up + +- Записать память проекта, `openspec archive`, PR, статус `review`. diff --git a/openspec/specs/auth/spec.md b/openspec/specs/auth/spec.md index 56d4ff2..ffcefc0 100644 --- a/openspec/specs/auth/spec.md +++ b/openspec/specs/auth/spec.md @@ -1,7 +1,8 @@ # auth Specification ## Purpose -TBD - created by archiving change tr-2-user-store-password-check. Update Purpose after archive. +Проверка логина и пароля по списку пользователей: у каждого свои данные, пароли хранятся только в +необратимой форме, а повторные неверные попытки временно закрывают вход под этим логином. ## Requirements diff --git a/openspec/specs/user-login/spec.md b/openspec/specs/user-login/spec.md new file mode 100644 index 0000000..c11dab2 --- /dev/null +++ b/openspec/specs/user-login/spec.md @@ -0,0 +1,121 @@ +# user-login Specification + +## Purpose +Вход в продукт по логину и паролю: посетитель вводит их на странице входа и, если они верны, +попадает на страницу после входа, где указан его логин. + +## Requirements + +### Requirement: Страница входа +Система SHALL показывать по адресу `/login` страницу входа с заголовком, пояснением, что +нужно сделать и что будет дальше, полями «Логин» и «Пароль» и кнопкой «Войти». Поле пароля +SHALL скрывать вводимые символы. Форма SHALL отправляться и кнопкой, и клавишей Enter в +любом из полей. + +#### Scenario: Страница входа открывается +- **GIVEN** посетитель не вошёл +- **WHEN** он открывает `/login` +- **THEN** он видит заголовок «Вход», поля «Логин» и «Пароль» и кнопку «Войти» +- **AND** символы в поле «Пароль» показаны точками +- **AND** над формой написано «Введите логин и пароль. После входа откроется главная страница.» + +#### Scenario: Вход нажатием Enter +- **GIVEN** в списке пользователей есть «anna» с паролем «s3cret-pass» +- **AND** посетитель ввёл на странице входа логин «anna» и пароль «s3cret-pass» +- **WHEN** он нажимает Enter в поле «Пароль», не трогая кнопку +- **THEN** открывается страница после входа `/` + +### Requirement: Вход по логину и паролю +Система SHALL пускать пользователя, если логин и пароль совпали с записью в списке +пользователей (см. спецификацию `auth`), и открывать страницу после входа. Логин SHALL сравниваться без учёта +регистра и пробелов по краям, пароль — точно. При ошибке система SHALL оставлять +пользователя на странице входа, сохранять введённый логин и не сообщать, что именно не подошло. + +#### Scenario: Успешный вход +- **GIVEN** в списке пользователей есть «anna» с паролем «s3cret-pass» +- **WHEN** посетитель вводит логин «anna», пароль «s3cret-pass» и нажимает «Войти» +- **THEN** открывается страница после входа `/` +- **AND** на ней написано «Вы вошли как anna» + +#### Scenario: Логин набран в другом регистре +- **GIVEN** в списке пользователей есть «anna» с паролем «s3cret-pass» +- **WHEN** посетитель вводит логин « Anna », пароль «s3cret-pass» и нажимает «Войти» +- **THEN** открывается страница после входа `/` + +#### Scenario Outline: Неверный логин или пароль +- **GIVEN** в списке пользователей есть «anna» с паролем «s3cret-pass» +- **WHEN** посетитель вводит логин «<логин>», пароль «<пароль>» и нажимает «Войти» +- **THEN** он остаётся на странице входа и видит «Неверный логин или пароль. Проверьте их и попробуйте ещё раз.» +- **AND** в поле «Логин» осталось «<логин>», поле «Пароль» пустое + +| логин | пароль | +|---|---| +| anna | wrong | +| boris | s3cret-pass | +| nobody | s3cret-pass | +| anna | S3CRET-PASS | + +#### Scenario Outline: Поле не заполнено +- **GIVEN** посетитель на странице входа +- **WHEN** он вводит логин «<логин>», пароль «<пароль>» и нажимает «Войти» +- **THEN** вход не происходит и над формой написано «Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти».» + +| логин | пароль | +|---|---| +| | s3cret-pass | +| anna | | +| | | + +### Requirement: Страница после входа +Система SHALL показывать вошедшему пользователю по адресу `/` страницу, где написано, что +вход выполнен, и указан его логин. Посетителя без входа, а также с подделанной или +испорченной отметкой о входе система SHALL перенаправлять с `/` на страницу входа. + +#### Scenario: Страница после входа +- **GIVEN** пользователь «anna» вошёл +- **WHEN** он открывает `/` +- **THEN** он видит «Вы вошли как anna» и «Вход выполнен.» + +#### Scenario: Страница после входа без входа +- **GIVEN** посетитель не вошёл +- **WHEN** он открывает `/` +- **THEN** его перенаправляет на `/login` + +#### Scenario: Подделанная отметка о входе +- **GIVEN** посетитель изменил в браузере сохранённую отметку о входе, подставив логин «admin» +- **WHEN** он открывает `/` +- **THEN** его перенаправляет на `/login` + +### Requirement: Язык экранов +Система SHALL показывать экраны на русском, казахском или английском: по выбору пользователя +в переключателе языка, иначе по языку браузера, иначе на русском. Выбор SHALL запоминаться. + +#### Scenario Outline: Язык выбран в переключателе +- **GIVEN** посетитель на странице входа +- **WHEN** он выбирает в переключателе язык «<язык>» +- **THEN** кнопка входа называется «<кнопка>» +- **AND** при следующем открытии `/login` язык остаётся «<язык>» + +| язык | кнопка | +|---|---| +| Русский | Войти | +| Қазақша | Кіру | +| English | Sign in | + +#### Scenario: Язык браузера не поддерживается +- **GIVEN** в браузере посетителя выбран немецкий язык и он ничего не выбирал в переключателе +- **WHEN** он открывает `/login` +- **THEN** страница показана на русском + +### Requirement: Проверка работоспособности +Система SHALL отвечать на `GET /healthz` кодом 200 без входа. + +#### Scenario: Сервис работает +- **GIVEN** приложение запущено +- **WHEN** приходит запрос `GET /healthz` без отметки о входе +- **THEN** ответ имеет код 200 + +#### Scenario: Неизвестный адрес +- **GIVEN** приложение запущено +- **WHEN** посетитель открывает `/no-such-page` +- **THEN** ответ имеет код 404 и текст «Такой страницы нет. Вернитесь на главную.» diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..7d81b61 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,2473 @@ +{ + "name": "testirovanie-robot", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "testirovanie-robot", + "version": "0.1.0", + "dependencies": { + "@sentry/node": "^11.12.0" + }, + "devDependencies": { + "@biomejs/biome": "2.6.7", + "@types/node": "^22.20.5", + "typescript": "^7.0.2", + "vitest": "^5.1.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@biomejs/biome": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-2.6.7.tgz", + "integrity": "sha512-2bT1FE6FvZZgPLFw4BjcDyRwG8Ry9zYla4X+Lw8oj2SxvqiXHiYkkEpjcrsWQrik6iYHygAa/D67YxLbVz9P1Q==", + "dev": true, + "license": "MIT OR Apache-2.0", + "bin": { + "biome": "bin/biome" + }, + "engines": { + "node": ">=14.21.3" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/biome" + }, + "optionalDependencies": { + "@biomejs/cli-android-arm64": "2.6.7", + "@biomejs/cli-android-x64": "2.6.7", + "@biomejs/cli-darwin-arm64": "2.6.7", + "@biomejs/cli-darwin-x64": "2.6.7", + "@biomejs/cli-linux-arm64": "2.6.7", + "@biomejs/cli-linux-arm64-musl": "2.6.7", + "@biomejs/cli-linux-x64": "2.6.7", + "@biomejs/cli-linux-x64-musl": "2.6.7", + "@biomejs/cli-win32-arm64": "2.6.7", + "@biomejs/cli-win32-x64": "2.6.7" + } + }, + "node_modules/@biomejs/cli-android-arm64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-arm64/-/cli-android-arm64-2.6.7.tgz", + "integrity": "sha512-f4fyRTl+rW6QZp+iHdZrKAKptG/xmIDijTnxWhpC1Hnzr8yvjaBm/aJ98JiMv5mMx7jL1MOu4+zwmQUzfcoKBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-android-x64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-android-x64/-/cli-android-x64-2.6.7.tgz", + "integrity": "sha512-eUdeN+mh2bwen+By1feKzpFkFGAfLG3Pxi6tbwpzMvePBwFGMd4mnE6gaxDRMiWJ1eMuc+Xhtg3ErbLLbtL5wQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-arm64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-2.6.7.tgz", + "integrity": "sha512-GewLcsnCsVblgnWYw5QRz5ydy9xphCtlFP37TpLKarezqwZMrH2qxrYblhY6DPOir4gnKyaqDnS/xZWIGVjaKw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-darwin-x64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-2.6.7.tgz", + "integrity": "sha512-AMPl+Q+bHjRcNUBn8gwBl+dJAnKRUWGZ7ZiJo2U8tQtdpqJ32OqvIg4cwTH+xv0jrcNVkUSE69nj57zsHZ1WBA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-2.6.7.tgz", + "integrity": "sha512-Qa2edxQClKn17y1ASWkOOuT96K2si1nTLiPbXMOMilNJ79eNsa1as1kaSbgxOXy1kRUENw76sp4pAddneq3l8Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-arm64-musl": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.6.7.tgz", + "integrity": "sha512-BIA7qVO1O15D2wVKxLTcvEWszgOqJVZRUhlksg1KQ9N0VtYCbvknV1vyjFiSrzuBT57+z59gbzhYQCinw9lRSQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-2.6.7.tgz", + "integrity": "sha512-VpHQ33CPNYrlIn0vyDdRS1KUlS3AiM17FiyEE2gwU000NwzyY4MgjzVHEv2KrmMb5D9Ksm3gFkwg+IOx/ULJNQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-linux-x64-musl": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-2.6.7.tgz", + "integrity": "sha512-+AOQyCsPR4nH5L4Hjzp8T0iaHm4UxY3unjL/KUJKc/8ziLnbkbmL3adtWmQW5ERB1zi6LRA1fsjaSuf/xGnLaQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-arm64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-2.6.7.tgz", + "integrity": "sha512-2nLivZfgcGMIXP/bI8w1FZP5JE2MetP+XZInyMQ7SvJBKlDoGrm/nRjN7uUi9dOaaSlpbRWkHSfb7PqcQR3nXg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@biomejs/cli-win32-x64": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-2.6.7.tgz", + "integrity": "sha512-uYfH+n+IAtVz3lh7m6JxdjxfJ3WCvAJDE3spHIUbU955V42oKymlhiQiu92fAhXZb7KOjvRcrfImySQbc1MFFg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT OR Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=14.21.3" + } + }, + "node_modules/@emnapi/core": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz", + "integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/wasi-threads": "2.2.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "2.0.0-beta.2", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz", + "integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz", + "integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm-eabi": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm-eabi/-/binding-android-arm-eabi-0.152.0.tgz", + "integrity": "sha512-393VtirINkae4XHBTkq/yQxhOwEr4V+r0et37P2fp+sYZSdYgZTRDPo5Um8vBh0QjMZ+RmaMy4PP0qwr4cTMwA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-android-arm64": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-android-arm64/-/binding-android-arm64-0.152.0.tgz", + "integrity": "sha512-iYFcExATJNZ0rZj0o02THbD1Nc9jAW0nVgIQPee6ejbSASpbZXlIMw8jxtpzaG14JQTWwGSZ6U5dEtRJXE6V3Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-arm64": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-arm64/-/binding-darwin-arm64-0.152.0.tgz", + "integrity": "sha512-fnU+DfUzi5/rFy0LzmipYRz06PAUUkOS8kCJQ3Eg6oqlunC1XZXoffFqxmdL51RmcbYtUG3P8DVG1U5fckoa2A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-darwin-x64": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-darwin-x64/-/binding-darwin-x64-0.152.0.tgz", + "integrity": "sha512-Y3U2okryWTs7hDld6UhjJwLNf8/do+x4g4C+1U5SiGwrTLwbO83WJYJA8+l9iFSilWBgnfpd/+U76tfeNxUHzA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-freebsd-x64": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-freebsd-x64/-/binding-freebsd-x64-0.152.0.tgz", + "integrity": "sha512-XkhkRrrPffEw+ZLv/d/5pEni0buxinm/E/N6fLbJCunD1DBbeCTtVP23ESV+4CWCWdSz397asks1ViGslpmWiQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-gnueabihf": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.152.0.tgz", + "integrity": "sha512-MLzsRRbdfmdzo6JEhbC1yKU9ItfvM8tEf18HM32jCiNYZEz6J3bRBRl3cTkKR0vBdrk9ZVlcARXtwHccs+epDA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm-musleabihf": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.152.0.tgz", + "integrity": "sha512-HHerTEJz7Iy10Ji6BGsk4gqG6PU0UzFuBu91jIEOX89FnrI5ECWSEr7BLpkYQhp7U0QFtMnBhNfQKI0hYZK78w==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-gnu": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.152.0.tgz", + "integrity": "sha512-9Bb8GyzZ2uSLzRDZ27usaKokr07mxiBe2dDF5b6bd2janmaJTT1gL51UfP7AU30yFiXrJvcRyFKREAgKwZYs0w==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-arm64-musl": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.152.0.tgz", + "integrity": "sha512-om7iDMUroI74A/lfRRWY9/Ev3VWrVsrUZ4tyvyh8raBey/sdcfyAD7tYWc+iykAiotnmftyKTpUKFr1QnaBrAQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-ppc64-gnu": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.152.0.tgz", + "integrity": "sha512-Lf1OL2lMTqwDMFC6jnRb30B+WYHKV0XT+bPHcFM6xHtNVwxpobiTzUIvKH6a0LWpvfwyru8Yu6zCGHqqFHH+gg==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-gnu": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.152.0.tgz", + "integrity": "sha512-BYWSMQK+YJ9ZILStPcmmiSVq8KEG9Qdq/c4BHPC3rUEq/fEDCVjUIwdj5ZzjgZ9P9is9PKu0tcAXzq1ZXg4urQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-riscv64-musl": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.152.0.tgz", + "integrity": "sha512-d2LqHNNNqdH185sRK5dPKWZu201JrNu9/CRFuVEuT+ht7n/QaVblEMWT9MALQPrDWYvhG10P+NSKJFquDWZ09w==", + "cpu": [ + "riscv64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-s390x-gnu": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.152.0.tgz", + "integrity": "sha512-8gBeHt5rA/8+pKhHl+zLggfa3L/V/L2at96p7ty6pBE7id6lFO19nFUc15u2PcjC4OYeYK465MKy1fhhbpFIGw==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-gnu": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.152.0.tgz", + "integrity": "sha512-ltgrSF6L+yPTVsIdaAyqKq3zTqzj/1VlNbxWZuxAe8flR3sWdyNsKvdXukoO8/ucJbLickhmieRBge+o/e8Ugw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-linux-x64-musl": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-linux-x64-musl/-/binding-linux-x64-musl-0.152.0.tgz", + "integrity": "sha512-LcMp6BvrBnewSfdkLHoSqidhoAq4syKOTBV5TYHWd+2VnGkfD/nPRRVIzTBt/Lkbt7pfOFDGtkiTntFS0p6sQQ==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-openharmony-arm64": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-openharmony-arm64/-/binding-openharmony-arm64-0.152.0.tgz", + "integrity": "sha512-jbhoMCslVxzRCRNQ8TSHxjYdSKRvk8O6ciLVDkahJvmyHDzBqba/bMQHM6ULKj/rgHNNbSzlIiakdx8SEfkJzA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-arm64-msvc": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.152.0.tgz", + "integrity": "sha512-JZYVlhv36mr/nertnRB7vchJECOBb1Lz6lltalILsB+o9M/is+H6BEDRLQKdqA4JKs6NjJszo46+iM5sfwj6jQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-ia32-msvc": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.152.0.tgz", + "integrity": "sha512-1X9oganvVsunRH0lH10UU05N+H9atpX6WsOybByUjwnfcd3h/0tYwvuv16XuHglrIUOnxV2TodbLVEwwafd64g==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-parser/binding-win32-x64-msvc": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-parser/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.152.0.tgz", + "integrity": "sha512-sw0M80/dn9rcpu+Rqqph/C+MjvDDce6MlXmFjsNQtPEymha0eJy3ml6+foSUTqFfpDIDyHZZ4eoJ43IoMe8bJw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz", + "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz", + "integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz", + "integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz", + "integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz", + "integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz", + "integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz", + "integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz", + "integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz", + "integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz", + "integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz", + "integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz", + "integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz", + "integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz", + "integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz", + "integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@emnapi/core": "2.0.0-beta.2", + "@emnapi/runtime": "2.0.0-beta.2", + "@napi-rs/wasm-runtime": "1.2.6" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz", + "integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz", + "integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz", + "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@sentry/bundler-plugins": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/bundler-plugins/-/bundler-plugins-11.12.0.tgz", + "integrity": "sha512-7vBXoHMoYKjYu08anYv5I0nplSWOfQyl7BqV0VOrLxEtGoOpk1+DxL2dyBiaWoAtISkaqJEV/ft813OsCGuuMg==", + "license": "MIT", + "dependencies": { + "@sentry/core": "11.12.0", + "dotenv": "^17.4.2", + "glob": "^14.0.3", + "magic-string": "~0.30.8 || ^1.0.0", + "oxc-parser": "^0.152.0", + "sentry": "^0.49.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + }, + "peerDependencies": { + "rollup": ">=3.2.0", + "webpack": ">=5.1.0" + }, + "peerDependenciesMeta": { + "rollup": { + "optional": true + }, + "webpack": { + "optional": true + } + } + }, + "node_modules/@sentry/conventions": { + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@sentry/conventions/-/conventions-0.32.0.tgz", + "integrity": "sha512-WkSQcDhUUsz1SwxR23LpmyPKba+dgxxiH0DWV4VSM9yaAvhhl87ppW2Ts3g4piIKCVflc31aJeWy+biUbYfsMQ==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@sentry/core": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/core/-/core-11.12.0.tgz", + "integrity": "sha512-HKER7EcRpPPgC8mLRe5BzP6njfRYFZ53BFLZxVp1whWbY6lp/b2mvTBk4q6+rKsUFhLhRDsd6jL8y/8ddEWv6A==", + "license": "MIT", + "dependencies": { + "@sentry/conventions": "^0.32.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + } + }, + "node_modules/@sentry/node": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/node/-/node-11.12.0.tgz", + "integrity": "sha512-MNSZDOd92Twrq5Z4ZAkxZdIfhr3YGytFb1T+vh5bNXVHkqByWpI/P2VtTSrzBR4Pi1IDRMz0i8t/OWNOsuAuBg==", + "license": "MIT", + "dependencies": { + "@opentelemetry/api": "^1.9.1", + "@sentry/bundler-plugins": "11.12.0", + "@sentry/conventions": "^0.32.0", + "@sentry/core": "11.12.0", + "@sentry/opentelemetry": "11.12.0", + "@sentry/server-runtime-injection": "11.12.0", + "@sentry/server-utils": "11.12.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + } + }, + "node_modules/@sentry/opentelemetry": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/opentelemetry/-/opentelemetry-11.12.0.tgz", + "integrity": "sha512-oWJwUdc2OSSvyOPXn/E1nWkC3GV5KNTWfR5prbw/0XxlKJepdlBsW19y+FAE9n3QznZ52aMZmetWEAFMsPJ0KQ==", + "license": "MIT", + "dependencies": { + "@sentry/conventions": "^0.32.0", + "@sentry/core": "11.12.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.9.0" + } + }, + "node_modules/@sentry/server-runtime-injection": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/server-runtime-injection/-/server-runtime-injection-11.12.0.tgz", + "integrity": "sha512-fAZjCFyEfhvyfEdbav0/X13Yqbom5Ka1+hG0Nyl6bd7GxkQIWd68unSIw/Rvzfj/DSO8A1JidezST3D6omALkw==", + "license": "MIT", + "dependencies": { + "@sentry/core": "11.12.0", + "@sentry/server-utils": "11.12.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + } + }, + "node_modules/@sentry/server-utils": { + "version": "11.12.0", + "resolved": "https://registry.npmjs.org/@sentry/server-utils/-/server-utils-11.12.0.tgz", + "integrity": "sha512-gAP5FLhXSiMs9vsU7guc54QNY1OzUJmhqyXMjhiP4SYlhQltoKtipcyo8pFWVsmylIzIkA8e2eGR6e0YA6YF3A==", + "license": "MIT", + "dependencies": { + "@opentelemetry/api": "^1.9.1", + "@sentry/conventions": "^0.32.0", + "@sentry/core": "11.12.0" + }, + "engines": { + "node": ">=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.1.0.tgz", + "integrity": "sha512-5umB9/jlWcqVS6fsrFmv5Gdnpu6wAUio/lEOwAmvB7v+lFo/IW2B9FhAD0p19GCULTgMzLCdUmuCDCnAzWgppQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.1.0", + "estree-walker": "^3.0.3", + "magic-string": "^1.4.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9 || ^3.0.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.1.0.tgz", + "integrity": "sha512-2DPO5OMHWKrBngC+fCmTQqemNF0gidRhp3lxbBmRhW+M1XJrfgPpqNqWVevXtn2f2ufD5ZaR1B6B641aAlcX5A==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/glob": { + "version": "14.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.6.tgz", + "integrity": "sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==", + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^11.0.5", + "minipass": "^7.1.3", + "path-scurry": "^3.0.0" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minipass": { + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/oxc-parser": { + "version": "0.152.0", + "resolved": "https://registry.npmjs.org/oxc-parser/-/oxc-parser-0.152.0.tgz", + "integrity": "sha512-ZztsZgaCWmPeKYMdoTT5e0oV/oxD1NeLWNR3kAtr/G707cUPYaaozRlVDHLCGnszHJRszN9mJwmPNpqgwloC0A==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "^0.152.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + }, + "optionalDependencies": { + "@oxc-parser/binding-android-arm-eabi": "0.152.0", + "@oxc-parser/binding-android-arm64": "0.152.0", + "@oxc-parser/binding-darwin-arm64": "0.152.0", + "@oxc-parser/binding-darwin-x64": "0.152.0", + "@oxc-parser/binding-freebsd-x64": "0.152.0", + "@oxc-parser/binding-linux-arm-gnueabihf": "0.152.0", + "@oxc-parser/binding-linux-arm-musleabihf": "0.152.0", + "@oxc-parser/binding-linux-arm64-gnu": "0.152.0", + "@oxc-parser/binding-linux-arm64-musl": "0.152.0", + "@oxc-parser/binding-linux-ppc64-gnu": "0.152.0", + "@oxc-parser/binding-linux-riscv64-gnu": "0.152.0", + "@oxc-parser/binding-linux-riscv64-musl": "0.152.0", + "@oxc-parser/binding-linux-s390x-gnu": "0.152.0", + "@oxc-parser/binding-linux-x64-gnu": "0.152.0", + "@oxc-parser/binding-linux-x64-musl": "0.152.0", + "@oxc-parser/binding-openharmony-arm64": "0.152.0", + "@oxc-parser/binding-win32-arm64-msvc": "0.152.0", + "@oxc-parser/binding-win32-ia32-msvc": "0.152.0", + "@oxc-parser/binding-win32-x64-msvc": "0.152.0" + } + }, + "node_modules/path-scurry": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC", + "peer": true + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.33", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz", + "integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.19", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz", + "integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.156.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.19", + "@rolldown/binding-android-arm64": "1.2.19", + "@rolldown/binding-darwin-arm64": "1.2.19", + "@rolldown/binding-darwin-x64": "1.2.19", + "@rolldown/binding-freebsd-x64": "1.2.19", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.19", + "@rolldown/binding-linux-arm64-gnu": "1.2.19", + "@rolldown/binding-linux-arm64-musl": "1.2.19", + "@rolldown/binding-linux-ppc64-gnu": "1.2.19", + "@rolldown/binding-linux-s390x-gnu": "1.2.19", + "@rolldown/binding-linux-x64-gnu": "1.2.19", + "@rolldown/binding-linux-x64-musl": "1.2.19", + "@rolldown/binding-openharmony-arm64": "1.2.19", + "@rolldown/binding-wasm32-wasi": "1.2.19", + "@rolldown/binding-win32-arm64-msvc": "1.2.19", + "@rolldown/binding-win32-x64-msvc": "1.2.19" + } + }, + "node_modules/rolldown/node_modules/@oxc-project/types": { + "version": "0.156.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz", + "integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/sentry": { + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/sentry/-/sentry-0.49.0.tgz", + "integrity": "sha512-9tjS0jTx5FQzhwAGhpcnwvqE0MlQiwJtunsIUNqGkw6E9CBOMbijlamIDUqvZTDtJAveVwa9L5ziP44bOJUzcQ==", + "license": "FSL-1.1-Apache-2.0", + "bin": { + "sentry": "dist/bin.cjs" + }, + "engines": { + "node": ">=20.0" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", + "integrity": "sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "dev": true, + "license": "0BSD", + "optional": true, + "peer": true + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.8", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz", + "integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.32", + "rolldown": "~1.2.18", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.1.0.tgz", + "integrity": "sha512-MzmNFnrwa8v8lF1bLxw3UJ4EREwVOVb75VqJZmUDRjJ6EluK/x9th7qTbaeDk41WxE1GxWqmTXcdsfobfH5sOA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.1.0", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.1.0", + "@vitest/browser-preview": "5.1.0", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.1.0", + "@vitest/coverage-v8": "5.1.0", + "@vitest/ui": "5.1.0", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + } + } +} diff --git a/package.json b/package.json index 9aed3fa..0e88668 100644 --- a/package.json +++ b/package.json @@ -2,9 +2,26 @@ "name": "testirovanie-robot", "version": "0.1.0", "private": true, + "type": "module", + "engines": { + "node": ">=22" + }, "scripts": { - "start": "node src/server.js", - "lint": "node --check src/server.js && node --check src/auth.js && node --check src/users.js && node --check src/i18n.js && node --check scripts/add-user.js", - "test": "node --test test/*.test.js" + "dev": "node --watch --experimental-strip-types src/index.ts", + "start": "node dist/index.js", + "build": "tsc -p tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "biome check .", + "format": "biome check --write .", + "test": "vitest run" + }, + "dependencies": { + "@sentry/node": "^11.12.0" + }, + "devDependencies": { + "@biomejs/biome": "2.6.7", + "@types/node": "^22.20.5", + "typescript": "^7.0.2", + "vitest": "^5.1.0" } } diff --git a/scripts/add-user.js b/scripts/add-user.js index a7249b9..34e7539 100644 --- a/scripts/add-user.js +++ b/scripts/add-user.js @@ -1,11 +1,3 @@ #!/usr/bin/env node -'use strict'; -const path = require('node:path'); -const { addUser } = require('../src/users'); -const [login, password] = process.argv.slice(2); -if (!login || !password) { - console.error('Usage: node scripts/add-user.js '); - process.exit(1); -} -addUser(process.env.USERS_FILE || path.join(__dirname, '..', 'data', 'users.json'), login, password); -console.log('User saved:', login); +// Новый пользователь: npm run build && node scripts/add-user.js <логин> <пароль> +import "../dist/add-user.js"; diff --git a/src/add-user.ts b/src/add-user.ts new file mode 100644 index 0000000..9c90ec1 --- /dev/null +++ b/src/add-user.ts @@ -0,0 +1,11 @@ +// Завести или обновить пользователя: node scripts/add-user.js <логин> <пароль> (после npm run build). +import { DEFAULT_USERS_FILE } from "./config.ts"; +import { addUser } from "./users.ts"; + +const [login, password] = process.argv.slice(2); +if (!login || !password) { + console.error("Usage: node scripts/add-user.js "); + process.exit(1); +} +addUser(process.env.USERS_FILE || DEFAULT_USERS_FILE, login, password); +console.log("User saved:", login); diff --git a/src/app.ts b/src/app.ts new file mode 100644 index 0000000..1732610 --- /dev/null +++ b/src/app.ts @@ -0,0 +1,162 @@ +import type { IncomingMessage, ServerResponse } from "node:http"; +import type { Auth } from "./auth.ts"; +import { LOCK_MS } from "./auth.ts"; +import { type Lang, pickLang } from "./i18n.ts"; +import { createSessionToken, readSessionToken } from "./session.ts"; +import { homePage, loginPage, messagePage, STYLESHEET } from "./views.ts"; + +export interface AppOptions { + /** Проверка логина и пароля по списку пользователей. */ + auth: Auth; + sessionSecret: Buffer; + cookieSecure: boolean; + now?: () => number; + onError?: (error: unknown) => void; +} + +const SESSION_COOKIE = "session"; +const LANG_COOKIE = "lang"; +const MAX_BODY_BYTES = 10_000; +const YEAR_SECONDS = 365 * 24 * 60 * 60; + +class BodyTooLargeError extends Error {} + +function parseCookies(header: string | undefined): Record { + const cookies: Record = {}; + for (const part of (header ?? "").split(";")) { + const eq = part.indexOf("="); + if (eq > 0) cookies[part.slice(0, eq).trim()] = part.slice(eq + 1).trim(); + } + return cookies; +} + +async function readForm(req: IncomingMessage): Promise { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req as AsyncIterable) { + size += chunk.length; + if (size > MAX_BODY_BYTES) throw new BodyTooLargeError(); + chunks.push(chunk); + } + return new URLSearchParams(Buffer.concat(chunks).toString("utf8")); +} + +export function createApp(options: AppOptions) { + const now = options.now ?? Date.now; + const secure = options.cookieSecure ? "; Secure" : ""; + + // Без Max-Age: вход действует, пока открыт браузер (долгий вход — вне TR-1). + const sessionCookie = (value: string) => + `${SESSION_COOKIE}=${value}; Path=/; HttpOnly; SameSite=Lax${secure}`; + + function send( + res: ServerResponse, + status: number, + body: string, + type = "text/html; charset=utf-8", + ) { + res.statusCode = status; + res.setHeader("Content-Type", type); + res.setHeader("Content-Length", Buffer.byteLength(body)); + res.end(res.req.method === "HEAD" ? undefined : body); + } + + function redirect(res: ServerResponse, location: string) { + res.statusCode = 303; + res.setHeader("Location", location); + res.end(); + } + + async function handle(req: IncomingMessage, res: ServerResponse, lang: Lang, url: URL) { + const method = req.method ?? "GET"; + const read = method === "GET" || method === "HEAD"; + const path = url.pathname; + const cookies = parseCookies(req.headers.cookie); + const user = readSessionToken(cookies[SESSION_COOKIE], options.sessionSecret, now()); + + if (path === "/healthz" && read) return send(res, 200, "ok\n", "text/plain; charset=utf-8"); + + if (path === "/static/style.css" && read) { + res.setHeader("Cache-Control", "public, max-age=300"); + return send(res, 200, STYLESHEET, "text/css; charset=utf-8"); + } + + if (path === "/" && read) { + if (!user) return redirect(res, "/login"); + return send(res, 200, homePage({ lang, login: user })); + } + + if (path === "/login" && read) { + return send(res, 200, loginPage({ lang })); + } + + if (path === "/login" && method === "POST") { + const form = await readForm(req); + const login = (form.get("login") ?? "").trim().slice(0, 200); + const password = form.get("password") ?? ""; + if (!login || !password) { + const error = { key: "login.errorEmpty" } as const; + return send(res, 400, loginPage({ lang, login, error })); + } + const result = options.auth.login(login, password); + if (!result.ok && result.reason === "locked") { + const minutes = Math.round(LOCK_MS / 60_000); + const error = { key: "login.errorLocked", params: { minutes } } as const; + return send(res, 429, loginPage({ lang, login, error })); + } + if (!result.ok) { + const error = { key: "login.errorInvalid" } as const; + return send(res, 401, loginPage({ lang, login, error })); + } + const token = createSessionToken(result.login, options.sessionSecret, now()); + res.appendHeader("Set-Cookie", sessionCookie(token)); + return redirect(res, "/"); + } + + const body = messagePage({ + lang, + path: "/", + title: "notFound.title", + text: "notFound.text", + link: "notFound.homeLink", + }); + return send(res, 404, body); + } + + return async function app(req: IncomingMessage, res: ServerResponse): Promise { + let lang: Lang = "ru"; + try { + const url = new URL(req.url ?? "/", "http://localhost"); + const choice = url.searchParams.get("lang") ?? undefined; + const cookies = parseCookies(req.headers.cookie); + lang = pickLang(choice, cookies[LANG_COOKIE], req.headers["accept-language"]); + if (choice === lang && cookies[LANG_COOKIE] !== lang) { + res.appendHeader( + "Set-Cookie", + `${LANG_COOKIE}=${lang}; Path=/; SameSite=Lax; Max-Age=${YEAR_SECONDS}${secure}`, + ); + } + res.setHeader("Content-Language", lang); + res.setHeader("Cache-Control", "no-store"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Referrer-Policy", "no-referrer"); + res.setHeader( + "Content-Security-Policy", + "default-src 'none'; style-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", + ); + await handle(req, res, lang, url); + } catch (error) { + const tooLarge = error instanceof BodyTooLargeError; + if (!tooLarge) options.onError?.(error); + if (res.headersSent) { + res.destroy(); + return; + } + const body = messagePage({ lang, path: "/", title: "error.title", text: "error.unexpected" }); + res.statusCode = tooLarge ? 413 : 500; + res.setHeader("Content-Type", "text/html; charset=utf-8"); + if (tooLarge) res.setHeader("Connection", "close"); + res.end(body); + } + }; +} diff --git a/src/auth.js b/src/auth.js deleted file mode 100644 index 5c45f7c..0000000 --- a/src/auth.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; -const { verifyPassword } = require('./users'); - -const MAX_FAILS = 5; -const LOCK_MS = 15 * 60 * 1000; -// Хеш заглушки: сверяем пароль с ним для несуществующего логина, чтобы ответ и время не выдавали, -// есть ли такой логин. -const DUMMY_HASH = 'scrypt$16384$8$1$AAAAAAAAAAAAAAAAAAAAAA==$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='; - -function createAuth({ users, now = Date.now }) { - const byLogin = new Map(users.map((u) => [u.login.toLowerCase(), u])); - const state = new Map(); // login -> { fails, lockedUntil } - - function login(rawLogin, password) { - const key = String(rawLogin).trim().toLowerCase(); - const st = state.get(key) || { fails: 0, lockedUntil: 0 }; - if (st.lockedUntil > now()) return { ok: false, reason: 'locked' }; - if (st.lockedUntil && st.lockedUntil <= now()) { st.fails = 0; st.lockedUntil = 0; } - - const user = byLogin.get(key); - const good = verifyPassword(String(password), user ? user.passwordHash : DUMMY_HASH) && !!user; - if (good) { - state.delete(key); - return { ok: true, login: user.login }; - } - st.fails += 1; - if (st.fails >= MAX_FAILS) st.lockedUntil = now() + LOCK_MS; - state.set(key, st); - return { ok: false, reason: 'invalid' }; - } - - return { login }; -} - -module.exports = { createAuth, MAX_FAILS, LOCK_MS }; diff --git a/src/auth.ts b/src/auth.ts new file mode 100644 index 0000000..89481ab --- /dev/null +++ b/src/auth.ts @@ -0,0 +1,65 @@ +import { type User, verifyPassword } from "./users.ts"; + +export const MAX_FAILS = 5; +export const LOCK_MS = 15 * 60 * 1000; +/** Сколько логинов со счётчиком ошибок держим в памяти (защита от переполнения). */ +const MAX_TRACKED_LOGINS = 10_000; + +// Хеш-заглушка: с ним сверяется пароль для несуществующего логина, чтобы ответ и время +// не выдавали, есть ли такой логин. +const DUMMY_HASH = + "scrypt$16384$8$1$AAAAAAAAAAAAAAAAAAAAAA==$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; + +export type LoginResult = { ok: true; login: string } | { ok: false; reason: "invalid" | "locked" }; + +export interface Auth { + login(rawLogin: string, password: string): LoginResult; +} + +export const normalizeLogin = (login: string) => login.trim().toLowerCase(); + +/** + * Проверка логина и пароля по списку пользователей. Логин — без учёта регистра и пробелов по + * краям, пароль — точно. После MAX_FAILS ошибок подряд вход под логином (в том числе + * несуществующим) закрыт на LOCK_MS; успешный вход обнуляет счётчик. Счётчики — в памяти процесса. + */ +export function createAuth(options: { users: User[]; now?: () => number }): Auth { + const now = options.now ?? Date.now; + const byLogin = new Map(options.users.map((user) => [normalizeLogin(user.login), user])); + const state = new Map(); + + function makeRoom() { + for (const [key, entry] of state) { + if (entry.lockedUntil && entry.lockedUntil <= now()) state.delete(key); + } + // Все записи ещё нужны: убираем самые старые (Map хранит порядок вставки). + for (const key of state.keys()) { + if (state.size < MAX_TRACKED_LOGINS) break; + state.delete(key); + } + } + + return { + login(rawLogin, password) { + const key = normalizeLogin(rawLogin); + const entry = state.get(key) ?? { fails: 0, lockedUntil: 0 }; + if (entry.lockedUntil > now()) return { ok: false, reason: "locked" }; + if (entry.lockedUntil) { + entry.fails = 0; + entry.lockedUntil = 0; + } + + const user = byLogin.get(key); + const passwordOk = verifyPassword(password, user ? user.passwordHash : DUMMY_HASH); + if (user && passwordOk) { + state.delete(key); + return { ok: true, login: user.login }; + } + entry.fails += 1; + if (entry.fails >= MAX_FAILS) entry.lockedUntil = now() + LOCK_MS; + if (!state.has(key) && state.size >= MAX_TRACKED_LOGINS) makeRoom(); + state.set(key, entry); + return { ok: false, reason: "invalid" }; + }, + }; +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..a1de4c5 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,53 @@ +import { randomBytes } from "node:crypto"; +import { join } from "node:path"; + +export interface Config { + port: number; + /** Файл со списком пользователей (`data/users.json`, меняется через USERS_FILE). */ + usersFile: string; + sessionSecret: Buffer; + cookieSecure: boolean; + sentry: { dsn: string | undefined; release: string | undefined; environment: string }; +} + +type Env = Record; + +const value = (env: Env, name: string) => env[name]?.trim() || undefined; + +/** Корень проекта: на уровень выше `src/` (разработка) и `dist/` (сборка). */ +export const DEFAULT_USERS_FILE = join(import.meta.dirname, "..", "data", "users.json"); + +/** prod / staging / dev по адресу стенда: `-prod.…`, `-staging.…`, остальное — dev. */ +export function environmentFromHost(host: string | undefined): string { + const name = host?.split(".")[0] ?? ""; + if (name.endsWith("-prod")) return "prod"; + if (name.endsWith("-staging")) return "staging"; + return "dev"; +} + +export function loadConfig(env: Env = process.env): Config { + // Без SESSION_SECRET ключ подписи случайный: после перезапуска нужно войти заново. + const explicitSecret = value(env, "SESSION_SECRET"); + const sessionSecret = explicitSecret ? Buffer.from(explicitSecret, "utf8") : randomBytes(32); + + const secureFlag = value(env, "COOKIE_SECURE"); + const cookieSecure = + secureFlag !== undefined ? secureFlag !== "false" : env.NODE_ENV === "production"; + + const port = Number(value(env, "PORT") ?? 3000); + if (!Number.isInteger(port) || port < 0 || port > 65535) { + throw new Error(`PORT должен быть числом от 0 до 65535, получено: ${env.PORT}`); + } + + return { + port, + usersFile: value(env, "USERS_FILE") ?? DEFAULT_USERS_FILE, + sessionSecret, + cookieSecure, + sentry: { + dsn: value(env, "SENTRY_DSN"), + release: value(env, "SENTRY_RELEASE"), + environment: value(env, "SENTRY_ENVIRONMENT") ?? environmentFromHost(value(env, "APP_HOST")), + }, + }; +} diff --git a/src/i18n.js b/src/i18n.js deleted file mode 100644 index e9c7c00..0000000 --- a/src/i18n.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; -const messages = { - ru: { - title: 'Вход', - intro: 'Введите логин и пароль, чтобы войти.', - login: 'Логин', - password: 'Пароль', - submit: 'Войти', - invalid: 'Неверный логин или пароль', - locked: 'Попыток было слишком много. Подождите 15 минут и попробуйте снова.', - required: 'Заполните это поле', - welcome: 'Вы вошли как {login}', - }, - kk: { - title: 'Кіру', - intro: 'Кіру үшін логин мен құпиясөзді енгізіңіз.', - login: 'Логин', - password: 'Құпиясөз', - submit: 'Кіру', - invalid: 'Логин немесе құпиясөз дұрыс емес', - locked: 'Әрекет тым көп болды. 15 минут күтіп, қайталап көріңіз.', - required: 'Бұл өрісті толтырыңыз', - welcome: 'Сіз {login} ретінде кірдіңіз', - }, - en: { - title: 'Sign in', - intro: 'Enter your login and password to sign in.', - login: 'Login', - password: 'Password', - submit: 'Sign in', - invalid: 'Wrong login or password', - locked: 'Too many attempts. Please wait 15 minutes and try again.', - required: 'Fill in this field', - welcome: 'You are signed in as {login}', - }, -}; -const pick = (lang) => messages[lang] || messages.ru; -module.exports = { messages, pick }; diff --git a/src/i18n.ts b/src/i18n.ts new file mode 100644 index 0000000..41b901c --- /dev/null +++ b/src/i18n.ts @@ -0,0 +1,48 @@ +import en from "./locales/en.json" with { type: "json" }; +import kk from "./locales/kk.json" with { type: "json" }; +import ru from "./locales/ru.json" with { type: "json" }; + +export type TextKey = keyof typeof ru; +export type Lang = "ru" | "kk" | "en"; + +export const DEFAULT_LANG: Lang = "ru"; +/** Языки в порядке показа в переключателе; подписи — самоназвания, не переводятся. */ +export const LANGS: ReadonlyArray<{ code: Lang; name: string }> = [ + { code: "ru", name: "Русский" }, + { code: "kk", name: "Қазақша" }, + { code: "en", name: "English" }, +]; + +export const locales: Record> = { ru, kk, en }; + +export function isLang(value: unknown): value is Lang { + return typeof value === "string" && LANGS.some((l) => l.code === value); +} + +export function t(lang: Lang, key: TextKey, params: Record = {}): string { + return locales[lang][key].replace(/\{(\w+)\}/g, (match, name: string) => + name in params ? String(params[name]) : match, + ); +} + +/** Выбор пользователя (?lang= или cookie) → язык браузера → русский. */ +export function pickLang( + choice: string | undefined, + cookie: string | undefined, + acceptLanguage: string | undefined, +): Lang { + if (isLang(choice)) return choice; + if (isLang(cookie)) return cookie; + const accepted = (acceptLanguage ?? "") + .split(",") + .map((part) => { + const [tag = "", ...rest] = part.trim().split(";"); + const q = rest.map((p) => p.trim()).find((p) => p.startsWith("q=")); + const weight = q ? Number(q.slice(2)) : 1; + return { code: tag.toLowerCase().split("-")[0], weight: Number.isNaN(weight) ? 0 : weight }; + }) + .filter((item) => item.weight > 0) + .sort((a, b) => b.weight - a.weight); + for (const item of accepted) if (isLang(item.code)) return item.code; + return DEFAULT_LANG; +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..8e96873 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,52 @@ +import { createServer } from "node:http"; +import * as Sentry from "@sentry/node"; +import { createApp } from "./app.ts"; +import { createAuth } from "./auth.ts"; +import { loadConfig } from "./config.ts"; +import { loadUsers } from "./users.ts"; + +const config = loadConfig(); + +// Без SENTRY_DSN отправка ошибок выключена. +if (config.sentry.dsn) { + Sentry.init({ + dsn: config.sentry.dsn, + release: config.sentry.release, + environment: config.sentry.environment, + // В @sentry/node 11 нет sendDefaultPii: персональные данные выключаются по категориям. + // Тело запроса входа содержит пароль, cookie — отметку о входе: не отправляем ничего. + dataCollection: { + userInfo: false, + cookies: false, + httpHeaders: false, + httpBodies: [], + urlQueryParams: false, + stackFrameVariables: false, + }, + }); +} + +const users = loadUsers(config.usersFile); +if (users.length === 0) console.warn("[config] Список пользователей пуст — войти нельзя."); + +const app = createApp({ + auth: createAuth({ users }), + sessionSecret: config.sessionSecret, + cookieSecure: config.cookieSecure, + onError: (error) => { + console.error(error); + Sentry.captureException(error); + }, +}); + +const server = createServer((req, res) => void app(req, res)); +server.listen(config.port, () => { + console.log(`Сервер слушает порт ${config.port}`); +}); + +for (const signal of ["SIGTERM", "SIGINT"] as const) { + process.on(signal, () => { + server.close(() => process.exit(0)); + server.closeIdleConnections(); + }); +} diff --git a/src/locales/en.json b/src/locales/en.json new file mode 100644 index 0000000..59ba495 --- /dev/null +++ b/src/locales/en.json @@ -0,0 +1,19 @@ +{ + "lang.label": "Language", + "login.title": "Sign in", + "login.lead": "Enter your login and password. After you sign in, the home page will open.", + "login.loginLabel": "Login", + "login.passwordLabel": "Password", + "login.submit": "Sign in", + "login.errorInvalid": "Wrong login or password. Check them and try again.", + "login.errorEmpty": "You left the login or password empty. Fill in both fields and press “Sign in”.", + "login.errorLocked": "Too many attempts. Wait {minutes} minutes and try again.", + "home.title": "Home", + "home.signedInAs": "You are signed in as {login}", + "home.lead": "You are signed in. Nothing is needed from you for now: product sections will appear here later.", + "notFound.title": "Page not found", + "notFound.text": "There is no such page. Go back to the home page.", + "notFound.homeLink": "Home page", + "error.title": "Error", + "error.unexpected": "Something went wrong. Refresh the page and try again." +} diff --git a/src/locales/kk.json b/src/locales/kk.json new file mode 100644 index 0000000..9554825 --- /dev/null +++ b/src/locales/kk.json @@ -0,0 +1,19 @@ +{ + "lang.label": "Тіл", + "login.title": "Кіру", + "login.lead": "Логин мен құпиясөзді енгізіңіз. Кіргеннен кейін басты бет ашылады.", + "login.loginLabel": "Логин", + "login.passwordLabel": "Құпиясөз", + "login.submit": "Кіру", + "login.errorInvalid": "Логин немесе құпиясөз қате. Оларды тексеріп, қайталап көріңіз.", + "login.errorEmpty": "Сіз логинді немесе құпиясөзді толтырмадыңыз. Екі өрісті де толтырып, «Кіру» түймесін басыңыз.", + "login.errorLocked": "Әрекет тым көп болды. {minutes} минут күтіп, қайталап көріңіз.", + "home.title": "Басты бет", + "home.signedInAs": "Сіз {login} ретінде кірдіңіз", + "home.lead": "Кіру орындалды. Әзірге сізден ештеңе талап етілмейді: өнімнің бөлімдері мұнда кейінірек пайда болады.", + "notFound.title": "Бет табылмады", + "notFound.text": "Мұндай бет жоқ. Басты бетке оралыңыз.", + "notFound.homeLink": "Басты бетке", + "error.title": "Қате", + "error.unexpected": "Бірдеңе дұрыс болмады. Бетті жаңартып, қайталап көріңіз." +} diff --git a/src/locales/ru.json b/src/locales/ru.json new file mode 100644 index 0000000..16f0712 --- /dev/null +++ b/src/locales/ru.json @@ -0,0 +1,19 @@ +{ + "lang.label": "Язык", + "login.title": "Вход", + "login.lead": "Введите логин и пароль. После входа откроется главная страница.", + "login.loginLabel": "Логин", + "login.passwordLabel": "Пароль", + "login.submit": "Войти", + "login.errorInvalid": "Неверный логин или пароль. Проверьте их и попробуйте ещё раз.", + "login.errorEmpty": "Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти».", + "login.errorLocked": "Попыток было слишком много. Подождите {minutes} минут и попробуйте снова.", + "home.title": "Главная", + "home.signedInAs": "Вы вошли как {login}", + "home.lead": "Вход выполнен. От вас пока ничего не требуется: разделы продукта появятся здесь позже.", + "notFound.title": "Страница не найдена", + "notFound.text": "Такой страницы нет. Вернитесь на главную.", + "notFound.homeLink": "На главную", + "error.title": "Ошибка", + "error.unexpected": "Что-то пошло не так. Обновите страницу и попробуйте ещё раз." +} diff --git a/src/server.js b/src/server.js deleted file mode 100644 index 14a40ca..0000000 --- a/src/server.js +++ /dev/null @@ -1,76 +0,0 @@ -'use strict'; -const http = require('node:http'); -const crypto = require('node:crypto'); -const path = require('node:path'); -const { loadUsers } = require('./users'); -const { createAuth } = require('./auth'); -const { pick } = require('./i18n'); - -const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); - -function page(t, lang, body) { - return `${esc(t.title)}${body}`; -} - -function loginPage(t, lang, { error = '', loginValue = '' } = {}) { - return page(t, lang, `

${esc(t.title)}

${esc(t.intro)}

${error ? `

${esc(error)}

` : ''} -
- - -
`); -} - -function createServer({ usersFile = path.join(__dirname, '..', 'data', 'users.json'), now = Date.now, secret = process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex') } = {}) { - const auth = createAuth({ users: loadUsers(usersFile), now }); - const sign = (v) => crypto.createHmac('sha256', secret).update(v).digest('base64url'); - const sessionLogin = (req) => { - const m = /(?:^|;\s*)session=([^;]+)/.exec(req.headers.cookie || ''); - if (!m) return null; - const [val, sig] = decodeURIComponent(m[1]).split('.'); - if (!val || !sig || sig.length !== sign(val).length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(sign(val)))) return null; - return Buffer.from(val, 'base64url').toString('utf8'); - }; - - return http.createServer((req, res) => { - const url = new URL(req.url, 'http://localhost'); - const lang = url.searchParams.get('lang'); - const t = pick(lang); - const lg = lang && ['ru', 'kk', 'en'].includes(lang) ? lang : 'ru'; - const html = (code, body, headers = {}) => { res.writeHead(code, { 'content-type': 'text/html; charset=utf-8', ...headers }); res.end(body); }; - console.log(req.method, url.pathname); // тела запросов и пароли не логируем - - if (url.pathname === '/healthz') { res.writeHead(200); return res.end('ok'); } - if (req.method === 'GET' && url.pathname === '/') return html(200, loginPage(t, lg)); - if (req.method === 'GET' && url.pathname === '/welcome') { - const who = sessionLogin(req); - if (!who) { res.writeHead(302, { location: `/?lang=${lg}` }); return res.end(); } - return html(200, page(t, lg, `

${esc(t.welcome.replace('{login}', who))}

`)); - } - if (req.method === 'POST' && url.pathname === '/login') { - let raw = ''; - req.on('data', (c) => { raw += c; if (raw.length > 10000) req.destroy(); }); - req.on('end', () => { - const form = new URLSearchParams(raw); - const login = form.get('login') || ''; - const password = form.get('password') || ''; - if (!login || !password) return html(400, loginPage(t, lg, { error: t.required, loginValue: login })); - const r = auth.login(login, password); - if (r.ok) { - const val = Buffer.from(r.login).toString('base64url'); - res.writeHead(302, { location: `/welcome?lang=${lg}`, 'set-cookie': `session=${encodeURIComponent(`${val}.${sign(val)}`)}; HttpOnly; SameSite=Lax; Path=/` }); - return res.end(); - } - const status = r.reason === 'locked' ? 429 : 401; - return html(status, loginPage(t, lg, { error: r.reason === 'locked' ? t.locked : t.invalid, loginValue: login })); - }); - return; - } - res.writeHead(404); res.end(); - }); -} - -if (require.main === module) { - const port = Number(process.env.PORT) || 3000; - createServer().listen(port, () => console.log('listening on', port)); -} -module.exports = { createServer }; diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 0000000..45a58c4 --- /dev/null +++ b/src/session.ts @@ -0,0 +1,39 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +/** Технический предел жизни отметки о входе на случай её утечки; не обещание пользователю. */ +export const SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; + +const sign = (payload: string, secret: Buffer) => + createHmac("sha256", secret).update(payload).digest("base64url"); + +/** Отметка о входе: `.<подпись>`, в payload логин и срок действия. */ +export function createSessionToken(login: string, secret: Buffer, now: number): string { + const payload = Buffer.from(JSON.stringify({ u: login, exp: now + SESSION_TTL_MS })).toString( + "base64url", + ); + return `${payload}.${sign(payload, secret)}`; +} + +/** Логин из отметки о входе или null, если она подделана, испорчена или просрочена. */ +export function readSessionToken( + token: string | undefined, + secret: Buffer, + now: number, +): string | null { + if (!token) return null; + const dot = token.indexOf("."); + if (dot <= 0) return null; + const payload = token.slice(0, dot); + const given = Buffer.from(token.slice(dot + 1)); + const expected = Buffer.from(sign(payload, secret)); + if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null; + try { + const data: unknown = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); + if (typeof data !== "object" || data === null) return null; + const { u, exp } = data as { u?: unknown; exp?: unknown }; + if (typeof u !== "string" || typeof exp !== "number" || exp <= now) return null; + return u; + } catch { + return null; + } +} diff --git a/src/users.js b/src/users.js deleted file mode 100644 index 06a0bc0..0000000 --- a/src/users.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict'; -const crypto = require('node:crypto'); -const fs = require('node:fs'); - -const N = 16384, R = 8, P = 1, KEYLEN = 32; - -function hashPassword(password) { - const salt = crypto.randomBytes(16); - const key = crypto.scryptSync(password, salt, KEYLEN, { N, r: R, p: P }); - return ['scrypt', N, R, P, salt.toString('base64'), key.toString('base64')].join('$'); -} - -function verifyPassword(password, stored) { - const parts = String(stored).split('$'); - if (parts.length !== 6 || parts[0] !== 'scrypt') return false; - const [, n, r, p, salt, hash] = parts; - const expected = Buffer.from(hash, 'base64'); - const key = crypto.scryptSync(password, Buffer.from(salt, 'base64'), expected.length, { - N: Number(n), r: Number(r), p: Number(p), - }); - return crypto.timingSafeEqual(key, expected); -} - -function loadUsers(file) { - try { - return JSON.parse(fs.readFileSync(file, 'utf8')).users || []; - } catch (e) { - if (e.code === 'ENOENT') return []; - throw e; - } -} - -function addUser(file, login, password) { - const users = loadUsers(file).filter((u) => u.login !== login); - users.push({ login, passwordHash: hashPassword(password) }); - fs.mkdirSync(require('node:path').dirname(file), { recursive: true }); - fs.writeFileSync(file, JSON.stringify({ users }, null, 2) + '\n'); -} - -module.exports = { hashPassword, verifyPassword, loadUsers, addUser }; diff --git a/src/users.ts b/src/users.ts new file mode 100644 index 0000000..a9ae325 --- /dev/null +++ b/src/users.ts @@ -0,0 +1,63 @@ +import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; + +/** Пользователь из списка: пароль хранится только в необратимой форме `scrypt$N$r$p$salt$hash`. */ +export interface User { + login: string; + passwordHash: string; +} + +const N = 16384; +const R = 8; +const P = 1; +const KEY_LENGTH = 32; + +export function hashPassword(password: string): string { + const salt = randomBytes(16); + const key = scryptSync(password, salt, KEY_LENGTH, { N, r: R, p: P }); + return ["scrypt", N, R, P, salt.toString("base64"), key.toString("base64")].join("$"); +} + +export function verifyPassword(password: string, stored: string): boolean { + const parts = stored.split("$"); + if (parts.length !== 6 || parts[0] !== "scrypt") return false; + const [, n, r, p, salt = "", hash = ""] = parts; + const expected = Buffer.from(hash, "base64"); + if (expected.length === 0) return false; + try { + const key = scryptSync(password, Buffer.from(salt, "base64"), expected.length, { + N: Number(n), + r: Number(r), + p: Number(p), + }); + return timingSafeEqual(key, expected); + } catch { + // Испорченная запись (недопустимые параметры scrypt) — пароль не подходит. + return false; + } +} + +/** Список пользователей из файла `{ "users": [{ login, passwordHash }] }`; нет файла — пустой список. */ +export function loadUsers(file: string): User[] { + let text: string; + try { + text = readFileSync(file, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; + throw error; + } + const data = JSON.parse(text) as { users?: unknown }; + if (!Array.isArray(data.users)) return []; + return data.users.filter( + (user): user is User => + typeof user?.login === "string" && typeof user?.passwordHash === "string", + ); +} + +export function addUser(file: string, login: string, password: string): void { + const users = loadUsers(file).filter((user) => user.login !== login); + users.push({ login, passwordHash: hashPassword(password) }); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, `${JSON.stringify({ users }, null, 2)}\n`); +} diff --git a/src/views.ts b/src/views.ts new file mode 100644 index 0000000..c108290 --- /dev/null +++ b/src/views.ts @@ -0,0 +1,120 @@ +import { LANGS, type Lang, type TextKey, t } from "./i18n.ts"; + +const ESCAPES: Record = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", +}; + +export const escapeHtml = (text: string) => text.replace(/[&<>"']/g, (ch) => ESCAPES[ch] ?? ch); + +export const STYLESHEET = ` +:root { color-scheme: light dark; --bg: #f4f5f7; --card: #fff; --text: #1c1e21; --muted: #5f6672; + --line: #d5d9e0; --accent: #2457d6; --accent-text: #fff; --error-bg: #fdecec; --error-text: #a11a1a; } +@media (prefers-color-scheme: dark) { + :root { --bg: #15171a; --card: #1f2226; --text: #eceef1; --muted: #a3aab5; --line: #3a3f47; + --accent: #6f95f5; --accent-text: #10131a; --error-bg: #3b1c1c; --error-text: #ffb4b4; } +} +* { box-sizing: border-box; } +body { margin: 0; min-height: 100vh; display: flex; flex-direction: column; align-items: center; + justify-content: center; gap: 16px; padding: 24px 16px; background: var(--bg); color: var(--text); + font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } +main { width: 100%; max-width: 400px; padding: 32px 28px; background: var(--card); + border: 1px solid var(--line); border-radius: 14px; } +h1 { margin: 0 0 8px; font-size: 26px; line-height: 1.2; overflow-wrap: anywhere; } +p { margin: 0 0 16px; } +.lead { color: var(--muted); } +.lead:last-child { margin-bottom: 0; } +.error { padding: 10px 12px; border-radius: 8px; font-size: 15px; background: var(--error-bg); + color: var(--error-text); } +label { display: block; margin: 0 0 6px; font-weight: 600; font-size: 15px; } +input { width: 100%; margin: 0 0 16px; padding: 11px 12px; font: inherit; color: inherit; + background: transparent; border: 1px solid var(--line); border-radius: 8px; } +input:focus-visible, button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); + outline-offset: 2px; } +button, .button { display: block; width: 100%; padding: 12px; font: inherit; font-weight: 600; + text-align: center; text-decoration: none; color: var(--accent-text); background: var(--accent); + border: 0; border-radius: 8px; cursor: pointer; } +form { margin: 0; } +nav { display: flex; gap: 14px; font-size: 14px; color: var(--muted); } +nav a { color: var(--accent); } +nav [aria-current] { color: var(--text); font-weight: 600; text-decoration: none; } +`; + +interface PageOptions { + lang: Lang; + path: string; + title: string; + body: string; +} + +function page({ lang, path, title, body }: PageOptions): string { + const switcher = LANGS.map(({ code, name }) => + code === lang + ? `${name}` + : `${name}`, + ).join(""); + return ` + + + + +${escapeHtml(title)} + + + +
+${body} +
+ + + +`; +} + +export interface LoginPageOptions { + lang: Lang; + login?: string; + error?: { key: TextKey; params?: Record }; +} + +export function loginPage({ lang, login = "", error }: LoginPageOptions): string { + const e = (key: TextKey, params?: Record) => + escapeHtml(t(lang, key, params)); + const body = `

${e("login.title")}

+

${e("login.lead")}

+${error ? `` : ""} +
+ + + + + +
`; + return page({ lang, path: "/login", title: t(lang, "login.title"), body }); +} + +export function homePage({ lang, login }: { lang: Lang; login: string }): string { + const e = (key: TextKey, params?: Record) => + escapeHtml(t(lang, key, params)); + const body = `

${e("home.signedInAs", { login })}

+

${e("home.lead")}

`; + return page({ lang, path: "/", title: t(lang, "home.title"), body }); +} + +/** Страница с одним сообщением: «страницы нет» или «что-то пошло не так». */ +export function messagePage(options: { + lang: Lang; + path: string; + title: TextKey; + text: TextKey; + link?: TextKey; +}): string { + const { lang } = options; + const body = `

${escapeHtml(t(lang, options.title))}

+

${escapeHtml(t(lang, options.text))}

+${options.link ? `${escapeHtml(t(lang, options.link))}` : ""}`; + return page({ lang, path: options.path, title: t(lang, options.title), body }); +} diff --git a/test/auth.test.js b/test/auth.test.js deleted file mode 100644 index e0cb165..0000000 --- a/test/auth.test.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; -const test = require('node:test'); -const assert = require('node:assert'); -const fs = require('node:fs'); -const os = require('node:os'); -const path = require('node:path'); -const { createServer } = require('../src/server'); -const { addUser } = require('../src/users'); - -const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'tr2-')), 'users.json'); -addUser(file, 'anna', 'Anna-pass-2026'); -addUser(file, 'boris', 'Boris-pass-2026'); - -let clock = 1_000_000; -async function start() { - const server = createServer({ usersFile: file, now: () => clock, secret: 's' }); - await new Promise((r) => server.listen(0, r)); - const base = `http://127.0.0.1:${server.address().port}`; - const post = (login, password) => fetch(`${base}/login`, { - method: 'POST', redirect: 'manual', - headers: { 'content-type': 'application/x-www-form-urlencoded' }, - body: new URLSearchParams({ login, password }), - }); - const welcome = async (res) => { - const r = await fetch(base + res.headers.get('location'), { headers: { cookie: res.headers.get('set-cookie').split(';')[0] } }); - return r.text(); - }; - return { server, post, welcome }; -} - -test('Сценарий: вход пользователя А и пользователя Б', async () => { - const { server, post, welcome } = await start(); - const a = await post('anna', 'Anna-pass-2026'); - assert.strictEqual(a.status, 302); - assert.match(await welcome(a), /Вы вошли как anna/); - const b = await post('boris', 'Boris-pass-2026'); - assert.match(await welcome(b), /Вы вошли как boris/); - server.close(); -}); - -test('Сценарий: логин А с паролем Б и несуществующий логин дают одинаковую ошибку', async () => { - const { server, post } = await start(); - const wrong = await post('anna', 'Boris-pass-2026'); - const ghost = await post('nobody', 'x'); - assert.strictEqual(wrong.status, 401); - assert.strictEqual(ghost.status, 401); - const [w, g] = [await wrong.text(), await ghost.text()]; - assert.match(w, /Неверный логин или пароль/); - assert.strictEqual(w.replace('value="anna"', ''), g.replace('value="nobody"', '')); - server.close(); -}); - -test('Сценарий: блокировка на 15 минут, потом вход, и успех обнуляет счётчик', async () => { - const { server, post } = await start(); - for (let i = 0; i < 5; i++) assert.strictEqual((await post('boris', 'bad')).status, 401); - const locked = await post('boris', 'Boris-pass-2026'); - assert.strictEqual(locked.status, 429); - assert.match(await locked.text(), /слишком много/); - clock += 15 * 60 * 1000 + 1; - assert.strictEqual((await post('boris', 'Boris-pass-2026')).status, 302); - // счётчик обнулён: 4 ошибки после успеха не закрывают вход - for (let i = 0; i < 4; i++) await post('anna', 'bad'); - assert.strictEqual((await post('anna', 'Anna-pass-2026')).status, 302); - for (let i = 0; i < 4; i++) await post('anna', 'bad'); - assert.strictEqual((await post('anna', 'Anna-pass-2026')).status, 302); - server.close(); -}); - -test('Сценарий: неверные попытки на несуществующий логин тоже блокируются', async () => { - const { server, post } = await start(); - for (let i = 0; i < 5; i++) await post('ghost', 'x'); - assert.strictEqual((await post('ghost', 'x')).status, 429); - server.close(); -}); - -test('Сценарий: пустые поля не выполняют вход', async () => { - const { server, post } = await start(); - const r = await post('anna', ''); - assert.strictEqual(r.status, 400); - server.close(); -}); - -test('Сценарий: пароли не видны в хранилище', () => { - const text = fs.readFileSync(file, 'utf8') + fs.readFileSync(path.join(__dirname, '..', 'data', 'users.json'), 'utf8'); - assert.ok(!text.includes('Anna-pass-2026')); - assert.ok(!text.includes('Boris-pass-2026')); -}); diff --git a/test/auth.test.ts b/test/auth.test.ts new file mode 100644 index 0000000..fe5e367 --- /dev/null +++ b/test/auth.test.ts @@ -0,0 +1,122 @@ +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { createAuth, LOCK_MS } from "../src/auth.ts"; +import { addUser, hashPassword, loadUsers, verifyPassword } from "../src/users.ts"; +import { cookieFrom, startApp, type TestApp } from "./helpers.ts"; + +// Сценарии openspec/specs/auth/spec.md (TR-2). Пользователи: anna / s3cret-pass, boris / Boris-pass-2026. +const INVALID = "Неверный логин или пароль"; +const LOCKED = "Попыток было слишком много. Подождите 15 минут и попробуйте снова."; + +let app: TestApp; +afterEach(() => app?.close()); + +const fail = async (login: string, times: number) => { + for (let i = 0; i < times; i++) { + expect((await app.post("/login", { login, password: "bad" })).status).toBe(401); + } +}; + +describe("Requirement: Вход по списку пользователей", () => { + it.each([ + ["Scenario: Вход пользователя А", "anna", "s3cret-pass"], + ["Scenario: Вход пользователя Б", "boris", "Boris-pass-2026"], + ])("%s", async (_name, login, password) => { + app = await startApp(); + const cookie = await app.signIn(login, password); + expect(await (await app.get("/", { cookie })).text()).toContain(`Вы вошли как ${login}`); + }); + + it("Scenario: Логин А с паролем Б", async () => { + app = await startApp(); + const response = await app.post("/login", { login: "anna", password: "Boris-pass-2026" }); + expect(response.status).toBe(401); + expect(await response.text()).toContain(INVALID); + expect(cookieFrom(response, "session")).toBeUndefined(); + }); +}); + +describe("Requirement: Одинаковая ошибка", () => { + it("Scenario: Несуществующий логин", async () => { + app = await startApp(); + const wrong = await app.post("/login", { login: "anna", password: "x" }); + const ghost = await app.post("/login", { login: "nobody", password: "x" }); + expect(ghost.status).toBe(wrong.status); + const [w, g] = [await wrong.text(), await ghost.text()]; + expect(g).toContain(INVALID); + expect(g.replace('value="nobody"', "")).toBe(w.replace('value="anna"', "")); + }); +}); + +describe("Requirement: Временная блокировка", () => { + it("Scenario: Блокировка после пяти ошибок", async () => { + app = await startApp(); + await fail("anna", 5); + const response = await app.post("/login", { login: "anna", password: "s3cret-pass" }); + expect(response.status).toBe(429); + expect(await response.text()).toContain(LOCKED); + expect(cookieFrom(response, "session")).toBeUndefined(); + // Закрыт только этот логин: другой пользователь входит. + expect((await app.post("/login", { login: "boris", password: "Boris-pass-2026" })).status).toBe( + 303, + ); + }); + + it("Scenario: Вход после 15 минут", async () => { + app = await startApp(); + await fail("anna", 5); + app.advance(LOCK_MS - 1000); + expect((await app.post("/login", { login: "anna", password: "s3cret-pass" })).status).toBe(429); + app.advance(1000); + const cookie = await app.signIn("anna", "s3cret-pass"); + expect(await (await app.get("/", { cookie })).text()).toContain("Вы вошли как anna"); + }); + + it("Scenario: Успешный вход обнуляет счётчик", async () => { + app = await startApp(); + await fail("anna", 4); + await app.signIn("anna", "s3cret-pass"); + await fail("anna", 4); + expect((await app.post("/login", { login: "anna", password: "s3cret-pass" })).status).toBe(303); + }); + + it("неверные попытки на несуществующий логин тоже блокируются", async () => { + app = await startApp(); + await fail("ghost", 5); + expect((await app.post("/login", { login: "ghost", password: "x" })).status).toBe(429); + }); + + it("счётчик один для логина в любом регистре", () => { + const auth = createAuth({ users: [], now: () => 0 }); + for (const login of ["Anna", " anna ", "ANNA", "anna", "aNNa"]) auth.login(login, "bad"); + expect(auth.login("anna", "bad")).toEqual({ ok: false, reason: "locked" }); + }); +}); + +describe("Requirement: Пароли не хранятся открыто", () => { + it("Scenario: Содержимое хранилища", () => { + const file = join(mkdtempSync(join(tmpdir(), "tr-users-")), "nested", "users.json"); + addUser(file, "anna", "Anna-pass-2026"); + addUser(file, "anna", "Anna-pass-2027"); + expect(readFileSync(file, "utf8")).not.toContain("Anna-pass"); + const users = loadUsers(file); + expect(users.map((user) => user.login)).toEqual(["anna"]); + expect(createAuth({ users }).login("anna", "Anna-pass-2027").ok).toBe(true); + expect(createAuth({ users }).login("anna", "Anna-pass-2026").ok).toBe(false); + }); + + it("в списке пользователей из репозитория нет открытых паролей", () => { + const users = loadUsers(new URL("../data/users.json", import.meta.url).pathname); + expect(users.length).toBeGreaterThanOrEqual(2); + for (const user of users) expect(user.passwordHash).toMatch(/^scrypt\$/); + }); + + it("нет файла — пустой список; испорченная запись не подходит ни к какому паролю", () => { + expect(loadUsers("/no/such/users.json")).toEqual([]); + expect(verifyPassword("x", "plain-text")).toBe(false); + expect(verifyPassword("x", "scrypt$3$8$1$AAAA$AAAA")).toBe(false); + expect(verifyPassword("x", hashPassword("x"))).toBe(true); + }); +}); diff --git a/test/helpers.ts b/test/helpers.ts new file mode 100644 index 0000000..fb72dab --- /dev/null +++ b/test/helpers.ts @@ -0,0 +1,78 @@ +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { type AppOptions, createApp } from "../src/app.ts"; +import { createAuth } from "../src/auth.ts"; +import { hashPassword, type User } from "../src/users.ts"; + +/** Список пользователей для тестов; хеши считаются один раз. */ +export const testUsers: User[] = [ + { login: "anna", passwordHash: hashPassword("s3cret-pass") }, + { login: "boris", passwordHash: hashPassword("Boris-pass-2026") }, +]; + +export interface TestApp { + /** Сдвинуть часы приложения вперёд. */ + advance(ms: number): void; + get(path: string, headers?: Record): Promise; + post( + path: string, + form: Record, + headers?: Record, + ): Promise; + /** Войти и вернуть cookie с отметкой о входе. */ + signIn(login: string, password: string): Promise; + close(): Promise; +} + +/** Значение cookie `name=value` из ответа (без атрибутов). */ +export function cookieFrom(response: Response, name: string): string | undefined { + return response.headers + .getSetCookie() + .map((cookie) => cookie.split(";")[0] ?? "") + .find((cookie) => cookie.startsWith(`${name}=`)); +} + +/** Приложение со списком пользователей: «anna» / «s3cret-pass» и «boris» / «Boris-pass-2026». */ +export async function startApp(overrides: Partial = {}): Promise { + let clock = Date.UTC(2026, 0, 1); + const now = () => clock; + const app = createApp({ + auth: createAuth({ users: testUsers, now }), + sessionSecret: Buffer.from("test-session-secret"), + cookieSecure: false, + now, + ...overrides, + }); + const server: Server = createServer((req, res) => void app(req, res)); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + + const get: TestApp["get"] = (path, headers = {}) => + fetch(base + path, { headers, redirect: "manual" }); + const post: TestApp["post"] = (path, form, headers = {}) => + fetch(base + path, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded", ...headers }, + body: new URLSearchParams(form).toString(), + redirect: "manual", + }); + + return { + advance: (ms) => { + clock += ms; + }, + get, + post, + signIn: async (login, password) => { + const response = await post("/login", { login, password }); + const cookie = cookieFrom(response, "session"); + if (response.status !== 303 || !cookie) throw new Error(`Вход не удался: ${response.status}`); + return cookie; + }, + close: () => + new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }), + }; +} diff --git a/test/login.test.ts b/test/login.test.ts new file mode 100644 index 0000000..99ed427 --- /dev/null +++ b/test/login.test.ts @@ -0,0 +1,241 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { createSessionToken } from "../src/session.ts"; +import { cookieFrom, startApp, type TestApp } from "./helpers.ts"; + +const INVALID = "Неверный логин или пароль. Проверьте их и попробуйте ещё раз."; +const EMPTY = "Вы не заполнили логин или пароль. Заполните оба поля и нажмите «Войти»."; + +let app: TestApp; +afterEach(() => app?.close()); + +/** Значение поля «Логин» на странице. */ +const loginFieldValue = (html: string) => /]* value="([^"]*)"/.exec(html)?.[1]; + +describe("Requirement: Страница входа", () => { + it("Scenario: Страница входа открывается", async () => { + app = await startApp(); + const response = await app.get("/login"); + const html = await response.text(); + expect(response.status).toBe(200); + expect(html).toContain("

Вход

"); + expect(html).toContain("Введите логин и пароль. После входа откроется главная страница."); + expect(html).toContain(''); + expect(html).toContain(''); + expect(html).toMatch(/]* type="password"/); + expect(html).toContain(''); + }); + + it("Scenario: Вход нажатием Enter", async () => { + app = await startApp(); + const html = await (await app.get("/login")).text(); + // Оба поля и кнопка отправки лежат в одной форме: Enter в любом поле отправляет её. + const form = + /
]*>([\s\S]*?)<\/form>/.exec(html)?.[1] ?? ""; + expect(form).toContain('name="login"'); + expect(form).toContain('name="password"'); + expect(form).toContain('