feat: add password-protected calculation admin

This commit is contained in:
nyan404 committed 2026-08-16 15:31:33 +03:00
1 parent 0cb5889ce2
commit 3d58b4fc9b
10 files changed
+169 -4

No files matched your search

+2
View File
@@ -7,3 +7,5 @@ VK_API_VERSION=5.199
BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki
# SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty. # SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty.
BELKI_IDENTITIES_DB=data/belki.sqlite3 BELKI_IDENTITIES_DB=data/belki.sqlite3
# Required to access /admin and /api/admin/calculations.
BELKI_ADMIN_PASSWORD=change-me
+1
View File
@@ -17,4 +17,5 @@
- VK onboarding asks first-time authors for `Имя [ID]`, stores the profile by `from_id` in SQLite, greets by name on later conversations, and accepts `сам`/`несам` as independence shortcuts. - VK onboarding asks first-time authors for `Имя [ID]`, stores the profile by `from_id` in SQLite, greets by name on later conversations, and accepts `сам`/`несам` as independence shortcuts.
- VK `/help` is a neutral FAQ: it explains step-by-step entry, complete commands, separator-free one-line input, confirmation, screenshots, and `/отмена` without audience-specific wording. - VK `/help` is a neutral FAQ: it explains step-by-step entry, complete commands, separator-free one-line input, confirmation, screenshots, and `/отмена` without audience-specific wording.
- Confirmed calculations are persisted through `BELKI_DATABASE_URL` by `app/belki/history.py`; PostgreSQL is the intended production store and SQLite is only a local fallback. - Confirmed calculations are persisted through `BELKI_DATABASE_URL` by `app/belki/history.py`; PostgreSQL is the intended production store and SQLite is only a local fallback.
- The admin history is served at `/admin`; `/api/admin/calculations` requires `BELKI_ADMIN_PASSWORD` via `X-Admin-Password` and supports sorting by kitten ID/name. The password is configured out-of-band and is not stored in browser localStorage.
- The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas. - The new domain uses 5 minutes = 1 adult point and 5 minutes = 2 kitten points; a non-self-sufficient main kitten gives the adult a 1.5x multiplier and each additional non-self-sufficient kitten adds 0.5x, matching the inspected Google Sheet formulas.
+3
View File
@@ -37,6 +37,8 @@ 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.
Админская история доступна по адресу `/admin`. Она защищена заголовком пароля и показывает сохранённые расчёты с сортировкой по ID или имени котёнка. Пароль задаётся через `BELKI_ADMIN_PASSWORD` в `.env` (для Kubernetes — в Secret); без него API админки отключено.
## Структура ## Структура
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей; - `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
@@ -45,6 +47,7 @@ python3 -m app.belki.vk_bot
- `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды; - `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды;
- `app/main.py` — веб-сервис и раздача сайта/userscript-файлов; - `app/main.py` — веб-сервис и раздача сайта/userscript-файлов;
- `web/calculator.html` — форма калькулятора; - `web/calculator.html` — форма калькулятора;
- `web/admin.html` — парольная история расчётов для администраторской проверки;
- `tests/` — unit-тесты. - `tests/` — unit-тесты.
Спецификация и план находятся в `docs/staging/`. Спецификация и план находятся в `docs/staging/`.
+32
View File
@@ -15,6 +15,7 @@ class CalculationStore:
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None: def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
self.database_url = database_url or "" self.database_url = database_url or ""
self.sqlite_path = Path(sqlite_path) if sqlite_path else None self.sqlite_path = Path(sqlite_path) if sqlite_path else None
fetch_limit = 5000
if self.database_url.startswith(("postgres://", "postgresql://")): if self.database_url.startswith(("postgres://", "postgresql://")):
import psycopg import psycopg
self._psycopg = psycopg self._psycopg = psycopg
@@ -85,3 +86,34 @@ class CalculationStore:
) )
return int(cursor.lastrowid) return int(cursor.lastrowid)
def list_calculations(self, *, sort_by: str = "kitten_id", descending: bool = True,
limit: int = 100) -> list[dict[str, Any]]:
"""Return admin rows with safe, application-level sorting by kitten identity."""
limit = max(1, min(int(limit), 500))
fetch_limit = 5000
if self.database_url.startswith(("postgres://", "postgresql://")):
with self._psycopg.connect(self.database_url) as connection:
rows = connection.execute(
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
FROM belki_calculations ORDER BY created_at DESC LIMIT %s""", (fetch_limit,)
).fetchall()
else:
with sqlite3.connect(self.sqlite_path) as connection:
rows = connection.execute(
"""SELECT id, actor_id, source, mode, input_json, result_json, message, created_at
FROM calculations ORDER BY created_at DESC LIMIT ?""", (fetch_limit,)
).fetchall()
records = []
for row in rows:
input_data = row[4] if isinstance(row[4], dict) else json.loads(row[4])
result_data = row[5] if isinstance(row[5], dict) or row[5] is None else json.loads(row[5])
records.append({
"id": row[0], "actor_id": row[1], "source": row[2], "mode": row[3],
"input": input_data, "result": result_data, "message": row[6],
"created_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7],
})
if sort_by not in {"kitten_id", "kitten_name"}:
sort_by = "kitten_id"
records.sort(key=lambda item: (item["input"].get(sort_by) is None, item["input"].get(sort_by, "")),
reverse=descending)
return records[:limit]
+30 -4
View File
@@ -5,13 +5,22 @@ import mimetypes
import os import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
from urllib.parse import unquote, urlparse from urllib.parse import parse_qs, unquote, urlparse
from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload from .belki.api import ApiError, calculate_and_store, inspect_bulk_payload, resolve_identity_payload
from .belki.history import CalculationStore
ROOT = Path(__file__).resolve().parents[1] ROOT = Path(__file__).resolve().parents[1]
WEB_ROOT = ROOT / "web" WEB_ROOT = ROOT / "web"
_HISTORY_STORE: CalculationStore | None = None
def history_store() -> CalculationStore:
global _HISTORY_STORE
if _HISTORY_STORE is None:
_HISTORY_STORE = CalculationStore.from_environment()
return _HISTORY_STORE
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
@@ -26,13 +35,30 @@ class Handler(BaseHTTPRequestHandler):
self.wfile.write(encoded) self.wfile.write(encoded)
def do_GET(self) -> None: # noqa: N802 def do_GET(self) -> None: # noqa: N802
if self.path in ("/health", "/api/health"): path = urlparse(self.path).path
if path in ("/health", "/api/health"):
self._json(200, {"status": "ok"}) self._json(200, {"status": "ok"})
return return
if self.path in ("/", "/calculator.html"): if path in ("/", "/calculator.html"):
self._file(WEB_ROOT / "calculator.html") self._file(WEB_ROOT / "calculator.html")
return return
requested = unquote(urlparse(self.path).path).lstrip("/") if path == "/admin":
self._file(WEB_ROOT / "admin.html")
return
if path == "/api/admin/calculations":
expected = os.getenv("BELKI_ADMIN_PASSWORD", "")
if not expected:
self._json(503, {"error": "Админская панель не настроена: задайте BELKI_ADMIN_PASSWORD"})
return
if self.headers.get("X-Admin-Password", "") != expected:
self._json(401, {"error": "Неверный пароль"})
return
query = parse_qs(urlparse(self.path).query)
sort_by = query.get("sort", ["kitten_id"])[0]
descending = query.get("direction", ["desc"])[0] != "asc"
self._json(200, {"items": history_store().list_calculations(sort_by=sort_by, descending=descending)})
return
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:
self._file(candidate) self._file(candidate)
+5
View File
@@ -33,6 +33,11 @@ spec:
secretKeyRef: secretKeyRef:
name: belki-vk name: belki-vk
key: BELKI_DATABASE_URL key: BELKI_DATABASE_URL
- name: BELKI_ADMIN_PASSWORD
valueFrom:
secretKeyRef:
name: belki-vk
key: BELKI_ADMIN_PASSWORD
readinessProbe: readinessProbe:
httpGet: httpGet:
path: /health path: /health
+1
View File
@@ -9,3 +9,4 @@ stringData:
VK_GROUP_ID: replace-out-of-band VK_GROUP_ID: replace-out-of-band
VK_API_VERSION: "5.199" VK_API_VERSION: "5.199"
BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki
BELKI_ADMIN_PASSWORD: replace-out-of-band
+1
View File
@@ -25,6 +25,7 @@
- Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git. - Character name/ID pairs are persisted automatically in the SQLite file from `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`); the database is local runtime data and ignored by Git.
- The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts. - The VK dialog onboards each author once, stores their profile by `from_id`, greets them by name, and keeps the profile in the same SQLite database across bot restarts.
- Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp. - Every confirmed calculation is persisted by `app/belki/history.py` to PostgreSQL from `BELKI_DATABASE_URL`; SQLite is only a local fallback. Records include actor, source, mode, input, result, rendered message, and timestamp.
- `/admin` and `/api/admin/calculations` expose the calculation history for review. The API requires `X-Admin-Password` matching `BELKI_ADMIN_PASSWORD`; the web page supports sorting by kitten ID or name and does not persist the password in browser storage.
- VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported. - VK `messages.send` responses include a serialized context-aware keyboard; button payloads are translated back into the same dialog commands, while text commands remain supported.
- No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped. - No k3s deployment or cluster state change has been made. The SSH tunnel used for read-only service inventory was stopped.
- Remote runner host: `root@10.3.1.236` (`docker-03.homelab.local`), GitLab Runner `stage-zone-runner`, Docker executor, privileged, with `docker:29.6.1-dind` as the service image. - Remote runner host: `root@10.3.1.236` (`docker-03.homelab.local`), GitLab Runner `stage-zone-runner`, Docker executor, privileged, with `docker:29.6.1-dind` as the service image.
+29
View File
@@ -0,0 +1,29 @@
import tempfile
import unittest
from pathlib import Path
from app.belki.history import CalculationStore
class CalculationHistoryTests(unittest.TestCase):
def test_admin_rows_sort_by_kitten_id_and_name(self) -> None:
with tempfile.TemporaryDirectory() as directory:
store = CalculationStore(sqlite_path=Path(directory) / "history.sqlite3")
for kitten_id, kitten_name in ((30, "Тучка"), (10, "Янтарь"), (20, "Белка")):
store.save(
actor_id=99,
source="vk",
payload={"mode": "coaching", "kitten_id": kitten_id, "kitten_name": kitten_name},
response={"mode": "coaching", "message": f"расчёт {kitten_id}", "result": {"points": 1}},
)
by_id = store.list_calculations(sort_by="kitten_id", descending=False)
self.assertEqual([row["input"]["kitten_id"] for row in by_id], [10, 20, 30])
by_name = store.list_calculations(sort_by="kitten_name", descending=False)
self.assertEqual([row["input"]["kitten_name"] for row in by_name], ["Белка", "Тучка", "Янтарь"])
self.assertEqual(by_name[0]["actor_id"], 99)
self.assertEqual(by_name[0]["result"]["points"], 1)
if __name__ == "__main__":
unittest.main()
+65
View File
@@ -0,0 +1,65 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Беличья нора — админка</title>
<style>
:root { color-scheme: dark; font-family: system-ui, sans-serif; }
body { margin: 0; background: #171516; color: #f4eeee; }
main { width: min(1180px, calc(100% - 32px)); margin: 32px auto; }
.toolbar { display: flex; gap: 8px; flex-wrap: wrap; align-items: end; margin: 20px 0; }
label { display: grid; gap: 5px; color: #d8cace; }
input, select, button { font: inherit; border: 1px solid #665159; border-radius: 7px; padding: 9px; background: #251e20; color: inherit; }
button { cursor: pointer; background: #d59b62; color: #211818; border-color: #d59b62; }
.error { color: #ff9f9f; white-space: pre-wrap; }
.table-wrap { overflow-x: auto; border: 1px solid #4a383d; border-radius: 10px; }
table { width: 100%; border-collapse: collapse; min-width: 820px; }
th, td { text-align: left; vertical-align: top; padding: 10px; border-bottom: 1px solid #4a383d; }
th { color: #d59b62; }
td pre { white-space: pre-wrap; margin: 0; max-width: 560px; }
.muted { color: #b9aaad; }
</style>
</head>
<body>
<main>
<h1>Беличья нора — админская</h1>
<p class="muted">История подтверждённых расчётов из VK-бота и веб-калькулятора.</p>
<div class="toolbar">
<label>Пароль администратора<input id="password" type="password" autocomplete="current-password"></label>
<label>Сортировать<select id="sort"><option value="kitten_id">ID котёнка</option><option value="kitten_name">Имя котёнка</option></select></label>
<label>Порядок<select id="direction"><option value="asc">А–Я / по возрастанию</option><option value="desc" selected>Я–А / по убыванию</option></select></label>
<button id="load">Загрузить</button>
</div>
<p class="error" id="error"></p>
<div class="table-wrap"><table><thead><tr><th>ID записи</th><th>Автор</th><th>Режим</th><th>Котёнок</th><th>Дата</th><th>Сообщение</th></tr></thead><tbody id="rows"></tbody></table></div>
</main>
<script>
const password = document.querySelector('#password');
const sort = document.querySelector('#sort');
const direction = document.querySelector('#direction');
const rows = document.querySelector('#rows');
const error = document.querySelector('#error');
function cell(text) { const node = document.createElement('td'); node.textContent = text ?? '—'; return node; }
async function load() {
error.textContent = ''; rows.textContent = '';
const query = new URLSearchParams({sort: sort.value, direction: direction.value});
try {
const response = await fetch(`/api/admin/calculations?${query}`, {headers: {'X-Admin-Password': password.value}});
const data = await response.json();
if (!response.ok) throw new Error(data.error || 'Не удалось загрузить историю');
data.items.forEach(item => {
const row = document.createElement('tr');
row.append(cell(item.id)); row.append(cell(item.actor_id || '—')); row.append(cell(item.mode));
row.append(cell(`${item.input.kitten_name || '—'} [${item.input.kitten_id || '—'}]`));
row.append(cell(item.created_at));
const message = document.createElement('td'); const pre = document.createElement('pre'); pre.textContent = item.message; message.append(pre); row.append(message);
rows.append(row);
});
} catch (err) { error.textContent = err.message; }
}
document.querySelector('#load').addEventListener('click', load);
if (password.value) load();
</script>
</body>
</html>