Skip to content

The agent that grows with you

fix: reject unknown delivery targets and allow API session preflight

Teknium33c1bb885c83
diff --git a/gateway/delivery.py b/gateway/delivery.py
index 105175801b9..6357eafef49 100644
--- a/gateway/delivery.py
+++ b/gateway/delivery.py
@@ -106,6 +106,11 @@ class DeliveryTarget:
thread_id: Optional[str] = None
is_origin: bool = False
is_explicit: bool = False # True if chat_id was explicitly specified
+ # Raw target string when the platform name is unknown. The platform falls
+ # back to LOCAL for routing, but the original name is preserved so
+ # deliver() can report {success: False, error: unknown_platform} instead
+ # of silently misrouting to local files.
+ unknown_platform: Optional[str] = None
@classmethod
def parse(cls, target: str, origin: Optional[SessionSource] = None) -> "DeliveryTarget":
@@ -114,12 +119,14 @@ class DeliveryTarget:
if target.lower() == "origin":
return (cls(platform=origin.platform, chat_id=origin.chat_id, thread_id=origin.thread_id, is_origin=True)
if origin else cls(platform=Platform.LOCAL, is_origin=True))
- # Platform names are case-insensitive; chat/thread ids keep case. Unknown platforms -> local.
+ # Platform names are case-insensitive; chat/thread ids keep case. Unknown platforms ->
+ # LOCAL for routing but preserve the raw target so deliver() reports
+ # unknown_platform instead of silently saving locally.
parts = target.split(":", 2)
try:
platform = Platform(parts[0].lower())
except ValueError:
- return cls(platform=Platform.LOCAL)
+ return cls(platform=Platform.LOCAL, unknown_platform=target)
return (cls(platform=platform, chat_id=parts[1], thread_id=parts[2] if len(parts) > 2 else None, is_explicit=True)
if len(parts) > 1 else cls(platform=platform))
@@ -127,6 +134,8 @@ class DeliveryTarget:
"""Convert back to string format."""
if self.is_origin:
return "origin"
+ if self.unknown_platform:
+ return self.unknown_platform
if self.platform == Platform.LOCAL:
return "local"
parts = [self.platform.value, self.chat_id, self.thread_id if self.chat_id else None]
@@ -159,6 +168,10 @@ class DeliveryRouter:
"""Deliver content to all targets; returns per-target results keyed by target string."""
results = {}
for target in targets:
+ if target.unknown_platform:
+ results[target.to_string()] = {
+ "success": False, "error": f"unknown_platform: {target.unknown_platform}"}
+ continue
# Skip targets proven permanently unreachable (deleted group, blocked bot, deactivated user) —
# re-sending each tick wastes flood-control budget. Self-healing: a later successful send
# clears the flag. LOCAL/origin-without-chat targets are never dead-tracked.
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 34876332db6..5869dfd8c8e 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -771,7 +771,7 @@ class ResponseStore:
_CORS_HEADERS = {
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
- "Access-Control-Allow-Headers": "Authorization, Content-Type, Idempotency-Key"}
+ "Access-Control-Allow-Headers": "Authorization, Content-Type, Idempotency-Key, X-Hermes-Session-Id"}
_SECURITY_HEADERS = {
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
diff --git a/tests/gateway/test_api_session_preflight.py b/tests/gateway/test_api_session_preflight.py
new file mode 100644
index 00000000000..7f7ee47e661
--- /dev/null
+++ b/tests/gateway/test_api_session_preflight.py
@@ -0,0 +1,36 @@
+"""The browser can send the advertised continuation header only from allowed origins."""
+
+import secrets
+
+import pytest
+from aiohttp import ClientSession
+
+from gateway.config import PlatformConfig
+from gateway.platforms.api_server import APIServerAdapter, _STATIC_FEATURE_FLAGS
+
+
+async def test_continuation_preflight_preserves_origin_allowlist():
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={
+ "host": "127.0.0.1", "port": 0, "key": secrets.token_hex(32),
+ "cors_origins": ["https://allowed.example"],
+ }))
+ assert await adapter.connect()
+ try:
+ port = adapter._site._server.sockets[0].getsockname()[1]
+ header = _STATIC_FEATURE_FLAGS["session_continuity_header"]
+ async with ClientSession() as client:
+ for origin, expected in [("https://allowed.example", 200), ("https://denied.example", 403)]:
+ async with client.options(f"http://127.0.0.1:{port}/v1/chat/completions", headers={
+ "Origin": origin, "Access-Control-Request-Method": "POST",
+ "Access-Control-Request-Headers": f"Authorization, Content-Type, {header}",
+ }) as response:
+ assert response.status == expected
+ if expected == 200:
+ allowed = {h.strip().lower() for h in response.headers["Access-Control-Allow-Headers"].split(",")}
+ assert header.lower() in allowed
+ assert response.headers["Access-Control-Allow-Origin"] == origin
+ else:
+ assert "Access-Control-Allow-Origin" not in response.headers
+ finally:
+ await adapter.disconnect()
diff --git a/tests/gateway/test_delivery_unknown_target.py b/tests/gateway/test_delivery_unknown_target.py
new file mode 100644
index 00000000000..3ff7623583d
--- /dev/null
+++ b/tests/gateway/test_delivery_unknown_target.py
@@ -0,0 +1,24 @@
+"""Unknown destinations must not acknowledge a successful local delivery."""
+
+from pathlib import Path
+
+import pytest
+
+from gateway.config import GatewayConfig
+from gateway.delivery import DeliveryRouter, DeliveryTarget
+
+
+async def test_unknown_destination_fails_without_writing_and_local_still_works(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ router = DeliveryRouter(GatewayConfig())
+ raw = "MisspelledPlatform:ChatID:ThreadID"
+ result = await router.deliver("must not save", [DeliveryTarget.parse(raw)], job_id="bad")
+ assert not any(receipt["success"] for receipt in result.values()), result
+ assert raw in result
+ assert result[raw]["error"] == f"unknown_platform: {raw}"
+ assert not list(tmp_path.rglob("*.txt"))
+ assert not list(tmp_path.rglob("*.md"))
+ result = await router.deliver("explicit local marker", [DeliveryTarget.parse("local")], job_id="good")
+ assert result["local"]["success"]
+ assert "explicit local marker" in Path(result["local"]["result"]["path"]).read_text(encoding="utf-8")