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): make standalone PWA login work + friendly OAuth error page
cyh5e8477e76da0
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.mdnew file mode 100644index 000000000..a8b4b5317--- /dev/null+++ b/docs/plans/pwa-oauth-login-state-desync.md@@ -0,0 +1,82 @@+# Fix: PWA login always fails with `invalid_oauth_state`++## Background++Installed (standalone) PWAs on iOS deterministically fail Avibe Cloud remote-access+login: after approving the avibe.bot consent screen, the user lands on+`/auth/callback` and gets `invalid_oauth_state` every time. Normal browsers work.++## Root cause (evidence-backed, from the master regression env)++Topology: the PWA and `/auth/callback` are both on the tunnel host+(`test-app.avibe.bot`); the authorize/token endpoints are on `avibe.bot` (parent+domain, cross-origin but same registrable domain → same-site).++Diagnostic logging on the callback (regression) showed, on every PWA failure:++```+cookie_parsed=True cookie_state_rid=<A> url_state_rid=<B> url_state_valid=True (A != B)+handshake_cookie_present=True sec_fetch_site=same-site ua=...iPhone OS 18_7...+```++So the handshake cookie **is** delivered and valid, and the callback URL's `state`+is **also** a valid token we signed — but they are **two different states**.++Why: iOS standalone PWAs open the cross-origin avibe.bot authorize page in a+separate in-app-browser context, while the PWA's main webview independently+re-mints its own `GET /` → state + handshake cookie. The cookie the callback reads+therefore belongs to a *different* `GET /` generation than the consent the user+actually approved. The existing check `cookie.state == url.state` is the wrong+invariant in this multi-context environment.++(An earlier hypothesis — the cookie was a session cookie dropped across the+excursion — was disproven by `handshake_cookie_present=True`. Adding `Max-Age`+only changed the symptom from "absent" to "present-but-stale".)++## Fix++Stop requiring `cookie.state == url.state`. Recover the PKCE secrets by the+**signature-verified URL state** instead:++- `GET /` (`_redirect_to_vibe_cloud_login`): generate `state` (signed, with random+ id `r`), `nonce`, `code_verifier`. Persist `{nonce, code_verifier, next}`+ **server-side keyed by `r`** (single-use, 5-min TTL), in addition to the existing+ cookie.+- `/auth/callback`: verify the URL `state` signature, then:+ - **cookie-first** — if the cookie is present and its state matches the URL state,+ use the cookie's secrets (unchanged strong per-browser binding for normal+ browsers);+ - **store-fallback** — otherwise look up the server-side handshake by the URL+ state's `r` (the iOS PWA / cookie-desync case);+ - if neither yields a record → existing one-shot retry, then the friendly+ re-login page.++Server-side store: per-file under `~/.avibe/runtime/oauth_handshakes/<r>.json`,+`0600`, single-use (deleted on read), pruned by TTL. Single UI process, so no+cross-process coordination needed; on-disk so an in-flight login survives a UI+restart.++## Security++The change does not weaken the real gate: **which identity may complete OAuth for+an instance is enforced by the avibe.bot backend** (`isEmailAuthorizedForInstance`);+the local instance only trusts backend-issued tokens (audience/issuer/nonce+checked at exchange). The `state` remains HMAC-signed and single-use, so it cannot+be forged or replayed. The cookie's state-equality was a defense-in-depth layer+that is simply unavailable (and counter-productive) in standalone PWAs.++## Testing++- Unit (`tests/test_ui_remote_access_auth.py`):+ - new: valid-but-mismatched cookie + matching server-side record → callback+ completes via the store, using the record's verifier/nonce (not the stale+ cookie's).+ - new: login redirect persists the handshake cookie (`Max-Age`).+ - existing cookie-path / retry / legacy-state / sanitization cases stay green.+- Manual: iOS standalone PWA login on the master regression env (`test-app.avibe.bot`).++## Rollout++1. Deploy to the master regression env; confirm PWA login succeeds (and the+ `recovered via server-side handshake` info log fires).+2. codex review (auth-path change) → open PR.diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pyindex caab1a4c0..95eec78ad 100644--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@ -1,12 +1,14 @@from __future__ import annotationsimport ipaddress+import jsonimport socketimport asynciofrom collections import namedtupleimport httpx+from config import pathsfrom config.v2_config import AgentsConfig, PlatformsConfig, RemoteAccessConfig, RuntimeConfig, SlackConfig, UiConfig, V2Configfrom config.v2_config import CONFIG_LOCKfrom tests.ui_server_test_helpers import csrf_headers@@ -116,6 +118,22 @@ def test_remote_host_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):assert state_payload["retry"] is False+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+ # back and deterministically fails with invalid_oauth_state. The handshake+ # cookie must be persistent. Regression guard for the PWA login dead-end.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ config = _save_config(tmp_path)++ with app.test_request_context("/dashboard", base_url="https://alex.avibe.bot"):+ response = ui_server._redirect_to_vibe_cloud_login(config)++ set_cookie = response.headers["Set-Cookie"]+ assert set_cookie.startswith(f"{ui_server.REMOTE_OAUTH_COOKIE_NAME}=")+ assert f"Max-Age={ui_server.REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS}" in set_cookie++def test_remote_setup_route_requires_vibe_cloud_login(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))config = _save_config(tmp_path)@@ -994,7 +1012,11 @@ def test_remote_callback_rejects_nonce_mismatch(monkeypatch, tmp_path):response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")assert response.status_code == 400- assert response.get_json()["error"] == "invalid_oauth_nonce"+ assert "text/html" in response.headers["Content-Type"]+ assert "invalid_oauth_nonce" in response.text+ assert "Sign in again" in response.text+ # Re-login button points back at the original destination from the handshake.+ assert 'href="/dashboard"' in response.textdef test_remote_callback_rejects_when_remote_access_is_disabled(monkeypatch, tmp_path):@@ -1064,19 +1086,107 @@ def test_remote_callback_does_not_restart_oauth_twice(monkeypatch, tmp_path):response = client.get(f"/auth/callback?code=test-code&state={state}", base_url="https://alex.avibe.bot")+ # Auto-retry already spent: render the friendly re-login page, not raw JSON.assert response.status_code == 400- assert response.get_json()["error"] == "invalid_oauth_state"+ assert "text/html" in response.headers["Content-Type"]+ assert "invalid_oauth_state" in response.text+ assert "Sign in again" in response.text+ # Retry recovers the original destination from the signed state param.+ assert 'href="/show/ses123/"' in response.text-def test_remote_callback_preserves_invalid_state_response_for_legacy_state(monkeypatch, tmp_path):+def test_remote_callback_renders_relogin_page_for_legacy_state(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))_save_config(tmp_path)client = app.test_client()response = client.get("/auth/callback?code=test-code&state=state-1", base_url="https://alex.avibe.bot")+ # Undecodable state has no recoverable destination, so the retry button+ # falls back to the home page.assert response.status_code == 400- assert response.get_json()["error"] == "invalid_oauth_state"+ assert "text/html" in response.headers["Content-Type"]+ assert "invalid_oauth_state" in response.text+ assert "Sign in again" in response.text+ assert 'href="/"' 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 step+ # runs in a separate in-app-browser context. The callback must still complete by+ # recovering the PKCE secrets from the server-side store, keyed by the signed URL+ # state. Regression guard for the deterministic PWA invalid_oauth_state dead-end.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ config = _save_config(tmp_path)+ secret = config.remote_access.vibe_cloud.session_secret+ client = app.test_client()++ # The flow the user actually approved: a signed state plus its server-side record.+ rid = "approvedrid000"+ state_url = ui_server._make_oauth_state(secret, next_target="/dashboard", rid=rid)+ remote_access.store_oauth_handshake(+ rid, nonce="nonce-approved", code_verifier="verifier-approved", next_target="/dashboard"+ )++ # A stale-but-valid cookie from a *different* GET / generation (different state).+ stale_cookie = ui_server._make_oauth_cookie(+ secret,+ {+ "state": ui_server._make_oauth_state(secret, next_target="/", rid="stalerid0000"),+ "nonce": "nonce-stale",+ "code_verifier": "verifier-stale",+ "next": "/",+ "exp": int(ui_server.datetime.now().timestamp()) + 300,+ },+ )+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, stale_cookie, domain="alex.avibe.bot")++ captured = {}++ def exchange(cfg, code, verifier):+ captured["verifier"] = verifier+ return {"claims": {"email": "[email protected]", "sub": "user-1", "nonce": "nonce-approved"}}++ monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)++ response = client.get(+ f"/auth/callback?code=test-code&state={state_url}",+ base_url="https://alex.avibe.bot",+ follow_redirects=False,+ )++ assert response.status_code == 302+ assert response.headers["Location"] == "/dashboard"+ # Used the server-side record's verifier, not the stale cookie's.+ assert captured["verifier"] == "verifier-approved"+ # Handshake is single-use: consumed by the callback.+ assert remote_access.pop_oauth_handshake(rid) is None+++def test_oauth_handshake_store_is_single_use_and_expires(monkeypatch, tmp_path):+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)++ remote_access.store_oauth_handshake("rid-abc", nonce="n", code_verifier="v", next_target="/x")+ first = remote_access.pop_oauth_handshake("rid-abc")+ assert first is not None+ assert first["code_verifier"] == "v"+ assert first["next"] == "/x"+ # Single-use: a second pop finds nothing.+ assert remote_access.pop_oauth_handshake("rid-abc") is None++ # An expired record is treated as absent (and removed).+ remote_access.store_oauth_handshake("rid-exp", nonce="n", code_verifier="v", next_target="/x")+ record_path = paths.get_runtime_dir() / "oauth_handshakes" / "rid-exp.json"+ data = json.loads(record_path.read_text())+ data["exp"] = 0+ record_path.write_text(json.dumps(data))+ assert remote_access.pop_oauth_handshake("rid-exp") is None++ # Invalid ids are rejected, never touching the filesystem.+ assert remote_access.pop_oauth_handshake("bad/rid") is None+ assert remote_access.pop_oauth_handshake(None) is Nonedef test_remote_callback_accepts_html_escaped_state_separator(monkeypatch, tmp_path):diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 3638f9b36..b358787cf 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -857,3 +857,96 @@ def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dictif not claims.get("email_verified"):raise ValueError("email_not_verified")return {"claims": claims, "token": token_payload}+++# --- OAuth handshake store -------------------------------------------------+#+# The login handshake (PKCE ``code_verifier`` + ``nonce``) is normally carried in+# a short-lived cookie. iOS standalone PWAs run the cross-origin authorize step in+# a separate in-app-browser context, so the cookie the callback reads belongs to a+# *different* ``GET /`` generation than the consent the user approved, and+# ``cookie.state == url.state`` never holds. We therefore also persist the+# handshake server-side, keyed by the signed state's random id, so the callback+# can recover it by the (signature-verified) state in the callback URL. The id is+# unguessable and single-use; the verifier never leaves the machine.++OAUTH_HANDSHAKE_TTL_SECONDS = 300+_OAUTH_HANDSHAKE_RID_RE = re.compile(r"\A[A-Za-z0-9_-]{1,64}\Z")+++def _oauth_handshake_dir() -> Path:+ return paths.get_runtime_dir() / "oauth_handshakes"+++def _prune_oauth_handshakes(directory: Path) -> None:+ cutoff = time.time() - OAUTH_HANDSHAKE_TTL_SECONDS+ try:+ entries = list(directory.glob("*.json"))+ except OSError:+ return+ for entry in entries:+ try:+ if entry.stat().st_mtime < cutoff:+ entry.unlink()+ except OSError:+ pass+++def store_oauth_handshake(rid: str, *, nonce: str, code_verifier: str, next_target: str) -> None:+ """Persist a login handshake keyed by the signed state's random id ``rid``.++ Single-use, ``OAUTH_HANDSHAKE_TTL_SECONDS`` TTL. Written atomically with+ owner-only permissions under the runtime dir. Invalid ids are ignored.+ """+ if not _OAUTH_HANDSHAKE_RID_RE.match(rid or ""):+ return+ directory = _oauth_handshake_dir()+ try:+ directory.mkdir(parents=True, exist_ok=True)+ directory.chmod(0o700)+ except OSError:+ pass+ _prune_oauth_handshakes(directory)+ payload = {+ "nonce": nonce,+ "code_verifier": code_verifier,+ "next": next_target,+ "exp": int(time.time()) + OAUTH_HANDSHAKE_TTL_SECONDS,+ }+ final = directory / f"{rid}.json"+ tmp = directory / f".{rid}.{os.getpid()}.tmp"+ try:+ tmp.write_text(json.dumps(payload, separators=(",", ":")), encoding="utf-8")+ try:+ tmp.chmod(0o600)+ except OSError:+ pass+ os.replace(tmp, final)+ except OSError:+ try:+ tmp.unlink()+ except OSError:+ pass+++def pop_oauth_handshake(rid: str | None) -> dict[str, Any] | None:+ """Return and delete (single-use) the handshake for ``rid``; None if absent/expired."""+ if not rid or not _OAUTH_HANDSHAKE_RID_RE.match(rid):+ return None+ path = _oauth_handshake_dir() / f"{rid}.json"+ try:+ raw = path.read_text(encoding="utf-8")+ except OSError:+ return None+ finally:+ try:+ path.unlink()+ except OSError:+ pass+ try:+ payload = json.loads(raw)+ except (ValueError, TypeError):+ return None+ if not isinstance(payload, dict) or int(payload.get("exp", 0)) <= int(time.time()):+ return None+ return payloaddiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 62d8747a9..9571a6878 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3,6 +3,7 @@ import asyncioimport gzipimport hashlibimport hmac+import htmlimport ipaddressimport jsonimport logging@@ -113,6 +114,12 @@ CSRF_COOKIE_NAME = "vibe_csrf_token"CSRF_HEADER_NAME = "X-Vibe-CSRF-Token"REMOTE_OAUTH_COOKIE_NAME = "__Host-vibe_remote_oauth"REMOTE_OAUTH_RETRY_PARAM = "__vibe_oauth_retry"+# Lifetime of the short-lived OAuth handshake (signed state + PKCE cookie). The+# cookie MUST carry an explicit Max-Age: iOS standalone PWAs drop session-scoped+# cookies (no Max-Age) across the cross-origin authorize excursion / app+# backgrounding, which silently breaks the callback. A persistent cookie with a+# short TTL survives. The signed payload's own `exp` enforces the real validity.+REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS = 300MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"}LOG_SOURCES = (("service", "vibe_remote.log", lambda: paths.get_logs_dir() / "vibe_remote.log"),@@ -1100,13 +1107,13 @@ def _b64url_decode(value: str) -> bytes:return base64.urlsafe_b64decode(f"{value}{padding}")-def _make_oauth_state(secret: str, *, next_target: str, retry: bool = False) -> str:+def _make_oauth_state(secret: str, *, next_target: str, retry: bool = False, rid: str | None = None) -> str:payload = {"v": 1,- "r": secrets.token_urlsafe(18),+ "r": rid or secrets.token_urlsafe(18),"next": next_target,"retry": bool(retry),- "exp": int(datetime.now().timestamp()) + 300,+ "exp": int(datetime.now().timestamp()) + REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,}payload_text = _b64url_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8"))signature = _b64url_encode(hmac.new(secret.encode("utf-8"), payload_text.encode("ascii"), hashlib.sha256).digest())@@ -1134,6 +1141,21 @@ def _read_oauth_state(secret: str, value: str | None) -> dict[str, Any] | None:return payload+def _peek_oauth_state_rid(token: str | None) -> str | None:+ """Best-effort extract a vr1 state token's random id, for diagnostics only.++ Does NOT verify the HMAC — purely to compare which state a request carries.+ The ``r`` field is a single-use random nonce, not a secret.+ """+ if not token or not token.startswith("vr1."):+ return None+ try:+ payload = json.loads(_b64url_decode(token.split(".")[1]).decode("utf-8"))+ return (str(payload.get("r", ""))[:12]) or None+ except Exception:+ return None++def _safe_remote_redirect_target(value: Any) -> str:if not isinstance(value, str):return "/"@@ -1176,12 +1198,19 @@ def _redirect_to_vibe_cloud_login(config: V2Config):code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")raw_next = request.full_path if request.query_string else request.pathnext_target = _strip_oauth_retry_param(raw_next)+ rid = secrets.token_urlsafe(18)state = _make_oauth_state(cloud.session_secret,next_target=next_target,retry=request.args.get(REMOTE_OAUTH_RETRY_PARAM) == "1",+ rid=rid,)nonce = secrets.token_urlsafe(24)+ # Persist the handshake server-side keyed by the state id, so the callback can+ # recover the PKCE secrets by the signed URL state even when the cookie desyncs+ # (iOS standalone PWA runs authorize in a separate in-app-browser context). The+ # cookie below is kept as the strong per-browser binding for normal browsers.+ remote_access.store_oauth_handshake(rid, nonce=nonce, code_verifier=code_verifier, next_target=next_target)oauth_cookie = _make_oauth_cookie(cloud.session_secret,{@@ -1189,7 +1218,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):"nonce": nonce,"code_verifier": code_verifier,"next": next_target,- "exp": int(datetime.now().timestamp()) + 300,+ "exp": int(datetime.now().timestamp()) + REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,},)response = Response(status=302)@@ -1201,6 +1230,7 @@ def _redirect_to_vibe_cloud_login(config: V2Config):secure=True,samesite="Lax",path="/",+ max_age=REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,)return response@@ -1216,6 +1246,167 @@ def _restart_vibe_cloud_login_from_state(config: V2Config, state: str | None):return response+# Human-readable copy for the OAuth callback error page, keyed by error code.+# Each entry is ``(headline, body)``. Codes not listed fall back to a generic+# "try again" message so an unexpected failure still renders a usable page.+_OAUTH_ERROR_PAGE_COPY: dict[str, tuple[str, str]] = {+ "invalid_oauth_state": (+ "Your sign-in session expired",+ "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": (+ "We couldn't finish signing you in",+ "Avibe Cloud didn't complete the sign-in just now. This is usually "+ "temporary — please try again.",+ ),+ "invalid_oauth_nonce": (+ "We couldn't verify this sign-in",+ "This sign-in attempt couldn't be verified, so we stopped to keep your "+ "account secure. Start over to continue.",+ ),+}+++def _render_oauth_error_html(error: str, *, retry_href: str) -> 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 single "Sign in again" button that navigates to ``retry_href`` (a sanitized+ same-origin path), which re-enters the login flow via the auth gate.+ """+ title, message = _OAUTH_ERROR_PAGE_COPY.get(+ error,+ ("Let's sign you in again", "Your sign-in didn't finish. Please try again."),+ )+ safe_title = html.escape(title)+ safe_message = html.escape(message)+ safe_href = html.escape(retry_href or "/", quote=True)+ safe_code = html.escape(error)+ hint = ""+ if error == "invalid_oauth_state":+ hint = (+ '<p class="oauth-error-hint">Still stuck after trying again? Make sure '+ "your browser allows cookies for this site.</p>"+ )+ return f"""<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="robots" content="noindex">+ <title>{safe_title}</title>+ <style>+ :root {{+ color-scheme: light;+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ background: #f6f7f9;+ color: #172033;+ }}+ body {{ margin: 0; min-height: 100vh; }}+ .oauth-error-shell {{+ min-height: 100vh;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 32px 18px;+ box-sizing: border-box;+ }}+ .oauth-error-panel {{+ width: min(460px, 100%);+ border: 1px solid rgba(23, 32, 51, 0.12);+ border-radius: 18px;+ background: rgba(255, 255, 255, 0.96);+ padding: clamp(28px, 6vw, 40px);+ box-shadow: 0 24px 80px rgba(23, 32, 51, 0.10);+ box-sizing: border-box;+ text-align: center;+ }}+ .oauth-error-eyebrow {{+ color: #526078;+ font-size: 13px;+ font-weight: 760;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ }}+ .oauth-error-panel h1 {{+ margin: 14px 0 0;+ font-size: clamp(24px, 6vw, 32px);+ line-height: 1.12;+ letter-spacing: 0;+ }}+ .oauth-error-panel p {{+ margin: 14px 0 0;+ line-height: 1.65;+ color: #526078;+ }}+ .oauth-error-hint {{ font-size: 13px; }}+ .oauth-error-actions {{ margin-top: 26px; }}+ .oauth-error-button {{+ display: inline-block;+ height: 44px;+ padding: 0 24px;+ border-radius: 12px;+ background: #0f172a;+ color: #fff;+ font: 700 15px/44px Inter, ui-sans-serif, system-ui;+ text-decoration: none;+ }}+ .oauth-error-button:hover {{ background: #1e293b; }}+ .oauth-error-code {{+ margin-top: 22px;+ font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ color: #94a3b8;+ }}+ </style>+ </head>+ <body>+ <main class="oauth-error-shell">+ <section class="oauth-error-panel">+ <div class="oauth-error-eyebrow">Avibe</div>+ <h1>{safe_title}</h1>+ <p>{safe_message}</p>+ {hint}+ <div class="oauth-error-actions">+ <a class="oauth-error-button" href="{safe_href}">Sign in again</a>+ </div>+ <div class="oauth-error-code">{safe_code}</div>+ </section>+ </main>+ </body>+</html>+"""+++def _oauth_callback_error_response(error: str, *, next_target: Any, status: int = 400):+ """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+ strips the auto-retry marker from ``next_target`` so the retry gets a fresh+ attempt (plus one silent auto-retry) instead of immediately failing again.+ """+ # Diagnostic only: whether the handshake cookie reached us at all is the key+ # signal for cookie-loss cases (e.g. iOS standalone PWA). No token values are+ # logged — only presence and a few non-secret request hints.+ logger.warning(+ "oauth callback rejected: error=%s handshake_cookie_present=%s ua=%r sec_fetch_site=%s",+ error,+ bool(request.cookies.get(REMOTE_OAUTH_COOKIE_NAME)),+ (request.headers.get("User-Agent") or "")[:140],+ request.headers.get("Sec-Fetch-Site") or "",+ )+ retry_href = _strip_oauth_retry_param(next_target if isinstance(next_target, str) else "/")+ response = Response(+ _render_oauth_error_html(error, retry_href=retry_href),+ status=status,+ mimetype="text/html; charset=utf-8",+ )+ response.headers["Cache-Control"] = "no-store"+ response.delete_cookie(REMOTE_OAUTH_COOKIE_NAME, path="/", secure=True, samesite="Lax")+ return response++@app.before_requestdef start_api_request_timer():if request.path.startswith("/api/"):@@ -2325,21 +2516,53 @@ def remote_access_auth_callback():cloud = config.remote_access.vibe_cloudif not cloud.enabled:return jsonify({"error": "remote_access_disabled"}), 400- oauth_state = _read_oauth_cookie(cloud.session_secret, request.cookies.get(REMOTE_OAUTH_COOKIE_NAME))- if not oauth_state or oauth_state.get("state") != _oauth_callback_arg("state"):- retry_response = _restart_vibe_cloud_login_from_state(config, _oauth_callback_arg("state"))+ url_state_token = _oauth_callback_arg("state")+ cookie_state = _read_oauth_cookie(cloud.session_secret, request.cookies.get(REMOTE_OAUTH_COOKIE_NAME))+ url_state = _read_oauth_state(cloud.session_secret, url_state_token)+ # Single-use: consume any server-side handshake for this verified state id, even+ # when we ultimately use the cookie, so the store stays clean.+ store_record = remote_access.pop_oauth_handshake(url_state.get("r")) if url_state else None++ # Prefer the cookie when it matches the URL state (strong per-browser binding,+ # the normal-browser path). Fall back to the server-side handshake when the+ # cookie is missing or carries a different state — the iOS standalone PWA case,+ # where the authorize step runs in a separate in-app-browser context and the+ # cookie desyncs from the state the user actually approved.+ if cookie_state and cookie_state.get("state") == url_state_token:+ code_verifier = cookie_state["code_verifier"]+ handshake_nonce = cookie_state.get("nonce")+ next_target = cookie_state.get("next")+ elif store_record is not None:+ logger.info("oauth callback recovered via server-side handshake (cookie-less or desynced context)")+ code_verifier = store_record["code_verifier"]+ handshake_nonce = store_record.get("nonce")+ next_target = store_record.get("next")+ else:+ # Neither the cookie nor the server-side store yielded the handshake.+ logger.warning(+ "oauth state check failed: cookie_parsed=%s cookie_state_rid=%s url_state_rid=%s url_state_valid=%s",+ cookie_state is not None,+ _peek_oauth_state_rid(cookie_state.get("state")) if cookie_state else None,+ _peek_oauth_state_rid(url_state_token),+ url_state is not None,+ )+ retry_response = _restart_vibe_cloud_login_from_state(config, url_state_token)if retry_response is not None:return retry_response- return jsonify({"error": "invalid_oauth_state"}), 400+ # Auto-retry exhausted (or the state is undecodable): show the re-login page,+ # recovering the original destination from the signed state when possible.+ next_target = url_state.get("next") if url_state else "/"+ return _oauth_callback_error_response("invalid_oauth_state", next_target=next_target)try:- result = remote_access.exchange_oauth_code(config, _oauth_callback_arg("code") or "", oauth_state["code_verifier"])+ result = remote_access.exchange_oauth_code(config, _oauth_callback_arg("code") or "", code_verifier)claims = result["claims"]except Exception as exc:- return jsonify({"error": "oauth_exchange_failed", "detail": str(exc)}), 400- if claims.get("nonce") != oauth_state.get("nonce"):- return jsonify({"error": "invalid_oauth_nonce"}), 400+ logger.warning("vibe cloud oauth code exchange failed: %s", exc)+ return _oauth_callback_error_response("oauth_exchange_failed", next_target=next_target)+ if claims.get("nonce") != handshake_nonce:+ return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)response = Response(status=302)- response.headers["Location"] = _safe_remote_redirect_target(oauth_state.get("next"))+ response.headers["Location"] = _safe_remote_redirect_target(next_target)response.set_cookie(remote_access.SESSION_COOKIE_NAME,remote_access.make_session_cookie(config, str(claims.get("email", "")), str(claims.get("sub", ""))),