From 826919bbfcf2701a7262cd60f52fafc140158ef3 Mon Sep 17 00:00:00 2001 From: p00ler Date: Fri, 11 Sep 2026 18:20:32 +0300 Subject: [PATCH 1/4] docs: define MAX TLS configuration --- .../2026-09-11-max-ssl-context-design.md | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 docs/superpowers/specs/2026-09-11-max-ssl-context-design.md diff --git a/docs/superpowers/specs/2026-09-11-max-ssl-context-design.md b/docs/superpowers/specs/2026-09-11-max-ssl-context-design.md new file mode 100644 index 0000000..15af7f5 --- /dev/null +++ b/docs/superpowers/specs/2026-09-11-max-ssl-context-design.md @@ -0,0 +1,49 @@ +# MAX TLS Configuration Design + +## Goal + +Allow applications using maxogram to configure trusted certificate authorities for +outgoing MAX API requests and, when desired, terminate HTTPS directly in the +embedded webhook server. + +## Public API + +`AiohttpSession` gains two keyword-only options: + +- `ssl_context: ssl.SSLContext | None` — a convenience option that creates an + `aiohttp.TCPConnector(ssl=ssl_context)` lazily; +- `connector: aiohttp.BaseConnector | None` — a preconfigured aiohttp connector + for callers that need transport options beyond an SSL context. + +The options are mutually exclusive. Passing both raises `ValueError`, avoiding a +silent choice between two potentially different TLS configurations. With neither +option, `AiohttpSession` keeps its current default `ClientSession` behavior, which +performs normal certificate and hostname verification. + +`WebhookManager` gains `ssl_context: ssl.SSLContext | None`. It is passed to +`aiohttp.web.TCPSite`; when omitted, the manager continues serving plain HTTP on +the internal listener, suitable for TLS termination by Nginx or Caddy. The public +webhook URL remains the caller's responsibility and must be an HTTPS URL on port +443 for MAX. + +## Resource ownership + +The client session passes a configured connector to `aiohttp.ClientSession` using +aiohttp's default connector ownership. Closing `AiohttpSession` therefore closes +the session and its connector. A custom connector is intended to live for the +session's lifetime; applications that need to share a connector should follow +aiohttp's connector ownership rules and manage that shared resource explicitly. + +## Error handling + +Configuration errors are reported at construction time for the mutually exclusive +client options. SSL handshake and certificate errors continue through the existing +aiohttp network-error path; no insecure fallback or verification disabling is +introduced. + +## Testing and documentation + +Tests cover default construction, custom connector forwarding, SSL context +conversion, mutual exclusion, and forwarding the server context to `TCPSite`. +Documentation shows both trusted-CA client setup and direct HTTPS server setup, +while retaining the reverse-proxy-on-port-8080 deployment path. From 9995c09d489996edb6f09932cd0f30a43eed3e8a Mon Sep 17 00:00:00 2001 From: p00ler Date: Fri, 11 Sep 2026 18:22:41 +0300 Subject: [PATCH 2/4] docs: add MAX TLS implementation plan --- .../plans/2026-09-11-max-ssl-context.md | 320 ++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 docs/superpowers/plans/2026-09-11-max-ssl-context.md diff --git a/docs/superpowers/plans/2026-09-11-max-ssl-context.md b/docs/superpowers/plans/2026-09-11-max-ssl-context.md new file mode 100644 index 0000000..031b4e6 --- /dev/null +++ b/docs/superpowers/plans/2026-09-11-max-ssl-context.md @@ -0,0 +1,320 @@ +# MAX TLS Configuration Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Expose safe custom TLS configuration for outbound MAX API requests and the optional embedded HTTPS webhook listener. + +**Architecture:** Keep `AiohttpSession` as the owner of the lazy `ClientSession`. A supplied connector is forwarded unchanged; a supplied SSL context is converted to a `TCPConnector` only when the first request creates the client session. Keep `WebhookManager` compatible with reverse-proxy deployments by passing an optional SSL context directly to `web.TCPSite` and leaving the default listener as HTTP. + +**Tech Stack:** Python 3.11+, aiohttp 3.9–3.x, asyncio, `ssl.SSLContext`, pytest, pytest-asyncio. + +--- + +### Task 1: Add outbound SSL and connector configuration + +**Files:** +- Modify: `src/maxogram/client/session/aiohttp.py` +- Test: `tests/test_session_aiohttp.py` + +- [ ] **Step 1: Write failing tests for client configuration.** + +Add a test class near the session-close tests. It must verify that the public +constructor rejects ambiguous configuration, that a supplied connector reaches +`ClientSession`, and that an SSL context is converted to a connector with that +same context: + +```python +import ssl + + +class TestSessionTLSConfiguration: + def test_connector_and_ssl_context_are_mutually_exclusive(self) -> None: + connector = MagicMock() + context = ssl.create_default_context() + + with pytest.raises(ValueError, match="connector.*ssl_context"): + AiohttpSession(connector=connector, ssl_context=context) + + @pytest.mark.asyncio + async def test_custom_connector_is_forwarded_to_client_session(self) -> None: + connector = MagicMock() + session = AiohttpSession(connector=connector) + client_session = MagicMock() + + with patch("aiohttp.ClientSession", return_value=client_session) as factory: + assert await session._get_session() is client_session + + factory.assert_called_once_with( + json_serialize=session._json_dumps, + connector=connector, + ) + + @pytest.mark.asyncio + async def test_ssl_context_creates_tcp_connector(self) -> None: + context = ssl.create_default_context() + session = AiohttpSession(ssl_context=context) + client_session = MagicMock() + + with ( + patch("aiohttp.TCPConnector") as connector_factory, + patch("aiohttp.ClientSession", return_value=client_session) as session_factory, + ): + connector = connector_factory.return_value + assert await session._get_session() is client_session + + connector_factory.assert_called_once_with(ssl=context) + session_factory.assert_called_once_with( + json_serialize=session._json_dumps, + connector=connector, + ) +``` + +- [ ] **Step 2: Run the focused tests and verify the expected RED state.** + +Run: + +```bash +poetry run pytest -q tests/test_session_aiohttp.py -k TLSConfiguration +``` + +Expected: collection succeeds and the new tests fail because the constructor +does not yet accept the new options. + +- [ ] **Step 3: Implement the minimal client configuration.** + +Import `ssl`, add keyword-only `connector` and `ssl_context` parameters after +`max_retries`, reject both when present, store them, and build the connector in +`_get_session`: + +```python +def __init__( + self, + proxy: str | None = None, + max_retries: int = 3, + *, + connector: aiohttp.BaseConnector | None = None, + ssl_context: ssl.SSLContext | None = None, + **kwargs: Any, +) -> None: + if connector is not None and ssl_context is not None: + raise ValueError("connector and ssl_context are mutually exclusive") + super().__init__(**kwargs) + self._proxy = proxy + self._max_retries = max_retries + self._connector = connector + self._ssl_context = ssl_context + self._session: aiohttp.ClientSession | None = None + +async def _get_session(self) -> aiohttp.ClientSession: + if self._session is None or self._session.closed: + connector = self._connector + if connector is None and self._ssl_context is not None: + connector = aiohttp.TCPConnector(ssl=self._ssl_context) + self._session = aiohttp.ClientSession( + json_serialize=self._json_dumps, + connector=connector, + ) + return self._session +``` + +The `ssl` argument must receive the context; do not use `ssl=False` or alter +aiohttp verification defaults. + +- [ ] **Step 4: Run focused and existing session tests.** + +Run: + +```bash +poetry run pytest -q tests/test_session_aiohttp.py tests/test_client/test_session/test_aiohttp.py +``` + +Expected: all session tests pass. + +- [ ] **Step 5: Commit the client change.** + +```bash +git add src/maxogram/client/session/aiohttp.py tests/test_session_aiohttp.py +git commit -m "feat: configure aiohttp TLS for API sessions" +``` + +### Task 2: Add optional HTTPS to WebhookManager + +**Files:** +- Modify: `src/maxogram/webhook/manager.py` +- Test: `tests/test_webhook/test_manager.py` + +- [ ] **Step 1: Write failing tests for server SSL forwarding.** + +Extend `TestWebhookManagerInit` with storage coverage and add a lifecycle test +that inspects the `TCPSite` constructor: + +```python +import ssl + + +def test_stores_ssl_context(self, dispatcher: MagicMock, bot: AsyncMock) -> None: + from maxogram.webhook.manager import WebhookManager + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + manager = WebhookManager(dispatcher=dispatcher, bot=bot, ssl_context=context) + + assert manager._ssl_context is context + + +@pytest.mark.asyncio +async def test_setup_passes_ssl_context_to_tcp_site( + self, dispatcher: MagicMock, bot: AsyncMock +) -> None: + from maxogram.webhook.manager import WebhookManager + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + manager = WebhookManager( + dispatcher=dispatcher, + bot=bot, + ssl_context=context, + resubscribe_interval=100.0, + ) + + with patch("aiohttp.web.AppRunner") as runner_cls: + runner = AsyncMock() + runner_cls.return_value = runner + with patch("aiohttp.web.TCPSite") as site_cls: + site = AsyncMock() + site_cls.return_value = site + + await manager._setup("https://example.com/webhook") + await manager._shutdown() + + site_cls.assert_called_once_with(runner, "0.0.0.0", 8080, ssl_context=context) +``` + +- [ ] **Step 2: Run the focused tests and verify RED.** + +Run: + +```bash +poetry run pytest -q tests/test_webhook/test_manager.py -k "ssl_context" +``` + +Expected: the constructor and `TCPSite` assertion fail because the manager has +no SSL option yet. + +- [ ] **Step 3: Implement optional server TLS.** + +Import `ssl`, add keyword-only `ssl_context: ssl.SSLContext | None = None`, +store it, and pass it to `web.TCPSite`: + +```python +self._ssl_context = ssl_context +site = web.TCPSite( + self._runner, + self._host, + self._port, + ssl_context=self._ssl_context, +) +``` + +Keep `ssl_context=None` as the default so Nginx/Caddy can terminate TLS and +forward to the internal HTTP listener. Update the startup log scheme to +`https` when a context is configured and `http` otherwise. + +- [ ] **Step 4: Run manager tests.** + +Run: + +```bash +poetry run pytest -q tests/test_webhook/test_manager.py +``` + +Expected: all manager tests pass. + +- [ ] **Step 5: Commit the manager change.** + +```bash +git add src/maxogram/webhook/manager.py tests/test_webhook/test_manager.py +git commit -m "feat: support HTTPS webhook listener" +``` + +### Task 3: Document safe TLS deployment + +**Files:** +- Modify: `docs/quickstart.md` +- Modify: `src/maxogram/client/README.md` +- Modify: `src/maxogram/webhook/README.md` +- Modify: `CHANGELOG.md` + +- [ ] **Step 1: Document outbound trusted-CA configuration.** + +Show `ssl.create_default_context(cafile=...)` passed to +`AiohttpSession(ssl_context=...)`, explain the alternative preconfigured +`aiohttp.TCPConnector`, and explicitly state that verification must remain +enabled. Mention that `connector` and `ssl_context` cannot be supplied +together. + +- [ ] **Step 2: Document direct and reverse-proxy webhook TLS.** + +Add a direct listener example using a server SSL context and +`load_cert_chain()`. Explain that MAX requires the external webhook URL to be +HTTPS on public port 443, while the embedded listener can remain on 8080 behind +Nginx/Caddy. State that a trusted certificate chain is required and that +disabling TLS verification is unsupported. + +- [ ] **Step 3: Run documentation consistency checks.** + +Run: + +```bash +rg -n "ssl_context|TCPConnector|port 443|8080|verification" docs/quickstart.md src/maxogram/client/README.md src/maxogram/webhook/README.md CHANGELOG.md +``` + +Expected: both client and server configuration paths are present and no example +uses an unverified SSL context. + +- [ ] **Step 4: Commit the documentation.** + +```bash +git add docs/quickstart.md src/maxogram/client/README.md src/maxogram/webhook/README.md CHANGELOG.md +git commit -m "docs: explain MAX TLS configuration" +``` + +### Task 4: Full verification and handoff + +**Files:** +- Verify: all changed files and the complete test suite + +- [ ] **Step 1: Run the complete test suite.** + +Run: + +```bash +poetry run pytest -q +``` + +Expected: the full suite passes with zero failures. + +- [ ] **Step 2: Run static checks.** + +Run: + +```bash +poetry run ruff check src tests +poetry run ruff format --check src tests +poetry run mypy src +git diff main...HEAD --check +``` + +Expected: ruff, formatting, mypy, and whitespace checks exit with status 0. + +- [ ] **Step 3: Review the final diff and branch state.** + +Run: + +```bash +git status --short --branch +git diff --stat main...HEAD +git log --oneline --decorate --max-count=8 +``` + +Confirm that only TLS configuration, tests, documentation, and the committed +design/plan are present, with no credentials, insecure TLS flags, or unrelated +changes. From 599d26aa4990dd21cbf103f605496773a14ba1c7 Mon Sep 17 00:00:00 2001 From: p00ler Date: Fri, 11 Sep 2026 18:25:25 +0300 Subject: [PATCH 3/4] feat: configure aiohttp TLS transports --- src/maxogram/client/session/aiohttp.py | 12 +++++++ src/maxogram/webhook/manager.py | 14 ++++++-- tests/test_session_aiohttp.py | 46 ++++++++++++++++++++++++++ tests/test_webhook/test_manager.py | 36 ++++++++++++++++++++ 4 files changed, 106 insertions(+), 2 deletions(-) diff --git a/src/maxogram/client/session/aiohttp.py b/src/maxogram/client/session/aiohttp.py index 9d5ecca..5cf9cbf 100644 --- a/src/maxogram/client/session/aiohttp.py +++ b/src/maxogram/client/session/aiohttp.py @@ -11,6 +11,7 @@ from maxogram.exceptions import MaxNetworkError, MaxTooManyRequestsError if TYPE_CHECKING: + import ssl from collections.abc import AsyncGenerator from maxogram.methods.base import MaxMethod @@ -32,18 +33,29 @@ def __init__( self, proxy: str | None = None, max_retries: int = 3, + *, + connector: aiohttp.BaseConnector | None = None, + ssl_context: ssl.SSLContext | None = None, **kwargs: Any, ) -> None: + if connector is not None and ssl_context is not None: + raise ValueError("connector and ssl_context are mutually exclusive") super().__init__(**kwargs) self._proxy = proxy self._max_retries = max_retries + self._connector = connector + self._ssl_context = ssl_context self._session: aiohttp.ClientSession | None = None async def _get_session(self) -> aiohttp.ClientSession: """Получить или создать aiohttp ClientSession (lazy).""" if self._session is None or self._session.closed: + connector = self._connector + if connector is None and self._ssl_context is not None: + connector = aiohttp.TCPConnector(ssl=self._ssl_context) self._session = aiohttp.ClientSession( json_serialize=self._json_dumps, + connector=connector, ) return self._session diff --git a/src/maxogram/webhook/manager.py b/src/maxogram/webhook/manager.py index fbdfa20..a1d87c0 100644 --- a/src/maxogram/webhook/manager.py +++ b/src/maxogram/webhook/manager.py @@ -12,6 +12,8 @@ from maxogram.webhook.handler import WebhookHandler if TYPE_CHECKING: + import ssl + from maxogram.client.bot import Bot from maxogram.dispatcher.dispatcher import Dispatcher @@ -46,6 +48,7 @@ def __init__( resubscribe_interval: float = _DEFAULT_RESUBSCRIBE_INTERVAL, close_bot_session: bool = True, handle_signals: bool = True, + ssl_context: ssl.SSLContext | None = None, ) -> None: self._dispatcher = dispatcher self._bot = bot @@ -56,6 +59,7 @@ def __init__( self._resubscribe_interval = resubscribe_interval self._close_bot_session = close_bot_session self._handle_signals = handle_signals + self._ssl_context = ssl_context self._handler = WebhookHandler(dispatcher=dispatcher, bot=bot) self._runner: web.AppRunner | None = None @@ -131,11 +135,17 @@ async def _setup(self, webhook_url: str) -> None: self._runner = web.AppRunner(app) await self._runner.setup() - site = web.TCPSite(self._runner, self._host, self._port) + site = web.TCPSite( + self._runner, + self._host, + self._port, + ssl_context=self._ssl_context, + ) await site.start() logger.info( - "Webhook server запущен: http://%s:%s%s", + "Webhook server запущен: %s://%s:%s%s", + "https" if self._ssl_context else "http", self._host, self._port, self._path, diff --git a/tests/test_session_aiohttp.py b/tests/test_session_aiohttp.py index ba67587..8316263 100644 --- a/tests/test_session_aiohttp.py +++ b/tests/test_session_aiohttp.py @@ -3,6 +3,8 @@ from __future__ import annotations import json +import ssl +from unittest.mock import MagicMock, patch import aresponses import pytest @@ -498,6 +500,50 @@ async def test_close_without_session(self) -> None: await session.close() # Не должно бросить исключение +class TestSessionTLSConfiguration: + """Настройка TLS и транспортного connector для API-сессии.""" + + def test_connector_and_ssl_context_are_mutually_exclusive(self) -> None: + connector = MagicMock() + context = ssl.create_default_context() + + with pytest.raises(ValueError, match="connector.*ssl_context"): + AiohttpSession(connector=connector, ssl_context=context) + + @pytest.mark.asyncio + async def test_custom_connector_is_forwarded_to_client_session(self) -> None: + connector = MagicMock() + session = AiohttpSession(connector=connector) + client_session = MagicMock() + + with patch("aiohttp.ClientSession", return_value=client_session) as factory: + assert await session._get_session() is client_session + + factory.assert_called_once_with( + json_serialize=session._json_dumps, + connector=connector, + ) + + @pytest.mark.asyncio + async def test_ssl_context_creates_tcp_connector(self) -> None: + context = ssl.create_default_context() + session = AiohttpSession(ssl_context=context) + client_session = MagicMock() + + with ( + patch("aiohttp.TCPConnector") as connector_factory, + patch("aiohttp.ClientSession", return_value=client_session) as session_factory, + ): + connector = connector_factory.return_value + assert await session._get_session() is client_session + + connector_factory.assert_called_once_with(ssl=context) + session_factory.assert_called_once_with( + json_serialize=session._json_dumps, + connector=connector, + ) + + # --- GET пустое body --- diff --git a/tests/test_webhook/test_manager.py b/tests/test_webhook/test_manager.py index 498cb9b..34ef7fc 100644 --- a/tests/test_webhook/test_manager.py +++ b/tests/test_webhook/test_manager.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import ssl from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -94,6 +95,14 @@ def test_default_resubscribe_interval(self, dispatcher: MagicMock, bot: AsyncMoc # 7.5 часов = 27000 секунд assert manager._resubscribe_interval == 27000.0 + def test_stores_ssl_context(self, dispatcher: MagicMock, bot: AsyncMock) -> None: + from maxogram.webhook.manager import WebhookManager + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + manager = WebhookManager(dispatcher=dispatcher, bot=bot, ssl_context=context) + + assert manager._ssl_context is context + class TestWebhookManagerSubscription: """Тесты подписки/отписки webhook.""" @@ -374,3 +383,30 @@ async def test_dispatcher_startup_shutdown_emitted( await manager._shutdown() dispatcher.emit_shutdown.assert_awaited_once() + + @pytest.mark.asyncio + async def test_setup_passes_ssl_context_to_tcp_site( + self, dispatcher: MagicMock, bot: AsyncMock + ) -> None: + """SSL-контекст передаётся встроенному HTTPS-серверу.""" + from maxogram.webhook.manager import WebhookManager + + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + manager = WebhookManager( + dispatcher=dispatcher, + bot=bot, + ssl_context=context, + resubscribe_interval=100.0, + ) + + with patch("aiohttp.web.AppRunner") as runner_cls: + runner = AsyncMock() + runner_cls.return_value = runner + with patch("aiohttp.web.TCPSite") as site_cls: + site = AsyncMock() + site_cls.return_value = site + + await manager._setup("https://example.com/webhook") + await manager._shutdown() + + site_cls.assert_called_once_with(runner, "0.0.0.0", 8080, ssl_context=context) From f4cdbfd5ee384e7c35d18345312da8c2188d0e0f Mon Sep 17 00:00:00 2001 From: p00ler Date: Fri, 11 Sep 2026 18:27:23 +0300 Subject: [PATCH 4/4] docs: explain MAX TLS configuration --- CHANGELOG.md | 5 +++++ docs/quickstart.md | 34 +++++++++++++++++++++++++++++++++- src/maxogram/client/README.md | 24 ++++++++++++++++++++++++ src/maxogram/webhook/README.md | 27 +++++++++++++++++++++++++++ 4 files changed, 89 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 682e2f0..0c518ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ ## [Unreleased] +### Added + +- Настраиваемые `ssl_context` и `aiohttp` connector для проверки доверенного CA + в исходящих API-запросах и прямого HTTPS webhook-сервера + ## [1.1.0] - 2026-03-25 ### Fixed diff --git a/docs/quickstart.md b/docs/quickstart.md index d2e3d22..94ed9c2 100644 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -254,7 +254,7 @@ manager = WebhookManager( ) import asyncio -asyncio.run(manager.start()) +asyncio.run(manager.start("https://example.com/webhook")) ``` `WebhookManager` автоматически: @@ -262,6 +262,38 @@ asyncio.run(manager.start()) - Переподписывается каждые 7.5 часов (Max отписывает через 8ч) - Отписывается и останавливает сервер при shutdown +MAX принимает webhook только по внешнему HTTPS URL на публичном порту 443. +Обычная production-схема — оставить встроенный aiohttp-сервер на внутреннем +порту 8080 и проксировать к нему запросы через Nginx или Caddy, которые +завершают TLS. Сертификат должен быть доверенным MAX, включая сертификат +Минцифры при использовании соответствующей инфраструктуры. + +Если TLS должен завершаться непосредственно в aiohttp, передайте серверный +`SSLContext` и сертификат с закрытым ключом: + +```python +import ssl + +server_ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +server_ssl_context.load_cert_chain( + "/etc/ssl/webhook/fullchain.pem", + "/etc/ssl/webhook/private.key", +) + +manager = WebhookManager( + dispatcher=dp, + bot=bot, + host="0.0.0.0", + port=443, + ssl_context=server_ssl_context, +) +asyncio.run(manager.start("https://example.com/webhook")) +``` + +Для защиты от поддельных запросов рекомендуется включать `secret` в подписке +webhook. `polling`/Long Polling используйте для разработки и тестирования, а в +production — Webhook. + Для защиты от поддельных запросов используйте `IPWhitelistMiddleware`: ```python diff --git a/src/maxogram/client/README.md b/src/maxogram/client/README.md index 976abff..b936710 100644 --- a/src/maxogram/client/README.md +++ b/src/maxogram/client/README.md @@ -46,6 +46,30 @@ bot = Bot( ) ``` +### Кастомный центр сертификации + +Если окружению нужен отдельный доверенный CA bundle (например, сертификат +Минцифры), создайте проверяющий `SSLContext` и передайте его в +`AiohttpSession`: + +```python +import ssl + +from maxogram.client import Bot +from maxogram.client.session.aiohttp import AiohttpSession + +api_ssl_context = ssl.create_default_context(cafile="/etc/ssl/max/ca-bundle.pem") +bot = Bot( + token="your_token", + session=AiohttpSession(ssl_context=api_ssl_context), +) +``` + +Для более тонкой настройки транспорта можно передать готовый +`aiohttp.TCPConnector(ssl=api_ssl_context)` через `connector`. Параметры +`connector` и `ssl_context` взаимоисключающие. Не используйте `ssl=False` и +не отключайте проверку сертификата или hostname. + ## Архитектура ``` diff --git a/src/maxogram/webhook/README.md b/src/maxogram/webhook/README.md index 744b037..442e560 100644 --- a/src/maxogram/webhook/README.md +++ b/src/maxogram/webhook/README.md @@ -48,6 +48,33 @@ manager = WebhookManager( await manager.start("https://example.com/webhook") ``` +MAX принимает webhook только на внешнем HTTPS URL через публичный порт 443. +Встроенный сервер обычно оставляют на HTTP-порту 8080 за Nginx/Caddy: +reverse proxy завершает TLS и проксирует запросы внутрь приложения. + +Для прямого HTTPS в aiohttp передайте серверный `SSLContext`: + +```python +import ssl + +server_ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) +server_ssl_context.load_cert_chain("/etc/ssl/webhook/fullchain.pem", "/etc/ssl/webhook/key.pem") + +manager = WebhookManager( + dp, + bot, + host="0.0.0.0", + port=443, + ssl_context=server_ssl_context, +) +await manager.start("https://example.com/webhook") +``` + +Для исходящих запросов к API отдельный доверенный CA задаётся через +`AiohttpSession(ssl_context=...)` или готовый `aiohttp.TCPConnector`. Проверку +сертификатов отключать нельзя. Для production также рекомендуется включать +secret webhook; Long Polling предназначен для разработки. + ## Архитектура - **`WebhookHandler`** — принимает POST, парсит JSON в discriminated union `Update` через Pydantic `TypeAdapter`, передаёт в `dispatcher.feed_update()`. Неизвестные `update_type` пропускаются с 200 OK (чтобы Max не отписал webhook)