This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-14 09:11:15 +02:00
1 parent 0086c32745
commit a27fbb80e5
5 files changed
+113 -3

No files matched your search

+12
View File
@@ -128,6 +128,18 @@ from cptr.utils.proxy_middleware import ProxyFallbackMiddleware
app.add_middleware(ProxyFallbackMiddleware)
# CORS middleware: uses CPTR_CORS_ALLOWED_ORIGINS env var (default "*").
from fastapi.middleware.cors import CORSMiddleware
from cptr.env import CORS_ALLOWED_ORIGINS
app.add_middleware(
CORSMiddleware,
allow_origins=CORS_ALLOWED_ORIGINS if isinstance(CORS_ALLOWED_ORIGINS, list) else ["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Path normalization middleware (Windows: \ → / in JSON responses)
import platform
+10
View File
@@ -37,3 +37,13 @@ STREAM_WRITE_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_WRITE_TIMEOUT",
# ── Automation scheduler ────────────────────────────────────
AUTOMATION_POLL_INTERVAL = int(os.environ.get("AUTOMATION_POLL_INTERVAL", "10"))
# ── CORS ────────────────────────────────────────────────────
# Socket.IO CORS allowed origins.
# Default → "*" (allow all origins)
# Comma-separated list → allow specific origins only
# e.g. "https://example.com,https://app.example.com"
_cors_raw = os.environ.get("CPTR_CORS_ALLOWED_ORIGINS", "*")
if _cors_raw.strip() == "*":
CORS_ALLOWED_ORIGINS = "*"
else:
CORS_ALLOWED_ORIGINS = [o.strip() for o in _cors_raw.split(",") if o.strip()] or "*"
+2 -1
View File
@@ -10,8 +10,9 @@ from __future__ import annotations
import socketio
from cptr.utils.config import check_access
from cptr.env import CORS_ALLOWED_ORIGINS
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*")
sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=CORS_ALLOWED_ORIGINS)
# user_id → set of connected sids
_user_sids: dict[str, set[str]] = {}
+30
View File
@@ -70,11 +70,41 @@ class ProxyFallbackMiddleware:
await self.app(scope, receive, send)
return
# Auth check: this middleware runs before the auth middleware (outermost),
# so we must verify the session ourselves to prevent unauthenticated SSRF.
if not self._is_authenticated(scope):
# Not authenticated — fall through to the normal app (which will
# either serve a page or return 401 via the auth middleware).
await self.app(scope, receive, send)
return
if scope["type"] == "http":
await self._proxy_http(scope, receive, send, port, path)
elif scope["type"] == "websocket":
await self._proxy_websocket(scope, receive, send, port, path)
@staticmethod
def _is_authenticated(scope: Scope) -> bool:
"""Check if the request carries a valid cptr session cookie."""
from cptr.utils.config import check_access
headers = dict(scope.get("headers", []))
cookie_header = (headers.get(b"cookie") or b"").decode("latin-1", errors="replace")
token = None
for part in cookie_header.split(";"):
part = part.strip()
if part.startswith("cptr_session="):
token = part.split("=", 1)[1]
break
if not token:
return False
client = scope.get("client")
client_host = client[0] if client else "127.0.0.1"
return check_access(client_host=client_host, jwt_token=token) is not None
def _resolve_port(self, scope: Scope) -> int | None:
"""Determine which proxy port this request belongs to."""
from cptr.routers.proxy import resolve_cached_port