Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): add global mutation request protection

cyhdaef388aac7b
diff --git a/tests/e2e/http.py b/tests/e2e/http.py
new file mode 100644
index 000000000..2d3046a35
--- /dev/null
+++ b/tests/e2e/http.py
@@ -0,0 +1,58 @@
+"""HTTP helpers for UI E2E tests with CSRF support."""
+
+from __future__ import annotations
+
+import http.cookiejar
+import json
+import urllib.error
+import urllib.request
+
+
+class JsonHttpClient:
+ def __init__(self, base_url: str):
+ self.base_url = base_url.rstrip("/")
+ self.cookie_jar = http.cookiejar.CookieJar()
+ self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie_jar))
+ self._csrf_token: str | None = None
+
+ def _request(self, path: str, *, method: str = "GET", body: dict | None = None, timeout: int = 5):
+ headers = {}
+ data = None
+ if body is not None:
+ data = json.dumps(body).encode()
+ headers["Content-Type"] = "application/json"
+
+ if method in {"POST", "PUT", "PATCH", "DELETE"}:
+ headers["Origin"] = self.base_url
+ headers["X-Vibe-CSRF-Token"] = self.csrf_token(timeout=timeout)
+
+ request = urllib.request.Request(f"{self.base_url}{path}", data=data, headers=headers, method=method)
+ return self.opener.open(request, timeout=timeout)
+
+ def csrf_token(self, timeout: int = 5) -> str:
+ if self._csrf_token:
+ return self._csrf_token
+
+ response = self.opener.open(f"{self.base_url}/api/csrf-token", timeout=timeout)
+ payload = json.loads(response.read())
+ self._csrf_token = payload["csrf_token"]
+ return self._csrf_token
+
+ def get_json(self, path: str, timeout: int = 5):
+ response = self._request(path, timeout=timeout)
+ return response.status, json.loads(response.read())
+
+ def post_json(self, path: str, body: dict | None = None, timeout: int = 5):
+ response = self._request(path, method="POST", body=body or {}, timeout=timeout)
+ return response.status, json.loads(response.read())
+
+ def delete_json(self, path: str, timeout: int = 5):
+ response = self._request(path, method="DELETE", timeout=timeout)
+ return response.status, json.loads(response.read())
+
+ def expect_error(self, path: str, *, method: str = "DELETE", timeout: int = 5):
+ try:
+ self._request(path, method=method, timeout=timeout)
+ raise AssertionError(f"Expected HTTP error for {method} {path}")
+ except urllib.error.HTTPError as exc:
+ return exc.code, json.loads(exc.read())
diff --git a/tests/e2e/test_api.py b/tests/e2e/test_api.py
index c59f0b445..3bad870a8 100644
--- a/tests/e2e/test_api.py
+++ b/tests/e2e/test_api.py
@@ -1,19 +1,10 @@
"""E2E tests: API endpoints."""
-import json
-import urllib.request
+from tests.e2e.http import JsonHttpClient
-def _get(url, timeout=5):
- resp = urllib.request.urlopen(url, timeout=timeout)
- return resp.status, json.loads(resp.read())
-
-
-def _post(url, body=None, timeout=5):
- data = json.dumps(body or {}).encode()
- req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
- resp = urllib.request.urlopen(req, timeout=timeout)
- return resp.status, json.loads(resp.read())
+def _client(api_url: str) -> JsonHttpClient:
+ return JsonHttpClient(api_url)
# Minimal valid config payload for POST /config
@@ -34,15 +25,16 @@ class TestConfigAPI:
def test_post_config_creates(self, api_url):
"""POST /config with valid payload should save and return config."""
- status, data = _post(f"{api_url}/config", _VALID_CONFIG)
+ status, data = _client(api_url).post_json("/config", _VALID_CONFIG)
assert status == 200
assert data["mode"] == "self_host"
assert data["runtime"]["default_cwd"] == "/tmp/test"
def test_post_then_get_config(self, api_url):
"""GET /config should return config after it's been created via POST."""
- _post(f"{api_url}/config", _VALID_CONFIG)
- status, data = _get(f"{api_url}/config")
+ client = _client(api_url)
+ client.post_json("/config", _VALID_CONFIG)
+ status, data = client.get_json("/config")
assert status == 200
assert "mode" in data
assert "version" in data
@@ -50,7 +42,7 @@ class TestConfigAPI:
def test_post_config_updates_cwd(self, api_url):
"""POST /config should update specific fields."""
payload = {**_VALID_CONFIG, "runtime": {"default_cwd": "/tmp/e2e_updated"}}
- status, data = _post(f"{api_url}/config", payload)
+ status, data = _client(api_url).post_json("/config", payload)
assert status == 200
assert data["runtime"]["default_cwd"] == "/tmp/e2e_updated"
@@ -59,13 +51,13 @@ class TestStatusAPI:
"""Service status endpoint."""
def test_status_returns_json(self, api_url):
- status, data = _get(f"{api_url}/status")
+ status, data = _client(api_url).get_json("/status")
assert status == 200
assert "running" in data
def test_status_shows_not_running(self, api_url):
"""In UI-only mode, service should not be running."""
- status, data = _get(f"{api_url}/status")
+ status, data = _client(api_url).get_json("/status")
assert status == 200
# In UI-only Docker mode, the service process is not started
assert data["running"] is False
@@ -75,7 +67,7 @@ class TestDoctorAPI:
"""Doctor diagnostic endpoint."""
def test_doctor_post(self, api_url):
- status, data = _post(f"{api_url}/doctor")
+ status, data = _client(api_url).post_json("/doctor")
assert status == 200
assert "groups" in data
assert "summary" in data
@@ -84,9 +76,10 @@ class TestDoctorAPI:
def test_doctor_get_after_post(self, api_url):
"""GET /doctor should return cached results after POST /doctor."""
# First run doctor
- _post(f"{api_url}/doctor")
+ client = _client(api_url)
+ client.post_json("/doctor")
# Then fetch cached result
- status, data = _get(f"{api_url}/doctor")
+ status, data = client.get_json("/doctor")
assert status == 200
# Should have groups from the last run
assert "groups" in data
@@ -96,7 +89,7 @@ class TestSlackManifest:
"""Slack manifest endpoint."""
def test_get_manifest(self, api_url):
- status, data = _get(f"{api_url}/slack/manifest")
+ status, data = _client(api_url).get_json("/slack/manifest")
assert status == 200
# Manifest is returned wrapped: {"manifest": "...", "ok": True}
assert data.get("ok") is True
@@ -107,7 +100,7 @@ class TestBrowseAPI:
"""Directory browsing endpoint."""
def test_browse_root(self, api_url):
- status, data = _post(f"{api_url}/browse", {"path": "/"})
+ status, data = _client(api_url).post_json("/browse", {"path": "/"})
assert status == 200
# Should return directory listing info
assert "path" in data or "entries" in data or "dirs" in data
@@ -118,6 +111,6 @@ class TestCLIDetect:
def test_detect_python(self, api_url):
"""Python should be detectable inside the container."""
- status, data = _get(f"{api_url}/cli/detect?binary=python3")
+ status, data = _client(api_url).get_json("/cli/detect?binary=python3")
assert status == 200
assert "found" in data or "path" in data
diff --git a/tests/e2e/test_settings.py b/tests/e2e/test_settings.py
index 8d9622004..7364fb848 100644
--- a/tests/e2e/test_settings.py
+++ b/tests/e2e/test_settings.py
@@ -1,19 +1,10 @@
"""E2E tests: Settings API endpoints."""
-import json
-import urllib.request
+from tests.e2e.http import JsonHttpClient
-def _get(url, timeout=5):
- resp = urllib.request.urlopen(url, timeout=timeout)
- return resp.status, json.loads(resp.read())
-
-
-def _post(url, body=None, timeout=5):
- data = json.dumps(body or {}).encode()
- req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
- resp = urllib.request.urlopen(req, timeout=timeout)
- return resp.status, json.loads(resp.read())
+def _client(api_url: str) -> JsonHttpClient:
+ return JsonHttpClient(api_url)
class TestSettingsAPI:
@@ -21,12 +12,13 @@ class TestSettingsAPI:
def test_get_settings_returns_json(self, api_url):
"""GET /settings should return current settings."""
- status, data = _get(f"{api_url}/settings")
+ status, data = _client(api_url).get_json("/settings")
assert status == 200
assert isinstance(data, dict)
def test_post_settings_roundtrip(self, api_url):
"""POST /settings should persist and return updated settings."""
+ client = _client(api_url)
# Save settings with a channel config
payload = {
"channels": {
@@ -36,11 +28,11 @@ class TestSettingsAPI:
}
}
}
- status, data = _post(f"{api_url}/settings", payload)
+ status, data = client.post_json("/settings", payload)
assert status == 200
# Verify the channel persisted
- status, data = _get(f"{api_url}/settings")
+ status, data = client.get_json("/settings")
assert status == 200
channels = data.get("channels", {})
assert "C_TEST_E2E" in channels
@@ -52,7 +44,7 @@ class TestLogsAPI:
def test_logs_returns_structure(self, api_url):
"""POST /logs should return log lines and total count."""
- status, data = _post(f"{api_url}/logs", {"lines": 10})
+ status, data = _client(api_url).post_json("/logs", {"lines": 10})
assert status == 200
assert "source" in data
assert "logs" in data
diff --git a/tests/e2e/test_users_and_bind.py b/tests/e2e/test_users_and_bind.py
index 834bdb4a4..7fb2a259a 100644
--- a/tests/e2e/test_users_and_bind.py
+++ b/tests/e2e/test_users_and_bind.py
@@ -1,36 +1,10 @@
"""E2E tests: User management and bind code API endpoints."""
-import json
-import urllib.request
-import urllib.error
+from tests.e2e.http import JsonHttpClient
-def _get(url, timeout=5):
- resp = urllib.request.urlopen(url, timeout=timeout)
- return resp.status, json.loads(resp.read())
-
-
-def _post(url, body=None, timeout=5):
- data = json.dumps(body or {}).encode()
- req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
- resp = urllib.request.urlopen(req, timeout=timeout)
- return resp.status, json.loads(resp.read())
-
-
-def _delete(url, timeout=5):
- req = urllib.request.Request(url, method="DELETE")
- resp = urllib.request.urlopen(req, timeout=timeout)
- return resp.status, json.loads(resp.read())
-
-
-def _expect_error(url, method="DELETE", timeout=5):
- """Send request and expect an HTTP error (4xx/5xx)."""
- req = urllib.request.Request(url, method=method)
- try:
- urllib.request.urlopen(req, timeout=timeout)
- return None, None # No error raised
- except urllib.error.HTTPError as e:
- return e.code, json.loads(e.read())
+def _client(api_url: str) -> JsonHttpClient:
+ return JsonHttpClient(api_url)
class TestBindCodeAPI:
@@ -38,14 +12,14 @@ class TestBindCodeAPI:
def test_get_bind_codes_empty(self, api_url):
"""GET /api/bind-codes should return empty list initially."""
- status, data = _get(f"{api_url}/api/bind-codes")
+ status, data = _client(api_url).get_json("/api/bind-codes")
assert status == 200
assert data.get("ok") is True
assert isinstance(data.get("bind_codes"), list)
def test_create_one_time_bind_code(self, api_url):
"""POST /api/bind-codes should create a one-time code."""
- status, data = _post(f"{api_url}/api/bind-codes", {"type": "one_time"})
+ status, data = _client(api_url).post_json("/api/bind-codes", {"type": "one_time"})
assert status == 200
assert data.get("ok") is True
assert "bind_code" in data
@@ -53,35 +27,37 @@ class TestBindCodeAPI:
def test_create_and_list_bind_codes(self, api_url):
"""Created bind codes should appear in GET listing."""
+ client = _client(api_url)
# Create a code
- _, create_data = _post(f"{api_url}/api/bind-codes", {"type": "one_time"})
+ _, create_data = client.post_json("/api/bind-codes", {"type": "one_time"})
code = create_data["bind_code"]["code"]
# List codes
- _, list_data = _get(f"{api_url}/api/bind-codes")
+ _, list_data = client.get_json("/api/bind-codes")
codes = [bc["code"] for bc in list_data.get("bind_codes", [])]
assert code in codes
def test_delete_bind_code(self, api_url):
"""DELETE /api/bind-codes/<code> should deactivate the code."""
+ client = _client(api_url)
# Create a code
- _, create_data = _post(f"{api_url}/api/bind-codes", {"type": "one_time"})
+ _, create_data = client.post_json("/api/bind-codes", {"type": "one_time"})
code = create_data["bind_code"]["code"]
# Delete it
- status, data = _delete(f"{api_url}/api/bind-codes/{code}")
+ status, data = client.delete_json(f"/api/bind-codes/{code}")
assert status == 200
assert data.get("ok") is True
def test_delete_nonexistent_code_returns_404(self, api_url):
"""DELETE /api/bind-codes/<nonexistent> should return 404."""
- error_code, data = _expect_error(f"{api_url}/api/bind-codes/NONEXISTENT_CODE_XYZ")
+ error_code, data = _client(api_url).expect_error("/api/bind-codes/NONEXISTENT_CODE_XYZ")
assert error_code == 404
def test_create_expiring_bind_code(self, api_url):
"""POST /api/bind-codes with type=expiring should accept expires_at."""
- status, data = _post(
- f"{api_url}/api/bind-codes",
+ status, data = _client(api_url).post_json(
+ "/api/bind-codes",
{"type": "expiring", "expires_at": "2099-12-31"},
)
assert status == 200
@@ -93,7 +69,7 @@ class TestFirstBindCodeAPI:
def test_first_bind_code(self, api_url):
"""GET /api/setup/first-bind-code should return a code."""
- status, data = _get(f"{api_url}/api/setup/first-bind-code")
+ status, data = _client(api_url).get_json("/api/setup/first-bind-code")
assert status == 200
assert data.get("ok") is True
assert "code" in data
@@ -104,13 +80,14 @@ class TestUsersAPI:
def test_get_users_returns_dict(self, api_url):
"""GET /api/users should return a users dict."""
- status, data = _get(f"{api_url}/api/users")
+ status, data = _client(api_url).get_json("/api/users")
assert status == 200
assert data.get("ok") is True
assert isinstance(data.get("users"), dict)
def test_save_users_creates_user(self, api_url):
"""POST /api/users should create/update users."""
+ client = _client(api_url)
payload = {
"users": {
"U_E2E_TEST": {
@@ -121,20 +98,21 @@ class TestUsersAPI:
}
}
}
- status, data = _post(f"{api_url}/api/users", payload)
+ status, data = client.post_json("/api/users", payload)
assert status == 200
assert data.get("ok") is True
# Verify the user persisted
- _, users_data = _get(f"{api_url}/api/users")
+ _, users_data = client.get_json("/api/users")
assert "U_E2E_TEST" in users_data.get("users", {})
assert users_data["users"]["U_E2E_TEST"]["display_name"] == "E2E Test User"
def test_toggle_admin(self, api_url):
"""POST /api/users/<id>/admin should toggle admin status."""
+ client = _client(api_url)
# First ensure user exists (as admin)
- _post(
- f"{api_url}/api/users",
+ client.post_json(
+ "/api/users",
{
"users": {
"U_ADMIN_TEST": {
@@ -154,8 +132,8 @@ class TestUsersAPI:
)
# Toggle non-admin to admin
- status, data = _post(
- f"{api_url}/api/users/U_NONADMIN_TEST/admin",
+ status, data = client.post_json(
+ "/api/users/U_NONADMIN_TEST/admin",
{"is_admin": True},
)
assert status == 200
@@ -163,9 +141,10 @@ class TestUsersAPI:
def test_delete_user(self, api_url):
"""DELETE /api/users/<id> should remove the user."""
+ client = _client(api_url)
# Create a user to delete (ensure at least one admin remains)
- _post(
- f"{api_url}/api/users",
+ client.post_json(
+ "/api/users",
{
"users": {
"U_KEEP_ADMIN": {
@@ -185,12 +164,12 @@ class TestUsersAPI:
)
# Delete the user
- status, data = _delete(f"{api_url}/api/users/U_TO_DELETE")
+ status, data = client.delete_json("/api/users/U_TO_DELETE")
assert status == 200
assert data.get("ok") is True
# Verify deleted
- _, users_data = _get(f"{api_url}/api/users")
+ _, users_data = client.get_json("/api/users")
assert "U_TO_DELETE" not in users_data.get("users", {})
@@ -199,25 +178,25 @@ class TestAgentModelsAPI:
def test_claude_agents_endpoint_exists(self, api_url):
"""GET /claude/agents should return JSON (ok or error)."""
- status, data = _get(f"{api_url}/claude/agents")
+ status, data = _client(api_url).get_json("/claude/agents")
assert status == 200
# May be {"ok": true, "agents": [...]} or {"ok": false, "error": "..."}
assert isinstance(data, dict)
def test_claude_models_endpoint_exists(self, api_url):
"""GET /claude/models should return JSON."""
- status, data = _get(f"{api_url}/claude/models")
+ status, data = _client(api_url).get_json("/claude/models")
assert status == 200
assert isinstance(data, dict)
def test_codex_models_endpoint_exists(self, api_url):
"""GET /codex/models should return JSON."""
- status, data = _get(f"{api_url}/codex/models")
+ status, data = _client(api_url).get_json("/codex/models")
assert status == 200
assert isinstance(data, dict)
def test_codex_agents_endpoint_exists(self, api_url):
"""GET /codex/agents should return JSON."""
- status, data = _get(f"{api_url}/codex/agents")
+ status, data = _client(api_url).get_json("/codex/agents")
assert status == 200
assert isinstance(data, dict)
diff --git a/tests/test_ui_server_install.py b/tests/test_ui_server_install.py
index 458a8b2b4..81a400c9e 100644
--- a/tests/test_ui_server_install.py
+++ b/tests/test_ui_server_install.py
@@ -1,78 +1,63 @@
from __future__ import annotations
-from config.v2_config import (
- AgentsConfig,
- RuntimeConfig,
- SlackConfig,
- UiConfig,
- V2Config,
-)
from vibe import api
from vibe.ui_server import app
+from tests.ui_server_test_helpers import csrf_headers
-def test_install_agent_allows_configured_private_setup_host(monkeypatch):
- monkeypatch.setattr(api, "load_config", lambda: {"ui": {"setup_host": "192.168.2.3"}})
+
+def test_install_agent_allows_same_origin_request(monkeypatch):
monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name, "path": "/usr/local/bin/claude"})
client = app.test_client()
response = client.post(
"/agent/claude/install",
- headers={"Origin": "http://192.168.2.3:15131"},
+ headers=csrf_headers(client, "http://192.168.2.3:15131"),
+ base_url="http://192.168.2.3:15131",
)
assert response.status_code == 200
assert response.get_json()["ok"] is True
-def test_install_agent_rejects_untrusted_origin(monkeypatch):
- monkeypatch.setattr(api, "load_config", lambda: {"ui": {"setup_host": "192.168.2.3"}})
+def test_install_agent_rejects_cross_origin_request(monkeypatch):
monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
client = app.test_client()
+ headers = csrf_headers(client, "http://192.168.2.3:15131")
+ headers["Origin"] = "http://evil.example"
response = client.post(
"/agent/claude/install",
- headers={"Origin": "http://evil.example"},
+ headers=headers,
+ base_url="http://192.168.2.3:15131",
)
assert response.status_code == 403
assert response.get_json()["message"] == "Forbidden: invalid origin"
-def test_install_agent_allows_private_trusted_origin_with_v2_config_object(monkeypatch):
- monkeypatch.setattr(
- api,
- "load_config",
- lambda: V2Config(
- mode="self_host",
- version="v2",
- slack=SlackConfig(),
- runtime=RuntimeConfig(default_cwd="/tmp"),
- agents=AgentsConfig(),
- ui=UiConfig(setup_host="192.168.2.3", setup_port=5123, open_browser=False),
- ),
- )
+def test_install_agent_rejects_missing_csrf_token(monkeypatch):
monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
client = app.test_client()
response = client.post(
- "/agent/claude/install",
- headers={"Origin": "http://192.168.2.3:15131"},
+ "/agent/codex/install",
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
)
- assert response.status_code == 200
- assert response.get_json()["ok"] is True
+ assert response.status_code == 403
+ assert response.get_json()["message"] == "Forbidden: invalid csrf token"
-def test_install_agent_rejects_configured_public_setup_host(monkeypatch):
- monkeypatch.setattr(api, "load_config", lambda: {"ui": {"setup_host": "example.com"}})
+def test_install_agent_rejects_missing_origin(monkeypatch):
monkeypatch.setattr(api, "install_agent", lambda name: {"ok": True, "name": name})
client = app.test_client()
response = client.post(
"/agent/codex/install",
- headers={"Origin": "http://example.com"},
+ headers={"X-Vibe-CSRF-Token": csrf_headers(client)["X-Vibe-CSRF-Token"]},
)
assert response.status_code == 403
- assert response.get_json()["message"] == "Forbidden: local access only"
+ assert response.get_json()["message"] == "Forbidden: missing origin header"
diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.py
index 3ee6e9fca..3eb9d5d8b 100644
--- a/tests/test_ui_server_logs.py
+++ b/tests/test_ui_server_logs.py
@@ -6,6 +6,7 @@ from datetime import datetime
from config import paths
from vibe.ui_server import app
from vibe import runtime
+from tests.ui_server_test_helpers import csrf_headers
def _set_mtime(path, timestamp: str) -> None:
@@ -26,7 +27,7 @@ def test_logs_endpoint_returns_multiple_sources(monkeypatch, tmp_path):
(paths.get_runtime_dir() / "ui_stderr.log").write_text("UI boot failed\nTraceback line\n", encoding="utf-8")
client = app.test_client()
- response = client.post("/logs", json={"lines": 20, "source": "ui_stderr"})
+ response = client.post("/logs", json={"lines": 20, "source": "ui_stderr"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
@@ -71,7 +72,7 @@ def test_logs_endpoint_returns_aggregated_all_view(monkeypatch, tmp_path):
_set_mtime(ui_stderr_log, "2026-03-25 15:51:19")
client = app.test_client()
- response = client.post("/logs", json={"lines": 20, "source": "all"})
+ response = client.post("/logs", json={"lines": 20, "source": "all"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
@@ -121,7 +122,7 @@ def test_logs_endpoint_caps_aggregated_all_view_to_requested_lines(monkeypatch,
)
client = app.test_client()
- response = client.post("/logs", json={"lines": 2, "source": "all"})
+ response = client.post("/logs", json={"lines": 2, "source": "all"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
@@ -147,7 +148,7 @@ def test_logs_endpoint_keeps_traceback_exception_summary_with_error_entry(monkey
)
client = app.test_client()
- response = client.post("/logs", json={"lines": 20, "source": "service"})
+ response = client.post("/logs", json={"lines": 20, "source": "service"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
@@ -177,7 +178,7 @@ def test_logs_endpoint_preserves_recent_unstructured_logs_in_all_view(monkeypatc
_set_mtime(ui_stderr_log, "2026-03-25 15:51:19")
client = app.test_client()
- response = client.post("/logs", json={"lines": 2, "source": "all"})
+ response = client.post("/logs", json={"lines": 2, "source": "all"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
@@ -199,7 +200,7 @@ def test_logs_endpoint_falls_back_to_service_for_unknown_source(monkeypatch, tmp
)
client = app.test_client()
- response = client.post("/logs", json={"lines": 20, "source": "unknown"})
+ response = client.post("/logs", json={"lines": 20, "source": "unknown"}, headers=csrf_headers(client))
assert response.status_code == 200
payload = response.get_json()
diff --git a/tests/test_ui_server_mutation_protection.py b/tests/test_ui_server_mutation_protection.py
new file mode 100644
index 000000000..38e536585
--- /dev/null
+++ b/tests/test_ui_server_mutation_protection.py
@@ -0,0 +1,52 @@
+from __future__ import annotations
+
+from http.cookies import SimpleCookie
+
+from vibe.ui_server import app
+
+from tests.ui_server_test_helpers import csrf_headers
+
+
+def test_csrf_token_endpoint_returns_cookie_and_token():
+ client = app.test_client()
+ response = client.get("/api/csrf-token", base_url="http://127.0.0.1:15131")
+
+ assert response.status_code == 200
+ payload = response.get_json()
+ assert payload["ok"] is True
+ assert isinstance(payload["csrf_token"], str)
+ assert payload["csrf_token"]
+ cookie_header = response.headers.get("Set-Cookie", "")
+ assert "vibe_csrf_token=" in cookie_header
+ cookie = SimpleCookie()
+ cookie.load(cookie_header)
+ assert cookie["vibe_csrf_token"].value == payload["csrf_token"]
+
+
+def test_config_post_rejects_cross_origin():
+ client = app.test_client()
+ headers = csrf_headers(client, "http://127.0.0.1:15131")
+ headers["Origin"] = "http://evil.example"
+
+ response = client.post(
+ "/config",
+ json={"mode": "self_host"},
+ headers=headers,
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["message"] == "Forbidden: invalid origin"
+
+
+def test_config_post_rejects_missing_csrf_token():
+ client = app.test_client()
+ response = client.post(
+ "/config",
+ json={"mode": "self_host"},
+ headers={"Origin": "http://127.0.0.1:15131"},
+ base_url="http://127.0.0.1:15131",
+ )
+
+ assert response.status_code == 403
+ assert response.get_json()["message"] == "Forbidden: invalid csrf token"
diff --git a/tests/ui_server_test_helpers.py b/tests/ui_server_test_helpers.py
new file mode 100644
index 000000000..e3bbedd88
--- /dev/null
+++ b/tests/ui_server_test_helpers.py
@@ -0,0 +1,15 @@
+from __future__ import annotations
+
+from urllib.parse import urlparse
+
+
+def csrf_headers(client, base_url: str = "http://localhost") -> dict[str, str]:
+ response = client.get("/api/csrf-token", base_url=base_url)
+ assert response.status_code == 200
+ token = response.get_json()["csrf_token"]
+ hostname = urlparse(base_url).hostname or "localhost"
+ client.set_cookie("vibe_csrf_token", token, domain=hostname)
+ return {
+ "Origin": base_url,
+ "X-Vibe-CSRF-Token": token,
+ }
diff --git a/ui/src/components/Dashboard.tsx b/ui/src/components/Dashboard.tsx
index 6f238bdb9..66447c130 100644
--- a/ui/src/components/Dashboard.tsx
+++ b/ui/src/components/Dashboard.tsx
@@ -4,6 +4,7 @@ import { useStatus } from '../context/StatusContext';
import { Play, Square, RotateCw, Activity, Terminal, CheckCircle, MessageSquare, Server, Settings, Info } from 'lucide-react';
import { Link } from 'react-router-dom';
import { getEnabledPlatforms, getPrimaryPlatform } from '../lib/platforms';
+import { apiFetch } from '../lib/apiFetch';
export const Dashboard: React.FC = () => {
const { t } = useTranslation();
@@ -43,7 +44,7 @@ export const Dashboard: React.FC = () => {
wechat: newConfig.wechat,
agents: newConfig.agents,
};
- await fetch('/config', {
+ await apiFetch('/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
@@ -67,13 +68,13 @@ export const Dashboard: React.FC = () => {
ui: { ...(config.ui || {}), ...uiPayload },
};
// Save config first
- await fetch('/config', {
+ await apiFetch('/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(configPayload),
});
// Restart UI service
- await fetch('/ui/reload', {
+ await apiFetch('/ui/reload', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ host: uiPayload.setup_host, port: uiPayload.setup_port }),
@@ -101,7 +102,7 @@ export const Dashboard: React.FC = () => {
const configPayload = {
runtime: runtimePayload,
};
- await fetch('/config', {
+ await apiFetch('/config', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(configPayload),
@@ -124,7 +125,7 @@ export const Dashboard: React.FC = () => {
const nextConfig = await res.json();
setConfig(nextConfig);
}
- const doctorRes = await fetch('/doctor', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
+ const doctorRes = await apiFetch('/doctor', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
if (doctorRes.ok) {
setDoctor(await doctorRes.json());
}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index d17853275..e9299d5b0 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1,5 +1,6 @@
import React, { createContext, useContext } from 'react';
import { useToast } from './ToastContext';
+import { apiFetch } from '../lib/apiFetch';
export type ApiContextType = {
getConfig: () => Promise<any>;
@@ -121,7 +122,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
const getJson = async (path: string) => {
- const res = await fetch(path);
+ const res = await apiFetch(path);
if (!res.ok) {
await handleApiError(res, path);
}
@@ -129,7 +130,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
};
const postJson = async (path: string, payload: any) => {
- const res = await fetch(path, {
+ const res = await apiFetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
@@ -148,10 +149,10 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getUsers: (platform) => getJson(platform ? `/api/users?platform=${encodeURIComponent(platform)}` : '/api/users'),
saveUsers: (payload, platform) => postJson('/api/users', platform ? { ...payload, platform } : payload),
toggleAdmin: (userId, isAdmin, platform) => postJson(`/api/users/${encodeURIComponent(userId)}/admin`, platform ? { is_admin: isAdmin, platform } : { is_admin: isAdmin }),
- removeUser: (userId, platform) => fetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),
+ removeUser: (userId, platform) => apiFetch(platform ? `/api/users/${encodeURIComponent(userId)}?platform=${encodeURIComponent(platform)}` : `/api/users/${encodeURIComponent(userId)}`, { method: 'DELETE' }).then(r => r.json()),
getBindCodes: () => getJson('/api/bind-codes'),
createBindCode: (type, expiresAt) => postJson('/api/bind-codes', { type, expires_at: expiresAt }),
- deleteBindCode: (code) => fetch(`/api/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),
+ deleteBindCode: (code) => apiFetch(`/api/bind-codes/${encodeURIComponent(code)}`, { method: 'DELETE' }).then(r => r.json()),
getFirstBindCode: () => getJson('/api/setup/first-bind-code'),
detectCli: (binary) => getJson(`/cli/detect?binary=${encodeURIComponent(binary)}`),
installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),
diff --git a/ui/src/context/StatusContext.tsx b/ui/src/context/StatusContext.tsx
index 13b5099fe..955fd2b32 100644
--- a/ui/src/context/StatusContext.tsx
+++ b/ui/src/context/StatusContext.tsx
@@ -1,4 +1,5 @@
import React, { createContext, useContext, useEffect, useState } from 'react';
+import { apiFetch } from '../lib/apiFetch';
interface RuntimeStatus {
last_action?: string;
@@ -44,7 +45,7 @@ export const StatusProvider: React.FC<{ children: React.ReactNode }> = ({ childr
const control = async (action: string, payload: any = {}) => {
try {
- const res = await fetch('/control', {
+ const res = await apiFetch('/control', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action, ...payload }),
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
new file mode 100644
index 000000000..a30f36812
--- /dev/null
+++ b/ui/src/lib/apiFetch.ts
@@ -0,0 +1,63 @@
+const CSRF_COOKIE_NAME = 'vibe_csrf_token';
+const CSRF_HEADER_NAME = 'X-Vibe-CSRF-Token';
+const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
+
+let csrfTokenPromise: Promise<string> | null = null;
+
+function readCookie(name: string): string | null {
+ if (typeof document === 'undefined') {
+ return null;
+ }
+
+ const prefix = `${name}=`;
+ for (const part of document.cookie.split(';')) {
+ const trimmed = part.trim();
+ if (trimmed.startsWith(prefix)) {
+ return decodeURIComponent(trimmed.slice(prefix.length));
+ }
+ }
+ return null;
+}
+
+async function fetchCsrfToken(): Promise<string> {
+ const response = await fetch('/api/csrf-token', {
+ credentials: 'same-origin',
+ });
+ if (!response.ok) {
+ throw new Error(`Failed to fetch CSRF token (${response.status})`);
+ }
+ const payload = await response.json();
+ const token = typeof payload?.csrf_token === 'string' ? payload.csrf_token : '';
+ if (!token) {
+ throw new Error('Missing CSRF token in response');
+ }
+ return token;
+}
+
+export async function ensureCsrfToken(): Promise<string> {
+ const existing = readCookie(CSRF_COOKIE_NAME);
+ if (existing) {
+ return existing;
+ }
+
+ if (!csrfTokenPromise) {
+ csrfTokenPromise = fetchCsrfToken().finally(() => {
+ csrfTokenPromise = null;
+ });
+ }
+ return csrfTokenPromise;
+}
+
+export async function apiFetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
+ const method = (init.method || 'GET').toUpperCase();
+ const nextInit: RequestInit = { ...init };
+
+ if (MUTATING_METHODS.has(method)) {
+ const token = await ensureCsrfToken();
+ const headers = new Headers(init.headers || {});
+ headers.set(CSRF_HEADER_NAME, token);
+ nextInit.headers = headers;
+ }
+
+ return fetch(input, nextInit);
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 23f59fb0d..6810fb14d 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1,9 +1,10 @@
import asyncio
-import ipaddress
+import hmac
import json
import logging
import mimetypes
import re
+import secrets
import threading
from datetime import datetime
from pathlib import Path
@@ -33,6 +34,9 @@ LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")
TRACEBACK_EXCEPTION_PATTERN = re.compile(
r"^[A-Za-z_][\w.]*(?:Error|Exception|Warning|Exit|Interrupt|Failure|Fault|Group)(?:[:(]|$)"
)
+CSRF_COOKIE_NAME = "vibe_csrf_token"
+CSRF_HEADER_NAME = "X-Vibe-CSRF-Token"
+MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"}
LOG_SOURCES = (
("service", "vibe_remote.log", lambda: paths.get_logs_dir() / "vibe_remote.log"),
("service_stdout", "service_stdout.log", lambda: paths.get_runtime_dir() / "service_stdout.log"),
@@ -117,52 +121,67 @@ def _serialize_log_entries(entries: list[dict[str, Any]]) -> list[dict[str, str]
]
-def _trusted_ui_hosts() -> set[str]:
- hosts = {"localhost", "127.0.0.1", "::1"}
+def _new_csrf_token() -> str:
+ return secrets.token_urlsafe(32)
- try:
- from vibe import api
- config = api.load_config()
- except Exception as exc:
- logger.warning("Failed to load UI config for install endpoint trust check: %s", exc)
- return hosts
+def _request_origin(value: str | None) -> str | None:
+ if not value:
+ return None
- if isinstance(config, dict):
- setup_host = (config.get("ui") or {}).get("setup_host")
- else:
- setup_host = getattr(getattr(config, "ui", None), "setup_host", None)
- if not setup_host:
- return hosts
+ parsed = urlparse(value)
+ if not parsed.scheme or not parsed.netloc:
+ return None
+ return f"{parsed.scheme}://{parsed.netloc}"
- parsed = urlparse(setup_host if "://" in setup_host else f"http://{setup_host}")
- candidate = parsed.hostname or setup_host
- if not candidate:
- return hosts
- try:
- ip = ipaddress.ip_address(candidate)
- except ValueError:
- hosts.add(candidate)
- return hosts
+def _current_origin() -> str:
+ parsed = urlparse(request.host_url)
+ return f"{parsed.scheme}://{parsed.netloc}"
- if not ip.is_unspecified:
- hosts.add(str(ip))
- return hosts
+def _ensure_csrf_cookie(response: Response) -> Response:
+ if response.headers.getlist("Set-Cookie"):
+ for cookie_header in response.headers.getlist("Set-Cookie"):
+ if cookie_header.startswith(f"{CSRF_COOKIE_NAME}="):
+ return response
-def _is_private_or_loopback_host(hostname: str | None) -> bool:
- if not hostname:
- return False
- if hostname in {"localhost", "127.0.0.1", "::1"}:
- return True
+ token = request.cookies.get(CSRF_COOKIE_NAME)
+ if not token:
+ response.set_cookie(
+ CSRF_COOKIE_NAME,
+ _new_csrf_token(),
+ httponly=False,
+ secure=request.is_secure,
+ samesite="Strict",
+ path="/",
+ )
+ return response
- try:
- ip = ipaddress.ip_address(hostname)
- except ValueError:
- return False
- return ip.is_loopback or ip.is_private
+def protect_mutating_ui_requests():
+ if request.method not in MUTATING_METHODS:
+ return None
+
+ source = _request_origin(request.headers.get("Origin")) or _request_origin(request.headers.get("Referer"))
+ if not source:
+ return jsonify({"ok": False, "message": "Forbidden: missing origin header"}), 403
+
+ if source != _current_origin():
+ return jsonify({"ok": False, "message": "Forbidden: invalid origin"}), 403
+
+ csrf_cookie = request.cookies.get(CSRF_COOKIE_NAME, "")
+ csrf_header = request.headers.get(CSRF_HEADER_NAME, "")
+ if not csrf_cookie or not csrf_header or not hmac.compare_digest(csrf_cookie, csrf_header):
+ return jsonify({"ok": False, "message": "Forbidden: invalid csrf token"}), 403
+
+ return None
+
+
+def add_csrf_cookie(response: Response) -> Response:
+ return _ensure_csrf_cookie(response)
def _read_log_entries(log_path: Path, source_key: str, lines: int) -> tuple[list[dict[str, Any]], int]:
@@ -308,6 +327,21 @@ def settings_get():
return jsonify(api.get_settings(request.args.get("platform") or None))
[email protected]("/api/csrf-token", methods=["GET"])
+def csrf_token_get():
+ token = request.cookies.get(CSRF_COOKIE_NAME) or _new_csrf_token()
+ response = jsonify({"ok": True, "csrf_token": token})
+ response.set_cookie(
+ CSRF_COOKIE_NAME,
+ token,
+ httponly=False,
+ secure=request.is_secure,
+ samesite="Strict",
+ path="/",
+ )
+ return response
+
+
@app.route("/cli/detect")
def cli_detect():
from vibe import api
@@ -755,28 +789,7 @@ def codex_models():
@app.route("/agent/<name>/install", methods=["POST"])
def agent_install(name):
- """Install an agent CLI tool (opencode, claude, codex).
-
- Security: Only allow same-origin requests from the configured private setup host
- or localhost. This keeps the endpoint unavailable to arbitrary web pages while
- still working behind Docker/macOS port-forwarding where remote_addr is unstable.
- """
- # Security: Require Origin or Referer header for CSRF protection
- origin = request.headers.get("Origin")
- referer = request.headers.get("Referer")
- if not origin and not referer:
- return jsonify({"ok": False, "message": "Forbidden: missing origin header"}), 403
-
- # Validate Origin/Referer is from a trusted setup host.
- check_header = origin or referer
- parsed = urlparse(check_header)
- trusted_hosts = _trusted_ui_hosts()
- if parsed.hostname not in trusted_hosts:
- return jsonify({"ok": False, "message": "Forbidden: invalid origin"}), 403
-
- if not _is_private_or_loopback_host(parsed.hostname):
- return jsonify({"ok": False, "message": "Forbidden: local access only"}), 403
-
+ """Install an agent CLI tool (opencode, claude, codex)."""
# Security: Allowlist validation
allowed_agents = {"opencode", "claude", "codex"}
if name not in allowed_agents: