This commit is contained in:
Timothy Jaeryang Baek committed 2026-07-10 14:35:27 -05:00
1 parent 5146bbe070
commit fdb9c456c4
5 files changed
+215 -44

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ export const updateBrowserSession = (sessionId: string, url: string, title: stri
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)}`;
return `/api/browser/frame/${sessionId}/${url.protocol.slice(0, -1)}/${encodeURIComponent(url.host)}${url.pathname}${url.search}${url.hash}`;
};
export const browserBlankUrl = (sessionId: string) => `/api/browser/sessions/${sessionId}/blank`;
@@ -1,7 +1,12 @@
<script lang="ts">
import { onDestroy, onMount } from 'svelte';
import { tooltip } from '$lib/tooltip';
import { browserBlankUrl, browserFrameUrl, getBrowserSession, updateBrowserSession } from '$lib/apis/browser';
import {
browserBlankUrl,
browserFrameUrl,
getBrowserSession,
updateBrowserSession
} from '$lib/apis/browser';
import { openBrowserTab } from '$lib/stores';
import Icon from './Icon.svelte';
import { t } from '$lib/i18n';
@@ -22,19 +27,27 @@
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 (proxyUrl.pathname === `/api/browser/frame/${sessionId}`)
return proxyUrl.searchParams.get('url') || value;
const marker = `/api/browser/frame/${sessionId}/`;
const index = proxyUrl.pathname.indexOf(marker);
if (index === -1) return value;
const [scheme, host, ...path] = value.slice(index + legacyMarker.length).split('/');
return scheme && host ? `${scheme}://${host}/${path.join('/')}` : value;
const [scheme, encodedHost, ...path] = proxyUrl.pathname
.slice(index + marker.length)
.split('/');
const host = decodeURIComponent(encodedHost || '');
return scheme && host
? `${scheme}://${host}/${path.join('/')}${proxyUrl.search}${proxyUrl.hash}`
: 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;
urlInput = new URL(
/^https?:\/\//i.test(publicUrl(value)) ? publicUrl(value) : `https://${publicUrl(value)}`
).href;
frameSrc = browserFrameUrl(sessionId, urlInput);
loading = true;
error = '';
@@ -49,6 +62,25 @@
iframeEl?.contentWindow?.location.reload();
}
function frameLoaded() {
loading = false;
try {
const current = new URL(iframeEl?.contentWindow?.location.href || '');
const framePrefix = `/api/browser/frame/${sessionId}`;
const blankPath = `/api/browser/sessions/${sessionId}/blank`;
if (current.origin !== location.origin || current.pathname.startsWith(framePrefix) || current.pathname === blankPath)
return;
const upstream = new URL(`${current.pathname}${current.search}${current.hash}`, urlInput).href;
urlInput = upstream;
loading = true;
void updateBrowserSession(sessionId, upstream, title).catch(() => {});
iframeEl?.contentWindow?.location.replace(browserFrameUrl(sessionId, upstream));
} catch {
// Cross-origin frames cannot be inspected; the proxy frame is same-origin.
}
}
function receiveMessage(event: MessageEvent) {
if (event.origin !== location.origin || event.source !== iframeEl?.contentWindow) return;
const data = event.data;
@@ -76,10 +108,18 @@
<div class="preview-container">
<div class="preview-toolbar">
<button class="preview-btn" onclick={() => iframeEl?.contentWindow?.history.back()} use:tooltip={$t('settings.back')}>
<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')}>
<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')}>
@@ -94,19 +134,22 @@
spellcheck="false"
/>
</div>
{#if title}<span class="browser-title" title={title}>{title}</span>{/if}
{#if title}<span class="browser-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>
<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)}
onload={frameLoaded}
onerror={() => {
error = $t('port.cannotConnect');
loading = false;
@@ -118,21 +161,109 @@
<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); }
.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, 0.06);
}
: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) .preview-btn:hover {
background: rgba(255, 255, 255, 0.06);
color: var(--color-gray-300);
}
</style>
+15 -4
View File
@@ -9,16 +9,20 @@
function remoteUrl(value = location.href) {
const url = new URL(value, location.href);
return url.pathname === prefix ? url.searchParams.get('url') || config.url : config.url;
if (url.pathname === prefix) return url.searchParams.get('url') || config.url;
if (!url.pathname.startsWith(`${prefix}/`)) return config.url;
const [scheme, encodedHost, ...path] = url.pathname.slice(prefix.length + 1).split('/');
if (!scheme || !encodedHost) return config.url;
return `${scheme}://${decodeURIComponent(encodedHost)}/${path.join('/')}${url.search}${url.hash}`;
}
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}`;
if (current.pathname.startsWith(`${prefix}/`)) return `${current.pathname}${current.search}${current.hash}`;
const url = new URL(value, base);
if (!/^https?:$/.test(url.protocol)) return value;
return `${prefix}?url=${encodeURIComponent(url.href)}`;
return `${prefix}/${url.protocol.slice(0, -1)}/${encodeURIComponent(url.host)}${url.pathname}${url.search}${url.hash}`;
} catch {
return value;
}
@@ -111,7 +115,7 @@
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());
const url = new URL(link.getAttribute('href'), remoteUrl());
if (!/^https?:$/.test(url.protocol)) return;
event.preventDefault();
if (link.target && link.target !== '_self') {
@@ -121,6 +125,13 @@
}
}, true);
document.addEventListener('submit', (event) => {
const form = event.target;
if (!(form instanceof HTMLFormElement)) return;
const url = new URL(form.getAttribute('action') || remoteUrl(), remoteUrl());
if (/^https?:$/.test(url.protocol)) form.action = 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);
+21 -4
View File
@@ -5,15 +5,16 @@ from __future__ import annotations
import asyncio
import json
from collections.abc import AsyncIterator
from pathlib import Path
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 fastapi.responses import FileResponse, 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.browser.proxy import manager, rewrite_css, rewrite_html, rewrite_javascript, target_url
from cptr.utils.config import AuthResult, check_access
router = APIRouter(prefix="/api/browser", tags=["browser"])
@@ -135,11 +136,14 @@ async def proxy_browser_request(request: Request, session_id: str, url: str, own
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)
final_url = str(upstream.url)
if parsed.hostname == "127.0.0.1" and urlsplit(final_url).hostname == "::1":
redirected = urlsplit(final_url)
final_url = urlunsplit((parsed.scheme, parsed.netloc, redirected.path, redirected.query, ""))
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")
content = rewrite_html(text, final_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:
@@ -147,6 +151,13 @@ async def proxy_browser_request(request: Request, session_id: str, url: str, own
content = rewrite_css(text, upstream_url, session_id).encode("utf-8")
headers.pop("content-type", None)
content_type = "text/css; charset=utf-8"
elif parsed.hostname in {"localhost", "127.0.0.1", "::1"} and (
"javascript" in content_type or "ecmascript" in content_type
):
text = content.decode(upstream.encoding or "utf-8", errors="replace")
content = rewrite_javascript(text, upstream_url, session_id).encode("utf-8")
headers.pop("content-type", None)
content_type = "text/javascript; charset=utf-8"
return Response(content=content, status_code=upstream.status_code, headers=headers, media_type=content_type)
@@ -160,6 +171,12 @@ async def create_session(request: Request):
return _session_payload(session)
@router.get("/runtime.js", response_class=FileResponse)
async def browser_runtime():
path = Path(__file__).parents[1] / "frontend" / "build" / "browser-runtime.js"
return FileResponse(path, media_type="text/javascript", headers={"cache-control": "no-store"})
@router.get("/sessions")
async def list_sessions(request: Request):
return {"session_ids": manager.ids(_owner(_auth(request)))}
+18 -6
View File
@@ -4,12 +4,11 @@ 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
from urllib.parse import quote, urljoin, urlsplit, urlunsplit
import httpx
@@ -115,7 +114,11 @@ def proxy_path(session_id: str, 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 f"/api/browser/frame/{session_id}?{urlencode({'url': url})}"
host = quote(parsed.netloc, safe=":[]")
path = quote(parsed.path or "/", safe="/%:@!$&'()*+,;=-._~")
query = f"?{parsed.query}" if parsed.query else ""
fragment = f"#{parsed.fragment}" if parsed.fragment else ""
return f"/api/browser/frame/{session_id}/{parsed.scheme}/{host}{path}{query}{fragment}"
def target_url(url: str) -> str:
@@ -210,13 +213,13 @@ def rewrite_html(content: str, base_url: str, session_id: str, final_url: 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>'
'<script src="/api/browser/runtime.js"></script>'
)
rendered = "".join(parser.output)
if urlsplit(final_url).hostname in {"localhost", "127.0.0.1", "::1"}:
rendered = rewrite_javascript(rendered, final_url, session_id)
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
@@ -236,4 +239,13 @@ def rewrite_css(content: str, base_url: str, session_id: str) -> str:
)
def rewrite_javascript(content: str, base_url: str, session_id: str) -> str:
"""Rewrite root-relative ES module imports used by local dev servers."""
return re.sub(
r"((?:from\s*|import\s*\(\s*|import\s*)['\"])(/[^'\"]+)",
lambda match: match.group(1) + rewrite_url(match.group(2), base_url, session_id),
content,
)
manager = BrowserProxyManager()