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.

merge(remote-access): integrate custom hostname heartbeat into org

Max7163df43fa66
diff --cc tests/test_remote_access_vibe_cloud.py
index 2db1188db,da3651c72..e988a8ce0
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@@ -1102,6 -949,6 +1130,18 @@@ def test_ra_tq_007_runtime_status_paylo
assert payload["tunnel_quality"]["grade"] == "good"
++def test_runtime_status_payload_omits_unknown_observed_origin(monkeypatch, tmp_path) -> None:
++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
++ config = _config()
++ monkeypatch.setattr(remote_access, "_local_ui_healthy", lambda cfg: True)
++ monkeypatch.setattr(remote_access, "status", lambda cfg: {"running": True, "binary_found": True})
++ monkeypatch.setattr(remote_access, "_observed_cloudflared_origin_service", lambda: None)
++
++ payload = remote_access.runtime_status_payload(config, event="heartbeat")
++
++ assert "observed_origin_service" not in payload
++
++
def test_observed_cloudflared_origin_service_reads_only_log_tail(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
remote_access._cloudflared_stderr_path().parent.mkdir(parents=True, exist_ok=True)
diff --cc tests/test_ui_remote_access_auth.py
index 05672bb72,db0b4a124..e6414c62a
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@@ -138,6 -119,136 +138,130 @@@ def test_remote_host_redirects_to_vibe_
assert state_payload["retry"] is False
+ def test_custom_hostname_uses_remote_auth_until_heartbeat_removes_it(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ responses = iter(
+ [
+ {"ok": True, "active_hostnames": ["max.fileguard.io"]},
+ {"ok": True, "active_hostnames": []},
+ ]
+ )
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: next(responses))
+ client = app.test_client()
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ allowed = client.get(
+ "/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert allowed.status_code == 302
+ assert httpx.URL(allowed.headers["Location"]).params["redirect_uri"] == (
+ "https://max.fileguard.io/auth/callback"
+ )
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ removed = client.get(
+ "/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert removed.status_code == 503
+ assert removed.get_json()["error"] == "remote_access_host_mismatch"
+
+
+ def test_persisted_custom_hostname_is_allowed_before_process_cache_warms(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ remote_access._clear_active_hostnames_cache()
+
+ response = app.test_client().get(
+ "/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert remote_access.active_hostnames(config) == frozenset({"max.fileguard.io"})
+
+
+ def test_custom_hostname_oauth_flow_reuses_redirect_uri_for_exchange(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ client = app.test_client()
+
+ login = client.get(
+ "/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+ authorize_params = httpx.URL(login.headers["Location"]).params
+ oauth_cookie_header = next(
+ header
+ for header in login.headers.getlist("Set-Cookie")
+ if header.startswith(f"{ui_server.REMOTE_OAUTH_COOKIE_NAME}=")
+ )
+ oauth_cookie = oauth_cookie_header.split(";", 1)[0].split("=", 1)[1]
+ handshake = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)
+ assert handshake is not None
+ state_payload = ui_server._read_oauth_state(
+ config.remote_access.vibe_cloud.session_secret,
+ authorize_params["state"],
+ )
+ assert state_payload is not None
+ stored = remote_access._oauth_handshakes[state_payload["r"]]
+
+ assert authorize_params["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+ assert handshake["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+ assert stored["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+
+ exchanged = {}
+
+ def exchange(cfg, code, verifier, redirect_uri=None):
+ exchanged.update({"code": code, "verifier": verifier, "redirect_uri": redirect_uri})
- return {
- "claims": {
- "email": "[email protected]",
- "sub": "user-1",
- "nonce": handshake["nonce"],
- }
- }
++ return _oauth_exchange_result(cfg, nonce=handshake["nonce"])
+
+ monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)
+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="max.fileguard.io")
+
+ callback = client.get(
+ f"/auth/callback?code=test-code&state={authorize_params['state']}",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert callback.status_code == 302
+ assert callback.headers["Location"] == "/dashboard"
+ assert exchanged == {
+ "code": "test-code",
+ "verifier": handshake["code_verifier"],
+ "redirect_uri": "https://max.fileguard.io/auth/callback",
+ }
+
+
+ def test_oauth_redirect_uri_falls_back_for_unlisted_request_host(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+
+ with app.test_request_context("/dashboard", base_url="https://unlisted.example"):
+ response = ui_server._redirect_to_vibe_cloud_login(config)
+
+ params = httpx.URL(response.headers["Location"]).params
+ assert params["redirect_uri"] == config.remote_access.vibe_cloud.redirect_uri
+
+
def test_login_redirect_sets_persistent_handshake_cookie(monkeypatch, tmp_path):
# iOS standalone PWAs drop session-scoped cookies (no Max-Age) across the
# cross-origin authorize excursion, so the callback can't read the handshake
@@@ -1266,6 -1195,29 +1390,34 @@@ def test_remote_config_post_accepts_pub
assert response.status_code == 200
+ def test_custom_hostname_config_post_accepts_same_origin(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
- remote_access.make_session_cookie(config, "[email protected]", "user-1"),
++ remote_access.make_session_cookie(
++ config,
++ "user-1",
++ session_claims=_oauth_exchange_result(config, nonce="unused")["session_claims"],
++ ),
+ domain="max.fileguard.io",
+ )
+ headers = csrf_headers(client, "https://max.fileguard.io")
+
+ response = client.post(
+ "/api/config",
+ json=api.config_to_payload(config),
+ headers=headers,
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ )
+
+ assert response.status_code == 200
+
+
def test_config_post_returns_saved_config_when_remote_reconcile_fails(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@@ -1349,7 -1301,13 +1501,10 @@@ def test_remote_callback_rejects_nonce_
monkeypatch.setattr(
remote_access,
"exchange_oauth_code",
- lambda cfg, code, verifier: _oauth_exchange_result(cfg, nonce="wrong-nonce"),
- lambda cfg, code, verifier, redirect_uri=None: {
- "claims": {
- "email": "[email protected]",
- "sub": "user-1",
- "nonce": "wrong-nonce",
- }
- },
++ lambda cfg, code, verifier, redirect_uri=None: _oauth_exchange_result(
++ cfg,
++ nonce="wrong-nonce",
++ ),
)
state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]
@@@ -1363,58 -1321,6 +1518,58 @@@
assert 'href="/dashboard"' in response.text
+def test_remote_callback_externalizes_large_organization_claims(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+
+ with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):
+ redirect = ui_server._redirect_to_vibe_cloud_login(config)
+ oauth_cookie = redirect.headers["Set-Cookie"].split(";", 1)[0].split("=", 1)[1]
+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")
+ oauth_state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)
+ group_ids = [f"00000000-0000-4000-8000-{index:012d}" for index in range(100)]
+
+ monkeypatch.setattr(
+ remote_access,
+ "exchange_oauth_code",
- lambda cfg, code, verifier: {
++ lambda cfg, code, verifier, redirect_uri=None: {
+ "claims": {
+ "email": "[email protected]",
+ "sub": "user-1",
+ "nonce": oauth_state["nonce"],
+ },
+ "session_claims": {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": group_ids,
+ },
+ },
+ )
+
+ response = client.get(
+ f"/auth/callback?code=test-code&state={oauth_state['state']}",
+ base_url="https://alex.avibe.bot",
+ )
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/dashboard"
+ session_header = next(
+ header
+ for header in response.headers.getlist("Set-Cookie")
+ if header.startswith(f"{remote_access.SESSION_COOKIE_NAME}=")
+ )
+ session_cookie = session_header.split(";", 1)[0].split("=", 1)[1]
+ assert len(session_cookie.encode("ascii")) <= remote_access.SESSION_COOKIE_MAX_VALUE_BYTES
+ payload = remote_access.parse_session_cookie(config, session_cookie)
+ assert payload is not None
+ assert payload["vibe_group_ids"] == group_ids
+
+
def test_remote_callback_explains_pairing_mismatch(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
@@@ -1677,9 -1584,10 +1833,10 @@@ def test_remote_callback_recovers_via_s
captured = {}
- def exchange(cfg, code, verifier):
+ def exchange(cfg, code, verifier, redirect_uri=None):
captured["verifier"] = verifier
+ captured["redirect_uri"] = redirect_uri
- return {"claims": {"email": "[email protected]", "sub": "user-1", "nonce": "nonce-approved"}}
+ return _oauth_exchange_result(cfg, nonce="nonce-approved")
monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)
@@@ -1997,9 -1906,15 +2155,9 @@@ def test_remote_callback_accepts_html_e
exchange_calls = []
client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="alex.avibe.bot")
- def exchange(cfg, code, verifier):
+ def exchange(cfg, code, verifier, redirect_uri=None):
exchange_calls.append((code, verifier))
- return {
- "claims": {
- "email": "[email protected]",
- "sub": "user-1",
- "nonce": "nonce-1",
- }
- }
+ return _oauth_exchange_result(cfg, nonce="nonce-1")
monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)
@@@ -2029,7 -1944,13 +2187,10 @@@ def test_remote_callback_sanitizes_prot
monkeypatch.setattr(
remote_access,
"exchange_oauth_code",
- lambda cfg, code, verifier: _oauth_exchange_result(cfg, nonce="nonce-1"),
- lambda cfg, code, verifier, redirect_uri=None: {
- "claims": {
- "email": "[email protected]",
- "sub": "user-1",
- "nonce": "nonce-1",
- }
- },
++ lambda cfg, code, verifier, redirect_uri=None: _oauth_exchange_result(
++ cfg,
++ nonce="nonce-1",
++ ),
)
response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")
@@@ -2315,38 -2236,39 +2476,76 @@@ def test_terminal_websocket_accepts_rem
assert accepted is True
[email protected](not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+def test_terminal_websocket_rejects_remote_viewer(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "user-viewer",
+ role="viewer",
+ access_source="email",
+ ),
+ domain="alex.avibe.bot",
+ )
+
+ with pytest.raises(WebSocketDisconnect) as exc:
+ with client.websocket_connect(
+ "wss://alex.avibe.bot/api/terminal/test",
+ headers={
+ "host": "alex.avibe.bot",
+ "origin": "https://alex.avibe.bot",
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert exc.value.code == 1008
+
+
+ @pytest.mark.skipif(not ui_server.TERMINAL_SUPPORTED, reason="terminal requires a POSIX pty")
+ def test_terminal_websocket_accepts_active_custom_hostname(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ accepted = False
+
+ async def fake_handle_websocket(websocket, session_id, *, initial_cwd=None):
+ nonlocal accepted
+ accepted = True
+
+ monkeypatch.setattr(ui_server.get_terminal_service(), "handle_websocket", fake_handle_websocket)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
- remote_access.make_session_cookie(config, "[email protected]", "user-1"),
++ remote_access.make_session_cookie(
++ config,
++ "user-1",
++ session_claims=_oauth_exchange_result(config, nonce="unused")["session_claims"],
++ ),
+ domain="max.fileguard.io",
+ )
+
+ with client.websocket_connect(
+ "wss://max.fileguard.io/api/terminal/test",
+ headers={
+ "host": "max.fileguard.io",
+ "origin": "https://max.fileguard.io",
+ "x-forwarded-for": "203.0.113.10",
+ },
+ ):
+ pass
+
+ assert accepted is True
+
+
def test_terminal_effective_session_id_scopes_remote_subjects():
client_id = "shared-session"
diff --cc vibe/remote_access.py
index f2ec8c9a6,f3ed032e0..5f026d231
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@@ -543,6 -611,6 +623,7 @@@ def _local_ui_healthy(config: V2Config
def runtime_status_payload(config: V2Config | None = None, event: str = "heartbeat", last_error: str | None = None) -> dict[str, Any]:
config = config or V2Config.load()
current = status(config)
++ observed_origin_service = _observed_cloudflared_origin_service()
payload = {
"event": event,
"local_version": "dev",
@@@ -550,8 -618,8 +631,9 @@@
"tunnel_running": bool(current.get("running")),
"cloudflared_found": bool(current.get("binary_found")),
"expected_origin_service": origin_service_for_pairing(config),
-- "observed_origin_service": _observed_cloudflared_origin_service(),
}
++ if observed_origin_service:
++ payload["observed_origin_service"] = observed_origin_service
quality = current.get("tunnel_quality")
if isinstance(quality, dict) and quality.get("schema_version") == 1:
payload["tunnel_quality"] = quality
@@@ -2689,21 -2642,20 +2774,27 @@@ def session_authorization_refresh_deadl
try:
claims_issued_at = int(payload.get("claims_issued_at", payload.get("iat", 0)))
except (TypeError, ValueError):
- return True
- return claims_issued_at <= 0 or current - claims_issued_at >= SESSION_ORGANIZATION_REFRESH_SECONDS
+ return None
+ if claims_issued_at <= 0:
+ return None
+ return claims_issued_at + SESSION_AUTHORIZATION_REFRESH_SECONDS
+
+
+def session_needs_authorization_refresh(payload: Mapping[str, Any], now: int | None = None) -> bool:
+ """Return whether authorization claims must be refreshed through OIDC."""
+
+ current = now if now is not None else int(time.time())
+ deadline = session_authorization_refresh_deadline(payload)
+ return deadline is None or current >= deadline
- def authorization_url(config: V2Config, state: str, nonce: str, code_challenge: str) -> str:
+ def authorization_url(
+ config: V2Config,
+ state: str,
+ nonce: str,
+ code_challenge: str,
+ redirect_uri: str | None = None,
+ ) -> str:
cloud = config.remote_access.vibe_cloud
params = {
"client_id": cloud.client_id,
diff --cc vibe/ui_server.py
index 6e614c4da,6ab6acf41..82c1b583c
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@@ -2734,50 -2572,9 +2777,50 @@@ def _show_runtime_websocket_authorized
return _websocket_is_local_request(websocket)
if _websocket_is_local_request(websocket, config):
return True
- if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
+ if not _remote_access_host_allowed(config, _websocket_normalized_host(websocket)):
return False
- return _remote_access_websocket_session_payload(websocket, config) is not None
+ payload = _remote_access_websocket_session_payload(websocket, config)
+ if payload is None:
+ return False
+ from vibe.authorization import context_from_session_payload
+
+ context = context_from_session_payload(payload)
+ if not context.has_role(minimum_role):
+ return False
+ if project_session_id is None or context.is_instance_owner:
+ return True
+ return _project_session_access_allowed(context, project_session_id, minimum_role)
+
+
+def _project_session_access_allowed(context: Any, session_id: str, minimum_role: str) -> bool:
+ from storage import project_access_service
+
+ if context is None or context.is_instance_owner:
+ return True
+ if not context.has_role(minimum_role):
+ return False
+ engine = _projects_engine()
+ with engine.connect() as conn:
+ role = project_access_service.get_effective_session_role(
+ conn,
+ context,
+ session_id,
+ )
+ return project_access_service.role_allows(role, minimum_role)
+
+
+async def _wait_for_project_session_access_loss(
+ queue: Any,
+ context: Any,
+ session_id: str,
+ minimum_role: str,
+) -> None:
+ while True:
+ event_type, _payload = await queue.get()
+ if event_type != "authorization.changed":
+ continue
+ if not _project_session_access_allowed(context, session_id, minimum_role):
+ return
def _show_runtime_websocket_resource_context(websocket: Any):
@@@ -2806,22 -2603,9 +2849,22 @@@ def _show_runtime_hmr_origin_allowed(we
def _remote_access_websocket_session_payload(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
+ payload = _remote_access_websocket_session_claims(websocket, config)
+ if payload is None:
+ return None
+ from vibe import remote_access
+
+ if remote_access.session_needs_authorization_refresh(payload):
+ return None
+ return payload
+
+
+def _remote_access_websocket_session_claims(websocket: Any, config: V2Config | None) -> dict[str, Any] | None:
+ """Return valid signed remote claims without applying their refresh deadline."""
+
if config is None or _websocket_is_local_request(websocket, config):
return None
- if _websocket_normalized_host(websocket) != _remote_access_public_host(config):
+ if not _remote_access_host_allowed(config, _websocket_normalized_host(websocket)):
return None
from vibe import remote_access