mirror of
https://github.com/open-webui/computer.git
synced 2026-11-24 22:37:40 -05:00
refac
This commit is contained in:
1 parent
b133e8fbe2
commit
5146bbe070
23 files changed
+942
-935
No files matched your search
+5
-11
@@ -11,6 +11,7 @@ from cptr.routers import (
|
||||
auth_router,
|
||||
automations_router,
|
||||
bridge_router,
|
||||
browser_router,
|
||||
webhook_router,
|
||||
chat_router,
|
||||
events_router,
|
||||
@@ -20,7 +21,6 @@ from cptr.routers import (
|
||||
images_router,
|
||||
memory_router,
|
||||
notifications_router,
|
||||
proxy_router,
|
||||
search_router,
|
||||
skills_router,
|
||||
state_router,
|
||||
@@ -84,11 +84,13 @@ async def shutdown():
|
||||
await cancel_all_async_subagents(reason="shutdown")
|
||||
except Exception:
|
||||
pass
|
||||
# Clean up browser sessions and launched Chrome
|
||||
# Clean up browser sessions and launched Chrome used by agent tools.
|
||||
try:
|
||||
from cptr.utils.browser.session import session_manager
|
||||
from cptr.utils.browser.launcher import shutdown_browser
|
||||
from cptr.utils.browser.proxy import manager as browser_proxy_manager
|
||||
|
||||
await browser_proxy_manager.close_all()
|
||||
await session_manager.close_all()
|
||||
await shutdown_browser()
|
||||
except Exception:
|
||||
@@ -153,14 +155,6 @@ if audit_level != AuditLevel.NONE:
|
||||
)
|
||||
|
||||
|
||||
# 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)
|
||||
|
||||
# CORS middleware: uses CPTR_CORS_ALLOWED_ORIGINS env var (default "*").
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from cptr.env import CORS_ALLOWED_ORIGINS
|
||||
@@ -260,6 +254,7 @@ app.include_router(audio_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(automations_router)
|
||||
app.include_router(bridge_router)
|
||||
app.include_router(browser_router)
|
||||
app.include_router(webhook_router)
|
||||
app.include_router(chat_router)
|
||||
app.include_router(events_router)
|
||||
@@ -269,7 +264,6 @@ app.include_router(git_router)
|
||||
app.include_router(images_router)
|
||||
app.include_router(memory_router)
|
||||
app.include_router(notifications_router)
|
||||
app.include_router(proxy_router)
|
||||
app.include_router(search_router)
|
||||
app.include_router(skills_router)
|
||||
app.include_router(state_router)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { fetchHandler, fetchJSON } from '$lib/apis';
|
||||
|
||||
export interface BrowserSession {
|
||||
session_id: string;
|
||||
url: string;
|
||||
title: string;
|
||||
}
|
||||
|
||||
export const createBrowserSession = () =>
|
||||
fetchJSON<BrowserSession>('/api/browser/sessions', { method: 'POST' });
|
||||
|
||||
export const listBrowserSessions = async () => {
|
||||
const data = await fetchJSON<{ session_ids: string[] }>('/api/browser/sessions');
|
||||
return data.session_ids;
|
||||
};
|
||||
|
||||
export const deleteBrowserSession = (sessionId: string) =>
|
||||
fetchHandler(`/api/browser/sessions/${sessionId}`, { method: 'DELETE' }).catch(() => {});
|
||||
|
||||
export const getBrowserSession = (sessionId: string) =>
|
||||
fetchJSON<BrowserSession>(`/api/browser/sessions/${sessionId}`);
|
||||
|
||||
export const updateBrowserSession = (sessionId: string, url: string, title: string) =>
|
||||
fetchJSON<BrowserSession>(`/api/browser/sessions/${sessionId}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ url, title })
|
||||
});
|
||||
|
||||
export const browserFrameUrl = (sessionId: string, rawUrl: string) => {
|
||||
const normalized = /^https?:\/\//i.test(rawUrl) ? rawUrl : `https://${rawUrl}`;
|
||||
const url = new URL(normalized);
|
||||
return `/api/browser/frame/${sessionId}?url=${encodeURIComponent(url.href)}`;
|
||||
};
|
||||
|
||||
export const browserBlankUrl = (sessionId: string) => `/api/browser/sessions/${sessionId}/blank`;
|
||||
@@ -0,0 +1,138 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from 'svelte';
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import { browserBlankUrl, browserFrameUrl, getBrowserSession, updateBrowserSession } from '$lib/apis/browser';
|
||||
import { openBrowserTab } from '$lib/stores';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
sessionId: string;
|
||||
groupId: string;
|
||||
initialUrl?: string;
|
||||
}
|
||||
|
||||
let { sessionId, groupId, initialUrl }: Props = $props();
|
||||
let iframeEl: HTMLIFrameElement | undefined = $state();
|
||||
let frameSrc = $state(browserBlankUrl(sessionId));
|
||||
let urlInput = $state(initialUrl ?? '');
|
||||
let title = $state('');
|
||||
let loading = $state(false);
|
||||
let error = $state('');
|
||||
|
||||
function publicUrl(value: string) {
|
||||
const proxyUrl = new URL(value, location.origin);
|
||||
if (proxyUrl.pathname === `/api/browser/frame/${sessionId}`) return proxyUrl.searchParams.get('url') || value;
|
||||
const legacyMarker = `/api/browser/frame/${sessionId}/`;
|
||||
const index = value.lastIndexOf(legacyMarker);
|
||||
if (index === -1) return value;
|
||||
const [scheme, host, ...path] = value.slice(index + legacyMarker.length).split('/');
|
||||
return scheme && host ? `${scheme}://${host}/${path.join('/')}` : value;
|
||||
}
|
||||
|
||||
function navigate(url = urlInput) {
|
||||
const value = url.trim();
|
||||
if (!value) return;
|
||||
try {
|
||||
urlInput = new URL(/^https?:\/\//i.test(publicUrl(value)) ? publicUrl(value) : `https://${publicUrl(value)}`).href;
|
||||
frameSrc = browserFrameUrl(sessionId, urlInput);
|
||||
loading = true;
|
||||
error = '';
|
||||
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
|
||||
} catch {
|
||||
error = $t('browser.invalidUrl');
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
loading = true;
|
||||
iframeEl?.contentWindow?.location.reload();
|
||||
}
|
||||
|
||||
function receiveMessage(event: MessageEvent) {
|
||||
if (event.origin !== location.origin || event.source !== iframeEl?.contentWindow) return;
|
||||
const data = event.data;
|
||||
if (data?.type === 'cptr-browser-state') {
|
||||
urlInput = publicUrl(data.url || urlInput);
|
||||
title = data.title || '';
|
||||
loading = false;
|
||||
void updateBrowserSession(sessionId, urlInput, title).catch(() => {});
|
||||
}
|
||||
if (data?.type === 'cptr-browser-popup' && data.url) openBrowserTab(groupId, data.url);
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
window.addEventListener('message', receiveMessage);
|
||||
void getBrowserSession(sessionId)
|
||||
.then((session) => {
|
||||
const url = publicUrl(session.url || initialUrl || '');
|
||||
title = session.title;
|
||||
if (url) navigate(url);
|
||||
})
|
||||
.catch(() => {});
|
||||
});
|
||||
onDestroy(() => window.removeEventListener('message', receiveMessage));
|
||||
</script>
|
||||
|
||||
<div class="preview-container">
|
||||
<div class="preview-toolbar">
|
||||
<button class="preview-btn" onclick={() => iframeEl?.contentWindow?.history.back()} use:tooltip={$t('settings.back')}>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
</button>
|
||||
<button class="preview-btn" onclick={() => iframeEl?.contentWindow?.history.forward()} use:tooltip={$t('common.forward')}>
|
||||
<Icon name="chevron-right" size={12} />
|
||||
</button>
|
||||
<button class="preview-btn" onclick={refresh} use:tooltip={$t('files.refresh')}>
|
||||
<Icon name="refresh" size={12} />
|
||||
</button>
|
||||
<div class="url-bar">
|
||||
<input
|
||||
class="url-input"
|
||||
bind:value={urlInput}
|
||||
onkeydown={(event) => event.key === 'Enter' && navigate()}
|
||||
placeholder="https://example.com"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
{#if title}<span class="browser-title" title={title}>{title}</span>{/if}
|
||||
</div>
|
||||
{#if loading}<div class="loading-track"><div class="loading-bar"></div></div>{/if}
|
||||
<div class="preview-content">
|
||||
{#if error}
|
||||
<div class="preview-error"><p class="error-title">{error}</p><button class="error-retry" onclick={() => navigate()}>{$t('files.retry')}</button></div>
|
||||
{:else}
|
||||
<iframe
|
||||
bind:this={iframeEl}
|
||||
src={frameSrc}
|
||||
title={title || $t('bar.newBrowser')}
|
||||
class="preview-iframe"
|
||||
onload={() => (loading = false)}
|
||||
onerror={() => {
|
||||
error = $t('port.cannotConnect');
|
||||
loading = false;
|
||||
}}
|
||||
></iframe>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
.preview-container { display: flex; flex-direction: column; height: 100%; overflow: hidden; }
|
||||
.preview-toolbar { display: flex; align-items: center; gap: 0.25rem; height: 2rem; padding: 0 0.375rem; border-bottom: 1px solid var(--color-gray-200); flex-shrink: 0; }
|
||||
.preview-btn { display: flex; align-items: center; justify-content: center; width: 1.375rem; height: 1.375rem; border-radius: 0.25rem; color: var(--color-gray-500); flex-shrink: 0; }
|
||||
.preview-btn:hover { background: var(--color-gray-100); color: var(--color-gray-700); }
|
||||
.url-bar { flex: 1; min-width: 0; }
|
||||
.url-input { width: 100%; border: 1px solid var(--color-gray-200); border-radius: 999px; padding: 0.1875rem 0.75rem; font-size: 0.6875rem; font-family: var(--font-mono); background: white; color: var(--color-gray-600); outline: none; }
|
||||
.browser-title { max-width: 10rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 0.6875rem; color: var(--color-gray-500); }
|
||||
.preview-content { flex: 1; min-height: 0; position: relative; }
|
||||
.preview-iframe { width: 100%; height: 100%; border: 0; display: block; background: white; }
|
||||
.loading-track { height: 2px; overflow: hidden; background: var(--color-gray-100); }
|
||||
.loading-bar { height: 100%; width: 35%; background: var(--color-brand-500); animation: browser-loading 1s ease-in-out infinite; }
|
||||
.preview-error { height: 100%; display: grid; place-content: center; gap: 0.5rem; text-align: center; }
|
||||
.error-retry { color: var(--color-brand-600); }
|
||||
@keyframes browser-loading { from { transform: translateX(-120%); } to { transform: translateX(320%); } }
|
||||
:global(.dark) .preview-toolbar { border-color: rgba(255,255,255,.06); }
|
||||
:global(.dark) .url-input { background: rgba(255,255,255,.04); border-color: rgba(255,255,255,.08); color: var(--color-gray-300); }
|
||||
:global(.dark) .preview-btn:hover { background: rgba(255,255,255,.06); color: var(--color-gray-300); }
|
||||
</style>
|
||||
@@ -9,6 +9,7 @@
|
||||
reorderTabs,
|
||||
openUntitledFileTab,
|
||||
openTerminalTab,
|
||||
openBrowserTab,
|
||||
openInSplit,
|
||||
closeGroup,
|
||||
moveTabToGroup,
|
||||
@@ -79,6 +80,8 @@
|
||||
return 'chat-bubble';
|
||||
case 'preview':
|
||||
return 'monitor';
|
||||
case 'browser':
|
||||
return 'browser';
|
||||
default:
|
||||
return 'page';
|
||||
}
|
||||
@@ -193,6 +196,11 @@
|
||||
openTerminalTab(group.id);
|
||||
}
|
||||
},
|
||||
{
|
||||
label: $t('bar.newBrowser'),
|
||||
icon: 'browser',
|
||||
onclick: () => openBrowserTab(group.id)
|
||||
},
|
||||
...($voiceMemosEnabled
|
||||
? [
|
||||
{
|
||||
|
||||
@@ -1,383 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { tooltip } from '$lib/tooltip';
|
||||
import Icon from './Icon.svelte';
|
||||
import { t } from '$lib/i18n';
|
||||
|
||||
interface Props {
|
||||
port: number;
|
||||
}
|
||||
|
||||
let { port }: Props = $props();
|
||||
|
||||
let path = $state('');
|
||||
let urlInput = $state(`localhost:${port}`);
|
||||
let iframeEl: HTMLIFrameElement | undefined = $state();
|
||||
let iframeKey = $state(0);
|
||||
let isLoading = $state(true);
|
||||
let loadError = $state(false);
|
||||
|
||||
// ── Navigation history ──────────────────────────────────────────
|
||||
let history = $state<string[]>(['']);
|
||||
let historyIndex = $state(0);
|
||||
|
||||
let canGoBack = $derived(historyIndex > 0);
|
||||
let canGoForward = $derived(historyIndex < history.length - 1);
|
||||
|
||||
let proxyPathPrefix = $derived(`/api/proxy/${port}/`);
|
||||
let proxyUrl = $derived(`/api/proxy/${port}/${path}`);
|
||||
|
||||
function makeDisplayUrl(p: string): string {
|
||||
return `localhost:${port}${p ? '/' + p : ''}`;
|
||||
}
|
||||
|
||||
function syncUrlBar() {
|
||||
urlInput = makeDisplayUrl(path);
|
||||
}
|
||||
|
||||
function pushHistory(newPath: string) {
|
||||
if (historyIndex < history.length - 1) {
|
||||
history = history.slice(0, historyIndex + 1);
|
||||
}
|
||||
history = [...history, newPath];
|
||||
historyIndex = history.length - 1;
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (!canGoBack) return;
|
||||
historyIndex -= 1;
|
||||
path = history[historyIndex];
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function goForward() {
|
||||
if (!canGoForward) return;
|
||||
historyIndex += 1;
|
||||
path = history[historyIndex];
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
isLoading = true;
|
||||
loadError = false;
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function navigateUrl() {
|
||||
const stripped = urlInput.trim();
|
||||
const localhostPrefix = `localhost:${port}`;
|
||||
let newPath = '';
|
||||
|
||||
if (stripped.startsWith(localhostPrefix)) {
|
||||
newPath = stripped.slice(localhostPrefix.length).replace(/^\//, '');
|
||||
} else if (stripped.startsWith('/') || !stripped.includes(':')) {
|
||||
newPath = stripped.replace(/^\//, '');
|
||||
}
|
||||
|
||||
if (newPath !== path) {
|
||||
path = newPath;
|
||||
pushHistory(path);
|
||||
}
|
||||
syncUrlBar();
|
||||
iframeKey += 1;
|
||||
}
|
||||
|
||||
function onIframeLoad() {
|
||||
isLoading = false;
|
||||
if (!iframeEl) return;
|
||||
try {
|
||||
const loc = iframeEl.contentWindow?.location;
|
||||
if (!loc) return;
|
||||
const iframePath = loc.pathname ?? '';
|
||||
const iframeSearch = loc.search ?? '';
|
||||
const iframeHash = loc.hash ?? '';
|
||||
|
||||
if (iframePath.startsWith(proxyPathPrefix)) {
|
||||
const relativePath = iframePath.slice(proxyPathPrefix.length) + iframeSearch + iframeHash;
|
||||
if (relativePath !== path) {
|
||||
path = relativePath;
|
||||
pushHistory(path);
|
||||
syncUrlBar();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Cross-origin, can't access
|
||||
}
|
||||
}
|
||||
|
||||
function openExternal() {
|
||||
window.open(`http://localhost:${port}/${path}`, '_blank');
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
navigateUrl();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="preview-container">
|
||||
<!-- Toolbar -->
|
||||
<div class="preview-toolbar">
|
||||
<!-- Back -->
|
||||
<button
|
||||
class="preview-btn {canGoBack ? '' : 'disabled'}"
|
||||
onclick={goBack}
|
||||
disabled={!canGoBack}
|
||||
use:tooltip={$t('settings.back')}
|
||||
>
|
||||
<Icon name="chevron-left" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- Forward -->
|
||||
<button
|
||||
class="preview-btn {canGoForward ? '' : 'disabled'}"
|
||||
onclick={goForward}
|
||||
disabled={!canGoForward}
|
||||
use:tooltip={$t('common.forward')}
|
||||
>
|
||||
<Icon name="chevron-right" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- Refresh -->
|
||||
<button class="preview-btn" onclick={refresh} use:tooltip={$t('files.refresh')}>
|
||||
<Icon name="refresh" size={12} />
|
||||
</button>
|
||||
|
||||
<!-- URL bar -->
|
||||
<div class="url-bar">
|
||||
<input
|
||||
type="text"
|
||||
class="url-input"
|
||||
bind:value={urlInput}
|
||||
onkeydown={onKeydown}
|
||||
placeholder="localhost:{port}"
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Open external -->
|
||||
<button class="preview-btn" onclick={openExternal} use:tooltip={$t('port.openInNewTab')}>
|
||||
<Icon name="external-link" size={12} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Loading bar -->
|
||||
{#if isLoading}
|
||||
<div class="loading-track">
|
||||
<div class="loading-bar"></div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Content -->
|
||||
<div class="preview-content">
|
||||
{#if loadError}
|
||||
<div class="preview-error">
|
||||
<p class="error-title">{$t('port.cannotConnect')}</p>
|
||||
<p class="error-sub">{$t('port.notResponding', { port })}</p>
|
||||
<button class="error-retry" onclick={refresh}>{$t('files.retry')}</button>
|
||||
</div>
|
||||
{:else}
|
||||
{#key iframeKey}
|
||||
<iframe
|
||||
bind:this={iframeEl}
|
||||
src={proxyUrl}
|
||||
title={$t('port.previewTitle', { port })}
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-downloads"
|
||||
class="preview-iframe"
|
||||
onload={onIframeLoad}
|
||||
onerror={() => {
|
||||
loadError = true;
|
||||
isLoading = false;
|
||||
}}
|
||||
></iframe>
|
||||
{/key}
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@reference "../../app.css";
|
||||
|
||||
.preview-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
height: 2rem;
|
||||
padding: 0 0.375rem;
|
||||
border-bottom: 1px solid var(--color-gray-200);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
:global(.dark) .preview-toolbar {
|
||||
border-bottom-color: rgba(255, 255, 255, 0.06);
|
||||
}
|
||||
|
||||
.preview-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.375rem;
|
||||
height: 1.375rem;
|
||||
border-radius: 0.25rem;
|
||||
color: var(--color-gray-500);
|
||||
transition: all 0.1s;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.preview-btn:hover:not(.disabled) {
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn {
|
||||
color: var(--color-gray-400);
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn:hover:not(.disabled) {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
.preview-btn.disabled {
|
||||
color: var(--color-gray-300);
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
:global(.dark) .preview-btn.disabled {
|
||||
color: var(--color-gray-700);
|
||||
}
|
||||
|
||||
.url-bar {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.url-input {
|
||||
width: 100%;
|
||||
border: 1px solid var(--color-gray-200);
|
||||
border-radius: 624.9375rem;
|
||||
padding: 0.1875rem 0.75rem;
|
||||
font-size: 0.6875rem;
|
||||
font-family: var(--font-mono);
|
||||
background: white;
|
||||
color: var(--color-gray-600);
|
||||
outline: none;
|
||||
transition: border-color 0.1s;
|
||||
}
|
||||
|
||||
.url-input:focus {
|
||||
border-color: oklch(0.65 0.15 250);
|
||||
box-shadow: 0 0 0 0.125rem oklch(0.65 0.15 250 / 0.15);
|
||||
}
|
||||
|
||||
:global(.dark) .url-input {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
border-color: rgba(255, 255, 255, 0.08);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
:global(.dark) .url-input:focus {
|
||||
border-color: oklch(0.65 0.15 250);
|
||||
box-shadow: 0 0 0 0.125rem oklch(0.65 0.15 250 / 0.1);
|
||||
}
|
||||
|
||||
.loading-track {
|
||||
height: 0.125rem;
|
||||
background: var(--color-gray-100);
|
||||
flex-shrink: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
:global(.dark) .loading-track {
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.loading-bar {
|
||||
height: 100%;
|
||||
background: oklch(0.65 0.15 250);
|
||||
border-radius: 624.9375rem;
|
||||
animation: loading-bar 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes loading-bar {
|
||||
0% {
|
||||
width: 0;
|
||||
margin-left: 0;
|
||||
}
|
||||
50% {
|
||||
width: 60%;
|
||||
margin-left: 20%;
|
||||
}
|
||||
100% {
|
||||
width: 0;
|
||||
margin-left: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.preview-content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.preview-iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: none;
|
||||
background: white;
|
||||
}
|
||||
|
||||
.preview-error {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.error-title {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-gray-500);
|
||||
}
|
||||
|
||||
.error-sub {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-gray-400);
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
|
||||
.error-retry {
|
||||
margin-top: 0.5rem;
|
||||
padding: 0.25rem 0.875rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
background: var(--color-gray-100);
|
||||
color: var(--color-gray-600);
|
||||
transition: all 0.1s;
|
||||
}
|
||||
|
||||
.error-retry:hover {
|
||||
background: var(--color-gray-200);
|
||||
}
|
||||
|
||||
:global(.dark) .error-retry {
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: var(--color-gray-300);
|
||||
}
|
||||
|
||||
:global(.dark) .error-retry:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
</style>
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Mehr anzeigen",
|
||||
"bar.newFile": "Neue Datei",
|
||||
"bar.newTerminal": "Neues Terminal",
|
||||
"bar.newBrowser": "Browser",
|
||||
"browser.invalidUrl": "Ungültige URL",
|
||||
"bar.closeTab": "Tab schließen",
|
||||
"bar.new": "Neu...",
|
||||
"bar.sidebar": "Seitenleiste",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Show more",
|
||||
"bar.newFile": "New File",
|
||||
"bar.newTerminal": "New Terminal",
|
||||
"bar.newBrowser": "Browser",
|
||||
"browser.invalidUrl": "Invalid URL",
|
||||
"bar.closeTab": "Close tab",
|
||||
"bar.new": "New...",
|
||||
"bar.sidebar": "Sidebar",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Mostrar más",
|
||||
"bar.newFile": "Nuevo archivo",
|
||||
"bar.newTerminal": "Nueva terminal",
|
||||
"bar.newBrowser": "Navegador",
|
||||
"browser.invalidUrl": "URL no válida",
|
||||
"bar.closeTab": "Cerrar pestaña",
|
||||
"bar.new": "Nuevo...",
|
||||
"bar.sidebar": "Barra lateral",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Afficher plus",
|
||||
"bar.newFile": "Nouveau fichier",
|
||||
"bar.newTerminal": "Nouveau terminal",
|
||||
"bar.newBrowser": "Navigateur",
|
||||
"browser.invalidUrl": "URL non valide",
|
||||
"bar.closeTab": "Fermer l'onglet",
|
||||
"bar.new": "Nouveau...",
|
||||
"bar.sidebar": "Barre latérale",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "もっと見る",
|
||||
"bar.newFile": "新規ファイル",
|
||||
"bar.newTerminal": "新規ターミナル",
|
||||
"bar.newBrowser": "ブラウザ",
|
||||
"browser.invalidUrl": "無効なURL",
|
||||
"bar.closeTab": "タブを閉じる",
|
||||
"bar.new": "新規...",
|
||||
"bar.sidebar": "サイドバー",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "더 보기",
|
||||
"bar.newFile": "새 파일",
|
||||
"bar.newTerminal": "새 터미널",
|
||||
"bar.newBrowser": "브라우저",
|
||||
"browser.invalidUrl": "잘못된 URL",
|
||||
"bar.closeTab": "탭 닫기",
|
||||
"bar.new": "새로 만들기...",
|
||||
"bar.sidebar": "사이드바",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Mostrar mais",
|
||||
"bar.newFile": "Novo arquivo",
|
||||
"bar.newTerminal": "Novo terminal",
|
||||
"bar.newBrowser": "Navegador",
|
||||
"browser.invalidUrl": "URL inválida",
|
||||
"bar.closeTab": "Fechar aba",
|
||||
"bar.new": "Novo...",
|
||||
"bar.sidebar": "Barra lateral",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "Показать ещё",
|
||||
"bar.newFile": "Новый файл",
|
||||
"bar.newTerminal": "Новый терминал",
|
||||
"bar.newBrowser": "Браузер",
|
||||
"browser.invalidUrl": "Недопустимый URL",
|
||||
"bar.closeTab": "Закрыть вкладку",
|
||||
"bar.new": "Создать...",
|
||||
"bar.sidebar": "Боковая панель",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "显示更多",
|
||||
"bar.newFile": "新建文件",
|
||||
"bar.newTerminal": "新建终端",
|
||||
"bar.newBrowser": "浏览器",
|
||||
"browser.invalidUrl": "无效网址",
|
||||
"bar.closeTab": "关闭标签",
|
||||
"bar.new": "新建...",
|
||||
"bar.sidebar": "侧边栏",
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
"sidebar.showMore": "顯示更多",
|
||||
"bar.newFile": "新增檔案",
|
||||
"bar.newTerminal": "新增終端機",
|
||||
"bar.newBrowser": "瀏覽器",
|
||||
"browser.invalidUrl": "無效網址",
|
||||
"bar.closeTab": "關閉分頁",
|
||||
"bar.new": "新增...",
|
||||
"bar.sidebar": "側邊欄",
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
saveWorkspaceState
|
||||
} from '$lib/apis/state';
|
||||
import { listSessions, createSession, deleteSession } from '$lib/apis/terminal';
|
||||
import { createBrowserSession, deleteBrowserSession, listBrowserSessions } from '$lib/apis/browser';
|
||||
import { changeLocale, i18next } from '$lib/i18n';
|
||||
import { streamingChatTabs } from '$lib/stores/chat';
|
||||
import { keybindings, loadKeybindings } from '$lib/stores/keybindings';
|
||||
@@ -44,13 +45,14 @@ export type { AppearancePreferences, Theme, ThemeConfig };
|
||||
|
||||
export interface Tab {
|
||||
id: string;
|
||||
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview';
|
||||
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
|
||||
label: string;
|
||||
filePath?: string;
|
||||
edit?: boolean;
|
||||
path?: string; // generic path (e.g. for chat)
|
||||
sessionId?: string;
|
||||
port?: number;
|
||||
port?: number; // legacy preview port, migrated on load
|
||||
browserSessionId?: string;
|
||||
unsaved?: boolean;
|
||||
permanent?: boolean;
|
||||
badge?: number;
|
||||
@@ -532,12 +534,42 @@ export async function loadWorkspace(path: string): Promise<void> {
|
||||
if (wsData && wsData.groups && (wsData.groups as EditorGroup[]).length > 0) {
|
||||
// Validate terminal sessions are still alive
|
||||
let aliveSessions: Set<string> = new Set();
|
||||
let aliveBrowserSessions: Set<string> = new Set();
|
||||
try {
|
||||
const sessions = await listSessions();
|
||||
aliveSessions = new Set(sessions.map((s) => s.session_id));
|
||||
} catch {}
|
||||
try {
|
||||
aliveBrowserSessions = new Set(await listBrowserSessions());
|
||||
} catch {}
|
||||
|
||||
const ws = wsData as unknown as WorkspaceState;
|
||||
ws.groups = await Promise.all(
|
||||
ws.groups.map(async (group) => ({
|
||||
...group,
|
||||
tabs: (
|
||||
await Promise.all(
|
||||
group.tabs.map(async (tab) => {
|
||||
if (tab.type !== 'preview' || !tab.port) return tab;
|
||||
try {
|
||||
const session = await createBrowserSession();
|
||||
aliveBrowserSessions.add(session.session_id);
|
||||
const { port, ...browserTab } = tab;
|
||||
return {
|
||||
...browserTab,
|
||||
type: 'browser' as const,
|
||||
label: `localhost:${port}`,
|
||||
browserSessionId: session.session_id,
|
||||
path: `http://127.0.0.1:${port}/`
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
)
|
||||
).filter((tab): tab is Tab => tab !== null)
|
||||
}))
|
||||
);
|
||||
|
||||
// Remove dead terminal tabs from all groups
|
||||
const cleanedGroups = ws.groups
|
||||
@@ -546,6 +578,12 @@ export async function loadWorkspace(path: string): Promise<void> {
|
||||
if (t.type === 'terminal' && t.sessionId && !aliveSessions.has(t.sessionId)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
t.type === 'browser' &&
|
||||
(!t.browserSessionId || !aliveBrowserSessions.has(t.browserSessionId))
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
const activeStillExists = filteredTabs.some((t: Tab) => t.id === g.activeTabId);
|
||||
@@ -861,7 +899,7 @@ export async function openTerminalTab(targetGroupId?: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export function openPreviewTab(port: number, targetGroupId?: string): void {
|
||||
export async function openPreviewTab(port: number, targetGroupId?: string): Promise<void> {
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws) return;
|
||||
|
||||
@@ -870,23 +908,34 @@ export function openPreviewTab(port: number, targetGroupId?: string): void {
|
||||
if (!group) return;
|
||||
|
||||
// Reuse existing tab within this group
|
||||
const existing = group.tabs.find((t) => t.type === 'preview' && t.port === port);
|
||||
const url = `http://127.0.0.1:${port}/`;
|
||||
const existing = group.tabs.find((t) => t.type === 'browser' && t.path === url);
|
||||
if (existing) {
|
||||
setActiveTab(existing.id, gid);
|
||||
return;
|
||||
}
|
||||
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'preview',
|
||||
label: `localhost:${port}`,
|
||||
port
|
||||
};
|
||||
await openBrowserTab(gid, url, `localhost:${port}`);
|
||||
}
|
||||
|
||||
updateGroupTabs(gid, (tabs) => ({
|
||||
tabs: [...tabs, newTab],
|
||||
activeTabId: newTab.id
|
||||
}));
|
||||
export async function openBrowserTab(targetGroupId?: string, url?: string, label = 'Browser'): Promise<void> {
|
||||
const ws = get(currentWorkspace);
|
||||
if (!ws) return;
|
||||
const gid = targetGroupId ?? ws.activeGroupId;
|
||||
if (!ws.groups.some((group) => group.id === gid)) return;
|
||||
try {
|
||||
const session = await createBrowserSession();
|
||||
const newTab: Tab = {
|
||||
id: nextId(),
|
||||
type: 'browser',
|
||||
label,
|
||||
browserSessionId: session.session_id,
|
||||
path: url
|
||||
};
|
||||
updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id }));
|
||||
} catch (error) {
|
||||
console.error('Failed to create browser session:', error);
|
||||
}
|
||||
}
|
||||
|
||||
export function openChatTab(chatId?: string, targetGroupId?: string): void {
|
||||
@@ -944,6 +993,9 @@ export function closeTab(tabId: string, groupId?: string): void {
|
||||
if (tab.type === 'terminal' && tab.sessionId) {
|
||||
deleteSession(tab.sessionId);
|
||||
}
|
||||
if (tab.type === 'browser' && tab.browserSessionId) {
|
||||
deleteBrowserSession(tab.browserSessionId);
|
||||
}
|
||||
|
||||
// Clean up streaming indicator for closed chat tabs
|
||||
if (tab.type === 'chat') {
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
import FileEditor from '$lib/components/FileEditor.svelte';
|
||||
import GitView from '$lib/components/GitView.svelte';
|
||||
import Terminal from '$lib/components/Terminal.svelte';
|
||||
import PortPreview from '$lib/components/PortPreview.svelte';
|
||||
import BrowserPreview from '$lib/components/BrowserPreview.svelte';
|
||||
import ChatPanel from '$lib/components/chat/ChatPanel.svelte';
|
||||
import DirectoryPicker from '$lib/components/DirectoryPicker.svelte';
|
||||
import GroupTabBar from '$lib/components/GroupTabBar.svelte';
|
||||
@@ -465,11 +465,11 @@
|
||||
): WorkspaceResume {
|
||||
const tabs = (state.groups ?? []).flatMap((group) => group.tabs ?? []);
|
||||
const previewPorts = tabs
|
||||
.filter((tab) => tab.type === 'preview' && tab.port)
|
||||
.map((tab) => tab.port!)
|
||||
.filter((tab) => tab.type === 'browser' && /^localhost:\d+$/.test(tab.label))
|
||||
.map((tab) => Number(tab.label.slice('localhost:'.length)))
|
||||
.filter((port, index, all) => all.indexOf(port) === index);
|
||||
const activeLabels = tabs
|
||||
.filter((tab) => !tab.permanent && ['terminal', 'chat', 'preview', 'file'].includes(tab.type))
|
||||
.filter((tab) => !tab.permanent && ['terminal', 'chat', 'browser', 'file'].includes(tab.type))
|
||||
.slice(0, 3)
|
||||
.map((tab) => tab.label);
|
||||
|
||||
@@ -976,9 +976,9 @@
|
||||
<Terminal sessionId={tab.sessionId!} />
|
||||
</div>
|
||||
{/each}
|
||||
{#each group.tabs.filter((tab) => tab.type === 'preview' && tab.port) as tab (tab.id)}
|
||||
{#each group.tabs.filter((tab) => tab.type === 'browser' && tab.browserSessionId) as tab (tab.id)}
|
||||
<div class="persisted-tab" class:persisted-tab-hidden={tab.id !== group.activeTabId}>
|
||||
<PortPreview port={tab.port!} />
|
||||
<BrowserPreview sessionId={tab.browserSessionId!} groupId={group.id} initialUrl={tab.path} />
|
||||
</div>
|
||||
{/each}
|
||||
{#if !groupTab || groupTab.type === 'files'}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
(() => {
|
||||
const config = window.__cptrBrowser;
|
||||
if (!config) return;
|
||||
|
||||
const prefix = `/api/browser/frame/${config.session}`;
|
||||
const api = `/api/browser/sessions/${config.session}`;
|
||||
const nativeFetch = window.fetch.bind(window);
|
||||
const nativeWebSocket = window.WebSocket;
|
||||
|
||||
function remoteUrl(value = location.href) {
|
||||
const url = new URL(value, location.href);
|
||||
return url.pathname === prefix ? url.searchParams.get('url') || config.url : config.url;
|
||||
}
|
||||
|
||||
function proxyUrl(value, base = remoteUrl()) {
|
||||
try {
|
||||
const current = new URL(value, location.href);
|
||||
if (current.pathname === prefix && current.searchParams.has('url')) return `${current.pathname}${current.search}`;
|
||||
const url = new URL(value, base);
|
||||
if (!/^https?:$/.test(url.protocol)) return value;
|
||||
return `${prefix}?url=${encodeURIComponent(url.href)}`;
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function report() {
|
||||
parent.postMessage({ type: 'cptr-browser-state', url: remoteUrl(), title: document.title }, location.origin);
|
||||
}
|
||||
|
||||
const originalPushState = history.pushState.bind(history);
|
||||
const originalReplaceState = history.replaceState.bind(history);
|
||||
history.pushState = (state, title, url) => {
|
||||
const result = originalPushState(state, title, url ? proxyUrl(url) : url);
|
||||
queueMicrotask(report);
|
||||
return result;
|
||||
};
|
||||
history.replaceState = (state, title, url) => {
|
||||
const result = originalReplaceState(state, title, url ? proxyUrl(url) : url);
|
||||
queueMicrotask(report);
|
||||
return result;
|
||||
};
|
||||
addEventListener('popstate', report);
|
||||
new MutationObserver(report).observe(document.querySelector('title') || document.head, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
characterData: true
|
||||
});
|
||||
|
||||
window.fetch = (input, init) => {
|
||||
if (input instanceof Request) return nativeFetch(new Request(proxyUrl(input.url), input), init);
|
||||
return nativeFetch(proxyUrl(input), init);
|
||||
};
|
||||
|
||||
const open = XMLHttpRequest.prototype.open;
|
||||
XMLHttpRequest.prototype.open = function (method, url, ...rest) {
|
||||
return open.call(this, method, proxyUrl(url), ...rest);
|
||||
};
|
||||
|
||||
window.WebSocket = function ProxyWebSocket(url, protocols) {
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
const native = new nativeWebSocket(`${scheme}://${location.host}${api}/ws`);
|
||||
const proxy = new EventTarget();
|
||||
let state = 0;
|
||||
let protocol = '';
|
||||
Object.defineProperties(proxy, {
|
||||
url: { value: String(url) },
|
||||
readyState: { get: () => state },
|
||||
protocol: { get: () => protocol },
|
||||
binaryType: { get: () => native.binaryType, set: (value) => { native.binaryType = value; } },
|
||||
onopen: { get: () => proxy._onopen, set: (value) => { proxy._onopen = value; } },
|
||||
onmessage: { get: () => proxy._onmessage, set: (value) => { proxy._onmessage = value; } },
|
||||
onclose: { get: () => proxy._onclose, set: (value) => { proxy._onclose = value; } },
|
||||
onerror: { get: () => proxy._onerror, set: (value) => { proxy._onerror = value; } }
|
||||
});
|
||||
const emit = (type, event) => {
|
||||
proxy.dispatchEvent(event);
|
||||
proxy[`_on${type}`]?.call(proxy, event);
|
||||
};
|
||||
native.addEventListener('open', () => native.send(JSON.stringify({ url: new URL(url, remoteUrl()).href, protocols })));
|
||||
native.addEventListener('message', (event) => {
|
||||
if (typeof event.data === 'string') {
|
||||
try {
|
||||
const control = JSON.parse(event.data);
|
||||
if (control.type === 'open') {
|
||||
state = 1; protocol = control.protocol || ''; emit('open', new Event('open')); return;
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
emit('message', new MessageEvent('message', { data: event.data }));
|
||||
});
|
||||
native.addEventListener('close', (event) => { state = 3; emit('close', event); });
|
||||
native.addEventListener('error', (event) => emit('error', event));
|
||||
proxy.send = (data) => {
|
||||
if (state !== 1) throw new DOMException('WebSocket is not open', 'InvalidStateError');
|
||||
native.send(data);
|
||||
};
|
||||
proxy.close = (code, reason) => { state = 2; native.close(code, reason); };
|
||||
return proxy;
|
||||
};
|
||||
window.WebSocket.prototype = nativeWebSocket.prototype;
|
||||
|
||||
const NativeEventSource = window.EventSource;
|
||||
if (NativeEventSource) {
|
||||
window.EventSource = function ProxyEventSource(url, options) {
|
||||
return new NativeEventSource(proxyUrl(url), options);
|
||||
};
|
||||
window.EventSource.prototype = NativeEventSource.prototype;
|
||||
}
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
const link = event.target.closest?.('a[href]');
|
||||
if (!link || event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
||||
const url = new URL(link.href, remoteUrl());
|
||||
if (!/^https?:$/.test(url.protocol)) return;
|
||||
event.preventDefault();
|
||||
if (link.target && link.target !== '_self') {
|
||||
parent.postMessage({ type: 'cptr-browser-popup', url: url.href }, location.origin);
|
||||
} else {
|
||||
location.assign(proxyUrl(url.href));
|
||||
}
|
||||
}, true);
|
||||
|
||||
const nativeOpen = window.open.bind(window);
|
||||
window.open = (url, target, features) => {
|
||||
if (url) parent.postMessage({ type: 'cptr-browser-popup', url: new URL(url, remoteUrl()).href }, location.origin);
|
||||
return target === '_blank' ? null : nativeOpen(proxyUrl(url || remoteUrl()), target, features);
|
||||
};
|
||||
|
||||
report();
|
||||
})();
|
||||
@@ -6,6 +6,7 @@ from cptr.routers.auth import router as auth_router
|
||||
from cptr.routers.automations import router as automations_router
|
||||
from cptr.routers.bridge import router as bridge_router
|
||||
from cptr.routers.bridge import webhook_router
|
||||
from cptr.routers.browser import router as browser_router
|
||||
from cptr.routers.chat import router as chat_router
|
||||
from cptr.routers.gateway import router as gateway_router
|
||||
from cptr.routers.events import router as events_router
|
||||
@@ -14,7 +15,6 @@ from cptr.routers.git import router as git_router
|
||||
from cptr.routers.images import router as images_router
|
||||
from cptr.routers.memory import router as memory_router
|
||||
from cptr.routers.notifications import router as notifications_router
|
||||
from cptr.routers.proxy import router as proxy_router
|
||||
from cptr.routers.search import router as search_router
|
||||
from cptr.routers.skills import router as skills_router
|
||||
from cptr.routers.state import router as state_router
|
||||
@@ -27,6 +27,7 @@ __all__ = [
|
||||
"auth_router",
|
||||
"automations_router",
|
||||
"bridge_router",
|
||||
"browser_router",
|
||||
"webhook_router",
|
||||
"chat_router",
|
||||
"events_router",
|
||||
@@ -36,7 +37,6 @@ __all__ = [
|
||||
"images_router",
|
||||
"memory_router",
|
||||
"notifications_router",
|
||||
"proxy_router",
|
||||
"search_router",
|
||||
"skills_router",
|
||||
"state_router",
|
||||
|
||||
@@ -0,0 +1,291 @@
|
||||
"""Same-origin HTTP/WebSocket proxy backing Browser editor tabs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from collections.abc import AsyncIterator
|
||||
from urllib.parse import urljoin, urlsplit, urlunsplit
|
||||
|
||||
import httpx
|
||||
import websockets
|
||||
from fastapi import APIRouter, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import HTMLResponse, StreamingResponse
|
||||
|
||||
from cptr.routers.auth import COOKIE_NAME
|
||||
from cptr.utils.browser.proxy import manager, rewrite_css, rewrite_html, target_url
|
||||
from cptr.utils.config import AuthResult, check_access
|
||||
|
||||
router = APIRouter(prefix="/api/browser", tags=["browser"])
|
||||
|
||||
_HOP_BY_HOP = {
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailers",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
}
|
||||
_SKIP_REQUEST_HEADERS = _HOP_BY_HOP | {
|
||||
"accept-encoding",
|
||||
"host",
|
||||
"cookie",
|
||||
"authorization",
|
||||
"content-length",
|
||||
}
|
||||
_SKIP_RESPONSE_HEADERS = _HOP_BY_HOP | {
|
||||
"content-encoding",
|
||||
"content-length",
|
||||
"content-security-policy",
|
||||
"set-cookie",
|
||||
"x-frame-options",
|
||||
}
|
||||
|
||||
|
||||
def _owner(auth: AuthResult) -> str:
|
||||
return auth.user_id or auth.username or "default"
|
||||
|
||||
|
||||
def _auth(request: Request) -> AuthResult:
|
||||
auth = getattr(request.state, "auth", None)
|
||||
if auth is None:
|
||||
raise HTTPException(status_code=401, detail="not authenticated")
|
||||
return auth
|
||||
|
||||
|
||||
def _headers(request: Request, upstream_url: str) -> dict[str, str]:
|
||||
headers = {
|
||||
key: value
|
||||
for key, value in request.headers.items()
|
||||
if key.lower() not in _SKIP_REQUEST_HEADERS and not key.lower().startswith("x-cptr-")
|
||||
}
|
||||
parsed = urlsplit(upstream_url)
|
||||
headers["host"] = parsed.netloc
|
||||
# The proxy rewrites HTML and CSS after httpx has decoded it. Do not negotiate
|
||||
# encodings a downstream browser supports but this process may not decode.
|
||||
headers["accept-encoding"] = "gzip, deflate"
|
||||
referer = request.headers.get("referer")
|
||||
if referer and "/api/browser/frame/" in referer:
|
||||
headers["referer"] = upstream_url
|
||||
if request.headers.get("origin"):
|
||||
headers["origin"] = f"{parsed.scheme}://{parsed.netloc}"
|
||||
return headers
|
||||
|
||||
|
||||
def _response_headers(upstream: httpx.Response) -> dict[str, str]:
|
||||
headers = {
|
||||
key: value for key, value in upstream.headers.items() if key.lower() not in _SKIP_RESPONSE_HEADERS
|
||||
}
|
||||
headers["x-cptr-browser-url"] = str(upstream.url)
|
||||
return headers
|
||||
|
||||
|
||||
def _session_payload(session) -> dict[str, str]:
|
||||
return {"session_id": session.session_id, "url": session.url, "title": session.title}
|
||||
|
||||
|
||||
async def _stream_response(upstream: httpx.Response) -> AsyncIterator[bytes]:
|
||||
try:
|
||||
async for chunk in upstream.aiter_bytes():
|
||||
yield chunk
|
||||
finally:
|
||||
await upstream.aclose()
|
||||
|
||||
|
||||
async def proxy_browser_request(request: Request, session_id: str, url: str, owner: str) -> Response:
|
||||
client = manager.client(session_id, owner)
|
||||
if client is None:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
try:
|
||||
upstream_url = target_url(url)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
|
||||
body = await request.body() if request.method not in {"GET", "HEAD"} else None
|
||||
upstream = None
|
||||
candidates = [upstream_url]
|
||||
parsed = urlsplit(upstream_url)
|
||||
if parsed.hostname == "127.0.0.1":
|
||||
port = f":{parsed.port}" if parsed.port else ""
|
||||
candidates.append(urlunsplit((parsed.scheme, f"[::1]{port}", parsed.path, parsed.query, "")))
|
||||
for candidate in candidates:
|
||||
try:
|
||||
upstream = await client.send(
|
||||
client.build_request(request.method, candidate, headers=_headers(request, candidate), content=body),
|
||||
stream=True,
|
||||
)
|
||||
break
|
||||
except httpx.ConnectError:
|
||||
continue
|
||||
if upstream is None:
|
||||
raise HTTPException(status_code=502, detail=f"Cannot connect to {parsed.netloc}")
|
||||
content_type = upstream.headers.get("content-type", "")
|
||||
headers = _response_headers(upstream)
|
||||
|
||||
if content_type.startswith("text/event-stream"):
|
||||
return StreamingResponse(
|
||||
_stream_response(upstream),
|
||||
status_code=upstream.status_code,
|
||||
headers=headers,
|
||||
media_type=content_type,
|
||||
)
|
||||
|
||||
content = await upstream.aread()
|
||||
await upstream.aclose()
|
||||
if "text/html" in content_type or "application/xhtml" in content_type:
|
||||
final_url = upstream_url if parsed.hostname == "127.0.0.1" else str(upstream.url)
|
||||
if f"/api/browser/frame/{session_id}/" not in urlsplit(final_url).path:
|
||||
await manager.update(session_id, owner, url=final_url)
|
||||
text = content.decode(upstream.encoding or "utf-8", errors="replace")
|
||||
content = rewrite_html(text, upstream_url, session_id, final_url).encode("utf-8")
|
||||
headers.pop("content-type", None)
|
||||
content_type = "text/html; charset=utf-8"
|
||||
elif "text/css" in content_type:
|
||||
text = content.decode(upstream.encoding or "utf-8", errors="replace")
|
||||
content = rewrite_css(text, upstream_url, session_id).encode("utf-8")
|
||||
headers.pop("content-type", None)
|
||||
content_type = "text/css; charset=utf-8"
|
||||
return Response(content=content, status_code=upstream.status_code, headers=headers, media_type=content_type)
|
||||
|
||||
|
||||
async def _proxy(request: Request, session_id: str, url: str) -> Response:
|
||||
return await proxy_browser_request(request, session_id, url, _owner(_auth(request)))
|
||||
|
||||
|
||||
@router.post("/sessions")
|
||||
async def create_session(request: Request):
|
||||
session = await manager.create(_owner(_auth(request)))
|
||||
return _session_payload(session)
|
||||
|
||||
|
||||
@router.get("/sessions")
|
||||
async def list_sessions(request: Request):
|
||||
return {"session_ids": manager.ids(_owner(_auth(request)))}
|
||||
|
||||
|
||||
@router.delete("/sessions/{session_id}")
|
||||
async def close_session(session_id: str, request: Request):
|
||||
if not await manager.close(session_id, _owner(_auth(request))):
|
||||
raise HTTPException(status_code=404, detail="Browser tab not found")
|
||||
return {"status": "closed"}
|
||||
|
||||
|
||||
@router.get("/sessions/{session_id}")
|
||||
async def get_session(session_id: str, request: Request):
|
||||
session = manager.session(session_id, _owner(_auth(request)))
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
return _session_payload(session)
|
||||
|
||||
|
||||
@router.patch("/sessions/{session_id}")
|
||||
async def update_session(session_id: str, request: Request):
|
||||
payload = await request.json()
|
||||
url = str(payload.get("url", ""))
|
||||
title = str(payload.get("title", ""))[:512]
|
||||
if url:
|
||||
parsed = urlsplit(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise HTTPException(status_code=400, detail="Invalid Browser URL")
|
||||
session = await manager.update(session_id, _owner(_auth(request)), url=url, title=title)
|
||||
if session is None:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
return _session_payload(session)
|
||||
|
||||
|
||||
@router.get("/sessions/{session_id}/blank")
|
||||
async def blank(session_id: str, request: Request):
|
||||
if manager.session(session_id, _owner(_auth(request))) is None:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
return HTMLResponse("<!doctype html><title>Browser</title>")
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/resources/{session_id}/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
)
|
||||
async def proxy_resource(session_id: str, path: str, request: Request):
|
||||
owner = _owner(_auth(request))
|
||||
session = manager.session(session_id, owner)
|
||||
if session is None or not session.origin:
|
||||
raise HTTPException(status_code=404, detail="Browser tab expired")
|
||||
url = urljoin(session.origin + "/", path.lstrip("/"))
|
||||
if request.url.query:
|
||||
url += f"?{request.url.query}"
|
||||
return await proxy_browser_request(request, session_id, url, owner)
|
||||
|
||||
|
||||
@router.api_route("/frame/{session_id}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
|
||||
async def proxy_frame(session_id: str, url: str, request: Request):
|
||||
return await _proxy(request, session_id, url)
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/frame/{session_id}/{scheme}/{host}/{path:path}",
|
||||
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
|
||||
)
|
||||
async def legacy_proxy_frame(session_id: str, scheme: str, host: str, path: str, request: Request):
|
||||
return await _proxy(request, session_id, urlunsplit((scheme, host, "/" + path.lstrip("/"), request.url.query, "")))
|
||||
|
||||
|
||||
@router.api_route(
|
||||
"/frame/{session_id}/{scheme}/{host}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
||||
)
|
||||
async def legacy_proxy_frame_root(session_id: str, scheme: str, host: str, request: Request):
|
||||
return await _proxy(request, session_id, urlunsplit((scheme, host, "/", request.url.query, "")))
|
||||
|
||||
|
||||
@router.websocket("/sessions/{session_id}/ws")
|
||||
async def proxy_websocket(websocket: WebSocket, session_id: str):
|
||||
client_host = websocket.client.host if websocket.client else "127.0.0.1"
|
||||
auth = check_access(client_host, websocket.cookies.get(COOKIE_NAME))
|
||||
owner = _owner(auth) if auth else ""
|
||||
if not auth or manager.session(session_id, owner) is None:
|
||||
await websocket.close(code=4001, reason="unauthorized")
|
||||
return
|
||||
await websocket.accept()
|
||||
try:
|
||||
open_message = await asyncio.wait_for(websocket.receive_json(), timeout=10)
|
||||
target = str(open_message.get("url", ""))
|
||||
parsed = urlsplit(target)
|
||||
if parsed.scheme not in {"ws", "wss"}:
|
||||
await websocket.close(code=4000, reason="invalid websocket URL")
|
||||
return
|
||||
client = manager.client(session_id, owner)
|
||||
assert client is not None
|
||||
prepared = client.build_request("GET", target.replace("ws:", "http:", 1).replace("wss:", "https:", 1))
|
||||
headers = {"cookie": prepared.headers["cookie"]} if "cookie" in prepared.headers else None
|
||||
upstream = await websockets.connect(target, additional_headers=headers)
|
||||
await websocket.send_json({"type": "open", "protocol": upstream.subprotocol or ""})
|
||||
|
||||
async def to_upstream() -> None:
|
||||
while True:
|
||||
message = await websocket.receive()
|
||||
if message.get("text") is not None:
|
||||
await upstream.send(message["text"])
|
||||
elif message.get("bytes") is not None:
|
||||
await upstream.send(message["bytes"])
|
||||
else:
|
||||
break
|
||||
|
||||
async def to_client() -> None:
|
||||
async for message in upstream:
|
||||
if isinstance(message, bytes):
|
||||
await websocket.send_bytes(message)
|
||||
else:
|
||||
await websocket.send_text(message)
|
||||
|
||||
done, pending = await asyncio.wait(
|
||||
(asyncio.create_task(to_upstream()), asyncio.create_task(to_client())),
|
||||
return_when=asyncio.FIRST_COMPLETED,
|
||||
)
|
||||
for task in pending:
|
||||
task.cancel()
|
||||
for task in done:
|
||||
task.result()
|
||||
await upstream.close()
|
||||
except (WebSocketDisconnect, asyncio.TimeoutError, json.JSONDecodeError):
|
||||
pass
|
||||
except Exception:
|
||||
await websocket.close(code=1011, reason="Browser WebSocket failed")
|
||||
@@ -1,286 +0,0 @@
|
||||
"""Reverse proxy to localhost services.
|
||||
|
||||
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, WebSocket, WebSocketDisconnect
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/proxy", tags=["proxy"])
|
||||
|
||||
# ── Shared async HTTP client ────────────────────────────────────
|
||||
|
||||
_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
def _get_client() -> httpx.AsyncClient:
|
||||
global _client
|
||||
if _client is None or _client.is_closed:
|
||||
_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(30.0, connect=5.0),
|
||||
follow_redirects=False,
|
||||
limits=httpx.Limits(max_connections=50),
|
||||
)
|
||||
return _client
|
||||
|
||||
|
||||
# ── 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",
|
||||
}
|
||||
|
||||
_SKIP_REQUEST_HEADERS = {
|
||||
"host",
|
||||
"connection",
|
||||
"accept-encoding",
|
||||
}
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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:
|
||||
headers[key] = value
|
||||
|
||||
# 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:
|
||||
parts = [p.strip() for p in csp.split(";") if "frame-ancestors" not in p]
|
||||
if parts:
|
||||
headers["content-security-policy"] = "; ".join(parts)
|
||||
else:
|
||||
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,
|
||||
status_code=upstream.status_code,
|
||||
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
|
||||
@@ -0,0 +1,239 @@
|
||||
"""In-memory sessions and response rewriting for the Browser proxy tab."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from html.parser import HTMLParser
|
||||
from urllib.parse import urlencode, urljoin, urlsplit, urlunsplit
|
||||
|
||||
import httpx
|
||||
|
||||
|
||||
_URL_ATTRIBUTES = {
|
||||
"action",
|
||||
"background",
|
||||
"cite",
|
||||
"data",
|
||||
"formaction",
|
||||
"href",
|
||||
"poster",
|
||||
"src",
|
||||
}
|
||||
_SKIP_SCHEMES = ("data:", "javascript:", "mailto:", "tel:", "about:", "blob:")
|
||||
|
||||
|
||||
@dataclass
|
||||
class BrowserSession:
|
||||
session_id: str
|
||||
owner: str
|
||||
url: str = ""
|
||||
title: str = ""
|
||||
origin: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class BrowserProfile:
|
||||
client: httpx.AsyncClient
|
||||
|
||||
|
||||
class BrowserProxyManager:
|
||||
"""Owns ephemeral Browser tab sessions and per-user upstream cookie jars."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._sessions: dict[str, BrowserSession] = {}
|
||||
self._profiles: dict[str, BrowserProfile] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
async def create(self, owner: str) -> BrowserSession:
|
||||
session = BrowserSession(uuid.uuid4().hex, owner)
|
||||
async with self._lock:
|
||||
self._sessions[session.session_id] = session
|
||||
self._profile(owner)
|
||||
return session
|
||||
|
||||
async def close(self, session_id: str, owner: str) -> bool:
|
||||
async with self._lock:
|
||||
session = self._sessions.get(session_id)
|
||||
if not session or session.owner != owner:
|
||||
return False
|
||||
self._sessions.pop(session_id, None)
|
||||
return True
|
||||
|
||||
def ids(self, owner: str) -> list[str]:
|
||||
return [session_id for session_id, session in self._sessions.items() if session.owner == owner]
|
||||
|
||||
def session(self, session_id: str, owner: str) -> BrowserSession | None:
|
||||
session = self._sessions.get(session_id)
|
||||
return session if session and session.owner == owner else None
|
||||
|
||||
async def update(
|
||||
self, session_id: str, owner: str, *, url: str | None = None, title: str | None = None
|
||||
) -> BrowserSession | None:
|
||||
async with self._lock:
|
||||
session = self.session(session_id, owner)
|
||||
if session is None:
|
||||
return None
|
||||
if url is not None:
|
||||
session.url = url
|
||||
parsed = urlsplit(url)
|
||||
session.origin = f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else ""
|
||||
if title is not None:
|
||||
session.title = title
|
||||
return session
|
||||
|
||||
def client(self, session_id: str, owner: str) -> httpx.AsyncClient | None:
|
||||
session = self.session(session_id, owner)
|
||||
return self._profile(session.owner).client if session else None
|
||||
|
||||
def _profile(self, owner: str) -> BrowserProfile:
|
||||
profile = self._profiles.get(owner)
|
||||
if profile is None:
|
||||
profile = BrowserProfile(
|
||||
httpx.AsyncClient(
|
||||
follow_redirects=True,
|
||||
timeout=httpx.Timeout(60.0, connect=10.0),
|
||||
limits=httpx.Limits(max_connections=30),
|
||||
)
|
||||
)
|
||||
self._profiles[owner] = profile
|
||||
return profile
|
||||
|
||||
async def close_all(self) -> None:
|
||||
clients = [profile.client for profile in self._profiles.values()]
|
||||
self._sessions.clear()
|
||||
self._profiles.clear()
|
||||
await asyncio.gather(*(client.aclose() for client in clients), return_exceptions=True)
|
||||
|
||||
|
||||
def proxy_path(session_id: str, url: str) -> str:
|
||||
"""Return the same-origin URL used by the Browser iframe for an upstream URL."""
|
||||
parsed = urlsplit(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("Only HTTP(S) URLs can be opened in Browser")
|
||||
return f"/api/browser/frame/{session_id}?{urlencode({'url': url})}"
|
||||
|
||||
|
||||
def target_url(url: str) -> str:
|
||||
parsed = urlsplit(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise ValueError("Only HTTP(S) URLs can be opened in Browser")
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, parsed.path or "/", parsed.query, ""))
|
||||
|
||||
|
||||
def resource_path(session_id: str, url: str) -> str:
|
||||
parsed = urlsplit(url)
|
||||
path = parsed.path or "/"
|
||||
return f"/api/browser/resources/{session_id}{path}" + (f"?{parsed.query}" if parsed.query else "")
|
||||
|
||||
|
||||
def rewrite_url(value: str, base_url: str, session_id: str) -> str:
|
||||
value = value.strip()
|
||||
if not value or value.startswith("#") or value.lower().startswith(_SKIP_SCHEMES):
|
||||
return value
|
||||
try:
|
||||
url = urljoin(base_url, value)
|
||||
return proxy_path(session_id, url)
|
||||
except ValueError:
|
||||
return value
|
||||
|
||||
|
||||
def _rewrite_srcset(value: str, base_url: str, session_id: str) -> str:
|
||||
parts = []
|
||||
for item in value.split(","):
|
||||
url, *descriptor = item.strip().split(maxsplit=1)
|
||||
parts.append(" ".join([rewrite_url(url, base_url, session_id), *descriptor]))
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
class _HtmlRewriter(HTMLParser):
|
||||
def __init__(self, base_url: str, session_id: str) -> None:
|
||||
super().__init__(convert_charrefs=False)
|
||||
self.base_url = base_url
|
||||
self.session_id = session_id
|
||||
self.output: list[str] = []
|
||||
|
||||
def handle_decl(self, decl: str) -> None:
|
||||
self.output.append(f"<!{decl}>")
|
||||
|
||||
def handle_comment(self, data: str) -> None:
|
||||
self.output.append(f"<!--{data}-->")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
self.output.append(data)
|
||||
|
||||
def handle_entityref(self, name: str) -> None:
|
||||
self.output.append(f"&{name};")
|
||||
|
||||
def handle_charref(self, name: str) -> None:
|
||||
self.output.append(f"&#{name};")
|
||||
|
||||
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
self._tag(tag, attrs, close=True)
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
self._tag(tag, attrs, close=False)
|
||||
|
||||
def _tag(self, tag: str, attrs: list[tuple[str, str | None]], close: bool) -> None:
|
||||
rewritten: list[tuple[str, str | None]] = []
|
||||
for key, value in attrs:
|
||||
lower = key.lower()
|
||||
if lower == "integrity":
|
||||
continue
|
||||
if value and lower in _URL_ATTRIBUTES:
|
||||
value = rewrite_url(value, self.base_url, self.session_id)
|
||||
elif value and lower == "srcset":
|
||||
value = _rewrite_srcset(value, self.base_url, self.session_id)
|
||||
elif tag.lower() == "meta" and lower == "content":
|
||||
value = re.sub(
|
||||
r"(?i)(url\s*=\s*)([^;]+)",
|
||||
lambda match: match.group(1)
|
||||
+ rewrite_url(match.group(2).strip(), self.base_url, self.session_id),
|
||||
value,
|
||||
)
|
||||
rewritten.append((key, value))
|
||||
attrs_text = "".join(
|
||||
f" {key}" if value is None else f' {key}="{html.escape(value, quote=True)}"'
|
||||
for key, value in rewritten
|
||||
)
|
||||
self.output.append(f"<{tag}{attrs_text}{' /' if close else ''}>")
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
self.output.append(f"</{tag}>")
|
||||
|
||||
|
||||
def rewrite_html(content: str, base_url: str, session_id: str, final_url: str) -> str:
|
||||
parser = _HtmlRewriter(base_url, session_id)
|
||||
parser.feed(content)
|
||||
parser.close()
|
||||
resource_prefix = f"/api/browser/resources/{session_id}/"
|
||||
runtime = (
|
||||
f'<script type="importmap">{json.dumps({"imports": {"/": resource_prefix}})}</script>'
|
||||
f'<script>window.__cptrBrowser={{session:{session_id!r},url:{final_url!r}}};</script>'
|
||||
'<script src="/browser-runtime.js"></script>'
|
||||
)
|
||||
rendered = "".join(parser.output)
|
||||
if re.search(r"<head(?:\s[^>]*)?>", rendered, re.I):
|
||||
return re.sub(r"(<head(?:\s[^>]*)?>)", r"\1" + runtime, rendered, count=1, flags=re.I)
|
||||
return runtime + rendered
|
||||
|
||||
|
||||
def rewrite_css(content: str, base_url: str, session_id: str) -> str:
|
||||
def replace_url(match: re.Match[str]) -> str:
|
||||
quote, value = match.group(1), match.group(2)
|
||||
return f"url({quote}{rewrite_url(value, base_url, session_id)}{quote})"
|
||||
|
||||
content = re.sub(r"url\(\s*(['\"]?)([^'\")]+)\1\s*\)", replace_url, content, flags=re.I)
|
||||
return re.sub(
|
||||
r"(@import\s+(?:url\()?['\"])([^'\"]+)",
|
||||
lambda match: match.group(1) + rewrite_url(match.group(2), base_url, session_id),
|
||||
content,
|
||||
flags=re.I,
|
||||
)
|
||||
|
||||
|
||||
manager = BrowserProxyManager()
|
||||
@@ -1,233 +0,0 @@
|
||||
"""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
|
||||
|
||||
# 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
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user