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(remote-access): explain OAuth pairing mismatches (#657)
Call White3a4f60c45297
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex f5930bc68..c7ce6bb32 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -4,6 +4,8 @@ import jsonimport threadingimport time+import pytest+from config import pathsfrom config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Configfrom vibe import remote_access@@ -28,6 +30,10 @@ def _config() -> V2Config:cloud.client_id = "vr_client_123"cloud.public_url = "https://alex.avibe.bot"cloud.session_secret = "session-secret"+ cloud.token_endpoint = "https://backend.test/oauth/token"+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"+ cloud.jwks_uri = "https://backend.test/oauth/jwks.json"+ cloud.issuer = "https://backend.test"return config@@ -79,12 +85,96 @@ def test_make_session_cookie_requires_session_secret() -> None:config = _config()config.remote_access.vibe_cloud.session_secret = ""- import pytest-with pytest.raises(ValueError, match="session secret"):remote_access.make_session_cookie(config, "[email protected]", "user-1")+def test_exchange_oauth_code_wraps_token_endpoint_rejection(monkeypatch) -> None:+ config = _config()++ class ResponseStub:+ text = '{"error":"invalid_code"}'++ def raise_for_status(self):+ raise remote_access.requests.HTTPError("400 Client Error")++ def json(self):+ return {"error": "invalid_code"}++ monkeypatch.setattr(remote_access.requests, "post", lambda *args, **kwargs: ResponseStub())++ with pytest.raises(remote_access.OAuthCodeExchangeError) as exc_info:+ remote_access.exchange_oauth_code(config, "code-1", "verifier-1")++ assert exc_info.value.reason == "token_endpoint_rejected"+ assert exc_info.value.detail == "invalid_code"+++def test_exchange_oauth_code_reports_instance_mismatch(monkeypatch) -> None:+ config = _config()++ class ResponseStub:+ def raise_for_status(self):+ return None++ def json(self):+ return {"id_token": "id-token"}++ class JwkClientStub:+ def __init__(self, uri):+ self.uri = uri++ def get_signing_key_from_jwt(self, id_token):+ return type("SigningKey", (), {"key": "secret"})()++ monkeypatch.setattr(remote_access.requests, "post", lambda *args, **kwargs: ResponseStub())+ monkeypatch.setattr(remote_access, "PyJWKClient", JwkClientStub)+ monkeypatch.setattr(+ remote_access.jwt,+ "decode",+ lambda *args, **kwargs: {+ "sub": "user-1",+ "vibe_instance_id": "inst_other",+ "email_verified": True,+ },+ )++ with pytest.raises(remote_access.OAuthCodeExchangeError) as exc_info:+ remote_access.exchange_oauth_code(config, "code-1", "verifier-1")++ assert exc_info.value.reason == "invalid_instance_id"+++def test_exchange_oauth_code_reports_immature_token_as_clock_mismatch(monkeypatch) -> None:+ config = _config()++ class ResponseStub:+ def raise_for_status(self):+ return None++ def json(self):+ return {"id_token": "id-token"}++ class JwkClientStub:+ def __init__(self, uri):+ self.uri = uri++ def get_signing_key_from_jwt(self, id_token):+ return type("SigningKey", (), {"key": "secret"})()++ def decode(*args, **kwargs):+ raise remote_access.jwt.ImmatureSignatureError("The token is not yet valid")++ monkeypatch.setattr(remote_access.requests, "post", lambda *args, **kwargs: ResponseStub())+ monkeypatch.setattr(remote_access, "PyJWKClient", JwkClientStub)+ monkeypatch.setattr(remote_access.jwt, "decode", decode)++ with pytest.raises(remote_access.OAuthCodeExchangeError) as exc_info:+ remote_access.exchange_oauth_code(config, "code-1", "verifier-1")++ assert exc_info.value.reason == "immature_id_token"++def test_pair_redeems_key_and_starts_connector(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _config()diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pyindex 9a774198f..81ed809a4 100644--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@ -1038,6 +1038,58 @@ def test_remote_callback_rejects_nonce_mismatch(monkeypatch, tmp_path):assert 'href="/dashboard"' in response.text+def test_remote_callback_explains_pairing_mismatch(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")++ def exchange(cfg, code, verifier):+ raise remote_access.OAuthCodeExchangeError("invalid_instance_id")++ monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)++ state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]+ response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")++ assert response.status_code == 400+ assert "text/html" in response.headers["Content-Type"]+ assert "remote_pairing_mismatch" in response.text+ assert "Reconnect this Avibe" in response.text+ assert "pair Remote Access again" in response.text+ assert "Technical details" in response.text+ assert "reason: invalid_instance_id" in response.text+ assert "error: remote_pairing_mismatch" in response.text+++def test_remote_callback_explains_clock_mismatch(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")++ def exchange(cfg, code, verifier):+ raise remote_access.OAuthCodeExchangeError("expired_id_token")++ monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)++ state = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)["state"]+ response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")++ assert response.status_code == 400+ assert "oauth_time_mismatch" in response.text+ assert "Check this machine's clock" in response.text+ assert "reason: expired_id_token" in response.text++def test_remote_callback_rejects_when_remote_access_is_disabled(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _save_config(tmp_path)@@ -1130,6 +1182,25 @@ def test_remote_callback_renders_relogin_page_for_legacy_state(monkeypatch, tmp_assert 'href="/"' in response.text+def test_remote_callback_diagnostics_do_not_expose_oauth_parameters(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ _save_config(tmp_path)+ client = app.test_client()++ response = client.get(+ "/auth/callback?code=secret-code&state=secret-state",+ base_url="https://alex.avibe.bot",+ )++ assert response.status_code == 400+ assert "invalid_oauth_state" in response.text+ assert "Technical details" in response.text+ assert "error: invalid_oauth_state" in response.text+ assert "host: alex.avibe.bot" in response.text+ assert "secret-code" not in response.text+ assert "secret-state" not in response.text++def test_remote_callback_recovers_via_store_when_cookie_state_desyncs(monkeypatch, tmp_path):# iOS standalone PWA: the handshake cookie carries a *different* (but valid)# state than the one the user approved, because the cross-origin authorize stepdiff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex a9ad6a3be..e12aba17c 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -425,6 +425,8 @@"remote_access": {"oauth_error": {"sign_in_again": "Sign in again",+ "diagnostics_summary": "Technical details",+ "diagnostics_hint": "Copy these details when contacting support.","cookie_hint": "Still stuck after trying again? Make sure your browser allows cookies for this site.","default_title": "Let's sign you in again","default_body": "Your sign-in didn't finish. Please try again.",@@ -432,6 +434,10 @@"invalid_oauth_state_body": "The secure login link expired or couldn't be matched to this browser. This usually happens when a sign-in link sits unused for a few minutes, or is opened in a different tab or window. Start over and you'll be right back in.","oauth_exchange_failed_title": "We couldn't finish signing you in","oauth_exchange_failed_body": "Avibe Cloud didn't complete the sign-in just now. This is usually temporary — please try again.",+ "remote_pairing_mismatch_title": "Reconnect this Avibe",+ "remote_pairing_mismatch_body": "This Avibe's local pairing no longer matches the Avibe Cloud record for this address. Open Avibe on the machine that owns this domain, then pair Remote Access again.",+ "oauth_time_mismatch_title": "Check this machine's clock",+ "oauth_time_mismatch_body": "Avibe Cloud finished the sign-in, but this machine rejected the security token because the local clock appears out of sync. Correct the system time, then try again.","invalid_oauth_nonce_title": "We couldn't verify this sign-in","invalid_oauth_nonce_body": "This sign-in attempt couldn't be verified, so we stopped to keep your account secure. Start over to continue."}diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex b2233c8a2..ae97ebdde 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -425,6 +425,8 @@"remote_access": {"oauth_error": {"sign_in_again": "重新登录",+ "diagnostics_summary": "技术细节",+ "diagnostics_hint": "联系支持时请复制这段信息。","cookie_hint": "重试后仍然卡住?请确认浏览器允许本站使用 Cookie。","default_title": "重新登录一下","default_body": "登录未完成,请重试。",@@ -432,6 +434,10 @@"invalid_oauth_state_body": "安全登录链接已过期,或无法与当前浏览器匹配。这通常是因为登录链接闲置了几分钟,或在另一个标签页/窗口中打开。重新登录即可继续。","oauth_exchange_failed_title": "登录未能完成","oauth_exchange_failed_body": "Avibe Cloud 刚才没能完成登录,这通常是暂时的,请重试。",+ "remote_pairing_mismatch_title": "需要重新配对这台 Avibe",+ "remote_pairing_mismatch_body": "这台 Avibe 的本地配对信息已经和当前域名在 Avibe Cloud 的记录不一致。请在拥有这个域名的机器上打开 Avibe,重新配对远程访问。",+ "oauth_time_mismatch_title": "请检查这台机器的时间",+ "oauth_time_mismatch_body": "Avibe Cloud 已完成登录,但这台机器因为本地时间不同步而拒绝了安全令牌。请校准系统时间后重试。","invalid_oauth_nonce_title": "无法验证此次登录","invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"}diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex c2124c8f3..ce20fb076 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -56,6 +56,14 @@ class BackendRequestError(Exception):self.payload = payload+class OAuthCodeExchangeError(Exception):+ def __init__(self, reason: str, detail: str | None = None):+ message = reason if not detail else f"{reason}: {detail}"+ super().__init__(message)+ self.reason = reason+ self.detail = detail or ""++def _bin_dir() -> Path:return paths.get_vibe_remote_dir() / "bin"@@ -847,18 +855,49 @@ def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dictheaders={"Accept": "application/json", "User-Agent": "avibe/dev"},timeout=20,)- response.raise_for_status()- token_payload = response.json()+ try:+ response.raise_for_status()+ except requests.HTTPError as exc:+ detail = ""+ try:+ payload = response.json()+ detail = str(payload.get("error") or payload.get("detail") or "")+ except Exception:+ detail = response.text[:120]+ raise OAuthCodeExchangeError("token_endpoint_rejected", detail or str(exc)) from exc+ try:+ token_payload = response.json()+ except ValueError as exc:+ raise OAuthCodeExchangeError("invalid_token_response", str(exc)) from excid_token = token_payload.get("id_token")if not id_token:- raise ValueError("missing_id_token")- jwk_client = PyJWKClient(cloud.jwks_uri)- signing_key = jwk_client.get_signing_key_from_jwt(id_token)- claims = jwt.decode(id_token, signing_key.key, algorithms=["RS256"], audience=cloud.client_id, issuer=cloud.issuer)+ raise OAuthCodeExchangeError("missing_id_token")+ try:+ jwk_client = PyJWKClient(cloud.jwks_uri)+ signing_key = jwk_client.get_signing_key_from_jwt(id_token)+ claims = jwt.decode(+ id_token,+ signing_key.key,+ algorithms=["RS256"],+ audience=cloud.client_id,+ issuer=cloud.issuer,+ )+ except jwt.InvalidIssuerError as exc:+ raise OAuthCodeExchangeError("invalid_issuer", str(exc)) from exc+ except jwt.InvalidAudienceError as exc:+ raise OAuthCodeExchangeError("invalid_audience", str(exc)) from exc+ except jwt.ExpiredSignatureError as exc:+ raise OAuthCodeExchangeError("expired_id_token", str(exc)) from exc+ except jwt.ImmatureSignatureError as exc:+ raise OAuthCodeExchangeError("immature_id_token", str(exc)) from exc+ except jwt.InvalidTokenError as exc:+ raise OAuthCodeExchangeError("invalid_id_token", str(exc)) from exc+ except Exception as exc:+ raise OAuthCodeExchangeError("jwks_or_token_validation_failed", str(exc)) from excif claims.get("vibe_instance_id") != cloud.instance_id:- raise ValueError("invalid_instance_id")+ raise OAuthCodeExchangeError("invalid_instance_id")if not claims.get("email_verified"):- raise ValueError("email_not_verified")+ raise OAuthCodeExchangeError("email_not_verified")return {"claims": claims, "token": token_payload}diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 0e5377e23..d25332bc8 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -18,7 +18,7 @@ import threadingimport timefrom collections import OrderedDictfrom contextlib import contextmanager-from datetime import datetime+from datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callablefrom urllib.parse import parse_qsl, quote, unquote, urlencode, urlparse, urlsplit, urlunsplit@@ -1333,7 +1333,57 @@ def _restart_vibe_cloud_login_from_state(config: V2Config, state: str | None):# Error codes with dedicated copy in vibe/i18n (remote_access.oauth_error.*); any# other code falls back to the generic "default_*" strings so an unexpected failure# still renders a usable page.-_OAUTH_ERROR_PAGE_CODES = {"invalid_oauth_state", "oauth_exchange_failed", "invalid_oauth_nonce"}+_OAUTH_ERROR_PAGE_CODES = {+ "invalid_oauth_state",+ "oauth_exchange_failed",+ "remote_pairing_mismatch",+ "oauth_time_mismatch",+ "invalid_oauth_nonce",+}++_OAUTH_EXCHANGE_ERROR_PAGE_BY_REASON = {+ "invalid_instance_id": "remote_pairing_mismatch",+ "invalid_issuer": "remote_pairing_mismatch",+ "invalid_audience": "remote_pairing_mismatch",+ "expired_id_token": "oauth_time_mismatch",+ "immature_id_token": "oauth_time_mismatch",+}++_OAUTH_DIAGNOSTIC_DETAIL_MAX_CHARS = 240+_OAUTH_DIAGNOSTIC_SECRET_PATTERN = re.compile(+ r"(?i)\b(code|state|id_token|access_token|refresh_token|code_verifier|nonce)"+ r"(\s*[=:]\s*|%3d)[^&\s,;}]+"+)+++def _oauth_exchange_error_page_code(exc: BaseException) -> str:+ from vibe import remote_access++ if isinstance(exc, remote_access.OAuthCodeExchangeError):+ return _OAUTH_EXCHANGE_ERROR_PAGE_BY_REASON.get(exc.reason, "oauth_exchange_failed")+ return "oauth_exchange_failed"+++def _sanitize_oauth_diagnostic_detail(value: str | None) -> str:+ if not value:+ return ""+ compact = " ".join(str(value).split())+ redacted = _OAUTH_DIAGNOSTIC_SECRET_PATTERN.sub(lambda match: f"{match.group(1)}=<redacted>", compact)+ if len(redacted) <= _OAUTH_DIAGNOSTIC_DETAIL_MAX_CHARS:+ return redacted+ return redacted[: _OAUTH_DIAGNOSTIC_DETAIL_MAX_CHARS - 1].rstrip() + "..."+++def _oauth_exchange_error_diagnostics(exc: BaseException) -> tuple[str, dict[str, str]]:+ from vibe import remote_access++ error = _oauth_exchange_error_page_code(exc)+ if isinstance(exc, remote_access.OAuthCodeExchangeError):+ return error, {+ "reason": exc.reason,+ "detail": _sanitize_oauth_diagnostic_detail(exc.detail),+ }+ return error, {"reason": exc.__class__.__name__}def _request_ui_language() -> str:@@ -1356,7 +1406,26 @@ def _request_ui_language() -> str:return "en"-def _render_oauth_error_html(error: str, *, retry_href: str, lang: str = "en") -> str:+def _oauth_error_diagnostics_text(diagnostics: dict[str, Any] | None) -> str:+ if not diagnostics:+ return ""+ fields = ("error", "reason", "detail", "time_utc", "host", "retry_path", "handshake_cookie_present")+ lines = []+ for key in fields:+ value = diagnostics.get(key)+ if value is None or value == "":+ continue+ lines.append(f"{key}: {value}")+ return "\n".join(lines)+++def _render_oauth_error_html(+ error: str,+ *,+ retry_href: str,+ lang: str = "en",+ diagnostics: dict[str, Any] | None = None,+) -> str:"""Render a branded, self-contained re-login page for a failed OAuth callback.Replaces the old raw-JSON dead-end: the user sees a plain-language reason and a@@ -1371,6 +1440,18 @@ def _render_oauth_error_html(error: str, *, retry_href: str, lang: str = "en") -safe_button = html.escape(t("remote_access.oauth_error.sign_in_again", lang))safe_href = html.escape(retry_href or "/", quote=True)safe_code = html.escape(error)+ diagnostics_text = _oauth_error_diagnostics_text(diagnostics)+ diagnostics_block = ""+ if diagnostics_text:+ safe_diagnostics_summary = html.escape(t("remote_access.oauth_error.diagnostics_summary", lang))+ safe_diagnostics_hint = html.escape(t("remote_access.oauth_error.diagnostics_hint", lang))+ safe_diagnostics = html.escape(diagnostics_text)+ diagnostics_block = f"""+ <details class="oauth-error-details">+ <summary>{safe_diagnostics_summary}</summary>+ <pre>{safe_diagnostics}</pre>+ <p>{safe_diagnostics_hint}</p>+ </details>"""hint = ""if error == "invalid_oauth_state":hint = f'<p class="oauth-error-hint">{html.escape(t("remote_access.oauth_error.cookie_hint", lang))}</p>'@@ -1443,6 +1524,36 @@ def _render_oauth_error_html(error: str, *, retry_href: str, lang: str = "en") -font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;color: #94a3b8;}}+ .oauth-error-details {{+ margin-top: 22px;+ border: 1px solid rgba(23, 32, 51, 0.10);+ border-radius: 12px;+ background: #f8fafc;+ text-align: left;+ }}+ .oauth-error-details summary {{+ cursor: pointer;+ padding: 12px 14px;+ color: #334155;+ font-size: 13px;+ font-weight: 720;+ }}+ .oauth-error-details pre {{+ margin: 0;+ padding: 0 14px 12px;+ color: #334155;+ font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ user-select: all;+ }}+ .oauth-error-details p {{+ margin: 0;+ padding: 0 14px 14px;+ color: #64748b;+ font-size: 12px;+ line-height: 1.5;+ }}</style></head><body>@@ -1456,6 +1567,7 @@ def _render_oauth_error_html(error: str, *, retry_href: str, lang: str = "en") -<a class="oauth-error-button" href="{safe_href}">{safe_button}</a></div><div class="oauth-error-code">{safe_code}</div>+ {diagnostics_block}</section></main></body>@@ -1488,7 +1600,13 @@ def _log_oauth_diag(key: str, message: str, *args: Any) -> None:logger.warning(message + extra, *args)-def _oauth_callback_error_response(error: str, *, next_target: Any, status: int = 400):+def _oauth_callback_error_response(+ error: str,+ *,+ next_target: Any,+ status: int = 400,+ diagnostics: dict[str, Any] | None = None,+):"""Build the HTML re-login response for a failed OAuth callback.Clears any stale handshake cookie so "Sign in again" starts a clean flow, and@@ -1508,8 +1626,22 @@ def _oauth_callback_error_response(error: str, *, next_target: Any, status: intrequest.headers.get("Sec-Fetch-Site") or "",)retry_href = _strip_oauth_retry_param(next_target if isinstance(next_target, str) else "/")+ diagnostic_payload: dict[str, Any] = {+ "error": error,+ "time_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),+ "host": request.host,+ "retry_path": retry_href,+ "handshake_cookie_present": str(bool(request.cookies.get(REMOTE_OAUTH_COOKIE_NAME))).lower(),+ }+ if diagnostics:+ diagnostic_payload.update(diagnostics)response = Response(- _render_oauth_error_html(error, retry_href=retry_href, lang=_request_ui_language()),+ _render_oauth_error_html(+ error,+ retry_href=retry_href,+ lang=_request_ui_language(),+ diagnostics=diagnostic_payload,+ ),status=status,mimetype="text/html; charset=utf-8",)@@ -2851,7 +2983,8 @@ def remote_access_auth_callback():except Exception as exc:# Unauthenticated-reachable (valid handshake + bad code), so rate-limited._log_oauth_diag("exchange_failed", "vibe cloud oauth code exchange failed: %s", exc)- return _oauth_callback_error_response("oauth_exchange_failed", next_target=next_target)+ error, diagnostics = _oauth_exchange_error_diagnostics(exc)+ return _oauth_callback_error_response(error, next_target=next_target, diagnostics=diagnostics)if claims.get("nonce") != handshake_nonce:return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)response = Response(status=302)