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
harden(remote-access): atomic single-use handshake claim + require same-origin cookie for store-fallback
cyh3744ee1dd903
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.mdindex a8b4b5317..2cfacb3b8 100644--- a/docs/plans/pwa-oauth-login-state-desync.md+++ b/docs/plans/pwa-oauth-login-state-desync.md@@ -63,7 +63,34 @@ an instance is enforced by the avibe.bot backend** (`isEmailAuthorizedForInstancthe local instance only trusts backend-issued tokens (audience/issuer/noncechecked at exchange). The `state` remains HMAC-signed and single-use, so it cannotbe forged or replayed. The cookie's state-equality was a defense-in-depth layer-that is simply unavailable (and counter-productive) in standalone PWAs.+that is unavailable (and counter-productive) in standalone PWAs.++Codex review (gpt-5.5, xhigh) hardening applied:++- **Store-fallback requires a valid same-origin handshake cookie to be present**+ (its state may differ — that's the PWA desync — but it must parse/verify). This+ proves the browser actually started a login on this instance, so a bare+ `code+state` callback URL can't be replayed in a browser that never did. The PWA+ always carries such a cookie, so the fix still works.+- **`pop_oauth_handshake` is atomic single-use** via `os.replace` to a unique+ private name before reading, so concurrent callbacks for one `rid` can't both+ consume 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.## Testingdiff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pyindex 95eec78ad..e972efeb1 100644--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@ -1189,6 +1189,71 @@ 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.+ 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()++ 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")++ 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",+ follow_redirects=False,+ )++ # Never exchanged the code, and never redirected the browser to the target.+ assert exchanged == []+ assert response.headers.get("Location") != "/dashboard"+++def test_oauth_handshake_pop_is_atomic_single_use_under_concurrency(monkeypatch, tmp_path):+ import threading+ from unittest import mock++ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ remote_access.store_oauth_handshake("race-rid000", nonce="n", code_verifier="v", next_target="/")++ barrier = threading.Barrier(2)+ orig_replace = remote_access.os.replace++ def delayed_replace(src, dst):+ try:+ barrier.wait(timeout=5)+ except threading.BrokenBarrierError:+ pass+ return orig_replace(src, dst)++ results = []++ def worker():+ results.append(remote_access.pop_oauth_handshake("race-rid000"))++ with mock.patch.object(remote_access.os, "replace", delayed_replace):+ threads = [threading.Thread(target=worker) for _ in range(2)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ # The atomic claim guarantees exactly one racer gets the record.+ assert sum(1 for r in results if r is not None) == 1++def test_remote_callback_accepts_html_escaped_state_separator(monkeypatch, tmp_path):monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))config = _save_config(tmp_path)diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex b358787cf..7b1dbfc1d 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -930,17 +930,28 @@ def store_oauth_handshake(rid: str, *, nonce: str, code_verifier: str, next_targdef pop_oauth_handshake(rid: str | None) -> dict[str, Any] | None:- """Return and delete (single-use) the handshake for ``rid``; None if absent/expired."""+ """Return and delete (single-use) the handshake for ``rid``; None if absent/expired.++ The claim is atomic: the record file is ``os.replace``d to a unique private name+ before it is read, so under concurrent callbacks for the same ``rid`` exactly one+ racer wins and the others get ``None``.+ """if not rid or not _OAUTH_HANDSHAKE_RID_RE.match(rid):return None- path = _oauth_handshake_dir() / f"{rid}.json"+ directory = _oauth_handshake_dir()+ path = directory / f"{rid}.json"+ claim = directory / f".{rid}.{os.getpid()}.{secrets.token_hex(8)}.claim"+ try:+ os.replace(path, claim) # atomic single-use claim — only one racer can win+ except OSError:+ return Nonetry:- raw = path.read_text(encoding="utf-8")+ raw = claim.read_text(encoding="utf-8")except OSError:return Nonefinally:try:- path.unlink()+ claim.unlink()except OSError:passtry:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 9571a6878..4f57f6454 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2532,7 +2532,13 @@ def remote_access_auth_callback():code_verifier = cookie_state["code_verifier"]handshake_nonce = cookie_state.get("nonce")next_target = cookie_state.get("next")- elif store_record is not None:+ 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)")code_verifier = store_record["code_verifier"]handshake_nonce = store_record.get("nonce")