diff --git a/.gitea/actions/kaniko-push/Dockerfile b/.gitea/actions/kaniko-push/Dockerfile new file mode 100644 index 0000000..f43c97c --- /dev/null +++ b/.gitea/actions/kaniko-push/Dockerfile @@ -0,0 +1,4 @@ +FROM ghcr.io/osscontainertools/kaniko:v1.28.5-debug@sha256:c73ca67a3b494bce79a8fb6090c4f73c18997ab272d80bffc460a62343aeb412 +COPY release-build.sh /usr/local/bin/release-build +COPY validate-destination.sh /usr/local/bin/validate-destination.sh +ENTRYPOINT ["/busybox/sh", "/usr/local/bin/release-build"] diff --git a/.gitea/actions/kaniko-push/action.yml b/.gitea/actions/kaniko-push/action.yml new file mode 100644 index 0000000..e98525b --- /dev/null +++ b/.gitea/actions/kaniko-push/action.yml @@ -0,0 +1,23 @@ +name: Publish a pinned Akyldash image +description: Build and push one commit-tagged image with pinned rootless Kaniko +inputs: + workspace: + description: Checked out source directory + required: true + dockerfile: + description: Dockerfile path relative to workspace + required: true + destination: + description: Commit-specific OCI tag + required: true + digest_file: + description: Workspace path for Kaniko's resulting digest + required: true +runs: + using: docker + image: Dockerfile + args: + - ${{ inputs.workspace }} + - ${{ inputs.dockerfile }} + - ${{ inputs.destination }} + - ${{ inputs.digest_file }} diff --git a/.gitea/actions/kaniko-push/release-build.sh b/.gitea/actions/kaniko-push/release-build.sh new file mode 100644 index 0000000..bc56aeb --- /dev/null +++ b/.gitea/actions/kaniko-push/release-build.sh @@ -0,0 +1,22 @@ +#!/busybox/sh +set -eu + +workspace=$1 +dockerfile=$2 +destination=$3 +digest_file=$4 +: "${REGISTRY_USERNAME:?registry username secret is required}" +: "${REGISTRY_PASSWORD:?registry password secret is required}" +/busybox/sh /usr/local/bin/validate-destination.sh "$dockerfile" "$destination" + +mkdir -p /kaniko/.docker "$(dirname "$digest_file")" +auth=$(printf '%s:%s' "$REGISTRY_USERNAME" "$REGISTRY_PASSWORD" | base64 | tr -d '\n') +umask 077 +printf '{"auths":{"git.vakanaut.ru":{"auth":"%s"}}}\n' "$auth" > /kaniko/.docker/config.json +unset auth REGISTRY_USERNAME REGISTRY_PASSWORD +/kaniko/executor \ + --context="dir://${workspace}" \ + --dockerfile="${workspace}/${dockerfile}" \ + --destination="$destination" \ + --digest-file="$digest_file" \ + --no-push-cache diff --git a/.gitea/actions/kaniko-push/validate-destination.sh b/.gitea/actions/kaniko-push/validate-destination.sh new file mode 100644 index 0000000..8650f41 --- /dev/null +++ b/.gitea/actions/kaniko-push/validate-destination.sh @@ -0,0 +1,49 @@ +#!/bin/sh +set -eu + +if [ "$#" -ne 2 ]; then + echo 'ERROR: expected Dockerfile path and image destination' >&2 + exit 2 +fi + +dockerfile=$1 +destination=$2 +case "$dockerfile" in + deploy/production/Dockerfile.backend) + repository=git.vakanaut.ru/admin/akyldash/backend + ;; + deploy/production/Dockerfile.opensearch) + repository=git.vakanaut.ru/admin/akyldash/opensearch + ;; + *) + echo 'ERROR: Dockerfile is outside the approved production image set' >&2 + exit 2 + ;; +esac + +case "$destination" in + "$repository":*) tag=${destination#"$repository":} ;; + *) + echo 'ERROR: destination is outside the approved registry repository' >&2 + exit 2 + ;; +esac + +commit=${tag%%-*} +run_id=${tag#*-} +case "$commit" in + ''|*[!0123456789abcdef]*) + echo 'ERROR: destination commit must be a lowercase Git SHA-1' >&2 + exit 2 + ;; +esac +if [ "${#commit}" -ne 40 ] || [ "$run_id" = "$tag" ]; then + echo 'ERROR: destination tag must contain a 40-character commit and run ID' >&2 + exit 2 +fi +case "$run_id" in + ''|*[!0123456789]*) + echo 'ERROR: destination run ID must be numeric' >&2 + exit 2 + ;; +esac diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml index 2bd50f4..6638e57 100644 --- a/.gitea/workflows/ci.yaml +++ b/.gitea/workflows/ci.yaml @@ -44,6 +44,7 @@ jobs: infra/bootstrap/verify.sh infra/bootstrap/verify-helper.sh infra/bootstrap/audit-host.sh \ infra/deploy/install-helper.sh infra/deploy/compose-helper.sh infra/deploy/test-compose-helper.sh \ infra/deploy/prepare-production-config.sh infra/deploy/test-production-config-guard.sh \ + .gitea/actions/kaniko-push/release-build.sh \ infra/bootstrap/test-audit-host.sh infra/bootstrap/test-root-guard.sh \ infra/bootstrap/test-verify-helper.sh infra/test/run-as-unprivileged.sh \ infra/runner/install-runner.sh infra/runner/install-runner-lib.sh \ @@ -52,6 +53,12 @@ jobs: infra/runner/test-ci-container-builds.sh python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/runner/secure-runner-image.py').read_text())" python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/validate_release.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/deploy_release.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/create_release_manifest.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_handoff.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_refs.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/release_state.py').read_text())" + python3 -c "import ast,pathlib; ast.parse(pathlib.Path('infra/deploy/deployment_lock.py').read_text())" - name: Run deployment contract and rollback tests run: python3 -m unittest discover -s infra/deploy -p 'test_*.py' -v - name: Validate production Compose and Caddyfile @@ -75,3 +82,14 @@ jobs: workspace: ${{ github.workspace }} dockerfile: deploy/production/Dockerfile.opensearch destination: akyldash-opensearch:ci + - name: Prepare a synthetic artifact compatibility marker + run: | + mkdir -p artifact-smoke + printf 'Gitea artifact upload smoke test; no release data.\n' > artifact-smoke/marker.txt + - name: Verify Gitea runtime artifact upload + uses: https://gitea.com/actions/gitea-upload-artifact@055b8b3f04a4a7ed853f2c6ab04256f83e4874dc + with: + name: artifact-smoke-${{ github.run_id }} + path: artifact-smoke/marker.txt + if-no-files-found: error + retention-days: 1 diff --git a/.gitea/workflows/deploy-handoff.yaml b/.gitea/workflows/deploy-handoff.yaml new file mode 100644 index 0000000..b187581 --- /dev/null +++ b/.gitea/workflows/deploy-handoff.yaml @@ -0,0 +1,64 @@ +name: Production handoff status (not deployed) + +on: + workflow_run: + workflows: ["Release production images"] + branches: [main] + types: [completed] + +jobs: + deployment-status: + name: NOT DEPLOYED - handoff status only + if: >- + gitea.event.workflow_run.conclusion == 'success' && + gitea.event.workflow_run.event == 'workflow_run' && + gitea.event.workflow_run.head_branch == 'main' + runs-on: akyldash-ci + steps: + - uses: actions/checkout@v4 + with: + ref: main + - name: Verify source release identity before artifact lookup + env: + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: python3 infra/deploy/release_handoff.py validate-handoff-source + - name: Read artifact metadata with the installed Gitea helper when available + env: + GITEA_URL: ${{ gitea.server_url }} + GITEA_TOKEN: ${{ gitea.token }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: | + if ! command -v gitea-api >/dev/null 2>&1; then + echo 'DRY-RUN only: gitea-api is unavailable in this job; artifact metadata and host handoff are not verified.' + python3 infra/deploy/release_handoff.py dry-run + exit 0 + fi + if [[ -z ${GITEA_TOKEN:-} ]]; then + echo 'DRY-RUN only: GITEA_TOKEN is unavailable; artifact metadata and host handoff are not verified.' + python3 infra/deploy/release_handoff.py dry-run + exit 0 + fi + metadata=$(mktemp) + trap 'rm -f "$metadata"' EXIT + gitea-api GET "/repos/admin/akyldash/actions/runs/${SOURCE_RUN_ID}/artifacts" > "$metadata" + python3 infra/deploy/release_handoff.py dry-run --artifact-metadata "$metadata" + - name: State that no deployment was performed + run: | + echo 'DEPLOYMENT STATUS: NOT DEPLOYED' + echo 'This workflow checks source provenance and may inspect artifact metadata only.' + echo 'It does not download the descriptor ZIP, open SSH, or invoke the Windows receiver.' + echo 'No Windows execution runner or automatic runtime binding has been verified.' diff --git a/.gitea/workflows/release-images.yaml b/.gitea/workflows/release-images.yaml new file mode 100644 index 0000000..866e4f9 --- /dev/null +++ b/.gitea/workflows/release-images.yaml @@ -0,0 +1,90 @@ +name: Release production images + +on: + workflow_run: + workflows: ["CI"] + branches: [main] + types: [completed] + +jobs: + publish-images: + if: >- + gitea.event.workflow_run.conclusion == 'success' && + gitea.event.workflow_run.event == 'push' && + gitea.event.workflow_run.head_branch == 'main' + runs-on: akyldash-ci + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ gitea.event.workflow_run.head_sha }} + - name: Verify successful CI source before using registry credentials + env: + SOURCE_WORKFLOW: ${{ gitea.event.workflow.name }} + SOURCE_WORKFLOW_PATH: ${{ gitea.event.workflow_run.path }} + SOURCE_EVENT: ${{ gitea.event.workflow_run.event }} + SOURCE_CONCLUSION: ${{ gitea.event.workflow_run.conclusion }} + SOURCE_BRANCH: ${{ gitea.event.workflow_run.head_branch }} + SOURCE_RUN_ID: ${{ gitea.event.workflow_run.id }} + SOURCE_SHA: ${{ gitea.event.workflow_run.head_sha }} + SOURCE_REPOSITORY: ${{ gitea.event.repository.full_name }} + run: python3 infra/deploy/release_handoff.py validate-ci-source + - name: Require explicitly configured Gitea registry credentials + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + run: | + test -n "$REGISTRY_USERNAME" || { echo 'REGISTRY_USERNAME repository secret is required'; exit 1; } + test -n "$REGISTRY_PASSWORD" || { echo 'REGISTRY_PASSWORD repository secret is required'; exit 1; } + - name: Build and publish backend image + uses: ./.gitea/actions/kaniko-push + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + with: + workspace: ${{ github.workspace }} + dockerfile: deploy/production/Dockerfile.backend + destination: git.vakanaut.ru/admin/akyldash/backend:${{ gitea.event.workflow_run.head_sha }}-${{ gitea.run_id }} + digest_file: ${{ github.workspace }}/release/backend.digest + - name: Build and publish OpenSearch image + uses: ./.gitea/actions/kaniko-push + env: + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }} + with: + workspace: ${{ github.workspace }} + dockerfile: deploy/production/Dockerfile.opensearch + destination: git.vakanaut.ru/admin/akyldash/opensearch:${{ gitea.event.workflow_run.head_sha }}-${{ gitea.run_id }} + digest_file: ${{ github.workspace }}/release/opensearch.digest + - name: Create and validate release descriptor + run: | + python3 infra/deploy/create_release_manifest.py \ + --repository admin/akyldash \ + --commit '${{ gitea.event.workflow_run.head_sha }}' \ + --run-id '${{ gitea.run_id }}' \ + --source-run-id '${{ gitea.event.workflow_run.id }}' \ + --backend-digest release/backend.digest \ + --opensearch-digest release/opensearch.digest \ + --output release/release-manifest.json + python3 infra/deploy/validate_release.py release/release-manifest.json \ + --policy infra/deploy/release-policy.json + (cd release && sha256sum release-manifest.json > release-manifest.json.sha256) + - id: descriptor + name: Record release descriptor digest + run: | + (cd release && sha256sum -c release-manifest.json.sha256) + digest=$(sha256sum release/release-manifest.json) + digest=${digest%% *} + printf 'descriptor_sha256=%s\n' "$digest" >> "$GITEA_OUTPUT" + - name: Upload verified release descriptor + uses: https://gitea.com/actions/gitea-upload-artifact@055b8b3f04a4a7ed853f2c6ab04256f83e4874dc + with: + name: release-descriptor-${{ gitea.run_id }}-${{ steps.descriptor.outputs.descriptor_sha256 }} + path: | + release/release-manifest.json + release/release-manifest.json.sha256 + if-no-files-found: error + retention-days: 90 + - name: Confirm uploaded release descriptor + run: | + (cd release && sha256sum -c release-manifest.json.sha256) + echo 'Release descriptor and checksum are available as this run artifact.' diff --git a/AGENTS.md b/AGENTS.md index a1e3fff..0c36664 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,11 @@ # Акылдаш — инструкции для агента Проект: юридическая информационно-аналитическая платформа; Search API на -Python, SQLite и OpenSearch. Production пока не развернут. +Python, SQLite и OpenSearch. На 2026-10-25 публичный `/review` и прямой origin +отвечают HTTP 200; состав production-контейнеров, готовность индекса и +проверенность backup/restore не подтверждены. Сверяй актуальное состояние с +[`CURRENT_STATE.md`](docs/operations/CURRENT_STATE.md), не считай HTTP 200 +доказательством готовности поиска. - Начинай с [инфраструктурного состояния](docs/operations/CURRENT_STATE.md) и [правил доступа](docs/operations/ACCESS.md). Не запрашивай доступы повторно. @@ -37,6 +41,31 @@ Python, SQLite и OpenSearch. Production пока не развернут. - После каждого изменения инфраструктуры обновляй `docs/operations/CURRENT_STATE.md` по фактическим проверкам. +## Delivery First: проверка по уровню риска + +- Перед работой укажи в PR уровень `LOW`, `MEDIUM` или `HIGH`; при сомнении + выбери более высокий. Уровень добавляет нужную проверку, но никогда не + отменяет CI, одобрение или защиту `main`. +- Каждый PR сохраняет текущие проверки Gitea Actions: job IDs + `tests-and-images` и `runner-smoke`. Не переименовывай и не обходи их, не + удаляй тесты или проверки безопасности ради скорости. +- `LOW`: документация, комментарии и тексты без изменения исполняемого + поведения или контракта; проверяй diff и актуальность утверждений, затем + дождись обычного CI. +- `MEDIUM`: изменение поведения в одном компоненте; добавь регрессионный тест, + выполни целевые проверки и обычный CI. +- `HIGH`: доступ/авторизация, данные и ingestion, схемы/хранилища, + backup/restore/recovery, production config, секреты, runner/CI, безопасность + или deploy; выполни целевые тесты вместе с обычным CI и приложи проверяемое + обоснование угроз, совместимости и rollback. Production-действия остаются + за владельцем. +- Ревью блокирует только конкретный воспроизводимый дефект, нарушение границы + доступа/безопасности, несовместимость данных или контракта, пропущенную + обязательную проверку либо отсутствие безопасного rollback. Идеи и стилистические + замечания перечисляй отдельно как неблокирующие. +- Полная процедура, метрики, Gitea-ограничения и проверенные временные бюджеты: + [DELIVERY_POLICY.md](docs/development/DELIVERY_POLICY.md). + ## Автономный workflow PR - Маршруты ниже указаны из контекста оркестратора/root: оркестратор — thread diff --git a/CHANGELOG.md b/CHANGELOG.md index f7eb34b..d41e71f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,49 @@ ## Не выпущено +- Успешный CI на `push` в `main` запускает release workflow: при настроенных + registry secrets он собирает образы rootless Kaniko, публикует digest + references и сохраняет schema-v4 descriptor с SHA-256 в Gitea artifact; + sidecar проверяется после извлечения из корня. Следующий workflow проверяет + source-run identity и, при доступном `gitea-api`, метаданные артефакта только + в dry-run и явно сообщает `NOT DEPLOYED`: ZIP не скачивается, SSH и host + apply не выполняются. Добавлена отдельная root-verified status→fixed-tuple→ + Windows `--once` привязка через строгий SSH dispatcher; она не использует + Gitea/PR runner и не требует Gitea token на Windows. Config и Task Scheduler + template выключены, задача не зарегистрирована и production CD не активирован. + Зелёный handoff не означает деплой. Подготовлены owner-run cutover и rollback с + проверкой backup, image IDs, RU/KY canaries и recovery journal; CI проверяет + synthetic artifact и завершается ошибкой при отсутствии файлов. Windows + receiver прошёл 17 synthetic client checks, 8 protocol checks и проверку + private owner ACL на disposable real-NTFS fixture. Inert Windows argv probe + подтвердил передачу пути скрипта с пробелами; Task Scheduler COM проверил + XML с `TASK_VALIDATE_ONLY` — задачу не регистрировали, не обновляли и не + запускали. Production D: path, SSH, установка на VPS и полный backup/restore + не проверены; cutover остаётся заблокирован до отдельного restore-теста и + owner bootstrap. Принимаются только завершённые успешные Gitea runs; pending + recovery journal записывается до остановки + сервисов, повторно применённый release отклоняется до простоя, а проверка + `main` использует явно заданный production checkout. Windows preflight + проверяет owner ACL и требует свободное место под максимальный допустимый + архив. +- Frontend `0.3.3` / Backend `0.13.2`: управление пользователями отображается + согласно правам аккаунта, подписи ролей локализованы, повторяющиеся действия + кабинета убраны, а знак лаборатории приведён к основному бренду. +- Добавлена политика Delivery First по уровням `LOW`/`MEDIUM`/`HIGH`: описаны + обязательная глубина проверок, регрессионные тесты и доказательства угроз, + совместимости и отката; обычные CI, одобрение и защита `main` остаются + обязательными. +- Frontend `0.3.2`: устранены пересечения названия бренда с поиском и + мобильной навигации документа; навигационные ссылки получили общие quiet и + primary состояния. +- Frontend `0.3.1`: уточнена компоновка поиска, лаборатории и кабинета; + splitter сохраняет минимальную ширину панелей, а на средних экранах фильтры + открываются доступной боковой панелью. Исправлено отображение футера на + маршруте пользователей и browser fixture смены пароля. +- Frontend `0.3.0` / Backend `0.13.1`: добавлен доступный splitter для + изменения ширины результатов и документа. Язык поиска находится в фильтрах; + состояния открытия, оглавление правовых заголовков, лаборатория и кабинет + приведены к последовательной и компактной компоновке. - Добавлен план развития платформы со сравнением возможностей «Токтом Онлайн», пробелов Акылдаша и этапов продуктовой проверки. - Frontend `0.2.6` / Backend `0.13.1`: двухпанельная компоновка поиска diff --git a/README.md b/README.md index c3f7aea..b5ec8c2 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,8 @@ Telegram-бот — только часть рабочего окружения ## Текущее состояние Сейчас реализованы Telegram-бот-секретарь версии `0.2.2`, backend версии -`0.13.0` и frontend `0.2.3` с поисковым экраном и внутренней лабораторией. +`0.13.2` и frontend `0.3.3` с поисковым экраном, внутренней лабораторией и +согласованным отображением доступных действий учетной записи. Авторизация хранится в SQLite; первый пользователь `admin` создаётся интерактивной CLI-командой. Поиск расширяет аббревиатуры организационно-правовых форм и поднимает @@ -19,8 +20,8 @@ SQLite; первый пользователь `admin` создаётся инт | Компонент | Версия | Состояние | |---|---:|---| | Telegram-бот | `0.2.2` | на Synology работает `0.2.1`; обновление после слияния | -| Backend | `0.13.0` | авторизация, поиск с фильтрами, ограниченный staging и статические ресурсы | -| Frontend | `0.2.3` | поиск по правовой базе, просмотр редакций и внутренняя лаборатория | +| Backend | `0.13.2` | авторизация, серверная capability управления пользователями, поиск и статические ресурсы | +| Frontend | `0.3.3` | поиск по правовой базе, просмотр редакций, внутренняя лаборатория и контекстная навигация кабинета | | Сбор и обработка правовых данных | `0.8.0` | добавлены relevance set и оценка выдачи | | RAG и база знаний | — | ещё не созданы | @@ -63,4 +64,4 @@ python3 -m unittest discover -s tools/telegram-bot -v --- -Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.0 · Frontend v0.2.3 +Акылдаш · Telegram-бот v0.2.2 · Backend v0.13.2 · Frontend v0.3.3 diff --git a/backend/README.md b/backend/README.md index 0aae543..d7e7e88 100644 --- a/backend/README.md +++ b/backend/README.md @@ -171,16 +171,31 @@ python3 backend/search/minjust_opensearch.py \ После проверки production-индекса следует переключать alias, чтобы удалённые фрагменты не оставались в поиске. -Чтобы переключить alias атомарно только после успешной полной загрузки, -передайте `--alias`: +Alias переключается только после refresh, точного сравнения полного fragment +count с inventory, обеих языковых canary-проверок и совпадения ожидаемого +текущего индекса. Перед cutover обязательно укажите RU/KY запросы и точное имя +старого target: ```bash python3 backend/search/minjust_opensearch.py \ --url http://127.0.0.1:9200 \ --index akyldash-fragments-v2 \ - --alias akyldash-fragments-current + --alias akyldash-fragments-current \ + --expected-old-index akyldash-fragments-v1 \ + --canary-ru 'утверждённый русский запрос' \ + --canary-ky 'бекитилген кыргызча суроо' ``` +Wildcard removal, пустой индекс и alias с несколькими target запрещены. Если +старый target успел измениться после проверки, OpenSearch отклонит атомарную +операцию удаления точного старого alias. `--resume` повторно проверяет весь +ожидаемый inventory, а не только количество документов текущего запуска. +Если ответ на alias request потерян после успешного переключения или процесс +остановился до записи завершённого checkpoint, повторный запуск проверит +фактическую цель alias. Уже опубликованный candidate оставляется на месте, и +checkpoint завершается; старый target позволяет безопасно повторить cutover, +а любой другой target останавливает операцию. + После каждого принятого Bulk-пакета загрузчик атомарно сохраняет checkpoint и печатает код безопасного возобновления. При временных HTTP 429/5xx, timeout и обрыве соединения запрос повторяется автоматически. Прерванную загрузку можно diff --git a/backend/search/api.py b/backend/search/api.py index bea9111..d69fe59 100644 --- a/backend/search/api.py +++ b/backend/search/api.py @@ -13,7 +13,7 @@ import urllib.parse from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from search.auth import AuthError, AuthStore +from search.auth import AuthError, AuthStore, can_manage_users from search.minjust_opensearch import APP_VERSION, request_json from search.catalog import CATALOGS, labels from search.query import build_search_query @@ -345,21 +345,21 @@ class Api: return 200, {"account": account, "session_token": token} except AuthError as error: raise ApiError(400, str(error)) from error - if user and user["username"].casefold() == "admin" and method == "GET" and parts == ["admin", "users"]: + if user and can_manage_users(user["username"]) and method == "GET" and parts == ["admin", "users"]: return 200, {"users": self.auth_store.list_users()} - if user and user["username"].casefold() == "admin" and method == "POST" and parts == ["admin", "users"]: + if user and can_manage_users(user["username"]) and method == "POST" and parts == ["admin", "users"]: try: self.auth_store.create_user(body.get("username"), body.get("password")) return 201, {"ok": True} except AuthError as error: raise ApiError(400, str(error)) from error - if user and user["username"].casefold() == "admin" and method == "DELETE" and len(parts) == 3 and parts[:2] == ["admin", "users"]: + if user and can_manage_users(user["username"]) and method == "DELETE" and len(parts) == 3 and parts[:2] == ["admin", "users"]: try: self.auth_store.delete_user(parts[2]) return 200, {"ok": True} except AuthError as error: raise ApiError(400, str(error)) from error - if user and user["username"].casefold() == "admin" and method == "POST" and len(parts) == 4 and parts[:2] == ["admin", "users"] and parts[3] == "reset-password": + if user and can_manage_users(user["username"]) and method == "POST" and len(parts) == 4 and parts[:2] == ["admin", "users"] and parts[3] == "reset-password": try: self.auth_store.reset_password(parts[2], body.get("password")) return 200, {"ok": True} @@ -424,7 +424,7 @@ def handler(api: Api): raise ApiError(401, "authentication required") if user["must_change_password"] and not (method == "POST" and route == "/auth/change-password") and not (method == "GET" and route == "/auth/me"): raise ApiError(403, "change password before continuing") - if route.startswith("/admin/users") and user["username"].casefold() != "admin": + if route.startswith("/admin/users") and not can_manage_users(user["username"]): raise ApiError(403, "admin account required") body = None if method in {"POST", "DELETE"}: @@ -503,7 +503,7 @@ def main() -> int: api = Api(arguments.url, arguments.index, arguments.data, arguments.reviews_db, secret, arguments.users_db, arguments.cookie_secure) if arguments.create_admin or arguments.reset_admin_password: users = api.auth_store.list_users() - admin_exists = any(user["username"].casefold() == "admin" for user in users) + admin_exists = any(can_manage_users(user["username"]) for user in users) if arguments.create_admin and users: parser.error("accounts already exist") if arguments.reset_admin_password and not admin_exists: diff --git a/backend/search/auth.py b/backend/search/auth.py index 3583a5e..bb50645 100644 --- a/backend/search/auth.py +++ b/backend/search/auth.py @@ -22,6 +22,10 @@ class AuthError(ValueError): pass +def can_manage_users(username: str) -> bool: + return isinstance(username, str) and username.casefold() == "admin" + + class AuthStore: def __init__(self, path: Path | str): if path != ":memory:": @@ -106,7 +110,8 @@ class AuthStore: @staticmethod def _public(user: sqlite3.Row) -> dict: - return {"username": user["username"], "role": "Администратор", "must_change_password": bool(user["must_change_password"]), "created_at": user["created_at"]} + can_manage = can_manage_users(user["username"]) + return {"username": user["username"], "role": "Администратор" if can_manage else "Пользователь", "can_manage_users": can_manage, "must_change_password": bool(user["must_change_password"]), "created_at": user["created_at"]} def user_for_token(self, token: str | None) -> dict | None: if not token: @@ -151,7 +156,7 @@ class AuthStore: raise AuthError("login already exists") from error def delete_user(self, username: str) -> None: - if username.casefold() == "admin": + if can_manage_users(username): raise AuthError("admin account cannot be deleted") with self._lock: self.connection.execute("DELETE FROM users WHERE username=?", (username,)) diff --git a/backend/search/minjust_opensearch.py b/backend/search/minjust_opensearch.py index 807ef09..0e67b8d 100644 --- a/backend/search/minjust_opensearch.py +++ b/backend/search/minjust_opensearch.py @@ -17,7 +17,7 @@ from typing import Iterator from search.catalog import authority_codes, legal_force_code, source_code -APP_VERSION = "0.13.1" +APP_VERSION = "0.13.3" LANGUAGES = {"ru", "ky"} DEFAULT_MAPPING = Path(__file__).with_name("minjust-fragments-index.json") @@ -342,10 +342,17 @@ def load_bulk( resume: bool = False, checkpoint: Path = Path("data/opensearch/minjust-fragments.checkpoint.json"), alias: str | None = None, + expected_old_index: str | None = None, + canary_ru: str | None = None, + canary_ky: str | None = None, ) -> tuple[int, int]: base = url.rstrip("/") if alias is not None and (not alias or alias == index): raise ValueError("--alias must differ from --index") + if alias is not None and (not expected_old_index or expected_old_index == index): + raise ValueError("alias publication requires an exact --expected-old-index") + if alias is not None and (not canary_ru or not canary_ky): + raise ValueError("alias publication requires both Russian and Kyrgyz canary queries") index_url = f"{base}/{urllib.parse.quote(index, safe='')}" if resume: cluster_uuid, index_uuid = opensearch_identity(base, index, index_url) @@ -364,6 +371,7 @@ def load_bulk( alias, ) documents = document_count(input_root, limit, start_at) + expected_fragments = sum(1 for _ in bulk_pairs(input_root, index, limit)) if alias else None if not resume: write_json_atomic(checkpoint, state) fragments = 0 @@ -398,27 +406,100 @@ def load_bulk( write_json_atomic(checkpoint, state) print(f"checkpoint={last_code} fragments={fragments}", flush=True) if alias: - switch_alias(base, index, alias) + if not expected_fragments: + raise ValueError("refusing to publish an index with an empty expected fragment inventory") + validate_candidate_index(base, index, expected_fragments, canary_ru, canary_ky) + switch_alias(base, index, alias, expected_old_index) state["complete"] = True write_json_atomic(checkpoint, state) return documents, fragments -def switch_alias(base: str, index: str, alias: str) -> None: +def alias_target(base: str, alias: str) -> str: + alias_url = f"{base.rstrip('/')}/_alias/{urllib.parse.quote(alias, safe='')}" + try: + result = request_json(alias_url, "GET", None, "application/json") + except RuntimeError as error: + if "failed with HTTP 404:" in str(error): + raise ValueError(f"alias {alias} has no current target; explicit bootstrap is required") from error + raise + if not isinstance(result, dict) or len(result) != 1: + raise ValueError(f"alias {alias} must point to exactly one index") + target, definition = next(iter(result.items())) + if not isinstance(definition, dict) or alias not in definition.get("aliases", {}): + raise ValueError(f"alias {alias} response is malformed") + return target + + +def validate_candidate_index( + base: str, index: str, expected_fragments: int, canary_ru: str, canary_ky: str +) -> None: + if expected_fragments <= 0: + raise ValueError("expected fragment count must be positive") + encoded_index = urllib.parse.quote(index, safe='') + refreshed = request_json(f"{base.rstrip('/')}/{encoded_index}/_refresh", "POST", None, "application/json") + shards = refreshed.get("_shards", {}) + if not isinstance(shards, dict) or shards.get("failed") != 0: + raise RuntimeError(f"refresh failed for candidate index {index}") + count_result = request_json(f"{base.rstrip('/')}/{encoded_index}/_count", "GET", None, "application/json") + if count_result.get("count") != expected_fragments: + raise RuntimeError( + f"candidate index {index} has {count_result.get('count')} fragments; expected {expected_fragments}" + ) + for language, query in (("ru", canary_ru), ("ky", canary_ky)): + payload = json.dumps({"size": 1, "query": {"match": {f"text_{language}": query}}}).encode() + result = request_json( + f"{base.rstrip('/')}/{encoded_index}/_search", "POST", payload, "application/json" + ) + hits = result.get("hits", {}).get("hits", []) + if not hits or not isinstance(hits[0].get("_source", {}).get(f"text_{language}"), str): + raise RuntimeError(f"candidate index {index} failed the {language} canary query") + + +def switch_alias(base: str, index: str, alias: str, expected_old_index: str) -> None: if not alias or alias == index: raise ValueError("--alias must differ from --index") - result = request_json( - f"{base.rstrip('/')}/_aliases", - "POST", - json.dumps({ - "actions": [ - {"remove": {"index": "*", "alias": alias, "must_exist": False}}, - {"add": {"index": index, "alias": alias}}, - ] - }).encode(), - "application/json", - ) - if result.get("acknowledged") is not True: + if not expected_old_index or expected_old_index == index: + raise ValueError("--expected-old-index must name the exact previous index") + actual_old_index = alias_target(base, alias) + if actual_old_index == index: + return + if actual_old_index != expected_old_index: + raise ValueError( + f"alias {alias} currently targets {actual_old_index}, expected {expected_old_index}; refusing cutover" + ) + try: + result = request_json( + f"{base.rstrip('/')}/_aliases", + "POST", + json.dumps({ + "actions": [ + {"remove": {"index": expected_old_index, "alias": alias, "must_exist": True}}, + {"add": {"index": index, "alias": alias}}, + ] + }).encode(), + "application/json", + ) + except Exception as error: + try: + current = alias_target(base, alias) + except Exception: + raise RuntimeError(f"alias switch outcome is unknown; inspect {alias} before resuming") from error + if current == index: + return + if current != expected_old_index: + raise ValueError( + f"alias {alias} now targets unexpected index {current}; refusing to retry publication" + ) from error + raise RuntimeError(f"alias switch failed; {alias} still targets {expected_old_index}") from error + if not isinstance(result, dict) or result.get("acknowledged") is not True: + current = alias_target(base, alias) + if current == index: + return + if current != expected_old_index: + raise ValueError( + f"alias {alias} now targets unexpected index {current}; refusing to retry publication" + ) raise RuntimeError(f"OpenSearch did not acknowledge alias switch: {alias}") @@ -430,6 +511,9 @@ def main() -> int: parser.add_argument("--limit", type=int) parser.add_argument("--url", help="create the index and stream bounded Bulk requests instead of writing a file") parser.add_argument("--alias", help="atomically point this alias at --index after a successful load") + parser.add_argument("--expected-old-index", help="exact current alias target required for guarded cutover") + parser.add_argument("--canary-ru", help="approved Russian query that must match the candidate index") + parser.add_argument("--canary-ky", help="approved Kyrgyz query that must match the candidate index") parser.add_argument("--mapping", type=Path, default=DEFAULT_MAPPING) parser.add_argument("--batch-mb", type=int, default=25) parser.add_argument("--resume", action="store_true", help="load into an existing index") @@ -460,12 +544,15 @@ def main() -> int: arguments.resume, checkpoint, arguments.alias, + arguments.expected_old_index, + arguments.canary_ru, + arguments.canary_ky, ) destination = arguments.url else: documents, fragments = export_bulk(arguments.input, arguments.output, arguments.index, arguments.limit) destination = arguments.output - print(f"documents={documents} fragments={fragments} destination={destination}\nAkyldash · Backend v{APP_VERSION} · Frontend v0.2.6") + print(f"documents={documents} fragments={fragments} destination={destination}\nAkyldash · Backend v{APP_VERSION} · Frontend v0.3.3") return 0 diff --git a/backend/search/review.html b/backend/search/review.html index 6a95198..d38c2c4 100644 --- a/backend/search/review.html +++ b/backend/search/review.html @@ -14,18 +14,18 @@ @font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-cyrillic-ext.woff2") format("woff2"); unicode-range: U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F; } @font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-cyrillic.woff2") format("woff2"); unicode-range: U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116; } @font-face { font-family: "Noto Serif"; font-style: normal; font-weight: 100 900; font-display: swap; src: url("/static/fonts/noto-serif-latin.woff2") format("woff2"); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } - :root { color-scheme: light; font: 16px/1.5 "Noto Sans", sans-serif; color: #38262A; background: #F7F2E8; --ink: #38262A; --muted: #786469; --line: #DED3CE; --surface: #fff; --surface-muted: #FBF8F4; --brand: #9D2633; --brand-dark: #84202B; --accent: #A37B32; --focus: #245C78; --subtle: #F8EBED; --serif: "Noto Serif", serif; } + :root { color-scheme: light; font: 16px/1.5 "Noto Sans", sans-serif; color: #38262A; background: #F7F2E8; --ink: #38262A; --muted: #786469; --line: #DED3CE; --surface: #fff; --surface-muted: #FBF8F4; --brand: #9D2633; --brand-dark: #84202B; --accent: #A37B32; --focus: #245C78; --subtle: #F8EBED; --sans: "Noto Sans", sans-serif; --serif: "Noto Serif", serif; } * { box-sizing: border-box; } body { margin: 0; color: var(--ink); background: #F7F2E8; } .review__skip { position: absolute; inset-block-start: 0; inset-inline-start: -10000px; padding: .5rem 1rem; background: var(--surface); } .review__skip:focus { inset-inline-start: 1rem; z-index: 2; } .review__header, .review__main { max-width: 1320px; margin: auto; padding-inline: clamp(1rem, 3vw, 3rem); } .review__header { padding-block: 0 1.5rem; background: var(--surface); border-block-end: 1px solid var(--line); } - .review__header h1 { max-width: 24ch; margin: 1.5rem 0 .4rem; font: 700 clamp(1.75rem, 3vw, 2rem)/1.2 var(--serif); } + .review__header h1 { max-width: none; margin: 1.5rem 0 .4rem; font: 700 clamp(1.75rem, 3vw, 2rem)/1.2 var(--serif); } .review__header p { max-width: 65ch; margin: 0; color: var(--muted); } .review__header-top { display: flex; justify-content: space-between; gap: 1rem; align-items: start; } .review__eyebrow { display: inline-flex; align-items: center; gap: .5rem; color: var(--ink); font: 600 1.1rem/1.25 var(--serif); } - .review__eyebrow::before { content: ''; width: 1.5rem; height: 1.5rem; border: 2px solid var(--brand); border-radius: 50%; background: linear-gradient(90deg, transparent 45%, var(--brand) 45% 55%, transparent 55%), linear-gradient(0deg, transparent 45%, var(--brand) 45% 55%, transparent 55%); } + .review__eyebrow-mark { display: block; flex: 0 0 1.5rem; width: 1.5rem; height: 1.5rem; } .review__main { padding-block-end: 2rem; } .review__search { display: grid; grid-template-columns: minmax(18rem, 1fr) 9rem 9rem auto; align-items: end; gap: .75rem; padding: 1rem; background: var(--surface); border: 1px solid var(--line); border-radius: 6px; } .review__field { display: grid; gap: .35rem; min-width: 0; } @@ -39,7 +39,8 @@ button:active { scale: .96; } button:disabled { cursor: wait; opacity: .55; } .review__button--primary { background: var(--brand); color: #fff; border-color: var(--brand); } - .review__status { min-height: 1.7rem; margin-block: 1rem; color: var(--muted); } + .review__status { min-height: 0; margin-block: 0; color: var(--muted); } + .review__status:not(:empty) { margin-block: .5rem; } .review__status--error { color: #9D2633; } .review__workspace { display: grid; grid-template-columns: minmax(24rem, .9fr) minmax(28rem, 1.1fr); gap: 1rem; align-items: start; } .review__results, .review__document { min-width: 0; background: var(--surface); border: 1px solid var(--line); border-radius: 6px; padding: clamp(1rem, 2vw, 1.5rem); } @@ -48,13 +49,13 @@ .review__panel-hint { color: var(--muted); font-size: .875rem; } .review__results-list { display: grid; gap: .75rem; margin: 0; padding: 0; list-style: none; } .review__result { padding: 1rem 0; border: 0; border-block-end: 1px solid var(--line); border-radius: 0; background: var(--surface); transition-property: background-color, border-color; transition-duration: 150ms; transition-timing-function: cubic-bezier(.2, 0, 0, 1); } - .review__result--selected { background: var(--subtle); box-shadow: none; } + .review__result--selected { padding: 8px 10px; background: var(--subtle); box-shadow: none; } .review__result:first-child { border-block-start: 1px solid var(--line); } .review__result-title { display: flex; gap: .65rem; align-items: baseline; width: 100%; min-height: 44px; text-align: start; font-weight: 700; border: 0; padding: 0; background: none; color: var(--brand-dark); } .review__rank { flex: 0 0 auto; color: var(--brand); font-variant-numeric: tabular-nums; } - .review__meta { margin-block: .5rem; color: var(--muted); font-size: .875rem; } - .review__rating { display: grid; grid-template-columns: repeat(4, 1fr); gap: .4rem; margin-block: 1rem .75rem; padding: 0; border: 0; } - .review__rating legend { width: 100%; margin-block-end: .35rem; font-size: .875rem; font-weight: 700; color: var(--muted); grid-column: 1 / -1; } + .review__meta { margin-block: 4px; color: var(--muted); font-size: .875rem; } + .review__rating { display: grid; grid-template-columns: repeat(4, 1fr); gap: .35rem; margin-block: 8px 6px; padding: 0; border: 0; } + .review__rating legend { width: 100%; margin-block-end: 2px; font-size: .875rem; font-weight: 700; color: var(--muted); grid-column: 1 / -1; } .review__rating label { display: grid; place-items: center; min-width: 0; min-height: 44px; padding: .45rem .25rem; border: 1px solid var(--line); border-radius: 6px; color: var(--muted); text-align: center; font-size: .875rem; cursor: pointer; } .review__rating label:has(input:checked) { border-color: var(--brand); background: var(--brand); color: #fff; } .review__rating label:has(input:focus-visible) { outline: 3px solid var(--focus); outline-offset: 2px; } @@ -110,7 +111,7 @@ .search__layout { display: grid; grid-template-columns: 230px minmax(320px, .9fr) minmax(420px, 1.2fr); min-height: 65vh; border-block: 1px solid var(--line); background: var(--surface); } .search__filters, .search__results, .search__document { min-width: 0; padding: 1rem; } .search__filters, .search__results { border-inline-end: 1px solid var(--line); } - .search__filters h2, .search__results h2, .search__document h2 { margin: 0; font: 600 1.5rem/1.3 var(--serif); } + .search__filters > .review__panel-heading h2, .search__results > .review__panel-heading h2 { margin: 0; font: 600 1.25rem/1.3 var(--sans); } .search__filters .review__panel-heading, .search__results .review__panel-heading { align-items: center; } .search__filter { margin-block: 1.25rem; } .search__filter h3 { margin: 0 0 .4rem; font-size: 1rem; } @@ -161,9 +162,11 @@ .review__workspace { grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); } .review__document { position: static; max-height: min(68dvh, 860px); overflow: auto; overscroll-behavior: contain; } .review__document-body { max-width: 72ch; margin-inline: auto; } + .review__document-body > h2:first-child { font: 600 30px/38px var(--serif); } .review__document-body table { display: block; max-width: 100%; overflow-x: auto; } .review__document-body p:empty { display: none; } .review__document-body a { color: var(--brand-dark); text-underline-offset: .18em; } + .review__document-meta a { color: var(--brand-dark); text-underline-offset: .18em; } .search__layout[data-filters-hidden="true"] { grid-template-columns: minmax(320px, .8fr) minmax(0, 1.5fr); } .search__layout[data-filters-hidden="true"] .search__filters { display: none; } .search__layout.is-expanded { position: fixed; z-index: 15; inset: 0; display: block; overflow: auto; background: var(--surface); } @@ -178,14 +181,15 @@ .search__layout:not([data-has-document="true"]) .search__toc, .search__layout:not([data-has-document="true"]) #document-source { display: none; } .search__layout:not([data-has-document="true"]) .search__document-body { display: none; } + .search__layout:not([data-has-document="true"]) .search__document-head h2 { display: none; } .search__mobile-filters { display: inline-flex; } .search__account button { display: inline-flex; width: auto; min-height: 44px; gap: 8px; align-items: center; padding: 8px 12px; } .search__account-label { display: inline; } .search__document-body table, .review__document-body table { display: block; max-width: 100%; overflow-x: auto; } .search__table-scroll { max-width: 100%; margin-block: 1rem; overflow-x: auto; overscroll-behavior-inline: contain; } .search__table-scroll table { width: max-content; min-width: 100%; border-collapse: collapse; } - .search__filters .review__panel-heading { align-items: center; flex-wrap: wrap; } - .search__filters .review__panel-heading h2 { flex: 1 1 auto; } + .search__filters .review__panel-heading { align-items: center; flex-wrap: nowrap; justify-content: space-between; gap: 8px; } + .search__filters .review__panel-heading h2 { flex: 0 1 auto; white-space: nowrap; } .search__filters .review__panel-heading button { flex: 0 0 auto; } .search__filter label { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 8px; min-height: 40px; } .search__filter label span { min-width: 0; overflow-wrap: anywhere; } @@ -212,6 +216,8 @@ body.is-users-route { min-height: 100dvh; display: flex; flex-direction: column; } body.is-users-route > .review__header { display: block; width: 100%; padding-block-end: 0; } body.is-users-route > .review__header > .review__header-content { display: none; } + body.is-users-route > .review__actions { display: none; } + body.is-users-route > .search__footer { display: none; } body.is-users-route > footer.review__header { display: block; margin-block-start: auto; } .review__users-page { width: min(1200px, 100%); flex: 1; margin-inline: auto; padding: 28px clamp(16px, 4vw, 48px); } .review__users-page[hidden] { display: none !important; } @@ -233,7 +239,6 @@ .search__layout:not([data-filters-hidden="true"]) .search__filters > .search__dates, .search__layout:not([data-filters-hidden="true"]) .search__filters > .search__date-label, .search__layout:not([data-filters-hidden="true"]) .search__filters > #filter-fields { grid-column: 1 / -1; } - .search__filters .search__ornament { display: none; } } @media (max-width: 900px) { body:has(.search:not([hidden])) { height: auto; min-height: 100dvh; overflow: visible; } @@ -281,12 +286,11 @@ body:has(.search:not([hidden])) > .search__chrome { display: block; } .search__chrome { display: none; background: var(--surface); border-block-end: 1px solid var(--line); } .search[hidden] { display: none !important; } - .search__topbar { min-height: var(--search-header-height); display: grid; grid-template-columns: minmax(390px, 430px) minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 5px 26px; border-block-end: 1px solid var(--line); } - .search__brand { display: flex; min-width: 0; align-items: center; gap: 12px; color: var(--ink); text-decoration: none; white-space: nowrap; } + .search__topbar { min-height: var(--search-header-height); display: grid; grid-template-columns: 166px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 5px 26px; border-block-end: 1px solid var(--line); } + .search__brand { display: flex; min-width: 0; align-items: center; gap: 8px; color: var(--ink); text-decoration: none; white-space: nowrap; } .search__brand-mark { width: 44px; height: 44px; flex: none; color: var(--brand); } - .search__brand-name { font: 700 26px/1.1 var(--serif); } - .search__brand-divider { width: 1px; height: 32px; background: var(--line); } - .search__brand-description { color: var(--muted); font-size: 14px; } + .search__brand-name { font: 700 22px/1.1 var(--serif); } + .search__brand-divider, .search__brand-description { display: none; } .search__query { display: grid; grid-template-columns: minmax(0, 1fr) 160px; gap: 12px; align-items: end; min-width: 0; padding: 0; border: 0; background: transparent; } .search__query label { display: grid; gap: 4px; color: var(--muted); font-size: 14px; font-weight: 500; } .search__query label > span { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } @@ -300,9 +304,10 @@ .search__ui-language button[aria-pressed="true"] { color: var(--ink); border-block-end: 2px solid var(--brand); } .search__account { display: flex; align-items: center; gap: 6px; margin-inline-start: auto; } .search__account button { width: 40px; min-height: 40px; padding: 8px; } - .search__account-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-block-end: 16px; } + .search__account-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-block: 24px 0; } .search__subnav { min-height: var(--search-nav-height); display: flex; align-items: center; gap: 12px; padding: 6px 26px; overflow-x: auto; white-space: nowrap; } - .search__subnav a, .search__subnav button { min-height: 36px; padding: 5px 14px; text-decoration: none; } + .search__subnav a, .search__subnav button { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 5px 14px; text-align: center; text-decoration: none; } + .search__subnav a:not(.is-active) { color: var(--ink); } .search__mobile-filters, .search__mobile-back, .search__filter-close, .search__filter-overlay { display: none; } .search__subnav a.is-active { min-width: 97px; background: var(--brand); color: #fff; border-color: var(--brand); } .search__subnav .search__nav-text { margin-inline: 11px 28px; padding-inline: 0; border: 0; color: var(--ink); font-size: 13px; } @@ -311,8 +316,7 @@ .search__chips .search__chip { padding-inline: 4px; } .search__chips .search__chip button { width: 16px; } .search__language-chip { padding-inline: 4px; } - .search__language-chip select { width: 78px; min-width: 0; min-height: 24px; border: 0; padding: 0 12px 0 0; background: transparent; font-size: 14px; } - html[lang="ky"] .search__language-chip select { width: 100px; } + .search__language-chip select { width: auto; min-width: 126px; min-height: 36px; border: 0; padding: 0 12px 0 0; background: transparent; font-size: 14px; } .search__chip button { min-height: 24px; width: 24px; padding: 0; border: 0; font-size: 18px; line-height: 1; } .search { width: 100%; max-width: none; min-height: 0; flex: 1; display: flex; flex-direction: column; margin: 0; } .search__sr-only { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } @@ -320,7 +324,9 @@ .search__layout { flex: 1; min-height: 0; grid-template-columns: minmax(210px, 226px) minmax(350px, 422px) minmax(400px, 1fr); border-block: 1px solid var(--line); } .search__filters, .search__results, .search__document { min-height: 0; padding: 14px 16px 20px; } .search__filters { position: relative; display: flex; flex-direction: column; overflow: auto; background: var(--surface-muted); padding-inline: 30px 16px; } - .search__filters .review__panel-heading { margin-block-end: 18px; } + .search__filters .review__panel-heading { margin-block-end: 8px; } + #search-filters > .review__panel-heading { margin-block-end: 0; } + #search-filters > .search__filter-language { margin-block-start: 0; } .search__filters .review__panel-heading button { min-height: 36px; padding: 2px; border: 0; color: var(--brand); text-decoration: underline; text-underline-offset: 3px; } .search__filter { margin-block: 0 16px; } .search__filter--document-type { margin-block-end: 24px; } @@ -340,7 +346,6 @@ .search__dates label:not(.has-value) input { color: transparent; } .search__date-placeholder { position: absolute; inset-inline-start: 9px; inset-block-start: 50%; color: var(--muted); font-size: 14px; pointer-events: none; transform: translateY(-50%); } .search__dates label.has-value .search__date-placeholder { display: none; } - .search__ornament { width: calc(100% - 12px); height: 56px; flex: none; margin: auto 6px 0; color: var(--accent); pointer-events: none; } .search__results { overflow: auto; background: var(--surface-muted); } .search__results .review__panel-heading { align-items: start; margin-block-end: 0; } .search__results .review__panel-heading select { min-height: 40px; padding: 6px 10px; font-size: 14px; } @@ -363,7 +368,7 @@ .search__document-head { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: start; } .search__breadcrumbs { display: flex; gap: 12px; align-items: center; color: var(--muted); font-size: 14px; } .search__breadcrumbs span:first-child { color: var(--brand); } - .search__document-head h2 { grid-column: 1 / -1; margin-block: 0 4px; color: var(--ink); font: 700 36px/1 var(--serif); } + .search__document-head h2 { grid-column: 1 / -1; margin-block: 0 4px; color: var(--ink); font: 600 30px/38px var(--serif); } .search__document-head .search__expand { min-height: 32px; border: 0; padding: 0 4px; } .search__document-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; border: 0; color: var(--muted); } .search__document-meta a { color: var(--brand); } @@ -374,7 +379,7 @@ .search__document-toolbar .search__edition-label { display: block; } .search__document-toolbar .search__edition-label select { width: 160px; max-width: 160px; } .search__source-link { max-width: 150px; margin-inline-start: auto; color: var(--brand); font-size: 14px; white-space: nowrap; } - .search__document-language { display: inline-flex !important; align-items: center; gap: 6px !important; margin-inline-start: auto; font-size: 12px !important; } + .search__document-language { display: inline-flex; align-items: center; gap: 6px; margin-inline-start: auto; font-size: 12px; } .search__document-language select { min-height: 28px; max-width: 130px; padding: 4px 8px; font-size: 14px; } .search__toc { margin-block-end: 0; } .search__toc summary { width: fit-content; min-height: 42px; padding: 9px 8px; border: 1px solid var(--line); border-radius: 6px; cursor: pointer; font-size: 14px; } @@ -428,8 +433,11 @@ .search__layout[data-mobile-view="results"] .search__document { display: none; } .search__layout[data-mobile-view="results"] .search__results { display: block; } .search__layout[data-mobile-view="document"] .search__filters { display: none; } - .search__ornament { display: none; } .search__document { min-height: 30rem; } + .search__document-head { grid-template-columns: minmax(0, 1fr); } + .search__document-head > div:nth-child(2) { display: flex; justify-content: space-between; gap: 8px; } + .search__breadcrumbs { min-width: 0; flex-wrap: wrap; } + .search__breadcrumbs #document-breadcrumb { min-width: 0; overflow-wrap: anywhere; } } @media (max-width: 600px) { .search__topbar { grid-template-columns: minmax(0,1fr) auto; gap: 8px; padding: 10px 16px; } @@ -466,6 +474,7 @@ body.is-users-route { width: 100%; height: auto; min-height: 100dvh; overflow: visible; display: flex; flex-direction: column; } body.is-users-route > header.review__header { display: block; width: 100%; padding-block-end: 0; } body.is-users-route > header.review__header > .review__header-content { display: none; } + body.is-users-route > .review__actions { display: none; } body.is-users-route > footer.review__header { display: block; width: 100%; margin-block-start: auto; } .search__layout { grid-template-columns: clamp(256px, 19.45vw, 280px) clamp(360px, 30vw, 408px) minmax(560px, 1fr); } .search__account button { width: auto; min-width: 44px; min-height: 44px; padding: 8px 12px; } @@ -486,14 +495,134 @@ .review__nav-links { order: 3; width: 100%; flex-wrap: wrap; } .review__nav-account { margin-inline-start: auto; } } + /* Shared follow-up corrections: consistent navigation, compact public search, + and a continuous workspace that keeps controls aligned to the same shell. */ + .review__nav { width: min(100%, 1440px); max-width: 1440px; } + .review__nav-links a, .review__nav-links button, #search-review-nav { + display: inline-flex; align-items: center; justify-content: center; min-height: 44px; + padding: 8px 14px; border: 1px solid var(--line); border-radius: 6px; + color: var(--brand); background: var(--surface); text-decoration: none; font: inherit; + } + .review__nav-links a:hover, .review__nav-links button:hover, #search-review-nav:hover { border-color: var(--line); background: var(--surface-muted); color: var(--brand); } + .review__nav-links .is-active, #search-review-nav.is-active { border-color: var(--brand); background: var(--brand); color: #fff; } + .review__nav-links .is-active:hover, #search-review-nav.is-active:hover { border-color: var(--brand-dark); background: var(--brand-dark); color: #fff; } + .review__nav-links a:focus-visible, .search__subnav a:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } + .review__nav-links [hidden], .search__account-actions [hidden] { display: none !important; } + .review__nav-account > span { color: var(--muted); } + .review__header-content { width: 100%; max-width: none; padding-inline: 24px; } + body:has(#review:not([hidden])) { min-height: 100dvh; height: 100dvh; overflow: hidden; } + body:has(#review:not([hidden])) > .review__header { padding: 0; } + body:has(#review:not([hidden])) > #review { width: 100%; max-width: none; min-height: 0; margin: 0; padding: 0; display: flex; flex-direction: column; } + body:has(#review:not([hidden])) > .review__actions { width: 100%; min-height: 96px; flex: 0 0 96px; box-sizing: border-box; margin: 0; padding: 0 24px; } + body:has(#review:not([hidden])) > footer.review__header { width: 100%; margin: 0; } + .review__header-content, .review__actions-inner { width: 100%; max-width: none; } + body:has(#review:not([hidden])) .review__nav { height: 64px; min-height: 64px; padding-block: 0; } + body:has(#review:not([hidden])) .review__header-content { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; height: 64px; } + body:has(#review:not([hidden])) .review__heading-copy { min-width: 0; display: grid; grid-template-rows: 32px 20px; align-content: center; } + body:has(#review:not([hidden])) .review__header-top { grid-column: 2; grid-row: 1; align-self: center; padding: 0; } + body:has(#review:not([hidden])) .review__header-content h1 { max-width: none; margin: 0; font: 600 26px/32px var(--sans); } + body:has(#review:not([hidden])) .review__header-content p { max-width: none; margin: 0; font: 400 14px/20px var(--sans); white-space: nowrap; } + .review__search { gap: 12px; padding: 12px 24px; border: 0; border-block-end: 1px solid var(--line); border-radius: 0; background: transparent; } + #status.review__status { grid-column: 1 / -1; margin: 0; } + #status.review__status:empty { display: none; } + #status.review__status--success { position: absolute; inline-size: 1px; block-size: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } + .review__workspace { min-height: 0; flex: 1 1 0; grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); gap: 0; align-items: stretch; overflow: hidden; border-block: 1px solid var(--line); background: var(--surface); } + .review__results, .review__document { min-height: 0; max-height: none; padding: 14px 24px; border: 0; border-radius: 0; background: var(--surface); } + .review__results { overflow: auto; border-inline-end: 1px solid var(--line); } + .review__document { position: static; overflow: auto; overscroll-behavior: contain; } + .review__document-meta { overflow-wrap: anywhere; } + .review__actions-inner { padding: 5px 24px; border: 0; border-block-start: 1px solid var(--line); border-radius: 0; background: transparent; } + body:has(#review:not([hidden])) > footer.review__header { height: 44px; min-height: 44px; } + body:has(#review:not([hidden])) > footer.review__header .review__header-content { display: flex; align-items: center; height: 44px; padding-block: 0; } + .search__subnav { flex-wrap: wrap; overflow: visible; white-space: normal; } + .search__subnav a.is-active { min-width: 0; text-align: center; } + .search__nav-text { flex: 0 0 auto; } + .search__chips { flex: 1 1 8rem; } + .search__filter-language { display: grid; gap: 5px; margin-block: 0 16px; color: var(--muted); font-size: .875rem; font-weight: 600; } + .search__filter-language select { min-height: 42px; width: 100%; padding: 7px 10px; color: var(--ink); background: var(--surface); border: 1px solid var(--line); } + .search__layout { grid-template-columns: minmax(264px, clamp(264px, calc(20vw + 8px), 288px)) minmax(360px, 38.1fr) 8px minmax(560px, 61.9fr); } + .search__layout[data-filters-hidden="true"] { grid-template-columns: minmax(360px, 38.1fr) 8px minmax(560px, 61.9fr); } + .search__filters { margin-inline-end: 8px; } + .search__mobile-filters { display: inline-flex; } + .search__layout[data-filters-hidden="true"] .search__filters { display: none; } + .search__splitter { position: relative; z-index: 1; align-self: stretch; justify-self: center; width: 12px; min-width: 12px; min-height: 100%; margin-inline: -2px; padding: 0; border: 0; border-radius: 0; background: linear-gradient(90deg, transparent 2px, var(--surface-muted) 2px 10px, transparent 10px); cursor: col-resize; touch-action: none; } + .search__splitter::before { position: absolute; inset-block: 0; inset-inline-start: 50%; width: 1px; background: var(--line); content: ''; transform: translateX(-50%); } + .search__splitter::after { position: absolute; inset-block-start: 50%; inset-inline-start: 50%; width: 3px; height: 40px; border-radius: 2px; background: var(--muted); content: ''; transform: translate(-50%, -50%); } + .search__splitter:hover::after, .search__splitter:focus-visible::after { background: var(--brand); } + body:has(#review:not([hidden])) > .review__header, body:has(#review:not([hidden])) > footer.review__header { width: 100%; max-width: none; margin: 0; padding-inline: 0; } + body:has(#review:not([hidden])) .review__nav, body:has(#review:not([hidden])) .review__header-content { width: 100%; max-width: none; padding-inline: 24px; } + body:has(#review:not([hidden])) .review__header-content h1 { font: 600 26px/32px var(--sans); } + body:has(#review:not([hidden])) .review__panel-heading h2 { font: 600 20px/26px var(--sans); } + body.is-users-route > .search__footer { display: none !important; } + + .search__pagination[hidden] { display: none; } + .search__document-language[hidden] { display: none; } + .search__account-actions { display: grid; grid-template-columns: max-content max-content; justify-content: start; gap: 8px; } + .search__account-actions a { display: inline-flex; align-items: center; justify-content: center; min-height: 44px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); color: var(--brand-dark); font-weight: 600; text-decoration: none; } + .search__account-actions a:hover { border-color: var(--brand); background: var(--subtle); } + #search-logout { grid-column: 1 / -1; justify-self: start; min-height: 36px; margin-block-start: 2px; padding-inline: 0; border: 0; color: var(--muted); background: transparent; } + #account-dialog dl { display: grid; grid-template-columns: minmax(7.5rem, max-content) minmax(0, 1fr); gap: 8px 16px; margin: 16px 0 24px; } + #account-dialog { width: min(560px, calc(100vw - 32px)); max-width: none; } + #account-dialog > .review__page { padding: 16px; } + #account-dialog dt { color: var(--muted); } + #account-dialog dd { min-width: 0; margin: 0; overflow-wrap: anywhere; } + #account-dialog .review__dialog-heading { inset-block-start: -16px; align-items: center; min-height: 44px; height: 44px; margin: -16px -16px 12px; padding: 0 16px; } + .review__password-field { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px; } + .review__password-field input { min-width: 0; } + .review__password-toggle { min-height: 44px; padding-inline: 10px; white-space: nowrap; } + #account-dialog .review__dialog-heading h2 { max-width: none; padding: 0; font: 600 20px/28px var(--sans); } + #account-dialog .review__dialog-heading button { display: grid; place-items: center; flex: 0 0 44px; width: 44px; min-height: 44px; padding: 0; } + #public-document-body img, #document-body img { max-width: 100%; height: auto; object-fit: contain; } + @media (min-width: 901px) and (max-width: 1191px) { + #search-layout { grid-template-columns: minmax(360px, 38.1fr) minmax(560px, 61.9fr); } + #search-layout .search__filters { display: none; } + #search-layout .search__filters.is-open { position: fixed; z-index: 21; inset: 16px auto 16px 16px; display: block; width: min(360px, calc(100vw - 32px)); overflow: auto; padding: 20px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); box-shadow: 0 12px 40px rgb(34 28 28 / .2); } + .search__filter-close { display: inline-flex; } + .search__filter-overlay.is-open { position: fixed; z-index: 20; inset: 0; display: block; background: rgb(56 38 42 / .42); } + .search__splitter { display: none; } + } + @media (max-width: 900px) { + body:has(#review:not([hidden])) { min-height: 100svh; height: auto; overflow: visible; } + body:has(#review:not([hidden])) > #review { flex: none; padding-inline: 16px; } + body:has(#review:not([hidden])) .review__nav, body:has(#review:not([hidden])) .review__header-content { padding-inline: 16px; } + body:has(#review:not([hidden])) .review__header-content { display: flex; flex-direction: column; align-items: stretch; gap: 8px; height: auto; padding-block: 12px; } + body:has(#review:not([hidden])) .review__heading-copy { display: block; } + body:has(#review:not([hidden])) .review__header-top { align-self: flex-start; } + .review__search { padding-inline: 16px; } + body:has(#review:not([hidden])) .review__header-top { padding-block: 0 8px; } + body:has(#review:not([hidden])) .review__header-content h1, body:has(#review:not([hidden])) .review__header-content p { display: block; } + body:has(#review:not([hidden])) .review__header-content p { white-space: normal; } + body:has(#review:not([hidden])) > footer.review__header { height: auto; min-height: 44px; } + .review__workspace { min-height: 0; max-height: none; flex: none; display: grid; grid-template-columns: minmax(0, 1fr); overflow: visible; } + .review__results, .review__document { max-height: none; overflow: visible; border-inline: 0; } + .review__results { border-block-end: 1px solid var(--line); } + .review__document { display: block; } + .review__results, .review__document { padding-inline: 16px; } + body:has(#review:not([hidden])) > .review__actions { flex: 0 0 auto; padding-inline: 0; } + .review__actions-inner { padding-inline: 16px; } + body:has(#review:not([hidden])) > footer.review__header { height: auto; min-height: 44px; } + .search__layout, .search__layout[data-filters-hidden="true"] { display: block; } + .search__splitter { display: none; } + .search__filter-language { margin-block-end: 16px; } + .search__filters { display: none; } + .search__filters.is-open { display: block; } + .search__mobile-filters { display: inline-flex; } + } + @media (max-width: 600px) { + .search__subnav { gap: 4px; padding-inline: 12px; } + .search__subnav a, .search__subnav button { padding-inline: 10px; } + .search__chips { flex: 1 1 100%; order: 4; } + .search__account { margin-inline-start: auto; } + #account-dialog dl { grid-template-columns: minmax(0, 1fr); gap: 2px; } + #account-dialog dd { margin-block-end: 10px; } + } Перейти к результатам
-
Акылдаш
-
-

