Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
libcairo2 libasound2 libx11-xcb1 libfontconfig1 libx11-6 \
libxcb1 libxext6 libxshmfence1 \
libglib2.0-0 libgtk-3-0 libpangocairo-1.0-0 libcairo-gobject2 \
libgdk-pixbuf-2.0-0 libxss1 libxtst6 fonts-liberation \
libgdk-pixbuf-2.0-0 libxss1 libxtst6 fonts-liberation fonts-wqy-zenhei \
libgl1-mesa-dri libegl-mesa0 \
procps wget ca-certificates xclip \
&& rm -rf /var/lib/apt/lists/*
Expand Down Expand Up @@ -57,7 +57,7 @@ RUN python -c "from cloakbrowser.download import ensure_binary; ensure_binary()"
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/api/status')" || exit 1
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/api/health')" || exit 1

VOLUME /data

Expand Down
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,10 +173,27 @@ When `AUTH_TOKEN` is set:
- The web UI shows a login page. Enter the token to unlock.
- API consumers pass the token via `Authorization: Bearer <token>` header.
- VNC WebSocket connections are authenticated via the login cookie.
- The `/api/status` endpoint remains unauthenticated (for Docker healthcheck).
- The `/api/health` endpoint remains unauthenticated (for Docker healthcheck); it exposes no system details. The `/api/status` endpoint (running counts, version) now requires authentication.

> **Note**: The auth token is transmitted in cleartext over HTTP. If you expose the Manager to the internet, put it behind a reverse proxy with HTTPS (Caddy, nginx, Traefik).

## Runtime UI configuration

The profile sidebar defaults to `16rem`. To use a wider or narrower sidebar without changing the frontend build, set `SIDEBAR_WIDTH` to a CSS length:

```bash
docker run -p 8080:8080 -v cloakprofiles:/data -e SIDEBAR_WIDTH=20rem cloakhq/cloakbrowser-manager
```

Or in `docker-compose.yml`:

```yaml
environment:
- SIDEBAR_WIDTH=20rem
```

Supported units are `px`, `rem`, `em`, and `vw`.

## License

- **This application** (GUI source code) — MIT. See [LICENSE](LICENSE).
Expand Down
45 changes: 45 additions & 0 deletions backend/browser_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,12 @@ async def launch(self, profile: dict[str, Any]) -> RunningProfile:
env={**os.environ, "DISPLAY": f":{display}"},
)

await self._fit_window_to_vnc(
context,
width=profile.get("screen_width", 1920),
height=profile.get("screen_height", 1080),
)

# Inject clipboard listener: captures copied text on every page
# so the GET /clipboard endpoint can read it via page.evaluate()
_clipboard_init_js = """
Expand Down Expand Up @@ -339,6 +345,45 @@ async def cleanup_stale(self):
"""Kill orphan processes from previous container runs."""
await self.vnc.cleanup_stale()

async def _fit_window_to_vnc(self, context: Any, width: int, height: int) -> None:
"""Keep the native browser window inside the VNC framebuffer."""
if not getattr(context, "pages", None):
logger.debug("Skipping VNC window fit: no pages available")
return

try:
session = await context.new_cdp_session(context.pages[0])
result = await session.send("Browser.getWindowForTarget")
bounds = result.get("bounds", {})
left = int(bounds.get("left", 0))
top = int(bounds.get("top", 0))
current_width = int(bounds.get("width", width))
current_height = int(bounds.get("height", height))

overflows = (
left != 0
or top != 0
or left + current_width > width
or top + current_height > height
)
if not overflows:
return

await session.send(
"Browser.setWindowBounds",
{
"windowId": result["windowId"],
"bounds": {"left": 0, "top": 0, "width": width, "height": height},
},
)
logger.info(
"Adjusted browser window to fit VNC framebuffer %dx%d",
width,
height,
)
except Exception as exc:
logger.warning("Failed to adjust browser window bounds: %s", exc)

async def auto_launch_all(self):
"""Launch all profiles with auto_launch=True. Called on startup."""
from . import database as db
Expand Down
36 changes: 34 additions & 2 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import hmac
import logging
import os
import re
import struct
import shutil
from contextlib import asynccontextmanager
Expand All @@ -34,6 +35,7 @@
ProfileResponse,
ProfileStatusResponse,
ProfileUpdate,
RuntimeConfigResponse,
StatusResponse,
TagResponse,
)
Expand All @@ -47,11 +49,14 @@

# Optional authentication via AUTH_TOKEN env var.
# If not set, all routes are open (local dev). If set, all /api/* routes
# (except /api/auth/* and /api/status) require Bearer token or cookie.
# (except /api/auth/status, /api/auth/login and /api/health) require Bearer
# token or cookie.
AUTH_TOKEN: str | None = os.environ.get("AUTH_TOKEN") or None
DEFAULT_SIDEBAR_WIDTH = "16rem"
_SIDEBAR_WIDTH_RE = re.compile(r"^\d+(?:\.\d+)?(?:px|rem|em|vw)$")

# Paths that bypass authentication even when AUTH_TOKEN is set
_AUTH_EXEMPT = frozenset({"/api/auth/status", "/api/auth/login", "/api/status"})
_AUTH_EXEMPT = frozenset({"/api/auth/status", "/api/auth/login", "/api/health"})


def _check_auth(scope: Scope) -> bool:
Expand Down Expand Up @@ -180,6 +185,17 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send):
FRONTEND_DIR = Path(__file__).parent.parent / "frontend" / "dist"


def get_sidebar_width() -> str:
"""Return a validated CSS length for the profile sidebar."""
value = os.environ.get("SIDEBAR_WIDTH", "").strip()
if not value:
return DEFAULT_SIDEBAR_WIDTH
if _SIDEBAR_WIDTH_RE.fullmatch(value):
return value
logger.warning("Ignoring invalid SIDEBAR_WIDTH=%r", value)
return DEFAULT_SIDEBAR_WIDTH


# ---------------------------------------------------------------------------
# RFB server message translator — KasmVNC BinaryClipboard → standard RFB
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -405,6 +421,12 @@ async def auth_status(request: starlette.requests.Request):
return {"auth_required": AUTH_TOKEN is not None, "authenticated": authenticated}


@app.get("/api/config", response_model=RuntimeConfigResponse)
async def runtime_config():
"""Return runtime UI configuration."""
return RuntimeConfigResponse(sidebar_width=get_sidebar_width())


@app.post("/api/auth/login")
async def auth_login(body: LoginRequest, request: Request, response: Response):
if not AUTH_TOKEN:
Expand Down Expand Up @@ -567,6 +589,16 @@ async def get_profile_status(profile_id: str):
# ── System Status ─────────────────────────────────────────────────────────────


@app.get("/api/health")
async def health_check():
"""Unauthenticated liveness probe for the Docker healthcheck.

Intentionally returns no system details; see /api/status (auth-gated)
for running counts and versions.
"""
return {"status": "ok"}


@app.get("/api/status", response_model=StatusResponse)
async def get_system_status():
from cloakbrowser.config import CHROMIUM_VERSION
Expand Down
4 changes: 4 additions & 0 deletions backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,10 @@ class StatusResponse(BaseModel):
profiles_total: int


class RuntimeConfigResponse(BaseModel):
sidebar_width: str


class ProfileStatusResponse(BaseModel):
status: str # "running" | "stopped"
vnc_ws_port: int | None = None
Expand Down
21 changes: 21 additions & 0 deletions backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,27 @@ def test_system_status(app_client: TestClient):
assert data["profiles_total"] >= 1


# ── Runtime Config ──────────────────────────────────────────────────────────


def test_runtime_config_default_sidebar_width(app_client: TestClient, monkeypatch):
monkeypatch.delenv("SIDEBAR_WIDTH", raising=False)

resp = app_client.get("/api/config")

assert resp.status_code == 200
assert resp.json() == {"sidebar_width": "16rem"}


def test_runtime_config_sidebar_width_from_env(app_client: TestClient, monkeypatch):
monkeypatch.setenv("SIDEBAR_WIDTH", "20rem")

resp = app_client.get("/api/config")

assert resp.status_code == 200
assert resp.json() == {"sidebar_width": "20rem"}


# ── Launch Args ─────────────────────────────────────────────────────────────


Expand Down
12 changes: 11 additions & 1 deletion backend/tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,18 @@ def test_logout_clears_cookie(client_auth: TestClient):


def test_healthcheck_always_accessible(client_auth: TestClient):
"""GET /api/status must work without auth (Docker healthcheck)."""
"""GET /api/health must work without auth (Docker healthcheck)."""
resp = client_auth.get("/api/health")
assert resp.status_code == 200


def test_status_requires_auth(client_auth: TestClient):
"""GET /api/status must require auth (leaks profile count and version)."""
resp = client_auth.get("/api/status")
assert resp.status_code == 401
resp = client_auth.get(
"/api/status", headers={"Authorization": "Bearer test-secret"}
)
assert resp.status_code == 200


Expand Down
50 changes: 50 additions & 0 deletions backend/tests/test_browser_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import pytest

import socket
from unittest.mock import AsyncMock, MagicMock

from backend.browser_manager import (
BASE_CDP_PORT,
Expand Down Expand Up @@ -176,6 +177,55 @@ def test_launch_args_none_no_effect():
assert len(args) == base_count


# ── VNC browser window bounds ─────────────────────────────────────────────────


@pytest.mark.anyio
async def test_fit_window_to_vnc_moves_oversized_window_back_inside_framebuffer():
mgr = BrowserManager()
page = MagicMock()
session = MagicMock()
session.send = AsyncMock(
side_effect=[
{
"windowId": 123,
"bounds": {
"left": 10,
"top": 10,
"width": 1928,
"height": 1078,
"windowState": "normal",
},
},
{
"windowId": 123,
"bounds": {
"left": 0,
"top": 0,
"width": 1919,
"height": 1079,
"windowState": "normal",
},
},
]
)
context = MagicMock()
context.pages = [page]
context.new_cdp_session = AsyncMock(return_value=session)

await mgr._fit_window_to_vnc(context, width=1920, height=1080)

context.new_cdp_session.assert_awaited_once_with(page)
session.send.assert_any_await("Browser.getWindowForTarget")
session.send.assert_any_await(
"Browser.setWindowBounds",
{
"windowId": 123,
"bounds": {"left": 0, "top": 0, "width": 1920, "height": 1080},
},
)


# ── _allocate_cdp_port ───────────────────────────────────────────────────────


Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ services:
- ~/.cloakbrowser-manager:/data
environment:
- AUTH_TOKEN=${AUTH_TOKEN:-}
- SIDEBAR_WIDTH=${SIDEBAR_WIDTH:-}
54 changes: 54 additions & 0 deletions frontend/src/App.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import App from "./App";
import { api } from "./lib/api";
import { useProfiles } from "./hooks/useProfiles";

vi.mock("./lib/api", () => ({
api: {
authStatus: vi.fn(),
getConfig: vi.fn(),
logout: vi.fn(),
},
setOnUnauthorized: vi.fn(),
}));

vi.mock("./hooks/useProfiles", () => ({
useProfiles: vi.fn(),
}));

const mockApi = api as {
authStatus: ReturnType<typeof vi.fn>;
getConfig: ReturnType<typeof vi.fn>;
logout: ReturnType<typeof vi.fn>;
};

const mockUseProfiles = useProfiles as ReturnType<typeof vi.fn>;

beforeEach(() => {
mockApi.authStatus.mockResolvedValue({ auth_required: false, authenticated: false });
mockApi.getConfig.mockResolvedValue({ sidebar_width: "20rem" });
mockApi.logout.mockResolvedValue({ ok: true });
mockUseProfiles.mockReturnValue({
profiles: [],
loading: false,
error: null,
refresh: vi.fn(),
create: vi.fn(),
update: vi.fn(),
remove: vi.fn(),
launch: vi.fn(),
stop: vi.fn(),
});
});

describe("App", () => {
it("applies the configured sidebar width", async () => {
render(<App />);

const sidebar = await screen.findByLabelText("Profile sidebar");

await waitFor(() => expect(mockApi.getConfig).toHaveBeenCalled());
expect(sidebar.getAttribute("style")).toContain("width: 20rem");
});
});
Loading