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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(auth): revoke stale remote sessions
Maxvintf68262515297
diff --git a/docs/plans/issue-1057-remote-session-revocation.md b/docs/plans/issue-1057-remote-session-revocation.mdnew file mode 100644index 000000000..1c548099f--- /dev/null+++ b/docs/plans/issue-1057-remote-session-revocation.md@@ -0,0 +1,65 @@+# Remote Session Revocation++## Background++Remote sessions currently retain an instance role and Organization membership+claims until their scheduled OIDC refresh. A hosted access downgrade can+therefore leave an already signed editor session active on every hostname that+serves the paired Instance.++## Goal++Invalidate remote authorization promptly after any hosted change that can alter+the effective Instance decision, while preserving owner-equivalent trusted+local access.++## Revision Contract++- The control plane owns a monotonic, non-negative revision for the effective+ authorization state of each Instance.+- Every OIDC decision includes that value as+ `vibe_instance_authorization_revision`.+- A paired device reads the current value from+ `GET /api/v1/instances/{instance_id}/authorization-revision`, authenticated by+ `X-Vibe-Device-Secret`. The response is+ `{ "authorization_revision": <integer> }`.+- The control plane advances the revision after member removal, granting-group+ removal or archival, role downgrade, and Instance access-binding removal.+- The runtime persists only monotonically newer device snapshots. A remote+ session is current only when its signed revision exactly matches a fresh+ device snapshot. Missing, malformed, stale, or expired revision state fails+ closed for paired remote access.++The revision is Instance-wide. Advancing it can require unaffected remote users+to reauthorize, but it guarantees that the default and custom hostnames share+one decision and avoids retaining hosted membership data in the local runtime.++## Enforcement++- HTTP and newly opened pages validate the revision while parsing the session.+- Session renewal preserves the OIDC revision and cannot stamp stale claims+ with a newer device revision.+- Workbench and Show Page SSE streams re-check the revision while connected.+- Private Show Page and terminal WebSockets race their normal handler against+ revision loss, so resumed connections close and reconnect through current+ authorization.+- Trusted local requests never consult the hosted revision snapshot.++## Acceptance Evidence++- `I1057-AC1`: editor downgrade removes mutation capability.+- `I1057-AC2`: member and granting-group removal invalidate active sessions.+- `I1057-AC3`: sessions on default and custom hostnames share one watermark.+- `I1057-AC4`: HTTP, SSE, and WebSocket paths re-check the same state.+- `I1057-AC5`: trusted local access remains owner-equivalent offline.+- `I1057-AC6`: stale revisions, reconnects, and all revocation causes have+ automated coverage.+- `I1057-AC7`: staging E2E remains a deployment-level manual check after the+ matching control-plane revision contract is available.++## Todo++- [x] Persist and poll the paired-device revision.+- [x] Bind remote sessions to the signed OIDC revision.+- [x] Re-check revision state on HTTP, SSE, and WebSocket paths.+- [x] Add focused unit and contract tests.diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex e988a8ce0..0f59ce7d5 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -66,12 +66,16 @@ def _config() -> V2Config:return config-def _session_claims(config: V2Config, *, role: str = "owner") -> dict[str, str]:- return {+def _session_claims(config: V2Config, *, role: str = "owner") -> dict[str, str | int]:+ claims = {"vibe_instance_id": config.remote_access.vibe_cloud.instance_id,"vibe_instance_role": role,"vibe_instance_access_source": "owner",}+ cloud = config.remote_access.vibe_cloud+ if cloud.instance_secret and cloud.backend_url:+ claims["vibe_instance_authorization_revision"] = 1+ return claimsdef _session_cookie(@@ -2238,6 +2242,7 @@ def test_mint_cloud_token_returns_none_on_backend_error(monkeypatch) -> None:def test_cloud_token_for_request_mints_for_authenticated_user(monkeypatch) -> None:config = _cloud_broker_config()+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)cookie = _session_cookie(config)monkeypatch.setattr(@@ -2269,6 +2274,7 @@ def test_cloud_token_for_request_returns_none_without_valid_session(monkeypatch)def test_cloud_token_for_request_rejects_stale_authorization_claims(monkeypatch) -> None:config = _cloud_broker_config()+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)cookie = _session_cookie(config)called = False@@ -2290,6 +2296,7 @@ def test_cloud_token_for_request_rejects_stale_authorization_claims(monkeypatch)def test_cloud_token_for_request_requires_editor_role(monkeypatch) -> None:config = _cloud_broker_config()+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *a, **k: 1)cookie = _session_cookie(config, role="viewer")called = Falsediff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.pynew file mode 100644index 000000000..812df124a--- /dev/null+++ b/tests/test_remote_authorization_revision.py@@ -0,0 +1,407 @@+from __future__ import annotations++import asyncio+import time+from typing import Any++import pytest++from config.v2_config import (+ AgentsConfig,+ PlatformsConfig,+ RemoteAccessConfig,+ RuntimeConfig,+ SlackConfig,+ UiConfig,+ V2Config,+)+from tests.ui_server_test_helpers import csrf_headers+from vibe import remote_access, ui_server+from vibe.authorization import context_from_session_payload+from vibe.ui_compat import g+from vibe.ui_server import app+++def _paired_config(tmp_path, *, revision: int = 41) -> V2Config:+ config = V2Config(+ mode="self_host",+ version="v2",+ platform="slack",+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),+ slack=SlackConfig(bot_token=""),+ runtime=RuntimeConfig(default_cwd="."),+ agents=AgentsConfig(),+ ui=UiConfig(),+ remote_access=RemoteAccessConfig(),+ )+ cloud = config.remote_access.vibe_cloud+ cloud.enabled = True+ cloud.backend_url = "https://backend.test"+ cloud.public_url = "https://alex.avibe.bot"+ cloud.client_id = "vr_client_123"+ cloud.instance_id = "inst_123"+ cloud.instance_secret = "instance-secret"+ cloud.session_secret = "session-secret"+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"+ config.save()+ remote_access._clear_authorization_revision_cache()+ remote_access._replace_authorization_revision(config, revision)+ return config+++def _organization_claims(+ config: V2Config,+ *,+ revision: int = 41,+ role: str = "editor",+) -> dict[str, Any]:+ return {+ "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,+ "vibe_instance_role": role,+ "vibe_instance_access_source": "organization_group",+ "vibe_instance_authorization_revision": revision,+ "vibe_organization_id": "org_123",+ "vibe_organization_member_id": "member_123",+ "vibe_organization_role": "member",+ "vibe_group_ids": ["group_research"],+ "vibe_membership_version": "membership-v1",+ }+++def _organization_cookie(+ config: V2Config,+ *,+ revision: int = 41,+ subject: str = "user-1",+) -> str:+ return remote_access.make_session_cookie(+ config,+ f"{subject}@example.com",+ subject,+ session_claims=_organization_claims(config, revision=revision),+ )+++def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_path):+ """I1057-AC2/AC3: one paired-device watermark drives every hostname."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ calls = []++ def request(cfg, method, suffix, payload=None, *, timeout=8.0):+ calls.append((cfg, method, suffix, payload, timeout))+ return {"authorization_revision": 42}++ monkeypatch.setattr(remote_access, "_device_json_request", request)++ assert remote_access.sync_authorization_revision_once(config) == {+ "ok": True,+ "authorization_revision": 42,+ }+ assert calls == [(config, "GET", "authorization-revision", None, 8.0)]+ assert remote_access.current_authorization_revision(config) == 42++ monkeypatch.setattr(+ remote_access,+ "_device_json_request",+ lambda *args, **kwargs: {"authorization_revision": 41},+ )+ assert remote_access.sync_authorization_revision_once(config) == {+ "ok": False,+ "error": "authorization_revision_regressed",+ }+ assert remote_access.current_authorization_revision(config) == 42+++def test_paired_session_requires_signed_current_revision(monkeypatch, tmp_path):+ """I1057-AC4: unsigned, missing, and stale authorization versions fail closed."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ missing = _organization_claims(config)+ missing.pop("vibe_instance_authorization_revision")++ with pytest.raises(+ remote_access.OAuthCodeExchangeError,+ match="invalid_authorization_revision",+ ):+ remote_access.make_session_cookie(+ config,+ "[email protected]",+ "user-1",+ session_claims=missing,+ )++ with pytest.raises(+ remote_access.OAuthCodeExchangeError,+ match="stale_authorization_revision",+ ):+ _organization_cookie(config, revision=40)+++ "hosted_change",+ [+ "role_downgrade",+ "group_membership_removal",+ "group_archival",+ "member_removal",+ "access_binding_removal",+ ],+)+def test_revision_advance_revokes_active_editor_http_session(+ monkeypatch,+ tmp_path,+ hosted_change,+):+ """I1057-AC1/AC2: every narrowing cause revokes active editor mutations."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ cookie = _organization_cookie(config)+ payload = remote_access.parse_session_cookie(config, cookie)+ assert payload is not None+ assert context_from_session_payload(payload).can_chat is True++ client = app.test_client()+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")+ headers = csrf_headers(client, "https://alex.avibe.bot")+ before = client.post(+ "/api/sessions",+ base_url="https://alex.avibe.bot",+ headers=headers,+ json={},+ )+ assert before.status_code == 400++ assert hosted_change+ remote_access._replace_authorization_revision(config, 42)+ after = client.post(+ "/api/sessions",+ base_url="https://alex.avibe.bot",+ headers=headers,+ json={},+ )++ assert after.status_code == 401+ assert after.get_json()["error"] == "remote_access_login_required"+++def test_default_and_custom_hostname_sessions_share_revision(monkeypatch, tmp_path):+ """I1057-AC3: host-scoped cookies cannot retain divergent authorization."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])+ default_client = app.test_client()+ custom_client = app.test_client()+ default_client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(config, subject="default-user"),+ domain="alex.avibe.bot",+ )+ custom_client.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _organization_cookie(config, subject="custom-user"),+ domain="max.fileguard.io",+ )++ assert default_client.get(+ "/api/session",+ base_url="https://alex.avibe.bot",+ ).get_json()["authenticated"] is True+ assert custom_client.get(+ "/api/session",+ base_url="https://max.fileguard.io",+ ).get_json()["authenticated"] is True++ remote_access._replace_authorization_revision(config, 42)++ assert default_client.get(+ "/api/session",+ base_url="https://alex.avibe.bot",+ ).get_json()["authenticated"] is False+ assert custom_client.get(+ "/api/session",+ base_url="https://max.fileguard.io",+ ).get_json()["authenticated"] is False+++def test_revision_snapshot_expiry_and_renewal_fail_closed(monkeypatch, tmp_path):+ """I1057-AC4: offline snapshots and renewal races cannot extend old claims."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ cookie = _organization_cookie(config)+ payload = remote_access.parse_session_cookie(config, cookie)+ assert payload is not None++ remote_access._replace_authorization_revision(config, 42)+ with pytest.raises(+ remote_access.OAuthCodeExchangeError,+ match="stale_authorization_revision",+ ):+ remote_access.make_session_cookie(+ config,+ "[email protected]",+ "user-1",+ session_claims=payload,+ )++ remote_access._replace_authorization_revision(config, 42)+ snapshot = remote_access._load_authorization_revision_snapshot(config)+ assert snapshot is not None+ _, updated_at = snapshot+ assert remote_access.session_authorization_is_current(+ config,+ {"vibe_instance_authorization_revision": 42},+ now=updated_at + remote_access.AUTHORIZATION_REVISION_MAX_AGE_SECONDS + 1,+ ) is False+++def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path):+ """I1057-AC4/AC6: active and resumed SSE streams converge on the watermark."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ cookie = _organization_cookie(config)+ payload = remote_access.parse_session_cookie(config, cookie)+ assert payload is not None+ context = context_from_session_payload(payload)++ class EmptyShowEventStore:+ def list(self, *args, **kwargs):+ return {"events": [], "next_after_id": None}++ def close(self):+ return None++ monkeypatch.setattr(ui_server, "_show_session_event_store", EmptyShowEventStore)++ async def exercise() -> None:+ with app.test_request_context("/api/events"):+ g.authorization_context = context+ g.remote_session_payload = payload+ response = await ui_server.workbench_events()+ iterator = response.body_iterator.__aiter__()+ try:+ for _ in range(3):+ await iterator.__anext__()+ remote_access._replace_authorization_revision(config, 42)+ with pytest.raises(StopAsyncIteration):+ await asyncio.wait_for(iterator.__anext__(), timeout=1)+ finally:+ await iterator.aclose()++ remote_access._replace_authorization_revision(config, 42)+ show_response = await ui_server._show_events_stream(+ "ses123",+ after_id="show_evt_resume",+ authorization_context=context,+ remote_session_payload=payload,+ remote_config=config,+ )+ show_iterator = show_response.body_iterator.__aiter__()+ try:+ with pytest.raises(StopAsyncIteration):+ await asyncio.wait_for(show_iterator.__anext__(), timeout=1)+ finally:+ await show_iterator.aclose()++ asyncio.run(exercise())+++def test_websocket_reconnect_and_active_waiter_recheck_revision(monkeypatch, tmp_path):+ """I1057-AC4/AC6: active sockets close and stale reconnects are rejected."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ cookie = _organization_cookie(config)++ class Socket:+ cookies = {remote_access.SESSION_COOKIE_NAME: cookie}++ websocket = Socket()+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)+ monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)+ monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")+ monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)++ payload = ui_server._remote_access_websocket_session_payload(websocket, config)+ assert payload is not None++ async def exercise() -> None:+ waiter = asyncio.create_task(+ ui_server._wait_for_remote_session_authorization_loss(config, payload)+ )+ await asyncio.sleep(0)+ remote_access._replace_authorization_revision(config, 42)+ await asyncio.wait_for(waiter, timeout=1)++ asyncio.run(exercise())+ assert ui_server._remote_access_websocket_session_payload(websocket, config) is None+++def test_terminal_websocket_fails_closed_when_revision_changes_after_gate(+ monkeypatch,+ tmp_path,+):+ """I1057-AC4: a gate-to-accept revision race cannot drop remote identity."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)++ class RecordingWebSocket:+ client = None+ query_params = {}++ def __init__(self):+ self.calls = []++ async def accept(self):+ self.calls.append(("accept", None))++ async def close(self, code=1000):+ self.calls.append(("close", code))++ websocket = RecordingWebSocket()+ monkeypatch.setattr(ui_server, "_terminal_enabled", lambda: True)+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)+ monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda socket: True)+ monkeypatch.setattr(ui_server, "_show_runtime_websocket_authorized", lambda *a, **k: True)+ monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: config)+ monkeypatch.setattr(ui_server, "_remote_access_websocket_session_claims", lambda *a: None)+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *a: False)+ monkeypatch.setattr(+ ui_server,+ "get_terminal_service",+ lambda: (_ for _ in ()).throw(AssertionError("stale socket reached terminal")),+ )++ asyncio.run(ui_server.terminal_websocket(websocket, "test"))++ assert websocket.calls == [+ ("accept", None),+ ("close", ui_server._AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE),+ ]+++def test_trusted_local_access_ignores_hosted_revision_state(monkeypatch, tmp_path):+ """I1057-AC5: trusted local access stays owner-equivalent while sync is offline."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _paired_config(tmp_path)+ state_path = remote_access._authorization_revision_state_path()+ state_path.unlink()+ remote_access._clear_authorization_revision_cache()+ assert remote_access.current_authorization_revision(config) is None++ response = app.test_client().get(+ "/api/config",+ base_url="http://127.0.0.1:5123",+ )++ assert response.status_code == 200+ assert response.get_json()["runtime"]["default_cwd"] == "."diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 5f026d231..168987d66 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -66,8 +66,16 @@ _STATUS_REPORT_PENDING: tuple[V2Config | None, str, str | None] | None = None_STATUS_REPORT_ATEXIT_REGISTERED = False_ACTIVE_HOSTNAMES_LOCK = threading.Lock()_ACTIVE_HOSTNAMES_CACHE: tuple[Path, str, frozenset[str], float | None] | None = None+_AUTHORIZATION_REVISION_KEY = "vibe_instance_authorization_revision"+_AUTHORIZATION_REVISION_LOCK = threading.Lock()+_AUTHORIZATION_REVISION_CACHE: tuple[Path, str, int, float] | None = None+_AUTHORIZATION_REVISION_SYNC_LOCK = threading.Lock()+_AUTHORIZATION_REVISION_POLL_LOCK = threading.Lock()+_AUTHORIZATION_REVISION_POLL_STARTED = FalseSTATUS_HEARTBEAT_SECONDS = 5 * 60RESOURCE_ACL_SYNC_INTERVAL_SECONDS = 30+AUTHORIZATION_REVISION_SYNC_INTERVAL_SECONDS = 15+AUTHORIZATION_REVISION_MAX_AGE_SECONDS = 60QUALITY_REPORT_SECONDS = 60QUALITY_SAMPLE_SECONDS = tunnel_quality.SAMPLE_INTERVAL_SECONDSSTATUS_LOG_TAIL_BYTES = 64 * 1024@@ -159,6 +167,10 @@ def _active_hostnames_state_path() -> Path:return paths.get_state_dir() / "remote-access-active-hostnames.json"+def _authorization_revision_state_path() -> Path:+ return paths.get_state_dir() / "remote-access-authorization-revision.json"++def _quality_state_path() -> Path:return paths.get_runtime_dir() / "remote-access-tunnel-quality.json"@@ -491,6 +503,136 @@ def _clear_active_hostnames_cache() -> None:_ACTIVE_HOSTNAMES_CACHE = None+def _authorization_revision_sync_configured(config: V2Config | None) -> bool:+ if config is None:+ return False+ cloud = config.remote_access.vibe_cloud+ return bool(+ cloud.enabled+ and cloud.instance_id+ and cloud.instance_secret+ and cloud.backend_url+ )+++def _normalize_authorization_revision(value: Any) -> int:+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:+ raise ValueError("invalid_authorization_revision")+ return value+++def _load_authorization_revision_snapshot(config: V2Config) -> tuple[int, float] | None:+ global _AUTHORIZATION_REVISION_CACHE++ instance_id = str(config.remote_access.vibe_cloud.instance_id or "").strip()+ if not instance_id:+ return None+ state_path = _authorization_revision_state_path()+ with _AUTHORIZATION_REVISION_LOCK:+ cached = _AUTHORIZATION_REVISION_CACHE+ if cached is not None and cached[0] == state_path and cached[1] == instance_id:+ return cached[2], cached[3]+ payload = runtime.read_json(state_path)+ if not isinstance(payload, dict) or payload.get("schema_version") != 1:+ return None+ if str(payload.get("instance_id") or "").strip() != instance_id:+ return None+ try:+ revision = _normalize_authorization_revision(payload.get("authorization_revision"))+ source_updated_at = float(payload["source_updated_at"])+ except (KeyError, TypeError, ValueError):+ return None+ _AUTHORIZATION_REVISION_CACHE = (+ state_path,+ instance_id,+ revision,+ source_updated_at,+ )+ return revision, source_updated_at+++def current_authorization_revision(+ config: V2Config,+ *,+ now: float | None = None,+) -> int | None:+ """Return the current fresh device-synchronized authorization revision."""++ snapshot = _load_authorization_revision_snapshot(config)+ if snapshot is None:+ return None+ revision, source_updated_at = snapshot+ current = time.time() if now is None else now+ age = current - source_updated_at+ if age < 0 or age > AUTHORIZATION_REVISION_MAX_AGE_SECONDS:+ return None+ return revision+++def _replace_authorization_revision(config: V2Config, value: Any) -> int:+ global _AUTHORIZATION_REVISION_CACHE++ revision = _normalize_authorization_revision(value)+ instance_id = str(config.remote_access.vibe_cloud.instance_id or "").strip()+ if not instance_id:+ raise ValueError("invalid_authorization_revision")+ state_path = _authorization_revision_state_path()+ source_updated_at = time.time()+ with _AUTHORIZATION_REVISION_LOCK:+ cached = _AUTHORIZATION_REVISION_CACHE+ if cached is not None and cached[0] == state_path and cached[1] == instance_id:+ previous_revision = cached[2]+ else:+ payload = runtime.read_json(state_path)+ previous_revision = None+ if (+ isinstance(payload, dict)+ and payload.get("schema_version") == 1+ and str(payload.get("instance_id") or "").strip() == instance_id+ ):+ try:+ previous_revision = _normalize_authorization_revision(+ payload.get("authorization_revision")+ )+ except ValueError:+ previous_revision = None+ if previous_revision is not None and revision < previous_revision:+ raise ValueError("authorization_revision_regressed")+ changed = previous_revision != revision+ payload = {+ "schema_version": 1,+ "instance_id": instance_id,+ "authorization_revision": revision,+ "source_updated_at": source_updated_at,+ }+ state_path.parent.mkdir(parents=True, exist_ok=True)+ runtime.write_json(state_path, payload)+ _AUTHORIZATION_REVISION_CACHE = (+ state_path,+ instance_id,+ revision,+ source_updated_at,+ )+ if changed:+ try:+ from vibe.sse_broker import broker++ broker.publish(+ "authorization.changed",+ {"instance_authorization_revision": revision},+ )+ except Exception:+ logger.debug("failed to publish authorization revision change", exc_info=True)+ return revision+++def _clear_authorization_revision_cache() -> None:+ global _AUTHORIZATION_REVISION_CACHE++ with _AUTHORIZATION_REVISION_LOCK:+ _AUTHORIZATION_REVISION_CACHE = None++def _state_connector(name: str) -> dict[str, Any] | None:state = _read_state()if not state:@@ -796,6 +938,85 @@ def _device_json_request(return parsed+def sync_authorization_revision_once(+ config: V2Config | None = None,+) -> dict[str, Any]:+ """Refresh the current paired-instance authorization watermark."""++ if not _AUTHORIZATION_REVISION_SYNC_LOCK.acquire(blocking=False):+ return {"ok": False, "error": "authorization_revision_sync_in_progress"}+ try:+ config = config or V2Config.load()+ if not _authorization_revision_sync_configured(config):+ return {"ok": False, "error": "authorization_revision_sync_not_configured"}+ result = _device_json_request(config, "GET", "authorization-revision")+ revision = _replace_authorization_revision(+ config,+ result.get("authorization_revision"),+ )+ return {"ok": True, "authorization_revision": revision}+ except BackendRequestError as exc:+ error = exc.payload.get("error")+ return {+ "ok": False,+ "error": error if isinstance(error, str) and error else "authorization_revision_sync_failed",+ }+ except Exception as exc:+ error = str(exc)+ if error not in {+ "authorization_revision_regressed",+ "invalid_authorization_revision",+ }:+ error = "authorization_revision_sync_failed"+ return {"ok": False, "error": error}+ finally:+ _AUTHORIZATION_REVISION_SYNC_LOCK.release()+++def start_authorization_revision_polling(+ config: V2Config | None = None,+ *,+ interval_seconds: int = AUTHORIZATION_REVISION_SYNC_INTERVAL_SECONDS,+) -> None:+ """Start the paired-device authorization watermark poller once."""++ global _AUTHORIZATION_REVISION_POLL_STARTED+ if config is None:+ try:+ config = V2Config.load()+ except Exception:+ return+ if not _authorization_revision_sync_configured(config):+ return++ def loop() -> None:+ while True:+ result = sync_authorization_revision_once()+ if not result.get("ok") and result.get("error") not in {+ "authorization_revision_sync_not_configured",+ "authorization_revision_sync_in_progress",+ }:+ logger.debug(+ "Authorization revision sync did not complete: %s",+ result.get("error"),+ )+ time.sleep(max(1, interval_seconds))++ with _AUTHORIZATION_REVISION_POLL_LOCK:+ if _AUTHORIZATION_REVISION_POLL_STARTED:+ return+ try:+ thread = threading.Thread(+ target=loop,+ name="vibe-authorization-revision-sync",+ daemon=True,+ )+ thread.start()+ except Exception:+ return+ _AUTHORIZATION_REVISION_POLL_STARTED = True++def _safe_resource_acl_identifier(value: Any, *, code: str = "invalid_resource_metadata", limit: int = 200) -> str:if not isinstance(value, str):raise ValueError(code)@@ -1971,6 +2192,7 @@ def start_runtime_monitoring(config: V2Config | None = None) -> None:start_tunnel_quality_monitor()start_status_heartbeat(config)+ start_authorization_revision_polling(config)from vibe.project_access_sync import start_project_access_syncstart_project_access_sync(config)@@ -2609,6 +2831,17 @@ def session_claims_from_oidc(config: V2Config, claims: Mapping[str, Any]) -> dic"vibe_instance_role": instance_role,"vibe_instance_access_source": access_source,}+ raw_authorization_revision = claims.get(_AUTHORIZATION_REVISION_KEY)+ if raw_authorization_revision is None:+ if _authorization_revision_sync_configured(config):+ raise OAuthCodeExchangeError("invalid_authorization_revision")+ else:+ try:+ session_claims[_AUTHORIZATION_REVISION_KEY] = _normalize_authorization_revision(+ raw_authorization_revision+ )+ except ValueError as exc:+ raise OAuthCodeExchangeError("invalid_authorization_revision") from excif not organization_claim_present:return session_claimsorganization_id = _oidc_claim_string(claims.get("vibe_organization_id"), reason="invalid_organization_claims")@@ -2641,6 +2874,28 @@ def session_claims_from_oidc(config: V2Config, claims: Mapping[str, Any]) -> dicreturn session_claims+def session_authorization_is_current(+ config: V2Config,+ payload: Mapping[str, Any],+ *,+ now: float | None = None,+) -> bool:+ """Return whether signed remote claims match the fresh device watermark."""++ if not _authorization_revision_sync_configured(config):+ return True+ current_revision = current_authorization_revision(config, now=now)+ if current_revision is None:+ return False+ try:+ signed_revision = _normalize_authorization_revision(+ payload.get(_AUTHORIZATION_REVISION_KEY)+ )+ except ValueError:+ return False+ return signed_revision == current_revision++def _encode_session_cookie(secret: str, payload: Mapping[str, Any]) -> str:payload_text = urllib.parse.quote(json.dumps(payload, separators=(",", ":")), safe="")signature = _session_signature(secret, payload_text)@@ -2669,6 +2924,10 @@ def make_session_cookie("exp": issued_at + SESSION_TTL_SECONDS,}validated_claims = session_claims_from_oidc(config, session_claims)+ if not session_authorization_is_current(config, validated_claims):+ if current_authorization_revision(config) is None:+ raise OAuthCodeExchangeError("authorization_revision_unavailable")+ raise OAuthCodeExchangeError("stale_authorization_revision")# Instance roles and optional organization membership must be refreshed# through OIDC instead of being slid indefinitely from a local cookie.payload["claims_issued_at"] = issued_at@@ -2744,6 +3003,8 @@ def parse_session_cookie(config: V2Config, cookie_value: str | None) -> dict[strsession_claims_from_oidc(config, payload)except OAuthCodeExchangeError:return None+ if not session_authorization_is_current(config, payload):+ return Nonetry:claims_issued_at = int(payload.get("claims_issued_at", payload.get("iat", 0)))except (TypeError, ValueError):diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex cff596372..0a5149d4a 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -22,7 +22,7 @@ from contextlib import contextmanagerfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any, Callable+from typing import Any, Callable, Mappingfrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplitimport psutil@@ -120,6 +120,7 @@ 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+_AUTHORIZATION_REVISION_RECHECK_SECONDS = 1.0_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+(.*)$")@@ -2184,6 +2185,7 @@ def enforce_remote_access_cookie():return _redirect_to_vibe_cloud_login(config)return jsonify({"ok": False, "error": "remote_access_authorization_refresh_required"}), 401g.authorization_context = context_from_session_payload(payload)+ g.remote_session_payload = payloadg.remote_authorization_refresh_at = remote_access.session_authorization_refresh_deadline(payload)if remote_access.session_needs_renewal(payload):g.remote_session_renew = payload@@ -2392,9 +2394,18 @@ def renew_remote_access_cookie(response: Response) -> Response:return responseemail = str(renew.get("email", ""))subject = str(renew.get("sub", ""))+ try:+ session_cookie = remote_access.make_session_cookie(+ config,+ email,+ subject,+ session_claims=renew,+ )+ except remote_access.OAuthCodeExchangeError:+ return responseresponse.set_cookie(remote_access.SESSION_COOKIE_NAME,- remote_access.make_session_cookie(config, email, subject, session_claims=renew),+ session_cookie,httponly=True,secure=True,samesite="Lax",@@ -2580,7 +2591,11 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):authorization_refresh_at = Noneauthorization_context = None- remote_payload = _remote_access_websocket_session_claims(websocket, _load_remote_access_config())+ remote_config = _load_remote_access_config()+ remote_payload = _remote_access_websocket_session_claims(websocket, remote_config)+ if remote_payload is None and not _websocket_is_local_request(websocket, remote_config):+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)+ returnif remote_payload is not None:from vibe import remote_accessfrom vibe.authorization import context_from_session_payload@@ -2613,10 +2628,19 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):if access_queue is not None and authorization_context is not Noneelse None)+ authorization_revision_task = (+ asyncio.create_task(+ _wait_for_remote_session_authorization_loss(remote_config, remote_payload)+ )+ if remote_config is not None and remote_payload is not None+ else None+ )try:waiters = {proxy_task}if revocation_task is not None:waiters.add(revocation_task)+ if authorization_revision_task is not None:+ waiters.add(authorization_revision_task)timeout = (Noneif authorization_refresh_at is None@@ -2632,6 +2656,10 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)elif proxy_task in done:await proxy_task+ elif authorization_revision_task is not None and authorization_revision_task in done:+ await authorization_revision_task+ logger.info("show_runtime.authorization_revoked session=%s", session_id)+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)else:await revocation_tasklogger.info("show_runtime.project_access_revoked session=%s", session_id)@@ -2640,11 +2668,12 @@ async def show_runtime_hmr_websocket(websocket: WebSocket, session_id: str):logger.debug("Show runtime HMR websocket unavailable", exc_info=True)await websocket.close(code=1011)finally:- for task in (proxy_task, revocation_task):+ tasks = (proxy_task, revocation_task, authorization_revision_task)+ for task in tasks:if task is not None and not task.done():task.cancel()await asyncio.gather(- *(task for task in (proxy_task, revocation_task) if task is not None),+ *(task for task in tasks if task is not None),return_exceptions=True,)if access_sub_id is not None:@@ -2703,6 +2732,9 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):await websocket.accept()config = _load_remote_access_config()remote_payload = _remote_access_websocket_session_claims(websocket, config)+ if remote_payload is None and not _websocket_is_local_request(websocket, config):+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)+ returnremote_addr = _websocket_client_host(websocket) or "unknown"remote_subject = Noneauthorization_refresh_at = None@@ -2720,18 +2752,47 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):# app). Validated server-side in the terminal service; an invalid/absent value silently# falls back to the default cwd and reattaching an existing session ignores it entirely.initial_cwd = websocket.query_params.get("cwd") or None+ handler_task = None+ authorization_revision_task = Nonetry:service = get_terminal_service()service.start_reaper()- handler = service.handle_websocket(websocket, effective_session_id, initial_cwd=initial_cwd)- if authorization_refresh_at is None:- await handler+ handler_task = asyncio.create_task(+ service.handle_websocket(+ websocket,+ effective_session_id,+ initial_cwd=initial_cwd,+ )+ )+ authorization_revision_task = (+ asyncio.create_task(+ _wait_for_remote_session_authorization_loss(config, remote_payload)+ )+ if config is not None and remote_payload is not None+ else None+ )+ waiters = {handler_task}+ if authorization_revision_task is not None:+ waiters.add(authorization_revision_task)+ timeout = (+ None+ if authorization_refresh_at is None+ else max(0.0, authorization_refresh_at - time.time())+ )+ done, _pending = await asyncio.wait(+ waiters,+ timeout=timeout,+ return_when=asyncio.FIRST_COMPLETED,+ )+ if not done:+ logger.info("terminal.authorization_refresh session_ref=%s", session_ref)+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)+ elif authorization_revision_task is not None and authorization_revision_task in done:+ await authorization_revision_task+ logger.info("terminal.authorization_revoked session_ref=%s", session_ref)+ await websocket.close(code=_AUTHORIZATION_REFRESH_WEBSOCKET_CLOSE_CODE)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)+ await handler_taskexcept 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@@ -2744,6 +2805,14 @@ async def terminal_websocket(websocket: WebSocket, session_id: str):logger.debug("Terminal websocket failed", exc_info=True)await websocket.close(code=1011)finally:+ tasks = (handler_task, authorization_revision_task)+ for task in tasks:+ if task is not None and not task.done():+ task.cancel()+ await asyncio.gather(+ *(task for task in tasks if task is not None),+ return_exceptions=True,+ )logger.info("terminal.session_close session_ref=%s remote_addr=%s", session_ref, remote_addr)@@ -2838,6 +2907,16 @@ async def _wait_for_project_session_access_loss(return+async def _wait_for_remote_session_authorization_loss(+ config: V2Config,+ payload: Mapping[str, Any],+) -> None:+ from vibe import remote_access++ while remote_access.session_authorization_is_current(config, payload):+ await asyncio.sleep(_AUTHORIZATION_REVISION_RECHECK_SECONDS)++def _show_runtime_websocket_resource_context(websocket: Any):"""Build the ACL context from the same signed session used by the socket gate."""@@ -5066,6 +5145,7 @@ def remote_access_auth_callback():if claims.get("nonce") != handshake_nonce:return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)try:+ remote_access.sync_authorization_revision_once(config)session_cookie = remote_access.make_session_cookie(config,str(claims.get("email", "")),@@ -8921,10 +9001,26 @@ async def workbench_events():authorization_context = getattr(g, "authorization_context", None)authorization_refresh_at = getattr(g, "remote_authorization_refresh_at", None)+ remote_session_payload = getattr(g, "remote_session_payload", None)+ remote_config = _load_remote_access_config() if remote_session_payload is not None else None++ def authorization_is_current() -> bool:+ if remote_session_payload is None:+ return True+ if remote_config is None:+ return False+ from vibe import remote_access++ return remote_access.session_authorization_is_current(+ remote_config,+ remote_session_payload,+ )async def generate():sub_id, queue = broker.subscribe()try:+ if not authorization_is_current():+ return# First chunk = handshake + sub_id so the client can include it in# subsequent debug logs / cancel calls if we ever need them.yield ": stream connected\n\n"@@ -8939,6 +9035,8 @@ async def workbench_events():)yield f"event: {WORKBENCH_EVENTS_BRIDGE_STATUS_EVENT}\ndata: {payload}\n\n"while True:+ if not authorization_is_current():+ returnwait_timeout = 15.0if authorization_refresh_at is not None:remaining = authorization_refresh_at - time.time()@@ -8947,6 +9045,8 @@ async def workbench_events():wait_timeout = min(wait_timeout, remaining)try:event_type, payload = await asyncio.wait_for(queue.get(), timeout=wait_timeout)+ if not authorization_is_current():+ returnif not can_receive_workbench_event(authorization_context, event_type):continuevisible = await asyncio.to_thread(@@ -8977,6 +9077,8 @@ async def workbench_events():)yield f"event: {event_type}\ndata: {payload}\n\n"except asyncio.TimeoutError:+ if not authorization_is_current():+ returnif authorization_refresh_at is not None and time.time() >= authorization_refresh_at:return# 15s keep-alive — Cloudflare Tunnel default idle is well@@ -10295,6 +10397,8 @@ async def _show_events_stream(public_share_id: str | None = None,authorization_refresh_at: float | None = None,authorization_context: Any = None,+ remote_session_payload: Mapping[str, Any] | None = None,+ remote_config: V2Config | None = None,):import asyncio@@ -10305,6 +10409,18 @@ async def _show_events_stream(def _event_visible(event_payload: dict[str, Any]) -> bool:return event_payload.get("session_id") == session_id+ def _authorization_is_current() -> bool:+ if remote_session_payload is None:+ return True+ if remote_config is None:+ return False+ from vibe import remote_access++ return remote_access.session_authorization_is_current(+ remote_config,+ remote_session_payload,+ )+async def generate():sub_id, queue = broker.subscribe()replayed_ids: set[str] = set()@@ -10312,6 +10428,8 @@ async def _show_events_stream(store = _show_session_event_store()try:cursor = after_id+ if not _authorization_is_current():+ returnyield ": show events connected\n\n"if not public and not _project_session_access_allowed(authorization_context,@@ -10320,6 +10438,8 @@ async def _show_events_stream():returnwhile True:+ if not _authorization_is_current():+ returnif authorization_refresh_at is not None and time.time() >= authorization_refresh_at:returnbatch = store.list(session_id, after_id=cursor, limit=500)@@ -10327,6 +10447,8 @@ async def _show_events_stream(if not events:breakfor event_payload in events:+ if not _authorization_is_current():+ returnif authorization_refresh_at is not None and time.time() >= authorization_refresh_at:returnif isinstance(event_payload.get("id"), str):@@ -10346,6 +10468,8 @@ async def _show_events_stream(store.close()while True:+ if not _authorization_is_current():+ returnwait_timeout = 15.0if authorization_refresh_at is not None:remaining = authorization_refresh_at - time.time()@@ -10354,6 +10478,8 @@ async def _show_events_stream(wait_timeout = min(wait_timeout, remaining)try:event_type, payload = await asyncio.wait_for(queue.get(), timeout=wait_timeout)+ if not _authorization_is_current():+ returndecoded = json.loads(payload)event_payload = decoded.get("data") if isinstance(decoded, dict) else Noneif event_type == "authorization.changed" and not public:@@ -10380,6 +10506,8 @@ async def _show_events_stream(elif event_type == "show.dispatch" and isinstance(event_payload, dict) and _event_visible(event_payload):yield _sse_frame("show.dispatch", _show_dispatch_response_payload(event_payload, public=public))except asyncio.TimeoutError:+ if not _authorization_is_current():+ returnif authorization_refresh_at is not None and time.time() >= authorization_refresh_at:returnyield ": ping\n\n"@@ -10419,6 +10547,14 @@ async def _show_events_response(authorization_context=(None if public else getattr(g, "authorization_context", None)),+ remote_session_payload=(+ None if public else getattr(g, "remote_session_payload", None)+ ),+ remote_config=(+ None+ if public or getattr(g, "remote_session_payload", None) is None+ else _load_remote_access_config()+ ),)store = _show_session_event_store()try: