This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-06 00:16:13 -04:00
1 parent 049280219b
commit 936a614957
7 files changed
+698 -129

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
.git
.github
.venv
.cptr
.claude
__pycache__
*.pyc
*.egg-info
dist/
build/
cptr/frontend/node_modules/
cptr/frontend/.svelte-kit/
cptr/frontend/build/
*.md
LICENSE
CONTRIBUTOR_LICENSE_AGREEMENT
.DS_Store
+19
View File
@@ -0,0 +1,19 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.0.1] - 2026-06-05
### Added
- 🚀 **Initial release.** First public version of cptr: your computer, from anywhere. Code, manage, and control your machine from the web.
- 🖥️ **Terminal emulator.** Full PTY-backed terminal accessible from the browser with support for macOS and Linux.
- 💬 **AI chat interface.** Built-in chat panel with multi-provider LLM support (OpenAI, Anthropic, Ollama, and OpenAI-compatible endpoints), tool calling, and streaming responses.
- 🔧 **Tool system.** Extensible tool framework enabling AI agents to interact with the local filesystem, run commands, search the web, and read URLs.
- 📁 **File browser.** Web-based file explorer with directory navigation, file viewing, and management capabilities.
- 🔐 **Authentication.** Username/password authentication with JWT-based session management.
- 🐳 **Docker support.** Multi-stage Dockerfile and GitHub Actions workflow for building and publishing to GHCR.
- 📦 **PyPI packaging.** Hatchling-based build with frontend assets bundled into the wheel, published via trusted OIDC publishing.
+55
View File
@@ -0,0 +1,55 @@
# ── Stage 1: Build the SvelteKit frontend ──────────────────
FROM node:22-slim AS frontend-builder
WORKDIR /build/frontend
COPY cptr/frontend/package.json cptr/frontend/package-lock.json ./
RUN npm ci
COPY cptr/frontend/ ./
RUN npm run build
# ── Stage 2: Install Python dependencies & build wheel ─────
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS backend-builder
WORKDIR /build
COPY pyproject.toml uv.lock ./
COPY cptr/ cptr/
# Drop the pre-built frontend into the package tree
COPY --from=frontend-builder /build/frontend/build cptr/frontend/build
# Build the wheel (includes frontend build as an artifact via hatch)
RUN uv build --wheel --out-dir /dist
# ── Stage 3: Minimal runtime image ─────────────────────────
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS runtime
LABEL org.opencontainers.image.source="https://github.com/open-webui/computer"
LABEL org.opencontainers.image.description="cptr - your computer, from anywhere"
LABEL org.opencontainers.image.licenses="BSL-1.1"
# Runtime deps: git for git operations, tini for PID 1
RUN apt-get update && \
apt-get install -y --no-install-recommends git tini && \
rm -rf /var/lib/apt/lists/*
# Create non-root user
RUN useradd --create-home --shell /bin/bash cptr
USER cptr
WORKDIR /home/cptr
# Install the wheel into an isolated venv
COPY --from=backend-builder /dist/*.whl /tmp/
RUN uv venv /home/cptr/.venv && \
uv pip install --python /home/cptr/.venv/bin/python /tmp/*.whl && \
rm /tmp/*.whl
ENV PATH="/home/cptr/.venv/bin:$PATH"
ENV CPTR_DATA_DIR="/data"
EXPOSE 8000
VOLUME ["/data"]
ENTRYPOINT ["tini", "--"]
CMD ["cptr", "run", "--host", "0.0.0.0", "--port", "8000", "--headless"]
+8
View File
@@ -63,6 +63,14 @@ async def auth_middleware(request: Request, call_next):
return await call_next(request)
# Proxy fallback middleware: intercepts sub-resource requests for proxied
# dev servers (JS modules, CSS, etc.) based on the Referer header chain.
# Added after auth middleware so it wraps outermost (runs before auth),
# since proxied sub-resources don't need cptr auth.
from cptr.utils.proxy_middleware import ProxyFallbackMiddleware
app.add_middleware(ProxyFallbackMiddleware)
# Path normalization middleware (Windows: \ → / in JSON responses)
import platform
if platform.system() == "Windows":
@@ -1,3 +1,9 @@
<script module>
// Module-level cache: survives component destroy/create cycles
const _treeExpandedCache = new Map();
const _treeContentsCache = new Map();
</script>
<script lang="ts">
import { activeWorkspace, setFileBrowserCwd, openFileTab, openPreviewTab } from '$lib/stores';
import { systemEvents } from '$lib/stores/systemEvents.svelte';
@@ -14,6 +20,11 @@
modified: string | null;
}
interface TreeEntry extends FileEntry {
path: string;
depth: number;
}
let entries = $state<FileEntry[]>([]);
let loading = $state(false);
let fetchTimer: ReturnType<typeof setTimeout> | null = null;
@@ -31,6 +42,10 @@
let sortBtnEl: HTMLButtonElement | undefined = $state();
let addBtnEl: HTMLButtonElement | undefined = $state();
// Tree view
let expandedDirs = $state<Set<string>>(new Set());
let dirContents = $state<Map<string, FileEntry[]>>(new Map());
// Sort
let sortBy = $state<'name' | 'size' | 'modified'>('name');
let sortDir = $state<'asc' | 'desc'>('asc');
@@ -41,7 +56,7 @@
let dragOverBreadcrumb = $state<string | null>(null);
// Context menu
let contextMenu = $state<{ x: number; y: number; entry: FileEntry; anchor?: HTMLElement } | null>(null);
let contextMenu = $state<{ x: number; y: number; entry: TreeEntry; anchor?: HTMLElement } | null>(null);
let renamingEntry = $state<string | null>(null);
let renameValue = $state('');
@@ -70,10 +85,26 @@
});
// Fetch directory on cwd change
let _prevCwd = '';
$effect(() => {
if (cwd) {
// Immediate fetch for navigation
fetchDirectoryImmediate(cwd);
if (cwd !== _prevCwd) {
const isNavigation = _prevCwd !== '';
_prevCwd = cwd;
if (isNavigation) {
// Navigated to a new directory: reset tree state
expandedDirs = new Set();
dirContents = new Map();
} else {
// Component (re)mount: restore tree state from cache
const cachedExpanded = _treeExpandedCache.get(cwd);
if (cachedExpanded) {
expandedDirs = new Set(cachedExpanded);
dirContents = new Map(_treeContentsCache.get(cwd) ?? []);
}
}
fetchDirectoryImmediate(cwd);
}
}
});
@@ -90,6 +121,10 @@
const _tick = systemEvents.fsTick; // subscribe
if (_tick > 0 && cwd && !fetching && systemEvents.isRelevantFsChange(cwd)) {
debouncedFetch(cwd);
// Also refresh expanded directories
for (const dir of expandedDirs) {
fetchSubdir(dir);
}
}
});
@@ -97,6 +132,11 @@
showHidden = !showHidden;
localStorage.setItem('fileBrowser:showHidden', String(showHidden));
fetchDirectory(cwd);
// Clear cache and re-fetch expanded dirs with new filter
dirContents = new Map();
for (const dir of expandedDirs) {
fetchSubdir(dir);
}
}
function debouncedFetch(path: string) {
@@ -138,27 +178,78 @@
debouncedFetch(path);
}
function handleClick(e: MouseEvent, entry: FileEntry, index: number) {
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
// ── Tree view: expand/collapse ─────────────────────────────
function saveTreeCache() {
if (cwd) {
_treeExpandedCache.set(cwd, [...expandedDirs]);
_treeContentsCache.set(cwd, [...dirContents.entries()]);
}
}
async function toggleDir(path: string) {
if (expandedDirs.has(path)) {
const next = new Set(expandedDirs);
next.delete(path);
expandedDirs = next;
} else {
if (!dirContents.has(path)) {
await fetchSubdir(path);
}
const next = new Set(expandedDirs);
next.add(path);
expandedDirs = next;
}
saveTreeCache();
}
async function fetchSubdir(path: string) {
try {
const data = await listDir(path);
const filtered = showHidden
? data.entries
: data.entries.filter((e: FileEntry) => !e.name.startsWith('.'));
dirContents = new Map(dirContents).set(path, filtered);
saveTreeCache();
} catch {
// Remove from expanded on error
const next = new Set(expandedDirs);
next.delete(path);
expandedDirs = next;
const nextContents = new Map(dirContents);
nextContents.delete(path);
dirContents = nextContents;
saveTreeCache();
}
}
/** Refresh a specific expanded directory's cached contents */
async function refreshParentDir(entryPath: string) {
const parentDir = entryPath.substring(0, entryPath.lastIndexOf('/'));
if (parentDir === cwd || parentDir === cwd.replace(/\/$/, '')) {
fetchDirectory(cwd);
} else if (dirContents.has(parentDir)) {
await fetchSubdir(parentDir);
}
}
function handleClick(e: MouseEvent, entry: TreeEntry, index: number) {
// Multi-select with ctrl/cmd or shift
if (e.metaKey || e.ctrlKey) {
const next = new Set(selectedPaths);
if (next.has(fullPath)) next.delete(fullPath);
else next.add(fullPath);
if (next.has(entry.path)) next.delete(entry.path);
else next.add(entry.path);
selectedPaths = next;
lastClickedIndex = index;
return;
}
if (e.shiftKey && lastClickedIndex >= 0) {
const list = sortedEntries();
const list = visibleEntries;
const start = Math.min(lastClickedIndex, index);
const end = Math.max(lastClickedIndex, index);
const next = new Set(selectedPaths);
for (let i = start; i <= end; i++) {
const p = cwd.endsWith('/') ? cwd + list[i].name : cwd + '/' + list[i].name;
next.add(p);
next.add(list[i].path);
}
selectedPaths = next;
return;
@@ -168,9 +259,9 @@
selectedPaths = new Set();
lastClickedIndex = index;
if (entry.type === 'directory') {
setFileBrowserCwd(fullPath);
toggleDir(entry.path);
} else {
openFileTab(fullPath);
openFileTab(entry.path);
}
}
@@ -210,15 +301,10 @@
return `${(bytes / 1048576).toFixed(1)} MB`;
}
let filteredEntries = $derived(
searchQuery
? entries.filter((e) => e.name.toLowerCase().includes(searchQuery.toLowerCase()))
: entries
);
let sortedEntries = $derived(() => {
const dirs = filteredEntries.filter((e) => e.type === 'directory');
const files = filteredEntries.filter((e) => e.type !== 'directory');
// ── Tree-aware visible entries ──────────────────────────────
function sortItems(items: FileEntry[]): FileEntry[] {
const dirs = items.filter((e) => e.type === 'directory');
const files = items.filter((e) => e.type !== 'directory');
function compare(a: FileEntry, b: FileEntry): number {
let result = 0;
@@ -235,6 +321,30 @@
dirs.sort(compare);
files.sort(compare);
return [...dirs, ...files];
}
let visibleEntries = $derived.by(() => {
const result: TreeEntry[] = [];
const query = searchQuery.toLowerCase();
function walk(parentPath: string, items: FileEntry[], depth: number) {
let filtered = query
? items.filter((e) => e.name.toLowerCase().includes(query))
: items;
for (const entry of sortItems(filtered)) {
const fullPath = parentPath.endsWith('/')
? parentPath + entry.name
: parentPath + '/' + entry.name;
result.push({ ...entry, path: fullPath, depth });
if (entry.type === 'directory' && expandedDirs.has(fullPath)) {
const children = dirContents.get(fullPath);
if (children) walk(fullPath, children, depth + 1);
}
}
}
walk(cwd, entries, 0);
return result;
});
function toggleSort(field: 'name' | 'size' | 'modified') {
@@ -253,9 +363,8 @@
function selectAll() {
const all = new Set<string>();
for (const e of sortedEntries()) {
const p = cwd.endsWith('/') ? cwd + e.name : cwd + '/' + e.name;
all.add(p);
for (const e of visibleEntries) {
all.add(e.path);
}
selectedPaths = all;
}
@@ -290,34 +399,33 @@
}
// ── Drag to move ────────────────────────────────────────────
function onDragStart(e: DragEvent, entry: FileEntry) {
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
draggedItem = fullPath;
e.dataTransfer?.setData('text/plain', fullPath);
function onDragStart(e: DragEvent, entry: TreeEntry) {
draggedItem = entry.path;
e.dataTransfer?.setData('text/plain', entry.path);
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
}
function onDragOverDir(e: DragEvent, entry: FileEntry) {
function onDragOverDir(e: DragEvent, entry: TreeEntry) {
if (entry.type !== 'directory') return;
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'move';
dragOverDir = entry.name;
dragOverDir = entry.path;
}
function onDragLeaveDir() {
dragOverDir = null;
}
async function onDropOnDir(e: DragEvent, entry: FileEntry) {
async function onDropOnDir(e: DragEvent, entry: TreeEntry) {
e.preventDefault();
dragOverDir = null;
// Handle file browser item drag
if (draggedItem) {
const dest = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
try {
await moveFile(draggedItem, dest);
await moveFile(draggedItem, entry.path);
fetchDirectory(cwd);
refreshParentDir(draggedItem);
} catch {}
draggedItem = null;
return;
@@ -326,8 +434,7 @@
// Handle external file upload
const files = e.dataTransfer?.files;
if (files && files.length) {
const dest = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
await uploadFiles(files, dest);
await uploadFiles(files, entry.path);
}
}
@@ -438,12 +545,12 @@
}
// ── Context menu ───────────────────────────────────────────
function onContextMenu(e: MouseEvent, entry: FileEntry) {
function onContextMenu(e: MouseEvent, entry: TreeEntry) {
e.preventDefault();
contextMenu = { x: e.clientX, y: e.clientY, entry };
}
function openEntryMenu(e: MouseEvent, entry: FileEntry) {
function openEntryMenu(e: MouseEvent | KeyboardEvent, entry: TreeEntry) {
e.stopPropagation();
contextMenu = { x: 0, y: 0, entry, anchor: e.currentTarget as HTMLElement };
}
@@ -452,41 +559,51 @@
contextMenu = null;
}
function startRename(entry: FileEntry) {
renamingEntry = entry.name;
function startRename(entry: TreeEntry) {
renamingEntry = entry.path;
renameValue = entry.name;
closeMenu();
}
async function confirmRename(oldName: string) {
async function confirmRename(entryPath: string) {
const oldName = entryPath.split('/').pop() ?? '';
if (!renameValue.trim() || renameValue === oldName) {
renamingEntry = null;
return;
}
const src = cwd.endsWith('/') ? cwd + oldName : cwd + '/' + oldName;
const dst = cwd.endsWith('/') ? cwd + renameValue.trim() : cwd + '/' + renameValue.trim();
const parentDir = entryPath.substring(0, entryPath.lastIndexOf('/'));
const dst = parentDir + '/' + renameValue.trim();
try {
await moveFile(src, dst);
await moveFile(entryPath, dst);
fetchDirectory(cwd);
if (dirContents.has(parentDir)) await fetchSubdir(parentDir);
} catch {}
renamingEntry = null;
}
async function deleteEntry(entry: FileEntry) {
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
async function deleteEntry(entry: TreeEntry) {
const label = entry.type === 'directory' ? $t('files.folder') : $t('files.file');
if (!confirm($t('files.deleteEntryConfirm', { type: label, name: entry.name }))) return;
try {
await deleteFiles([fullPath]);
await deleteFiles([entry.path]);
fetchDirectory(cwd);
refreshParentDir(entry.path);
// Clean up expand state for deleted directories
if (entry.type === 'directory') {
const next = new Set(expandedDirs);
next.delete(entry.path);
expandedDirs = next;
const nextContents = new Map(dirContents);
nextContents.delete(entry.path);
dirContents = nextContents;
}
} catch {}
closeMenu();
}
function downloadEntry(entry: FileEntry) {
const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name;
function downloadEntry(entry: TreeEntry) {
const a = document.createElement('a');
a.href = `/api/workspace/files/download?path=${encodeURIComponent(fullPath)}`;
a.href = `/api/workspace/files/download?path=${encodeURIComponent(entry.path)}`;
a.download = entry.name;
a.click();
closeMenu();
@@ -627,34 +744,34 @@
onclick={() => fetchDirectory(cwd)}
>{$t('files.retry')}</button>
</div>
{:else if sortedEntries().length === 0 && !showNewInput}
{:else if visibleEntries.length === 0 && !showNewInput}
<div class="flex items-center justify-center py-12">
<p class="text-xs text-gray-400 dark:text-gray-600">
{searchQuery ? $t('files.noMatches') : $t('files.emptyDirectory')}
</p>
</div>
{:else}
{#each sortedEntries() as entry, i (entry.name)}
{#if renamingEntry === entry.name}
{#each visibleEntries as entry, i (entry.path)}
{#if renamingEntry === entry.path}
<!-- Inline rename -->
<div class="flex items-center gap-2 h-7 px-2">
<div class="flex items-center gap-2 h-7" style="padding-left: {8 + entry.depth * 16}px; padding-right: 8px;">
<Icon name={fileIconName(entry)} size={14} class="text-gray-400 shrink-0" />
<input
type="text"
class="flex-1 border-none outline-none bg-transparent text-xs text-gray-900 dark:text-white"
bind:value={renameValue}
onkeydown={(e) => { if (e.key === 'Enter') confirmRename(entry.name); if (e.key === 'Escape') renamingEntry = null; }}
onblur={() => confirmRename(entry.name)}
onkeydown={(e) => { if (e.key === 'Enter') confirmRename(entry.path); if (e.key === 'Escape') renamingEntry = null; }}
onblur={() => confirmRename(entry.path)}
autofocus
/>
</div>
{:else}
{@const fullPath = cwd.endsWith('/') ? cwd + entry.name : cwd + '/' + entry.name}
{@const isSelected = selectedPaths.has(fullPath)}
{@const isSelected = selectedPaths.has(entry.path)}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<button
class="group flex items-center gap-2 w-full h-7 px-2 rounded-lg text-left transition-colors duration-75
{isSelected ? 'bg-blue-50 dark:bg-blue-500/10' : dragOverDir === entry.name ? 'bg-blue-100 dark:bg-blue-500/20' : 'hover:bg-gray-100 dark:hover:bg-white/4'}"
class="group flex items-center gap-1 w-full h-7 rounded-lg text-left transition-colors duration-75
{isSelected ? 'bg-blue-50 dark:bg-blue-500/10' : dragOverDir === entry.path ? 'bg-blue-100 dark:bg-blue-500/20' : 'hover:bg-gray-100 dark:hover:bg-white/4'}"
style="padding-left: {8 + entry.depth * 16}px; padding-right: 8px;"
onclick={(e) => handleClick(e, entry, i)}
oncontextmenu={(e) => onContextMenu(e, entry)}
draggable="true"
@@ -664,18 +781,31 @@
ondrop={(e) => onDropOnDir(e, entry)}
ondragend={onDragEnd}
>
{#if entry.type === 'directory'}
<span class="flex items-center justify-center w-4 shrink-0 text-gray-400 dark:text-gray-600">
<Icon name={expandedDirs.has(entry.path) ? 'chevron-down' : 'chevron-right'} size={10} />
</span>
{:else}
<span class="w-4 shrink-0"></span>
{/if}
<span class="flex items-center justify-center w-4 shrink-0 {entry.type === 'directory' ? 'text-gray-500 dark:text-gray-400' : 'text-gray-400 dark:text-gray-500'}">
<Icon name={fileIconName(entry)} size={14} strokeWidth={1.4} />
</span>
<span class="flex-1 text-xs text-gray-800 dark:text-gray-200 truncate">{entry.name}</span>
{#if entry.type === 'directory'}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<span
class="flex-1 text-xs text-gray-800 dark:text-gray-200 truncate hover:underline cursor-pointer"
role="button"
tabindex="-1"
onclick={(e) => { e.stopPropagation(); setFileBrowserCwd(entry.path); }}
onkeydown={(e) => { if (e.key === 'Enter') { e.stopPropagation(); setFileBrowserCwd(entry.path); } }}
>{entry.name}</span>
{:else}
<span class="flex-1 text-xs text-gray-800 dark:text-gray-200 truncate">{entry.name}</span>
{/if}
{#if entry.type !== 'directory' && entry.size !== null}
<span class="text-[11px] font-mono text-gray-400 dark:text-gray-600 shrink-0">{formatSize(entry.size)}</span>
{/if}
{#if entry.type === 'directory'}
<span class="text-gray-300 dark:text-gray-700 shrink-0 flex">
<Icon name="chevron-right" size={12} />
</span>
{/if}
<!-- Three-dot menu per entry -->
<span
class="flex items-center justify-center w-5 h-5 rounded shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-200 dark:hover:bg-white/10 transition-all duration-75"
+209 -64
View File
@@ -1,22 +1,30 @@
"""Reverse proxy to localhost services.
Proxies requests to 127.0.0.1:{port} so that dev servers
started in terminal sessions are accessible from any device.
Proxies HTTP requests and WebSocket connections to 127.0.0.1:{port}
so that dev servers started in terminal sessions are accessible
from any device through the cptr UI.
The proxy path cache (shared with proxy_middleware) tracks which
request paths belong to which ports, enabling sub-resource loading
without URL rewriting.
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
import httpx
from fastapi import APIRouter, Request, Response
from fastapi.responses import StreamingResponse
from fastapi import APIRouter, Request, Response, WebSocket, WebSocketDisconnect
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/proxy", tags=["proxy"])
# Shared async client, reused across requests
# ── Shared async HTTP client ────────────────────────────────────
_client: httpx.AsyncClient | None = None
@@ -26,92 +34,140 @@ def _get_client() -> httpx.AsyncClient:
_client = httpx.AsyncClient(
timeout=httpx.Timeout(30.0, connect=5.0),
follow_redirects=False,
limits=httpx.Limits(max_connections=20),
limits=httpx.Limits(max_connections=50),
)
return _client
# Headers we should NOT forward from the upstream
# ── Path → port cache (used by both proxy router and middleware) ──
# Maps request paths to (port, timestamp). Populated when requests
# flow through /api/proxy/{port}/... and also by the middleware when
# it proxies sub-resources based on Referer.
proxy_path_cache: dict[str, tuple[int, float]] = {}
CACHE_TTL = 300 # seconds
def cache_path(path: str, port: int) -> None:
"""Associate a request path with a proxy port."""
proxy_path_cache[path] = (port, time.time())
# Lazy eviction: prune stale entries when cache gets large
if len(proxy_path_cache) > 2000:
now = time.time()
stale = [k for k, (_, ts) in proxy_path_cache.items() if now - ts > CACHE_TTL]
for k in stale:
proxy_path_cache.pop(k, None)
def resolve_cached_port(path: str) -> int | None:
"""Look up a port for a previously-proxied path."""
entry = proxy_path_cache.get(path)
if entry is None:
return None
port, ts = entry
if time.time() - ts > CACHE_TTL:
proxy_path_cache.pop(path, None)
return None
return port
# ── Headers ────────────────────────────────────────────────────
_HOP_BY_HOP = {
"connection", "keep-alive", "proxy-authenticate", "proxy-authorization",
"te", "trailers", "transfer-encoding", "upgrade",
}
# Headers we should NOT forward from the client
_SKIP_REQUEST_HEADERS = {
"host", "connection", "accept-encoding",
}
@router.api_route("/{port}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
async def proxy_request(port: int, path: str, request: Request) -> Response:
"""Proxy a request to localhost:{port}/{path}."""
if port < 1 or port > 65535:
return Response(content="Invalid port", status_code=400)
# Build target URL
target_url = f"http://127.0.0.1:{port}/{path}"
if request.url.query:
target_url += f"?{request.url.query}"
# Forward relevant headers
def _build_request_headers(request: Request, port: int) -> dict[str, str]:
"""Build headers to forward to the upstream server."""
headers = {}
for key, value in request.headers.items():
if key.lower() not in _SKIP_REQUEST_HEADERS:
headers[key] = value
headers["host"] = f"127.0.0.1:{port}"
return headers
# Read body for non-GET requests
body = await request.body() if request.method not in ("GET", "HEAD") else None
client = _get_client()
try:
upstream = await client.request(
method=request.method,
url=target_url,
headers=headers,
content=body,
follow_redirects=False,
)
except httpx.ConnectError:
return Response(
content=f"Cannot connect to localhost:{port}",
status_code=502,
media_type="text/plain",
)
except httpx.TimeoutException:
return Response(
content=f"Timeout connecting to localhost:{port}",
status_code=504,
media_type="text/plain",
)
except Exception as e:
logger.error(f"Proxy error for port {port}: {e}")
return Response(
content=f"Proxy error: {e}",
status_code=502,
media_type="text/plain",
)
# Build response headers, skipping hop-by-hop
response_headers = {}
for key, value in upstream.headers.items():
def _build_response_headers(upstream_headers: httpx.Headers) -> dict[str, str]:
"""Build headers to return to the client, stripping hop-by-hop and frame blockers."""
headers = {}
for key, value in upstream_headers.items():
if key.lower() not in _HOP_BY_HOP:
response_headers[key] = value
headers[key] = value
# Remove X-Frame-Options and CSP frame-ancestors so iframe works
response_headers.pop("x-frame-options", None)
response_headers.pop("X-Frame-Options", None)
csp = response_headers.get("content-security-policy", "")
# Remove X-Frame-Options so iframe embedding works
headers.pop("x-frame-options", None)
headers.pop("X-Frame-Options", None)
# Remove frame-ancestors from CSP
csp = headers.get("content-security-policy", "")
if "frame-ancestors" in csp:
# Remove frame-ancestors directive
parts = [p.strip() for p in csp.split(";") if "frame-ancestors" not in p]
if parts:
response_headers["content-security-policy"] = "; ".join(parts)
headers["content-security-policy"] = "; ".join(parts)
else:
response_headers.pop("content-security-policy", None)
headers.pop("content-security-policy", None)
# Drop content-length (we might not change the body, but the framework
# will set it correctly)
headers.pop("content-length", None)
headers.pop("Content-Length", None)
return headers
# ── Core proxy function (reused by middleware) ──────────────────
async def proxy_http_request(port: int, path: str, request: Request) -> Response:
"""Proxy an HTTP request to localhost:{port}/{path}.
This is the shared implementation used by both the explicit
/api/proxy/{port}/{path} route and the fallback middleware.
"""
if port < 1 or port > 65535:
return Response(content="Invalid port", status_code=400)
# Build target URL
target_url = f"http://127.0.0.1:{port}/{path}"
query = str(request.url.query) if request.url.query else ""
if query:
target_url += f"?{query}"
headers = _build_request_headers(request, port)
body = await request.body() if request.method not in ("GET", "HEAD") else None
client = _get_client()
# Try IPv4, fall back to IPv6
upstream: httpx.Response | None = None
for host in ("127.0.0.1", "[::1]"):
url = target_url if host == "127.0.0.1" else target_url.replace("127.0.0.1", "[::1]")
try:
upstream = await client.request(
method=request.method,
url=url,
headers=headers,
content=body,
follow_redirects=False,
)
break
except httpx.ConnectError:
continue
except httpx.TimeoutException:
return Response(content=f"Timeout connecting to localhost:{port}", status_code=504, media_type="text/plain")
except Exception as e:
logger.error(f"Proxy error for port {port}: {e}")
return Response(content=f"Proxy error: {e}", status_code=502, media_type="text/plain")
if upstream is None:
return Response(content=f"Cannot connect to localhost:{port}", status_code=502, media_type="text/plain")
response_headers = _build_response_headers(upstream.headers)
return Response(
content=upstream.content,
@@ -119,3 +175,92 @@ async def proxy_request(port: int, path: str, request: Request) -> Response:
headers=response_headers,
media_type=upstream.headers.get("content-type"),
)
# ── HTTP proxy route ────────────────────────────────────────────
@router.api_route("/{port}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"])
async def proxy_route(port: int, path: str, request: Request) -> Response:
"""Proxy an HTTP request to localhost:{port}/{path}."""
# Cache this path so the middleware can resolve sub-resources
cache_path(f"/api/proxy/{port}/{path}", port)
return await proxy_http_request(port, path, request)
# ── WebSocket proxy route ──────────────────────────────────────
@router.websocket("/{port}/ws-proxy")
@router.websocket("/{port}/ws-proxy/{path:path}")
async def proxy_websocket(websocket: WebSocket, port: int, path: str = ""):
"""Proxy a WebSocket connection to localhost:{port}/{path}.
Used for things like Vite HMR. Relays frames bidirectionally.
"""
if port < 1 or port > 65535:
await websocket.close(code=4000, reason="Invalid port")
return
await websocket.accept()
# Build upstream WS URL -- try IPv6 if IPv4 fails
query = str(websocket.url.query) if websocket.url.query else ""
qs = f"?{query}" if query else ""
upstream_ws = None
for host in ("127.0.0.1", "[::1]"):
ws_url = f"ws://{host}:{port}/{path}{qs}"
try:
import websockets
upstream_ws = await asyncio.wait_for(
websockets.connect(ws_url, additional_headers={"host": f"127.0.0.1:{port}"}),
timeout=5.0,
)
break
except Exception:
continue
if upstream_ws is None:
await websocket.close(code=4002, reason=f"Cannot connect to localhost:{port}")
return
async def client_to_upstream():
"""Relay messages from client WebSocket to upstream."""
try:
while True:
data = await websocket.receive()
if "text" in data:
await upstream_ws.send(data["text"])
elif "bytes" in data:
await upstream_ws.send(data["bytes"])
else:
break
except (WebSocketDisconnect, Exception):
pass
async def upstream_to_client():
"""Relay messages from upstream WebSocket to client."""
try:
async for msg in upstream_ws:
if isinstance(msg, str):
await websocket.send_text(msg)
elif isinstance(msg, bytes):
await websocket.send_bytes(msg)
except Exception:
pass
try:
done, pending = await asyncio.wait(
[asyncio.create_task(client_to_upstream()), asyncio.create_task(upstream_to_client())],
return_when=asyncio.FIRST_COMPLETED,
)
for t in pending:
t.cancel()
finally:
try:
await upstream_ws.close()
except Exception:
pass
try:
await websocket.close()
except Exception:
pass
+195
View File
@@ -0,0 +1,195 @@
"""Proxy fallback middleware.
Intercepts requests for sub-resources of proxied dev servers.
When a page is loaded through /api/proxy/{port}/, its sub-resources
(JS modules, CSS, images) use absolute paths like /@vite/client or
/node_modules/... which resolve against the cptr origin. This
middleware detects those requests via the Referer header and a
path-to-port cache, then proxies them to the correct local port.
The cache chain works like this:
1. /api/proxy/5174/ loads HTML with <script src="/@vite/client">
2. Browser requests /@vite/client with Referer containing /api/proxy/5174/
3. Middleware extracts port 5174, proxies, caches /@vite/client -> 5174
4. /@vite/client imports /node_modules/foo
5. Referer is /@vite/client, middleware looks up cache -> port 5174
6. Chain continues indefinitely
"""
from __future__ import annotations
import logging
import re
from urllib.parse import urlparse
from starlette.requests import Request
from starlette.responses import Response
from starlette.types import ASGIApp, Receive, Scope, Send
logger = logging.getLogger(__name__)
# Regex to extract port from a proxy Referer URL
_PROXY_PORT_RE = re.compile(r"/api/proxy/(\d+)/")
# Paths that should never be intercepted by the proxy middleware
_PASSTHROUGH_PREFIXES = (
"/api/",
"/_app/",
"/socket.io/",
"/favicon",
)
def _extract_port_from_referer(referer: str) -> int | None:
"""Extract the proxy port from a Referer like /api/proxy/5174/..."""
m = _PROXY_PORT_RE.search(referer)
return int(m.group(1)) if m else None
class ProxyFallbackMiddleware:
"""ASGI middleware that intercepts sub-resource requests for proxied dev servers."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] not in ("http", "websocket"):
await self.app(scope, receive, send)
return
path: str = scope.get("path", "")
# Never intercept known cptr paths
if any(path.startswith(prefix) for prefix in _PASSTHROUGH_PREFIXES):
await self.app(scope, receive, send)
return
# Try to resolve a proxy port for this request
port = self._resolve_port(scope)
if port is None:
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)
def _resolve_port(self, scope: Scope) -> int | None:
"""Determine which proxy port this request belongs to."""
from cptr.routers.proxy import resolve_cached_port
path: str = scope.get("path", "")
# 1. Check the path cache (handles chained imports)
cached = resolve_cached_port(path)
if cached is not None:
return cached
# 2. Check Referer header
headers = dict(scope.get("headers", []))
referer_bytes = headers.get(b"referer", b"")
if referer_bytes:
referer = referer_bytes.decode("latin-1", errors="replace")
# Direct: Referer is /api/proxy/{port}/...
port = _extract_port_from_referer(referer)
if port:
return port
# Indirect: Referer is a previously-cached path
try:
ref_path = urlparse(referer).path
except Exception:
ref_path = ""
if ref_path:
cached = resolve_cached_port(ref_path)
if cached is not None:
return cached
return None
async def _proxy_http(self, scope: Scope, receive: Receive, send: Send, port: int, path: str) -> None:
"""Proxy an HTTP request through the shared proxy function."""
from cptr.routers.proxy import proxy_http_request, cache_path
# Cache this path for future chained requests
cache_path(path, port)
request = Request(scope, receive)
response = await proxy_http_request(port, path.lstrip("/"), request)
await response(scope, receive, send)
async def _proxy_websocket(self, scope: Scope, receive: Receive, send: Send, port: int, path: str) -> None:
"""Proxy a WebSocket connection to the dev server.
This handles the case where Vite HMR or similar tools try to
connect a WebSocket to the page origin (e.g. ws://remote:8000/)
instead of through /api/proxy/{port}/ws-proxy/.
"""
import asyncio
from starlette.websockets import WebSocket
websocket = WebSocket(scope, receive, send)
await websocket.accept()
# Build query string
qs_bytes = scope.get("query_string", b"")
qs = f"?{qs_bytes.decode()}" if qs_bytes else ""
upstream_ws = None
for host in ("127.0.0.1", "[::1]"):
ws_url = f"ws://{host}:{port}{path}{qs}"
try:
import websockets
upstream_ws = await asyncio.wait_for(
websockets.connect(ws_url, additional_headers={"host": f"127.0.0.1:{port}"}),
timeout=5.0,
)
break
except Exception:
continue
if upstream_ws is None:
await websocket.close(code=4002, reason=f"Cannot connect to localhost:{port}")
return
async def client_to_upstream():
try:
while True:
data = await websocket.receive()
if "text" in data:
await upstream_ws.send(data["text"])
elif "bytes" in data:
await upstream_ws.send(data["bytes"])
else:
break
except Exception:
pass
async def upstream_to_client():
try:
async for msg in upstream_ws:
if isinstance(msg, str):
await websocket.send_text(msg)
elif isinstance(msg, bytes):
await websocket.send_bytes(msg)
except Exception:
pass
try:
done, pending = await asyncio.wait(
[asyncio.create_task(client_to_upstream()), asyncio.create_task(upstream_to_client())],
return_when=asyncio.FIRST_COMPLETED,
)
for t in pending:
t.cancel()
finally:
try:
await upstream_ws.close()
except Exception:
pass
try:
await websocket.close()
except Exception:
pass