fix(web): remove password from public applications
This commit is contained in:
1 parent
0c59d8cb15
commit
e5bd31b428
9 files changed
+9
-91
No files matched your search
@@ -75,7 +75,6 @@ deploy:
|
|||||||
- test -n "$BELKI_DATABASE_URL"
|
- test -n "$BELKI_DATABASE_URL"
|
||||||
- test -n "$POSTGRES_PASSWORD"
|
- test -n "$POSTGRES_PASSWORD"
|
||||||
- test -n "$BELKI_ADMIN_PASSWORD"
|
- test -n "$BELKI_ADMIN_PASSWORD"
|
||||||
- export BELKI_WEB_PASSWORD="${BELKI_WEB_PASSWORD:-$BELKI_ADMIN_PASSWORD}"
|
|
||||||
- mkdir -p "$CI_PROJECT_DIR/.kube"
|
- mkdir -p "$CI_PROJECT_DIR/.kube"
|
||||||
- printf '%s' "$KUBE_CONFIG_B64" | base64 -d > "$CI_PROJECT_DIR/.kube/config"
|
- printf '%s' "$KUBE_CONFIG_B64" | base64 -d > "$CI_PROJECT_DIR/.kube/config"
|
||||||
- export KUBECONFIG="$CI_PROJECT_DIR/.kube/config"
|
- export KUBECONFIG="$CI_PROJECT_DIR/.kube/config"
|
||||||
@@ -90,7 +89,6 @@ deploy:
|
|||||||
--from-literal=BELKI_DATABASE_URL="$BELKI_DATABASE_URL" \
|
--from-literal=BELKI_DATABASE_URL="$BELKI_DATABASE_URL" \
|
||||||
--from-literal=POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
|
--from-literal=POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
|
||||||
--from-literal=BELKI_ADMIN_PASSWORD="$BELKI_ADMIN_PASSWORD" \
|
--from-literal=BELKI_ADMIN_PASSWORD="$BELKI_ADMIN_PASSWORD" \
|
||||||
--from-literal=BELKI_WEB_PASSWORD="$BELKI_WEB_PASSWORD" \
|
|
||||||
--dry-run=client -o yaml | kubectl apply -f -
|
--dry-run=client -o yaml | kubectl apply -f -
|
||||||
- >
|
- >
|
||||||
sed -E "s#image: reg.nyan404.ru/cwshed-clone/belki:[^[:space:]]+#image: $DOCKER_IMAGE_REPOSITORY:$CI_COMMIT_SHORT_SHA#g" deploy/k8s/production.yaml | kubectl apply -f -
|
sed -E "s#image: reg.nyan404.ru/cwshed-clone/belki:[^[:space:]]+#image: $DOCKER_IMAGE_REPOSITORY:$CI_COMMIT_SHORT_SHA#g" deploy/k8s/production.yaml | kubectl apply -f -
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
- 2026-08-21: CI final images use immutable registry base images. Any runtime dependency change requires rebuilding/pushing the matching base (`Dockerfile.base` for `requirements.txt`, `Dockerfile.gateway-base` for `nginx.conf`) and changing the tag used by the final Dockerfile.
|
- 2026-08-21: CI final images use immutable registry base images. Any runtime dependency change requires rebuilding/pushing the matching base (`Dockerfile.base` for `requirements.txt`, `Dockerfile.gateway-base` for `nginx.conf`) and changing the tag used by the final Dockerfile.
|
||||||
- 2026-08-21: use Context7 for fresh official integration documentation and `prevent-eol` before dependency changes; lifecycle status is not a vulnerability verdict.
|
- 2026-08-21: use Context7 for fresh official integration documentation and `prevent-eol` before dependency changes; lifecycle status is not a vulnerability verdict.
|
||||||
- 2026-08-21: project-local frontend instructions include `frontend-craft`, `frontend-design`, and `ui-ux-pro-max`; use them together for UI work.
|
- 2026-08-21: project-local frontend instructions include `frontend-craft`, `frontend-design`, and `ui-ux-pro-max`; use them together for UI work.
|
||||||
- 2026-08-21: `/belki` is the single public Belki workspace: reports are available without `BELKI_WEB_PASSWORD`, while its “Заявки” tab uses the password-gated application flow. The old `/applications` route remains only as a direct legacy entry point.
|
- 2026-08-21: `/belki` is the single public Belki workspace: both reports and its “Заявки” tab are open without a password. The old `/applications` route remains only as a direct legacy entry point. `/admin` is the only password-protected surface.
|
||||||
- 2026-08-21: `/admin` now keeps a server-memory `HttpOnly` cookie session across page refreshes instead of retaining an admin password in the browser. Its authenticated WebSocket sends a refresh signal every 25 seconds; this needs the cwshed Nginx `/api/` Upgrade proxy settings.
|
- 2026-08-21: `/admin` now keeps a server-memory `HttpOnly` cookie session across page refreshes instead of retaining an admin password in the browser. Its authenticated WebSocket sends a refresh signal every 25 seconds; this needs the cwshed Nginx `/api/` Upgrade proxy settings.
|
||||||
# 2026-08-16 — несколько котят в прокачке
|
# 2026-08-16 — несколько котят в прокачке
|
||||||
|
|
||||||
|
|||||||
@@ -37,11 +37,11 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
Каждый подтверждённый расчёт сохраняется в PostgreSQL через `BELKI_DATABASE_URL`: автор, режим, исходные поля, результат, сообщение и время. Если URL не задан, для локальной разработки используется SQLite-файл `data/belki.sqlite3`; production должен запускаться с PostgreSQL.
|
||||||
|
|
||||||
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` защищён паролем `BELKI_WEB_PASSWORD` и позволяет выбрать несколько скриншотов; сервер загружает их на image host (в production — `https://img.nyan404.ru`) и сохраняет ссылки вместе с отчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же image host. Google Sheets пока не подключён.
|
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их на image host (в production — `https://img.nyan404.ru`) и сохраняет ссылки вместе с отчётом. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же image host. Google Sheets пока не подключён.
|
||||||
|
|
||||||
## Заявки
|
## Заявки
|
||||||
|
|
||||||
`/applications` — защищённая той же веб-сессией форма для пожертвования перьев, бельчонка, белки-летяги и куратора. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев.
|
`/applications` — открытая форма для пожертвования перьев, бельчонка, белки-летяги и куратора; эти же формы находятся на вкладке «Заявки» в `/belki`. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев.
|
||||||
|
|
||||||
В `/admin` есть верхняя вкладка «Заявки» рядом с «Отчётами»; внутри неё — вкладки новых и принятых заявок, полное содержимое и действие «Принять». После принятия VK-заявки бот пишет заявителю в личные сообщения. У веб-заявки нет автоматически известного VK-получателя: она получает номер, а VK-ссылку можно оставить для ручной связи.
|
В `/admin` есть верхняя вкладка «Заявки» рядом с «Отчётами»; внутри неё — вкладки новых и принятых заявок, полное содержимое и действие «Принять». После принятия VK-заявки бот пишет заявителю в личные сообщения. У веб-заявки нет автоматически известного VK-получателя: она получает номер, а VK-ссылку можно оставить для ручной связи.
|
||||||
|
|
||||||
|
|||||||
+1
-35
@@ -24,7 +24,6 @@ WEB_ROOT = ROOT / "web"
|
|||||||
_HISTORY_STORE: CalculationStore | None = None
|
_HISTORY_STORE: CalculationStore | None = None
|
||||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||||
_APPLICATION_STORE: ApplicationStore | None = None
|
_APPLICATION_STORE: ApplicationStore | None = None
|
||||||
_WEB_SESSIONS: set[str] = set()
|
|
||||||
_ADMIN_SESSIONS: set[str] = set()
|
_ADMIN_SESSIONS: set[str] = set()
|
||||||
|
|
||||||
|
|
||||||
@@ -109,18 +108,6 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def _web_authorized(self) -> bool:
|
|
||||||
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
||||||
if not expected:
|
|
||||||
self._json(503, {"error": "Веб-доступ не настроен: задайте BELKI_WEB_PASSWORD"})
|
|
||||||
return False
|
|
||||||
cookies = self.headers.get("Cookie", "")
|
|
||||||
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
||||||
if token not in _WEB_SESSIONS:
|
|
||||||
self._json(401, {"error": "Требуется авторизация"})
|
|
||||||
return False
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None:
|
def _json_with_cookie(self, status: int, body: dict, cookie: str) -> None:
|
||||||
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
encoded = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||||
self.send_response(status)
|
self.send_response(status)
|
||||||
@@ -198,12 +185,6 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
status = query.get("status", [None])[0] or None
|
status = query.get("status", [None])[0] or None
|
||||||
self._json(200, {"items": application_store().list(status=status)})
|
self._json(200, {"items": application_store().list(status=status)})
|
||||||
return
|
return
|
||||||
if path == "/api/web/session":
|
|
||||||
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
||||||
cookies = self.headers.get("Cookie", "")
|
|
||||||
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
||||||
self._json(200, {"authenticated": bool(expected and token in _WEB_SESSIONS)})
|
|
||||||
return
|
|
||||||
requested = unquote(path).lstrip("/")
|
requested = unquote(path).lstrip("/")
|
||||||
candidate = (WEB_ROOT / requested).resolve()
|
candidate = (WEB_ROOT / requested).resolve()
|
||||||
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
|
if candidate.is_file() and WEB_ROOT.resolve() in candidate.parents:
|
||||||
@@ -220,7 +201,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
self.wfile.write(content)
|
self.wfile.write(content)
|
||||||
|
|
||||||
def do_POST(self) -> None: # noqa: N802
|
def do_POST(self) -> None: # noqa: N802
|
||||||
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/auth", "/api/web/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
||||||
"/api/save-profile", "/api/get-profile", "/api/applications"):
|
"/api/save-profile", "/api/get-profile", "/api/applications"):
|
||||||
self._json(404, {"error": "Не найдено"})
|
self._json(404, {"error": "Не найдено"})
|
||||||
return
|
return
|
||||||
@@ -238,21 +219,6 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
elif self.path == "/api/admin/logout":
|
elif self.path == "/api/admin/logout":
|
||||||
_ADMIN_SESSIONS.discard(self._session_token("belki_admin_session"))
|
_ADMIN_SESSIONS.discard(self._session_token("belki_admin_session"))
|
||||||
self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
|
self._json_with_cookie(200, {"authenticated": False}, "belki_admin_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
|
||||||
elif self.path == "/api/web/auth":
|
|
||||||
expected = os.getenv("BELKI_WEB_PASSWORD", "")
|
|
||||||
if not expected or not secrets.compare_digest(str(payload.get("password", "")), expected):
|
|
||||||
self._json(401, {"error": "Неверный пароль"})
|
|
||||||
return
|
|
||||||
token = secrets.token_urlsafe(32)
|
|
||||||
_WEB_SESSIONS.add(token)
|
|
||||||
self._json_with_cookie(200, {"authenticated": True}, f"belki_session={token}; Path=/; HttpOnly; SameSite=Lax")
|
|
||||||
elif self.path == "/api/web/logout":
|
|
||||||
cookies = self.headers.get("Cookie", "")
|
|
||||||
token = next((part.strip().split("=", 1)[1] for part in cookies.split(";") if part.strip().startswith("belki_session=")), "")
|
|
||||||
_WEB_SESSIONS.discard(token)
|
|
||||||
self._json_with_cookie(200, {"authenticated": False}, "belki_session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax")
|
|
||||||
elif self.path == "/api/applications" and not self._web_authorized():
|
|
||||||
return
|
|
||||||
elif self.path == "/api/web/upload":
|
elif self.path == "/api/web/upload":
|
||||||
raw = str(payload.get("data", ""))
|
raw = str(payload.get("data", ""))
|
||||||
if "," in raw:
|
if "," in raw:
|
||||||
|
|||||||
@@ -119,11 +119,6 @@ spec:
|
|||||||
secretKeyRef:
|
secretKeyRef:
|
||||||
name: belki-runtime
|
name: belki-runtime
|
||||||
key: BELKI_ADMIN_PASSWORD
|
key: BELKI_ADMIN_PASSWORD
|
||||||
- name: BELKI_WEB_PASSWORD
|
|
||||||
valueFrom:
|
|
||||||
secretKeyRef:
|
|
||||||
name: belki-runtime
|
|
||||||
key: BELKI_WEB_PASSWORD
|
|
||||||
- name: BELKI_IMAGE_HOST_API_URL
|
- name: BELKI_IMAGE_HOST_API_URL
|
||||||
value: https://img.nyan404.ru
|
value: https://img.nyan404.ru
|
||||||
readinessProbe:
|
readinessProbe:
|
||||||
|
|||||||
@@ -11,4 +11,3 @@ stringData:
|
|||||||
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
|
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
|
||||||
POSTGRES_PASSWORD: replace-out-of-band
|
POSTGRES_PASSWORD: replace-out-of-band
|
||||||
BELKI_ADMIN_PASSWORD: replace-out-of-band
|
BELKI_ADMIN_PASSWORD: replace-out-of-band
|
||||||
BELKI_WEB_PASSWORD: replace-out-of-band
|
|
||||||
@@ -18,12 +18,11 @@
|
|||||||
- The job targets GitLab runner tag `fast` and builds through a privileged `docker:29.6.1-dind` service at `DOCKER_HOST=tcp://docker:2375`, with an explicit `alias: docker` and `DOCKER_TLS_CERTDIR=""`.
|
- The job targets GitLab runner tag `fast` and builds through a privileged `docker:29.6.1-dind` service at `DOCKER_HOST=tcp://docker:2375`, with an explicit `alias: docker` and `DOCKER_TLS_CERTDIR=""`.
|
||||||
- Runtime dependency layers are prebuilt and stored in the private registry: `reg.nyan404.ru/cwshed-clone/belki-base:py312-d375af9a0f80` contains Python 3.12 plus the current `requirements.txt`; `reg.nyan404.ru/cwshed/cwshed-base:nginx-c2431df29ccc` contains Nginx plus `nginx.conf`. Adding, removing, or updating a runtime dependency requires rebuilding/pushing and retagging the matching base image before CI; ordinary CI builds only copy application or static files.
|
- Runtime dependency layers are prebuilt and stored in the private registry: `reg.nyan404.ru/cwshed-clone/belki-base:py312-d375af9a0f80` contains Python 3.12 plus the current `requirements.txt`; `reg.nyan404.ru/cwshed/cwshed-base:nginx-c2431df29ccc` contains Nginx plus `nginx.conf`. Adding, removing, or updating a runtime dependency requires rebuilding/pushing and retagging the matching base image before CI; ordinary CI builds only copy application or static files.
|
||||||
- The `ryzen-runner-dind` service on `root@10.3.1.168` has a valid Runner registration and its helper container can reach `https://git.nyan404.ru/`. On 2026-08-21 its malformed `DOCKER_AUTH_CONFIG` was removed and the pre-change configuration was backed up on the host as `/etc/gitlab-runner/config.toml.bak-20260821-1334`.
|
- The `ryzen-runner-dind` service on `root@10.3.1.168` has a valid Runner registration and its helper container can reach `https://git.nyan404.ru/`. On 2026-08-21 its malformed `DOCKER_AUTH_CONFIG` was removed and the pre-change configuration was backed up on the host as `/etc/gitlab-runner/config.toml.bak-20260821-1334`.
|
||||||
- The Belki deploy job copies `BELKI_WEB_PASSWORD` into `Secret/belki-runtime`; if that optional CI variable is absent, it falls back to the already required `BELKI_ADMIN_PASSWORD` so the web Deployment can start. Configure `BELKI_WEB_PASSWORD` separately when a distinct web password is needed.
|
|
||||||
- The job waits for the DinD daemon and runs `docker info` before starting the build.
|
- The job waits for the DinD daemon and runs `docker info` before starting the build.
|
||||||
- GitLab Runner retries source checkout up to three times (`GET_SOURCES_ATTEMPTS=3`) to absorb transient connectivity failures before the job script starts. A persistent inability to reach `git.nyan404.ru:443` still requires repair on the selected runner host.
|
- GitLab Runner retries source checkout up to three times (`GET_SOURCES_ATTEMPTS=3`) to absorb transient connectivity failures before the job script starts. A persistent inability to reach `git.nyan404.ru:443` still requires repair on the selected runner host.
|
||||||
- The local image is currently `belki-calculator:test`; the CI target is now `$DOCKER_REGISTRY/belki:latest`.
|
- The local image is currently `belki-calculator:test`; the CI target is now `$DOCKER_REGISTRY/belki:latest`.
|
||||||
- GitLab CI runs `python -m compileall -q app tests` and `python -m unittest discover -s tests -q` in a dedicated `test` stage before build/deploy. The job explicitly clears `BELKI_DATABASE_URL` and uses `/tmp/belki-test-identities.sqlite3`, preventing unit tests from reaching the Kubernetes PostgreSQL service. Local validation was performed with the same tests, JavaScript syntax check, a local browser/API smoke test, and container health/API smoke.
|
- GitLab CI runs `python -m compileall -q app tests` and `python -m unittest discover -s tests -q` in a dedicated `test` stage before build/deploy. The job explicitly clears `BELKI_DATABASE_URL` and uses `/tmp/belki-test-identities.sqlite3`, preventing unit tests from reaching the Kubernetes PostgreSQL service. Local validation was performed with the same tests, JavaScript syntax check, a local browser/API smoke test, and container health/API smoke.
|
||||||
- `/belki` is the single public workspace: the “Отчёты” tab creates reports and uploads their screenshots without a web-password session; the “Заявки” tab contains the four typed application forms and requests `BELKI_WEB_PASSWORD` only when a user sends an application. `/applications` is kept as a legacy direct route. `/admin` remains password-protected.
|
- `/belki` is the single public workspace: its “Отчёты” and “Заявки” tabs, screenshot uploads, and the legacy `/applications` direct route require no password. `/admin` is the only password-protected surface.
|
||||||
- The VK dialog layer is covered by tests for step-by-step entry, bulk detection, clarification, confirmation, and cancellation.
|
- The VK dialog layer is covered by tests for step-by-step entry, bulk detection, clarification, confirmation, and cancellation.
|
||||||
- Bulk input accepts a natural one-line format without pipes, e.g. `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; the web form calls `/api/inspect-bulk` and fills recognized fields.
|
- Bulk input accepts a natural one-line format without pipes, e.g. `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; the web form calls `/api/inspect-bulk` and fills recognized fields.
|
||||||
- Training and inspection have the same stepwise/bulk flow. Character identity can be resolved through `/api/resolve-identity` and the persistent SQLite directory; missing pairs produce an explicit prompt instead of guessed data.
|
- Training and inspection have the same stepwise/bulk flow. Character identity can be resolved through `/api/resolve-identity` and the persistent SQLite directory; missing pairs produce an explicit prompt instead of guessed data.
|
||||||
@@ -55,7 +54,7 @@
|
|||||||
- 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case.
|
- 2026-08-16: corrected coaching payout direction for non-self-sufficient kittens. The escort receives the 1-per-5-minutes base rate or 1.5x for non-self-sufficient ЛУ; kitten points are not reported. Added a 30-minute regression case.
|
||||||
- 2026-08-16: adopted `2026-08-16-krylany-calculator-rules.md`: Krylan is the Belka/escort role, kittens always receive 1 point per 5 minutes, non-self-sufficient ЛУ multiplies escort points by 1.5, and ZU forces self-sufficient calculation.
|
- 2026-08-16: adopted `2026-08-16-krylany-calculator-rules.md`: Krylan is the Belka/escort role, kittens always receive 1 point per 5 minutes, non-self-sufficient ЛУ multiplies escort points by 1.5, and ZU forces self-sufficient calculation.
|
||||||
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
|
- 2026-08-17: aligned `web/calculator.html` status controls with the VK bot and shared domain: LU allows at most one non-self-sufficient kitten, while ZU forces all kittens to self-sufficient; extra-kitten status controls are synchronized and validated before submission.
|
||||||
- 2026-08-17: added password-gated web sessions via `BELKI_WEB_PASSWORD` and `/api/web/auth`; web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments.
|
- 2026-08-17: web-selected screenshots are sent through `/api/web/upload` to `BELKI_IMAGE_HOST_API_URL` (production `https://img.nyan404.ru`) and persisted as report attachments.
|
||||||
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
|
- 2026-08-21: added structured community applications for feathers, kitten, flying-squirrel, and curator roles across VK, `/applications`, and the top-level `/admin` "Заявки" tab; acceptance is a status transition, not a generated forum post.
|
||||||
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
|
- 2026-08-21: added a disabled durable Google Sheets export outbox for application-created and application-accepted events; no external request is attempted until an approved Apps Script URL and `BELKI_GOOGLE_EXPORT_ENABLED=1` are configured.
|
||||||
# Обновление 2026-08-16: несколько котят
|
# Обновление 2026-08-16: несколько котят
|
||||||
|
|||||||
@@ -21,8 +21,7 @@
|
|||||||
</head>
|
</head>
|
||||||
<body><main>
|
<body><main>
|
||||||
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
|
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
|
||||||
<section id="auth" class="auth"><h2>Вход</h2><p class="hint">Введите пароль, чтобы подать заявку и приложить скриншоты.</p><form id="authForm"><label>Пароль<input id="password" type="password" autocomplete="current-password" required></label><p id="authError" class="error"></p><button class="primary" type="submit">Войти</button></form></section>
|
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Не нужно готовить форумную отпись.</p>
|
||||||
<section id="app" class="hidden"><h1>Новая заявка</h1><p class="intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Не нужно готовить форумную отпись.</p>
|
|
||||||
<div class="types" role="radiogroup" aria-label="Тип заявки">
|
<div class="types" role="radiogroup" aria-label="Тип заявки">
|
||||||
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
|
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -36,9 +35,7 @@
|
|||||||
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
|
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
|
||||||
</section>
|
</section>
|
||||||
</main><script>
|
</main><script>
|
||||||
const auth=document.querySelector('#auth'), app=document.querySelector('#app'), form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation';
|
const form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation';
|
||||||
function activate(){auth.classList.add('hidden');app.classList.remove('hidden')} async function session(){const r=await fetch('/api/web/session');const d=await r.json();if(d.authenticated)activate()}
|
|
||||||
document.querySelector('#authForm').addEventListener('submit',async e=>{e.preventDefault();const r=await fetch('/api/web/auth',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({password:document.querySelector('#password').value})});const d=await r.json();if(!r.ok){document.querySelector('#authError').textContent=d.error||'Не удалось войти';return}activate()});session().catch(()=>{});
|
|
||||||
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
|
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
|
||||||
function sync(){document.querySelector('#featherFields').classList.toggle('hidden',active!=='feather_donation');document.querySelector('#kittenFields').classList.toggle('hidden',active!=='kitten');document.querySelector('#curatorFields').classList.toggle('hidden',active!=='curator');document.querySelector('#flyingFields').classList.toggle('hidden',active!=='flying_squirrel');document.querySelector('#vkField').classList.toggle('hidden',active!=='flying_squirrel');document.querySelectorAll('.type').forEach(x=>x.classList.toggle('active',x.dataset.type===active))} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
|
function sync(){document.querySelector('#featherFields').classList.toggle('hidden',active!=='feather_donation');document.querySelector('#kittenFields').classList.toggle('hidden',active!=='kitten');document.querySelector('#curatorFields').classList.toggle('hidden',active!=='curator');document.querySelector('#flyingFields').classList.toggle('hidden',active!=='flying_squirrel');document.querySelector('#vkField').classList.toggle('hidden',active!=='flying_squirrel');document.querySelectorAll('.type').forEach(x=>x.classList.toggle('active',x.dataset.type===active))} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
|
||||||
document.querySelector('[name="practiced_before"]').onchange=e=>document.querySelector('#practiceLink').classList.toggle('hidden',e.target.value!=='yes');
|
document.querySelector('[name="practiced_before"]').onchange=e=>document.querySelector('#practiceLink').classList.toggle('hidden',e.target.value!=='yes');
|
||||||
|
|||||||
+1
-37
@@ -150,16 +150,7 @@
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
|
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
|
||||||
<div id="applicationAuth" class="panel auth-panel">
|
<div id="applicationWorkspace">
|
||||||
<h2>Подача заявки</h2>
|
|
||||||
<p class="muted">Введите пароль, чтобы отправить заявку на рассмотрение и приложить скриншоты.</p>
|
|
||||||
<form id="applicationAuthForm">
|
|
||||||
<label>Пароль<input id="applicationPassword" type="password" autocomplete="current-password" required></label>
|
|
||||||
<p id="applicationAuthError" class="error" role="alert"></p>
|
|
||||||
<button class="primary" type="submit">Войти</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
<div id="applicationWorkspace" class="hidden">
|
|
||||||
<h2>Новая заявка</h2>
|
<h2>Новая заявка</h2>
|
||||||
<p class="muted application-intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Форумную отпись готовить не нужно.</p>
|
<p class="muted application-intro">Заполните форму — администратор получит структурированную заявку для рассмотрения. Форумную отпись готовить не нужно.</p>
|
||||||
<div class="application-types" role="group" aria-label="Тип заявки">
|
<div class="application-types" role="group" aria-label="Тип заявки">
|
||||||
@@ -366,9 +357,6 @@
|
|||||||
const reportsSection = document.querySelector('#reportsSection');
|
const reportsSection = document.querySelector('#reportsSection');
|
||||||
const applicationsSection = document.querySelector('#applicationsSection');
|
const applicationsSection = document.querySelector('#applicationsSection');
|
||||||
const sectionTabs = [...document.querySelectorAll('[data-section]')];
|
const sectionTabs = [...document.querySelectorAll('[data-section]')];
|
||||||
const applicationAuth = document.querySelector('#applicationAuth');
|
|
||||||
const applicationWorkspace = document.querySelector('#applicationWorkspace');
|
|
||||||
const applicationAuthError = document.querySelector('#applicationAuthError');
|
|
||||||
const applicationForm = document.querySelector('#applicationForm');
|
const applicationForm = document.querySelector('#applicationForm');
|
||||||
const applicationError = document.querySelector('#applicationError');
|
const applicationError = document.querySelector('#applicationError');
|
||||||
const applicationSuccess = document.querySelector('#applicationSuccess');
|
const applicationSuccess = document.querySelector('#applicationSuccess');
|
||||||
@@ -385,7 +373,6 @@
|
|||||||
tab.classList.toggle('active', selected);
|
tab.classList.toggle('active', selected);
|
||||||
tab.setAttribute('aria-selected', String(selected));
|
tab.setAttribute('aria-selected', String(selected));
|
||||||
});
|
});
|
||||||
if (isApplications) checkApplicationSession();
|
|
||||||
if (updateUrl) {
|
if (updateUrl) {
|
||||||
const url = new URL(window.location.href);
|
const url = new URL(window.location.href);
|
||||||
if (isApplications) url.searchParams.set('section', 'applications');
|
if (isApplications) url.searchParams.set('section', 'applications');
|
||||||
@@ -396,29 +383,6 @@
|
|||||||
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
|
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
|
||||||
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false));
|
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section') === 'applications' ? 'applications' : 'reports', false));
|
||||||
|
|
||||||
function showApplicationWorkspace() {
|
|
||||||
applicationAuth.classList.add('hidden');
|
|
||||||
applicationWorkspace.classList.remove('hidden');
|
|
||||||
}
|
|
||||||
async function checkApplicationSession() {
|
|
||||||
try {
|
|
||||||
const response = await fetch('/api/web/session');
|
|
||||||
const data = await response.json();
|
|
||||||
if (data.authenticated) showApplicationWorkspace();
|
|
||||||
} catch (_) { /* The login form remains available and explains any error. */ }
|
|
||||||
}
|
|
||||||
document.querySelector('#applicationAuthForm').addEventListener('submit', async event => {
|
|
||||||
event.preventDefault();
|
|
||||||
applicationAuthError.textContent = '';
|
|
||||||
const response = await fetch('/api/web/auth', {
|
|
||||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
||||||
body: JSON.stringify({password: document.querySelector('#applicationPassword').value}),
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
|
||||||
if (!response.ok) { applicationAuthError.textContent = data.error || 'Не удалось войти'; return; }
|
|
||||||
showApplicationWorkspace();
|
|
||||||
});
|
|
||||||
|
|
||||||
function addApplicationFeather(values = {}) {
|
function addApplicationFeather(values = {}) {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'feather';
|
row.className = 'feather';
|
||||||
|
|||||||
Reference in new issue
Block a user