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(auth): expire remote capabilities at refresh

Maxvint2f882c736621
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 95007a7fc..8b5228500 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -154,6 +154,10 @@ def test_session_cookie_requires_signed_instance_role() -> None:
def test_authorization_claims_require_oidc_refresh() -> None:
now = 1_700_000_000
+ assert remote_access.session_authorization_refresh_deadline({"claims_issued_at": now}) == (
+ now + remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS
+ )
+ assert remote_access.session_authorization_refresh_deadline({"claims_issued_at": "invalid"}) is None
assert remote_access.session_needs_authorization_refresh(
{"claims_issued_at": now}, now=now + remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS - 1
) is False
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index ce8740a73..f5bfaf9d1 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -1428,6 +1428,39 @@ def test_terminal_websocket_unsupported_accepts_before_policy_close(monkeypatch)
assert websocket.calls == [("accept", None), ("close", 1008)]
+def test_terminal_websocket_closes_at_authorization_refresh_deadline(monkeypatch):
+ from vibe import remote_access
+
+ class BlockingTerminalService:
+ def start_reaper(self) -> None:
+ pass
+
+ async def handle_websocket(self, websocket, session_id, *, initial_cwd=None):
+ await asyncio.Event().wait()
+
+ monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)
+ monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda websocket: True)
+ monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda websocket, **kwargs: True)
+ monkeypatch.setattr(
+ ui_server,
+ "_remote_access_websocket_session_claims",
+ lambda websocket, config: {"sub": "remote-owner", "claims_issued_at": 1},
+ )
+ monkeypatch.setattr(remote_access, "session_authorization_refresh_deadline", lambda payload: 0)
+ monkeypatch.setattr(ui_server, "get_terminal_service", lambda: BlockingTerminalService())
+ websocket = _RecordingWebSocket()
+ websocket.client = None
+ websocket.query_params = {}
+
+ asyncio.run(ui_server.terminal_websocket(websocket, "test"))
+
+ assert websocket.calls == [
+ ("accept", None),
+ ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),
+ ]
+
+
def test_terminal_websocket_rejects_forwarded_request(monkeypatch, tmp_path):
monkeypatch.setenv("VIBE_UI_ENABLE_TERMINAL", "1")
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 7f9e0ce69..eebec61b7 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -1187,6 +1187,27 @@ def test_workbench_events_filter_privileged_events_for_viewers():
assert "hidden-secret" not in body
+def test_workbench_events_end_at_authorization_refresh_deadline():
+ from vibe.authorization import AuthorizationContext
+ from vibe.ui_compat import g
+
+ async def collect_until_expired() -> list[str | bytes]:
+ with app.test_request_context("/api/events"):
+ g.authorization_context = AuthorizationContext(instance_role="owner", is_remote=True)
+ g.remote_authorization_refresh_at = ui_server.time.time()
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ chunks = [await iterator.__anext__() for _ in range(3)]
+ with pytest.raises(StopAsyncIteration):
+ await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ finally:
+ await iterator.aclose()
+ return chunks
+
+ assert len(asyncio.run(collect_until_expired())) == 3
+
+
def test_json_api_gzip_skips_attachments_and_existing_encoding():
body = b'{"items":[' + (b'"payload",' * 300) + b'"end"]}'
attachment = ui_server.Response(
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 76c99bb0d..729fb3b32 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -1893,6 +1893,51 @@ def test_private_show_me_is_always_available(monkeypatch, tmp_path):
assert response.headers["cache-control"] == "no-store, private"
+def test_private_show_page_treats_remote_viewer_as_read_only(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _create_show_page("ses123", "private")
+ manager = _FakeShowRuntimeManager(
+ body=b'<!doctype html><html><body><script type="module" src="/src/main.tsx"></script></body></html>'
+ )
+ set_show_runtime_manager_for_tests(manager)
+ 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",
+ )
+ try:
+ me_response = client.get(
+ "/show/ses123/__show/me",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ page_response = client.get(
+ "/show/ses123/",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+
+ assert me_response.status_code == 200
+ assert me_response.get_json() == {"authenticated": False, "canAnnotate": False}
+ assert page_response.status_code == 200
+ body = page_response.content.decode("utf-8")
+ assert '"authenticated":false' in body
+ assert '"writeToken"' not in body
+ cookies = "\n".join(page_response.headers.getlist("set-cookie"))
+ assert "vibe_show_event_token=" in cookies
+ assert "Max-Age=0" in cookies
+
+
def test_public_show_me_is_anonymous_without_oauth_session(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index b7125e8fc..db9ae6cca 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -25,6 +25,7 @@ export type TerminalStatus = 'connecting' | 'ready' | 'closed' | 'disabled' | 'e
const ENC = new TextEncoder();
const MAX_BUSY_RETRIES = 3; // auto-retry a transient "busy" (1013) close this many times
+const AUTHORIZATION_REFRESH_CLOSE_CODE = 4401;
// The terminal window is theme-locked to dark (registry lockTheme: a shell is conventionally
// dark, like a code editor), so xterm carries a fixed dark palette regardless of the global theme.
@@ -334,6 +335,10 @@ export const TerminalView: React.FC<{
term.write(new Uint8Array(ev.data as ArrayBuffer));
};
ws.onclose = (ev: CloseEvent) => {
+ if (ev.code === AUTHORIZATION_REFRESH_CLOSE_CODE) {
+ window.location.reload();
+ return;
+ }
// 1013 = transient "try again shortly" (the session id is mid-open/teardown, or the cap
// is momentarily full). Auto-retry a few times with a short backoff before surfacing an
// error, so a reconnect that races a CLOSING teardown recovers on its own.
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index f7a8587b3..a0e9617e3 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -2084,15 +2084,24 @@ def session_needs_renewal(payload: dict[str, Any], now: int | None = None) -> bo
return int(payload.get("exp", 0)) - current < SESSION_TTL_SECONDS // 2
-def session_needs_authorization_refresh(payload: Mapping[str, Any], now: int | None = None) -> bool:
- """Return whether authorization claims must be refreshed through OIDC."""
+def session_authorization_refresh_deadline(payload: Mapping[str, Any]) -> int | None:
+ """Return the wall-clock deadline for refreshing signed authorization claims."""
- current = now if now is not None else int(time.time())
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_AUTHORIZATION_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:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 3417291f1..004ffe0ec 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -118,6 +118,7 @@ _SHOW_RUNTIME_COMPRESSIBLE_MIN_BYTES = 1024
TERMINAL_ENABLED_ENV = "VIBE_UI_ENABLE_TERMINAL"
TERMINAL_IDLE_TIMEOUT_ENV = "VIBE_UI_TERMINAL_IDLE_TIMEOUT_SECONDS"
TERMINAL_MAX_SESSIONS_ENV = "VIBE_UI_TERMINAL_MAX_SESSIONS"
+_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE = 4401
_TRUE_BOOL_STRINGS = {"1", "true", "yes", "on"}
STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")
@@ -2125,6 +2126,7 @@ def enforce_remote_access_cookie():
return _redirect_to_vibe_cloud_login(config)
return jsonify({"ok": False, "error": "remote_access_authorization_refresh_required"}), 401
g.authorization_context = context_from_session_payload(payload)
+ g.remote_authorization_refresh_at = remote_access.session_authorization_refresh_deadline(payload)
if remote_access.session_needs_renewal(payload):
g.remote_session_renew = payload
return None
@@ -2513,8 +2515,18 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
return
await websocket.accept()
+ config = _load_remote_access_config()
+ remote_payload = _remote_access_websocket_session_claims(websocket, config)
remote_addr = _websocket_client_host(websocket) or "unknown"
- remote_subject = _remote_access_websocket_subject(websocket)
+ remote_subject = None
+ authorization_refresh_at = None
+ if remote_payload is not None:
+ from vibe import remote_access
+
+ subject = str(remote_payload.get("sub") or "").strip()
+ email = str(remote_payload.get("email") or "").strip()
+ remote_subject = subject or email or None
+ authorization_refresh_at = remote_access.session_authorization_refresh_deadline(remote_payload)
effective_session_id = _terminal_effective_session_id(session_id, remote_subject)
session_ref = _terminal_session_log_ref(effective_session_id)
logger.info("terminal.session_open session_ref=%s remote_addr=%s", session_ref, remote_addr)
@@ -2525,7 +2537,15 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):
try:
service = get_terminal_service()
service.start_reaper()
- await service.handle_websocket(websocket, effective_session_id, initial_cwd=initial_cwd)
+ handler = service.handle_websocket(websocket, effective_session_id, initial_cwd=initial_cwd)
+ if authorization_refresh_at is None:
+ await handler
+ else:
+ timeout = max(0.0, authorization_refresh_at - time.time())
+ await asyncio.wait_for(handler, timeout=timeout)
+ except asyncio.TimeoutError:
+ logger.info("terminal.authorization_refresh session_ref=%s", session_ref)
+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)
except TerminalServiceError as exc:
# Transient "try again shortly" conditions (not server faults): too_many_sessions (cap
# full) and session_opening (the id is mid-open or mid-teardown). Close with 1013 so
@@ -2599,6 +2619,19 @@ def _show_runtime_hmr_origin_allowed(websocket: Any) -> bool:
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):
@@ -2611,8 +2644,6 @@ def _remote_access_websocket_session_payload(websocket: Any, config: V2Config |
config,
websocket.cookies.get(remote_access.SESSION_COOKIE_NAME),
)
- if payload is None or remote_access.session_needs_authorization_refresh(payload):
- return None
return payload
@@ -8079,6 +8110,7 @@ async def workbench_events():
from vibe.sse_broker import broker
authorization_context = getattr(g, "authorization_context", None)
+ authorization_refresh_at = getattr(g, "remote_authorization_refresh_at", None)
async def generate():
sub_id, queue = broker.subscribe()
@@ -8097,12 +8129,20 @@ async def workbench_events():
)
yield f"event: {WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT}\ndata: {payload}\n\n"
while True:
+ wait_timeout = 15.0
+ if authorization_refresh_at is not None:
+ remaining = authorization_refresh_at - time.time()
+ if remaining <= 0:
+ return
+ wait_timeout = min(wait_timeout, remaining)
try:
- event_type, payload = await asyncio.wait_for(queue.get(), timeout=15.0)
+ event_type, payload = await asyncio.wait_for(queue.get(), timeout=wait_timeout)
if not can_receive_workbench_event(authorization_context, event_type):
continue
yield f"event: {event_type}\ndata: {payload}\n\n"
except asyncio.TimeoutError:
+ if authorization_refresh_at is not None and time.time() >= authorization_refresh_at:
+ return
# 15s keep-alive — Cloudflare Tunnel default idle is well
# below 100s but this still keeps mid-tier proxies happy.
yield ": ping\n\n"
@@ -9094,6 +9134,15 @@ def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
from vibe import remote_access
from vibe.authorization import context_from_session_payload
+ if not public:
+ context = getattr(g, "authorization_context", None)
+ if context is not None:
+ if not context.has_role("editor"):
+ return None
+ if context.is_remote:
+ return {"kind": "user", "email": context.email} if context.email else None
+ return {"kind": "local"}
+
config = _load_remote_access_config()
if config is not None:
session = remote_access.parse_session_cookie(
@@ -9105,9 +9154,11 @@ def _show_request_author(*, public: bool = False) -> dict[str, str] | None:
if session is not None and not remote_access.session_needs_authorization_refresh(session)
else None
)
- email = str(session.get("email", "")).strip() if context is not None else ""
- if email and context.has_role("editor"):
- return {"kind": "user", "email": email}
+ if context is not None:
+ email = str(session.get("email", "")).strip()
+ if email and context.has_role("editor"):
+ return {"kind": "user", "email": email}
+ return None
cloud = config.remote_access.vibe_cloud
if public and cloud.enabled:
@@ -9789,7 +9840,7 @@ async def _show_page_runtime_response(
show_config_session_id or session_id,
base_path=base_path,
authenticated=show_authenticated,
- include_write_token=external_prefix is None,
+ include_write_token=external_prefix is None and show_authenticated,
)
if external_prefix:
response_headers["Referrer-Policy"] = "same-origin"
@@ -10254,12 +10305,14 @@ async def serve_private_show_page(session_id, asset_path):
return _show_page_not_found_response()
if _is_show_page_runtime_denied_path(asset_path, session_id=page.session_id):
return _show_page_file_not_found_response()
+ show_author = _show_request_author()
+ can_annotate = show_author is not None
if asset_path.strip("/") == "__show/me":
if request.method not in {"GET", "HEAD"}:
return jsonify({"ok": False, "code": "method_not_allowed"}), 405
return _show_me_response(
- {"kind": "local"},
- write_token=show_event_write_token(page.session_id),
+ show_author,
+ write_token=show_event_write_token(page.session_id) if can_annotate else None,
)
if asset_path.strip("/") in {"__show/events", "__events"}:
return await _show_events_response(page.session_id)
@@ -10273,7 +10326,7 @@ async def serve_private_show_page(session_id, asset_path):
asset_path,
starlette_request,
inject_show_config=request.method == "GET" and not _is_show_api_asset(asset_path),
- show_authenticated=True,
+ show_authenticated=can_annotate,
)
except Exception:
if _is_show_api_asset(asset_path) or _is_show_annotation_asset(asset_path):
@@ -10293,7 +10346,7 @@ async def serve_private_show_page(session_id, asset_path):
if request.method in {"GET", "HEAD"}:
if _is_show_runtime_immutable_asset_path(asset_path):
return response
- return _with_show_event_write_cookie(response, page.session_id, enabled=True)
+ return _with_show_event_write_cookie(response, page.session_id, enabled=can_annotate)
return response
finally:
store.close()