From a27fbb80e58b505775a9be284d052392b4e3e4e6 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 14 Jun 2026 09:11:15 +0200 Subject: [PATCH] refac --- README.md | 61 ++++++++++++++++++++++++++++++++-- cptr/app.py | 12 +++++++ cptr/env.py | 10 ++++++ cptr/socket/main.py | 3 +- cptr/utils/proxy_middleware.py | 30 +++++++++++++++++ 5 files changed, 113 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 98ade4c..d60a270 100644 --- a/README.md +++ b/README.md @@ -12,10 +12,67 @@ Push a hotfix from the train. Check on a deploy from bed. Ship a side project fr Close the tab. Come back tomorrow on any device. Everything is where you left it. Sessions survive disconnects. Your work doesn't care which screen you're on. -AI is there if you want it. Bring your own key. Works fine without it. - Life is short. Touch grass. +## What you get + +| | | +|---|---| +| ๐Ÿ“ **File browser** | Navigate, create, rename, upload, drag and drop. Icons by type, sizes at a glance. | +| โŒจ๏ธ **Terminal** | Full PTY-backed shell in the browser. Anything you'd run at your desk. | +| ๐Ÿ”€ **Git** | Stage, commit, diff, branch, push. Visual changes view. No command line required. | +| โœ๏ธ **Editor** | Syntax-highlighted editing with tabs. Open multiple files side by side. | +| ๐Ÿ“‚ **Workspaces** | Multiple projects, one instance. Switch without losing your place. | +| ๐Ÿ” **Search** | Find files by name, search across file contents and chat history. โŒ˜K to find anything. | +| ๐Ÿ“ฑ **Mobile-first** | Not a desktop UI made smaller. Built for the screen in your pocket. | +| ๐Ÿ”„ **Sessions persist** | Terminal keeps running when you close the tab. Come back on any device. | + +## AI agent + +Bring your own API key. Works with OpenAI, Anthropic, Ollama, or any OpenAI-compatible endpoint. + +| | | +|---|---| +| ๐Ÿ’ฌ **Chat** | Built-in AI with streaming responses and tool calling. Not just conversation: it can act. | +| ๐Ÿ”ง **File tools** | AI reads, writes, edits, and searches your codebase directly. | +| โ–ถ๏ธ **Run commands** | AI executes shell commands and reads the output. Foreground or background. | +| ๐ŸŒ **Web browsing** | Navigate pages, click elements, fill forms, take screenshots. | +| ๐Ÿ” **Web search** | Brave, DuckDuckGo, Exa, Tavily, Perplexity, or any chat completions endpoint. | +| ๐Ÿ–ผ๏ธ **Image understanding** | AI reads and describes images and screenshots from your workspace. | +| ๐Ÿ“‹ **Plan mode** | Request an implementation plan before the AI writes a single line. | +| โœ๏ธ **Output editing** | Review and edit AI-generated changes before applying. | +| ๐Ÿ“Ž **File mentions** | Type `@` to give the AI context about specific files. | +| ๐Ÿงฉ **Skills** | Reusable instruction sets (SKILL.md files). Type `$` to mention one. | +| โฑ๏ธ **Automations** | Schedule recurring AI tasks. "Run tests every morning." "Deploy every Friday." | +| ๐Ÿค– **Sub-agents** | AI spins up parallel workers for complex tasks. Each gets full tool access. | +| ๐Ÿ”Œ **Tool servers** | Connect external tools via MCP or OpenAPI. | +| ๐Ÿง  **Context compaction** | Long conversations are automatically summarised to stay fast. | + +## Messaging bots + +Connect the AI to your chat apps. Full tool access, streaming responses, conversations synced back to the web UI. + +**Telegram** ยท **Discord** ยท **Slack** ยท **WhatsApp** ยท **Signal** + +Message your computer from wherever you are. Ask it to check a build, push a fix, or explain a file. Switch workspaces with `/workspace`, start fresh with `/new`. + +## Gateway API + +cptr exposes an OpenAI-compatible API (`/v1/chat/completions`). Any client that speaks OpenAI, including [Open WebUI](https://github.com/open-webui/open-webui), can use each cptr workspace as a model with full agent capabilities: file access, terminal, web search, tools. + +## More + +| | | +|---|---| +| ๐ŸŽ™๏ธ **Voice memos** | Record audio, auto-transcribe to markdown. | +| ๐Ÿ’ฌ **Message queue** | Queue follow-up messages while the AI is responding. | +| ๐Ÿ”” **Notifications** | Browser notifications and webhooks (Slack, Discord, Teams) when tasks finish. | +| ๐Ÿ“Š **Usage** | Token counts and timing on every response. | +| ๐Ÿ“„ **System prompts** | Per-model, per-workspace, or global. Template variables included. | +| โŒจ๏ธ **Keyboard shortcuts** | Customisable keybindings with a settings panel. | +| ๐ŸŒ **10 languages** | EN, DE, ES, FR, JA, KO, PT-BR, RU, ZH-CN, ZH-TW. | +| ๐Ÿ” **Auth** | Username/password with JWT sessions. Signup toggle for admins. | + ## Design principles **Mobile is first-class.** The interface is built for the phone. Touch-native, portrait-native, designed for the screen people carry. Sessions survive disconnects because on a phone, they will. If a feature only works at a desk, it's not done. diff --git a/cptr/app.py b/cptr/app.py index 7ee442f..4c09e0c 100644 --- a/cptr/app.py +++ b/cptr/app.py @@ -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 diff --git a/cptr/env.py b/cptr/env.py index 6d50a38..dc178f3 100644 --- a/cptr/env.py +++ b/cptr/env.py @@ -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 "*" diff --git a/cptr/socket/main.py b/cptr/socket/main.py index 0f20e92..b46c229 100644 --- a/cptr/socket/main.py +++ b/cptr/socket/main.py @@ -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]] = {} diff --git a/cptr/utils/proxy_middleware.py b/cptr/utils/proxy_middleware.py index 616093b..8cc2a7d 100644 --- a/cptr/utils/proxy_middleware.py +++ b/cptr/utils/proxy_middleware.py @@ -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