Проверка качества поиска

Сопоставляйте запрос с текстом документов и сохраняйте оценку выдачи.

+
Акылдаш
+

Проверка качества поиска

Сопоставляйте запрос с текстом документов и сохраняйте оценку выдачи.

@@ -504,7 +633,7 @@
- +
-

Результаты поиска

Оцените каждый документ
  1. Начните с запросаВведите юридический вопрос выше, чтобы увидеть результаты.

Просмотр документа

Откройте результат
Выберите название в списке, чтобы прочитать документ.
@@ -522,16 +651,17 @@

Поиск по правовой базе

-
-

Результаты

Введите запрос
  1. Начните с поискаВведите запрос, чтобы найти документы.
Страница 1
-
ДокументВыберите результат

Документ

Выберите результат, чтобы прочитать доступную редакцию.

Содержание
+
+

Результаты

  1. Введите запрос, чтобы начать поиск.
+ +

Документ

Выберите документ в выдаче, чтобы открыть текст.

Содержание
-
Акылдаш Правовая база КыргызстанаFrontend v0.2.6 Backend v0.13.1
+
Акылдаш Правовая база КыргызстанаFrontend v0.3.3 Backend v0.13.3

Черновик появится после поиска.

Вход в Акылдаш

Введите учетные данные, выданные администратором.

