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): bind OAuth store-fallback to a stable per-browser device cookie
cyh5b50cf4e3503
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.mdindex 2cfacb3b8..23fc03128 100644--- a/docs/plans/pwa-oauth-login-state-desync.md+++ b/docs/plans/pwa-oauth-login-state-desync.md@@ -76,21 +76,27 @@ Codex review (gpt-5.5, xhigh) hardening applied:private name before reading, so concurrent callbacks for one `rid` can't bothconsume the same record.-### Known limitation / follow-up--The fallback still binds finalization to *a* same-origin login attempt, not to the-*specific* browser tab that approved consent (the cookie/jar that would provide-that binding is exactly what desyncs on iOS). On an instance that authorizes-**multiple** identities, an attacker who holds a valid `code+state` for their own-authorized identity could induce a victim's browser (which has visited the-instance) to hit that callback and be logged in as the attacker — a login-CSRF.--Bounded today: Avibe instances are single-identity (one authorized email), so no-second identity exists to mount this. The complete fix, for when multi-identity-matters, is a same-origin binding the desync can't break: the login-start page-writes a random nonce to `localStorage`, the store keeps its hash, and a JS-finalizer on the callback page POSTs `{code, state, nonce}` — tracked as a-follow-up rather than blocking this PWA fix.+### Per-browser binding for the store-fallback (login-CSRF closed)++A bare `code+state` callback URL must not log a *different* browser in. The+store-fallback is therefore bound to a **stable per-browser device cookie**+(`__Host-vibe_oauth_device`):++- The login redirect sets it once (reused on later flows, 180-day TTL). Unlike the+ per-flow handshake *state*, it is not regenerated per `GET /`, so it stays+ consistent across the iOS authorize excursion.+- The handshake record stores `hmac(session_secret, device_id)`. The callback's+ store-fallback only proceeds when the request's device cookie hashes to that+ value — proving it is the same browser that started the flow.+- An attacker cannot present a victim's device cookie (HttpOnly, Secure,+ per-browser), so inducing a victim to hit an attacker's `code+state` callback no+ longer logs the victim in as the attacker.++This was chosen over a `localStorage`-nonce + JS-finalizer flow because it needs no+interstitial pages, no client JS, and no change to the normal-browser login UX —+while giving the same binding. Its one assumption (iOS keeps the persistent device+cookie stable across the excursion) is verified on the regression PWA; if that ever+fails, the `localStorage`-nonce variant is the fallback.## Testingdiff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pyindex e972efeb1..ea0cc7fe8 100644--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@ -134,6 +134,26 @@ def test_login_redirect_sets_persistent_handshake_cookie(monkeypatch, tmp_path):assert f"Max-Age={ui_server.REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS}" in set_cookie+def test_login_redirect_sets_stable_device_binding_cookie(monkeypatch, tmp_path):+ # The store-fallback recovery is bound to this persistent per-browser device+ # cookie, which (unlike the per-flow handshake state) survives the iOS authorize+ # excursion. The login redirect must seed it, long-lived.+ 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)++ device_cookies = [+ c for c in response.headers.getlist("Set-Cookie")+ if c.startswith(f"{ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME}=")+ ]+ assert len(device_cookies) == 1+ assert f"Max-Age={ui_server.REMOTE_OAUTH_DEVICE_TTL_SECONDS}" in device_cookies[0]+ assert "HttpOnly" in device_cookies[0]+ assert "Secure" in device_cookies[0]++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)@@ -1122,11 +1142,17 @@ def test_remote_callback_recovers_via_store_when_cookie_state_desyncs(monkeypatcsecret = config.remote_access.vibe_cloud.session_secretclient = app.test_client()- # The flow the user actually approved: a signed state plus its server-side record.+ # The flow the user actually approved: a signed state plus its server-side record,+ # bound to this browser's stable device id.rid = "approvedrid000"+ device_id = "device-abc-123"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"+ rid,+ nonce="nonce-approved",+ code_verifier="verifier-approved",+ next_target="/dashboard",+ device_hash=ui_server._oauth_device_hash(secret, device_id),)# A stale-but-valid cookie from a *different* GET / generation (different state).@@ -1141,6 +1167,8 @@ def test_remote_callback_recovers_via_store_when_cookie_state_desyncs(monkeypatc},)client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, stale_cookie, domain="alex.avibe.bot")+ # The device cookie is stable across the excursion and matches the record's bind.+ client.set_cookie(ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME, device_id, domain="alex.avibe.bot")captured = {}@@ -1189,11 +1217,11 @@ def test_oauth_handshake_store_is_single_use_and_expires(monkeypatch, tmp_path):assert remote_access.pop_oauth_handshake(None) is None-def test_remote_callback_refuses_store_fallback_without_cookie(monkeypatch, tmp_path):- # Defense-in-depth: a callback URL (code+state) must not become a cross-browser- # bearer login. With NO same-origin handshake cookie present, the server-side- # store must not be used to complete login, even though a record exists for the- # signed state. The PWA fix only relaxes the *state-equality* of a present cookie.+def test_remote_callback_refuses_store_fallback_without_device_binding(monkeypatch, tmp_path):+ # Login-CSRF block: a code+state callback URL must not complete in a browser that+ # isn't the one that started the flow. The store record is bound to the attacker's+ # device id; the victim's browser presents its own (different) device cookie plus a+ # stale handshake cookie, so the store-fallback must refuse — no token exchange.monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))config = _save_config(tmp_path)secret = config.remote_access.vibe_cloud.session_secret@@ -1201,14 +1229,33 @@ def test_remote_callback_refuses_store_fallback_without_cookie(monkeypatch, tmp_rid = "victimrid0001"state_url = ui_server._make_oauth_state(secret, next_target="/dashboard", rid=rid)- remote_access.store_oauth_handshake(rid, nonce="n", code_verifier="v", next_target="/dashboard")+ remote_access.store_oauth_handshake(+ rid,+ nonce="n",+ code_verifier="v",+ next_target="/dashboard",+ device_hash=ui_server._oauth_device_hash(secret, "attacker-device"),+ )++ # Victim browser: a valid-but-stale handshake cookie and its OWN device cookie.+ stale_cookie = ui_server._make_oauth_cookie(+ secret,+ {+ "state": ui_server._make_oauth_state(secret, next_target="/", rid="victimst0000"),+ "nonce": "x",+ "code_verifier": "x",+ "next": "/",+ "exp": int(ui_server.datetime.now().timestamp()) + 300,+ },+ )+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, stale_cookie, domain="alex.avibe.bot")+ client.set_cookie(ui_server.REMOTE_OAUTH_DEVICE_COOKIE_NAME, "victim-device", domain="alex.avibe.bot")exchanged = []monkeypatch.setattr(remote_access, "exchange_oauth_code", lambda *a, **k: exchanged.append(a) or {"claims": {}})- # No oauth handshake cookie on the client.response = client.get(f"/auth/callback?code=test-code&state={state_url}",base_url="https://alex.avibe.bot",diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex 7b1dbfc1d..7002005d6 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -892,11 +892,14 @@ def _prune_oauth_handshakes(directory: Path) -> None:pass-def store_oauth_handshake(rid: str, *, nonce: str, code_verifier: str, next_target: str) -> None:+def store_oauth_handshake(+ rid: str, *, nonce: str, code_verifier: str, next_target: str, device_hash: str | None = None+) -> None:"""Persist a login handshake keyed by the signed state's random id ``rid``.Single-use, ``OAUTH_HANDSHAKE_TTL_SECONDS`` TTL. Written atomically withowner-only permissions under the runtime dir. Invalid ids are ignored.+ ``device_hash`` binds a later store-fallback recovery to the originating browser."""if not _OAUTH_HANDSHAKE_RID_RE.match(rid or ""):return@@ -911,6 +914,7 @@ def store_oauth_handshake(rid: str, *, nonce: str, code_verifier: str, next_targ"nonce": nonce,"code_verifier": code_verifier,"next": next_target,+ "device_hash": device_hash,"exp": int(time.time()) + OAUTH_HANDSHAKE_TTL_SECONDS,}final = directory / f"{rid}.json"diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 4f57f6454..099d0705d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -120,6 +120,14 @@ REMOTE_OAUTH_RETRY_PARAM = "__vibe_oauth_retry"# 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 = 300+# Stable, per-browser binding id. Unlike the per-flow handshake state (which the+# iOS standalone PWA desyncs), this cookie is set once and reused, so it stays+# consistent across the cross-origin authorize excursion. The callback's+# server-side store-fallback is bound to hmac(secret, device_id), which an+# attacker cannot supply for a victim's browser — this closes the login-CSRF that+# a bare code+state callback URL would otherwise allow.+REMOTE_OAUTH_DEVICE_COOKIE_NAME = "__Host-vibe_oauth_device"+REMOTE_OAUTH_DEVICE_TTL_SECONDS = 180 * 24 * 60 * 60MUTATING_METHODS = {"POST", "PUT", "PATCH", "DELETE"}LOG_SOURCES = (("service", "vibe_remote.log", lambda: paths.get_logs_dir() / "vibe_remote.log"),@@ -1077,6 +1085,30 @@ def _oauth_cookie_signature(secret: str, payload: str) -> str:return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()+def _oauth_device_hash(secret: str, device_id: str) -> str:+ return hmac.new(secret.encode("utf-8"), f"device:{device_id}".encode("utf-8"), hashlib.sha256).hexdigest()+++def _oauth_device_id() -> str:+ """The caller's stable per-browser binding id from its device cookie (or None)."""+ return request.cookies.get(REMOTE_OAUTH_DEVICE_COOKIE_NAME) or ""+++def _oauth_store_record_device_bound(secret: str, record: dict[str, Any] | None) -> bool:+ """True when the request's device cookie matches the handshake record's binding.++ The store-fallback (cookie-state desync path) is only safe when we can prove the+ callback comes from the same browser that started the flow. The device cookie is+ that proof: it is stable across the iOS authorize excursion and an attacker+ cannot present a victim's value.+ """+ expected = (record or {}).get("device_hash")+ device_id = _oauth_device_id()+ if not expected or not device_id:+ return False+ return hmac.compare_digest(str(expected), _oauth_device_hash(secret, device_id))++def _make_oauth_cookie(secret: str, payload: dict[str, Any]) -> str:payload_text = quote(json.dumps(payload, separators=(",", ":")), safe="")signature = _oauth_cookie_signature(secret, payload_text)@@ -1206,11 +1238,22 @@ def _redirect_to_vibe_cloud_login(config: V2Config):rid=rid,)nonce = secrets.token_urlsafe(24)+ # Stable per-browser binding id: reuse the existing device cookie so it stays+ # consistent across the iOS authorize excursion (it is NOT regenerated per flow,+ # unlike the handshake state), generating one only on first use.+ device_id = _oauth_device_id() or 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)+ # device_hash binds that recovery to this browser; the cookie below stays the+ # strong per-browser binding for normal browsers.+ remote_access.store_oauth_handshake(+ rid,+ nonce=nonce,+ code_verifier=code_verifier,+ next_target=next_target,+ device_hash=_oauth_device_hash(cloud.session_secret, device_id),+ )oauth_cookie = _make_oauth_cookie(cloud.session_secret,{@@ -1232,6 +1275,15 @@ def _redirect_to_vibe_cloud_login(config: V2Config):path="/",max_age=REMOTE_OAUTH_HANDSHAKE_TTL_SECONDS,)+ response.set_cookie(+ REMOTE_OAUTH_DEVICE_COOKIE_NAME,+ device_id,+ httponly=True,+ secure=True,+ samesite="Lax",+ path="/",+ max_age=REMOTE_OAUTH_DEVICE_TTL_SECONDS,+ )return response@@ -2532,14 +2584,14 @@ def remote_access_auth_callback():code_verifier = cookie_state["code_verifier"]handshake_nonce = cookie_state.get("nonce")next_target = cookie_state.get("next")- elif cookie_state is not None and store_record is not None:- # Store-fallback for the iOS standalone PWA case. Require a *valid* same-origin- # handshake cookie to be present (even though its state differs): that proves- # this browser actually started a login on this instance, so the callback URL- # alone can't be replayed in a browser that never did (closes the cookie-absent- # bearer-login vector). The PWA always carries such a cookie — only its state- # desyncs because authorize ran in a separate in-app-browser context.- logger.info("oauth callback recovered via server-side handshake (cookie-less or desynced context)")+ elif store_record is not None and _oauth_store_record_device_bound(cloud.session_secret, store_record):+ # Store-fallback for the iOS standalone PWA case, where the handshake cookie's+ # state desyncs (authorize ran in a separate in-app-browser context). Gated on+ # the stable device cookie matching the handshake record, which proves this is+ # the same browser that started the flow — so a bare code+state callback URL+ # can't be replayed in another browser (closes login-CSRF). The PWA carries the+ # device cookie unchanged across the excursion, so recovery still succeeds.+ logger.info("oauth callback recovered via server-side handshake (device-bound, desynced cookie context)")code_verifier = store_record["code_verifier"]handshake_nonce = store_record.get("nonce")next_target = store_record.get("next")