diff --git a/MEMORY.md b/MEMORY.md index 7e3aea9..b315331 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -34,6 +34,7 @@ - 2026-08-25: VK now exposes the goal calculator in the main keyboard and through `/цель`/`/калькулятор`; its interactive state collects points, session duration, skill, independence, and kitten count, then confirms the calculated result without screenshots. - 2026-08-25: public goal calculations reject non-finite scores and bound session length to 1–1440 minutes and kitten count to 1–50, consistently across domain, API, and VK input. - 2026-08-25: screenshot uploads are public by product design but are bounded before JSON parsing (20 MiB) and after base64 decoding (15 MiB); only verified PNG/JPEG/WebP bytes and basename-only filenames reach image hosting. +- 2026-08-25: public web identity completion is deliberately ephemeral; it no longer writes the identity directory used by VK, and unused global web-profile endpoints were removed. # 2026-08-16 — несколько котят в прокачке `CoachingSession.extra_kittens` теперь влияет на баллы сопровождающего через количество подопечных: 1-й ×1, 2-й ×1,5, каждый последующий ×1,15 (коэффициенты перемножаются), вместо сложения полной прибыли. Базовый коэффициент самостоятельности основного котёнка сохраняется. Веб-форма отправляет список `extra_kittens`; VK принимает `доп. котята: ...` в pipe-команде. diff --git a/app/belki/api.py b/app/belki/api.py index 4358346..ea39b98 100644 --- a/app/belki/api.py +++ b/app/belki/api.py @@ -74,7 +74,9 @@ def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]: """ Разрешает связку имени и ID персонажа из справочника. - Поддерживает поиск по имени или ID, а также сохранение новой связки. + Поддерживает поиск по имени или ID. Публичный веб-вход не меняет общий + справочник: новую пару можно использовать в текущем расчёте, но она не + влияет на профили и последующие диалоги других пользователей. """ if not isinstance(payload, dict): raise ApiError("Ожидался JSON-объект") @@ -91,8 +93,10 @@ def resolve_identity_payload(payload: dict[str, Any]) -> dict[str, Any]: if identity: return {"status": "found", "name": identity.name, "character_id": identity.character_id} if payload.get("remember") and name and character_id is not None: - identity = directory.remember(name=name, character_id=character_id) - return {"status": "saved", "name": identity.name, "character_id": identity.character_id} + return { + "status": "provided", "name": name, "character_id": character_id, + "message": "Связка будет использована только в текущем расчёте.", + } return { "status": "needs_input", "name": name or "", diff --git a/app/main.py b/app/main.py index e0abacd..c609f84 100644 --- a/app/main.py +++ b/app/main.py @@ -75,32 +75,6 @@ def sync_application_exports() -> int: return GoogleSheetsExportService(application_store()).sync_pending() -_WEB_PROFILE_KEY = "web_user" - - -def save_profile(payload): - name = str(payload.get("name", "")).strip() - raw_id = payload.get("character_id") - try: - character_id = int(raw_id) if raw_id not in (None, "") else None - except (TypeError, ValueError): - raise ApiError("ID персонажа должно быть числом") - if not name or character_id is None: - raise ApiError("Нужно указать и имя, и ID персонажа") - identity = identity_dir().remember(name=name, character_id=character_id) - actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0 - identity_dir().remember_profile(actor_id=actor_id, name=name, character_id=character_id) - return {"status": "saved", "name": identity.name, "character_id": identity.character_id} - - -def get_profile(): - actor_id = int(_WEB_PROFILE_KEY.encode().hex(), 16) if isinstance(_WEB_PROFILE_KEY, str) else 0 - profile = identity_dir().profile(actor_id=actor_id) - if profile: - return {"status": "found", "name": profile.name, "character_id": profile.character_id} - return {"status": "not_found"} - - class Handler(BaseHTTPRequestHandler): server_version = "BelkiCalculator/0.1" protocol_version = "HTTP/1.1" @@ -243,7 +217,7 @@ class Handler(BaseHTTPRequestHandler): def do_POST(self) -> None: # noqa: N802 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/applications"): self._json(404, {"error": "Не найдено"}) return try: @@ -288,10 +262,6 @@ class Handler(BaseHTTPRequestHandler): self._json(200, inspect_bulk_payload(payload)) elif self.path == "/api/resolve-identity": self._json(200, resolve_identity_payload(payload)) - elif self.path == "/api/save-profile": - self._json(200, save_profile(payload)) - elif self.path == "/api/get-profile": - self._json(200, get_profile()) elif self.path == "/api/applications": application = validate_application(payload) application_id = application_store().create(application=application, actor_id=None, reply_peer_id=None, source="web") diff --git a/structure_and_data.md b/structure_and_data.md index df7a66e..9208651 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -61,6 +61,7 @@ - 2026-08-25: added the goal calculator to the VK menu as `/цель` and `/калькулятор`; the bot now runs the same goal calculation interactively with step prompts, choice buttons, and confirmation without report attachments. - 2026-08-25: hardened the public goal calculator: point values must be finite, one session is limited to 1–1440 minutes, and one calculation to 1–50 kittens. The same validation is applied by the domain, JSON API, and VK dialogue, with regression tests for `NaN`, infinity, and excessive values. - 2026-08-25: hardened public JSON and screenshot uploads. The web handler caps encoded JSON at 20 MiB before parsing, decodes at most 15 MiB of image bytes, accepts only PNG/JPEG/WebP signatures, rejects MIME mismatches, and strips path components from upload names. The public UI advertises the same supported formats. +- 2026-08-25: removed unused public web-profile endpoints and made `/api/resolve-identity` stateless for submitted pairs. A browser can fill its current inspection form, but cannot overwrite the persistent identity directory shared with VK users. # Обновление 2026-08-16: несколько котят Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`. diff --git a/tests/test_api.py b/tests/test_api.py index 88bbaff..c3a3ff3 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -86,6 +86,13 @@ class ApiTests(unittest.TestCase): self.assertEqual(response["status"], "needs_input") self.assertIn("имя", response["message"].lower()) + def test_public_identity_completion_does_not_write_shared_directory(self): + directory = IdentityDirectory() + with patch.object(api, "_IDENTITY_DIRECTORY", directory): + response = resolve_identity_payload({"name": "Серолап", "character_id": 1617140, "remember": True}) + self.assertEqual(response["status"], "provided") + self.assertIsNone(directory.resolve(character_id=1617140)) + def test_calculation_store_persists_full_record(self): with TemporaryDirectory() as directory: path = f"{directory}/history.sqlite3"