Создайте новый пароль

Для продолжения замените временный пароль. Используйте не менее 12 символов.

-

Личный кабинет

Логин
Роль
Администратор
Дата создания
+

Личный кабинет

Логин
Роль
Администратор
Дата создания

Пользователи

Права на действия определяются сервером.

@@ -545,7 +675,7 @@

Документ

Источники документов

Поиск выполняется по документам, подготовленным из правовых источников Кыргызской Республики. Для каждого результата доступная редакция и ссылка на официальный источник показываются в панели документа.

Официальный источник: Централизованный банк данных правовой информации Министерства юстиции Кыргызской Республики.

Короткое знакомство

-
Акылдаш · Frontend v0.2.6 · Backend v0.13.1 · Внутренняя лаборатория релевантности
+
Акылдаш · Frontend v0.3.3 · Backend v0.13.3 · Внутренняя лаборатория релевантности
`; +const previewHtml = html.replace('', `${warning}`); +const json = (response, status, value) => { + response.writeHead(status, {'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}); + response.end(JSON.stringify(value)); +}; +const readBody = (request) => new Promise((resolve) => { + let body = ''; + request.on('data', (chunk) => { body += chunk; if (body.length > 32768) request.destroy(); }); + request.on('end', () => { try { resolve(JSON.parse(body || '{}')); } catch { resolve({}); } }); +}); +const sendHtml = (response) => { + response.writeHead(200, { + 'Content-Type':'text/html; charset=utf-8', + 'Cache-Control':'no-store', + 'X-Content-Type-Options':'nosniff', + 'Referrer-Policy':'no-referrer', + 'Content-Security-Policy':"default-src 'self' data:; connect-src 'self'; img-src 'self' data:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'none'; object-src 'none'; frame-ancestors 'none'; navigate-to 'self'" + }); + response.end(previewHtml); +}; + +const server = http.createServer(async (request, response) => { + const url = new URL(request.url, 'http://127.0.0.1'); + const method = request.method || 'GET'; + if (method === 'GET' && ['/', '/review', '/users'].includes(url.pathname)) return sendHtml(response); + if (method === 'GET' && url.pathname === '/auth/me') return json(response, 200, {account:passwordChangeAccount}); + if (method === 'POST' && url.pathname === '/auth/logout') return json(response, 200, {ok:true}); + if (method === 'POST' && url.pathname === '/auth/change-password') return json(response, 200, {account:passwordChangeAccount}); + if (method === 'GET' && url.pathname === '/search/filters') return json(response, 200, catalogs); + if (method === 'GET' && url.pathname === '/search') { + const query = url.searchParams.get('q') || ''; + const lab = url.searchParams.has('page_size') && !url.searchParams.has('sort'); + return json(response, 200, {results:query === 'not-found' ? [] : (lab ? visualReviewDocs : visualDocs),has_next:false,review_token:'fixture-only-token'}); + } + if (method === 'GET' && url.pathname === '/documents/doc-2/editions') return json(response, 200, {available_languages:[],editions:[]}); + if (method === 'GET' && url.pathname === '/documents/doc-3/editions') return json(response, 503, {error:'Fixture editions error'}); + if (method === 'GET' && url.pathname === '/documents/doc-1/editions') return json(response, 200, {available_languages:['ru','ky'],editions:[{source_code:'2024',name:{ru:'Редакция от 12 января 2024 года',ky:'2024-жылдын 12-январындагы редакция'},available_languages:['ru','ky']},{source_code:'2023',name:{ru:'Редакция только на русском'},available_languages:['ru']}]}); + const visualReviewEdition = url.pathname.match(/^\/documents\/(review-a|review-b)\/editions\/(2026|2025)$/); + if (method === 'GET' && visualReviewEdition) return json(response, 200, {content:{ru:{html:visualReviewArticles[visualReviewEdition[1]]}}}); + const edition = url.pathname.match(/^\/documents\/doc-1\/editions\/(2024|2023)$/); + if (method === 'GET' && edition) { + const language = url.searchParams.get('language') || 'ru'; + const content = edition[1] === '2023' ? '

Russian-only edition

Regression fixture.

' : language === 'ky' ? articleKy : visualArticle; + return json(response, 200, {content:{[language]:{html:content}}}); + } + if (method === 'GET' && url.pathname === '/admin/users') return json(response, 200, {users}); + if (method === 'POST' && url.pathname === '/admin/users') { + const body = await readBody(request); const username = String(body.username || 'fixture-created'); + users.push({username,role:'Пользователь',can_manage_users:false,must_change_password:true,last_login_at:null,first_login_at:1780000000,password_reset_at:null}); + return json(response, 201, {username}); + } + if (method === 'POST' && /^\/admin\/users\/[^/]+\/reset-password$/.test(url.pathname)) return json(response, 200, {ok:true}); + if (method === 'DELETE' && /^\/admin\/users\/[^/]+$/.test(url.pathname)) return json(response, 200, {ok:true}); + if (method === 'POST' && url.pathname === '/search-reviews') return json(response, 200, {id:42}); + if (method === 'GET' && url.pathname.startsWith('/static/')) { + const name = path.basename(url.pathname); + const file = path.join(staticRoot, url.pathname.endsWith('.woff2') ? 'fonts' : '', name); + if (!fs.existsSync(file) || !fs.statSync(file).isFile()) return json(response, 404, {error:'Not found'}); + const type = name.endsWith('.woff2') ? 'font/woff2' : name.endsWith('.svg') ? 'image/svg+xml' : 'image/png'; + response.writeHead(200, {'Content-Type':type,'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'}); + return fs.createReadStream(file).pipe(response); + } + return json(response, 404, {error:'Fixture route not found'}); +}); + +server.on('error', (error) => { process.stderr.write(`${error.code || error.name}\n`); process.exitCode = 1; }); +server.listen(port, '127.0.0.1', () => { + process.stdout.write(`fixture preview listening at http://127.0.0.1:${port}/ (pid ${process.pid})\n`); +});