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
refactor(remote-access): rate-limit unauthenticated /auth + move handshake store in-memory
cyh7e173b8de495
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.mdindex 197575ae1..5c54bc333 100644--- a/docs/plans/pwa-oauth-login-state-desync.md+++ b/docs/plans/pwa-oauth-login-state-desync.md@@ -51,10 +51,13 @@ Stop requiring `cookie.state == url.state`. Recover the PKCE secrets by the- if neither yields a record → existing one-shot retry, then the friendlyre-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.+Server-side store: an **in-memory** dict keyed by the state id (`vibe/remote_access.py`),+single-use (`pop` under a lock), TTL-pruned, with a size cap. The UI server is a+single process that handles both the redirect and the callback, so memory is shared+and admission/single-use are trivially atomic under one lock. It is deliberately+*not* on disk — the handshake is short-lived and a mid-flow restart just means the+user logs in again; keeping it in memory removes the disk/inode DoS surface and the+file-cleanup/atomic-rename machinery entirely.## Security@@ -98,12 +101,21 @@ while giving the same binding. Its one assumption (iOS keeps the persistent devicookie stable across the excursion) is verified on the regression PWA; if that everfails, the `localStorage`-nonce variant is the fallback.-### Review round 2 (Codex P2s)--- **Bounded store** — the handshake store is written on every unauthenticated- redirect, so it now caps live entries (`OAUTH_HANDSHAKE_MAX_ENTRIES`) and sheds- *new* writes when full (preserving in-flight logins), preventing inode exhaustion- from a burst of unauthenticated requests.+### Hardening the unauthenticated path (Codex review)++The login-start redirect and `/auth/callback` are reachable without a session, so+unauthenticated floods are the root of the resource-growth concerns. Addressed at+the highest layer plus backstops:++- **Root: per-client rate limit** on the unauthenticated `/auth` path (`ui_server.py`,+ fixed window keyed by the Cloudflare-forwarded IP). A flood is `429`'d at the door,+ so the downstream store and diagnostics stay bounded; a real login spends only a+ couple of requests, far under the budget.+- **In-memory store with a size cap** — no disk/inode surface; the cap sheds new+ entries when full (preserving in-flight logins) as a backstop.+- **Rate-limited diagnostics** — every unauthenticated-reachable failure log goes+ through a per-key throttle; the capacity warning is throttled; the success-recovery+ line is `debug`.- **i18n** — the re-login page copy lives in `vibe/i18n` (`remote_access.oauth_error.*`,en + zh) and renders in the browser's `Accept-Language` (the only server-readablelocale signal pre-auth; the SPA keeps its language only in localStorage).diff --git a/tests/conftest.py b/tests/conftest.pyindex 367fa8ed1..e0c3c9ba8 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -39,3 +39,25 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):returnmonkeypatch.delenv("AVIBE_HOME", raising=False)monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path / ".vibe_remote"))++[email protected](autouse=True)+def _reset_oauth_runtime_state():+ """Reset module-level in-memory OAuth caches between tests.++ The handshake store, diagnostic-log throttles, and the unauthenticated /auth+ rate limiter live in process memory (not under the isolated VIBE_REMOTE_HOME),+ so without this they would leak across tests sharing a pytest process — e.g. the+ rate limiter accumulating across files and spuriously 429-ing an unrelated test.+ """+ try:+ from vibe import remote_access, ui_server+ except Exception:+ yield+ return+ caches = (remote_access._oauth_handshakes, ui_server._oauth_diag_log_state, ui_server._auth_ratelimit)+ for cache in caches:+ cache.clear()+ yield+ for cache in caches:+ cache.clear()diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.pyindex 062968931..d8494259b 100644--- a/tests/test_ui_remote_access_auth.py+++ b/tests/test_ui_remote_access_auth.py@@ -1,14 +1,13 @@from __future__ import annotationsimport ipaddress-import jsonimport socketimport asynciofrom collections import namedtupleimport httpx+import pytest-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@@ -1204,12 +1203,9 @@ def test_oauth_handshake_store_is_single_use_and_expires(monkeypatch, tmp_path):# 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).+ # An expired record is treated as absent.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))+ remote_access._oauth_handshakes["rid-exp"]["exp"] = 0assert remote_access.pop_oauth_handshake("rid-exp") is None# Invalid ids are rejected, never touching the filesystem.@@ -1257,8 +1253,28 @@ def test_oauth_handshake_cap_holds_under_concurrency(monkeypatch, tmp_path):for t in threads:t.join()- live = list((paths.get_runtime_dir() / "oauth_handshakes").glob("*.json"))- assert len(live) <= 5+ assert len(remote_access._oauth_handshakes) <= 5+++def test_unauthenticated_auth_requests_are_rate_limited(monkeypatch, tmp_path):+ # Root-level bound: a flood of unauthenticated login-start requests from one+ # client is 429'd, instead of each one doing handshake/cookie/log work.+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))+ _save_config(tmp_path)+ monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_PER_WINDOW", 3)+ client = app.test_client()++ statuses = [+ client.get(+ "/dashboard",+ base_url="https://alex.avibe.bot",+ environ_base={"REMOTE_ADDR": "203.0.113.77"},+ follow_redirects=False,+ ).status_code+ for _ in range(5)+ ]+ assert statuses[:3] == [302, 302, 302] # within budget -> redirect to login+ assert statuses[3:] == [429, 429] # over budget -> throttleddef test_oauth_diag_log_is_rate_limited(monkeypatch):diff --git a/vibe/remote_access.py b/vibe/remote_access.pyindex c41cc64f6..8fac8097f 100644--- a/vibe/remote_access.py+++ b/vibe/remote_access.py@@ -864,53 +864,39 @@ def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dict# --- 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.+# The login handshake (PKCE ``code_verifier`` + ``nonce`` + device binding) lives+# only between the login-start redirect and the ``/auth/callback`` of one flow+# (~5 min). iOS standalone PWAs run the cross-origin authorize step in a separate+# in-app-browser context, so the handshake *cookie* the callback reads can belong+# to a different ``GET /`` generation than the consent the user approved; we+# therefore also keep the handshake here, keyed by the signed state's random id, so+# the callback can recover it by the (signature-verified) state in the callback URL.+#+# Kept in process memory, not on disk: the UI server is a single process that+# handles both the redirect and the callback, the data is short-lived, and a+# mid-flow restart just means the user logs in again. This avoids a disk/inode DoS+# surface entirely and makes single-use + the cap trivially atomic under one lock.OAUTH_HANDSHAKE_TTL_SECONDS = 300-# Hard cap on live handshake files. The store is written on every unauthenticated-# redirect, so without a bound a burst of unauthenticated requests could exhaust-# inodes within the TTL. The cap sheds *new* writes when full (preserving in-flight-# logins) and is far above any realistic concurrent-login count.+# Cap on live handshakes — bounds memory under a burst of unauthenticated login+# starts; sheds new entries when full (preserving in-flight logins). Far above any+# realistic concurrent-login count. (The unauthenticated /auth rate limiter is the+# primary bound; this is a backstop.)OAUTH_HANDSHAKE_MAX_ENTRIES = 2048_OAUTH_HANDSHAKE_RID_RE = re.compile(r"\A[A-Za-z0-9_-]{1,64}\Z")-# Serializes prune+capacity-check+write so the cap is enforced atomically under a-# concurrent burst (count-then-write without a lock could blow past the cap).+# Guards prune + capacity-check + insert/pop so admission and single-use are atomic._OAUTH_STORE_LOCK = threading.Lock()-# Throttle the "at capacity" warning: under a sustained flood it would otherwise be-# emitted on every shed write and grow the log unbounded — the very thing the cap-# is meant to prevent.+_oauth_handshakes: dict[str, dict[str, Any]] = {}+# Throttle the "at capacity" warning so it can't itself grow the log under the flood+# it reports._OAUTH_STORE_CAPACITY_WARN_INTERVAL_SECONDS = 60.0_oauth_store_capacity_warned_at = 0.0-def _oauth_handshake_dir() -> Path:- return paths.get_runtime_dir() / "oauth_handshakes"---def _prune_oauth_handshakes(directory: Path) -> int:- """Delete expired records; return the number of surviving (live) entries."""- cutoff = time.time() - OAUTH_HANDSHAKE_TTL_SECONDS- survivors = 0- try:- entries = list(directory.glob("*.json"))- except OSError:- return 0- for entry in entries:- try:- if entry.stat().st_mtime < cutoff:- entry.unlink()- else:- survivors += 1- except OSError:- pass- return survivors+def _prune_oauth_handshakes(now: int) -> None:+ """Drop expired handshakes. Caller must hold ``_OAUTH_STORE_LOCK``."""+ for rid in [rid for rid, record in _oauth_handshakes.items() if record.get("exp", 0) <= now]:+ _oauth_handshakes.pop(rid, None)def _warn_oauth_store_at_capacity() -> None:@@ -925,80 +911,42 @@ def _warn_oauth_store_at_capacity() -> 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``.+ """Persist a login handshake in memory, keyed by the signed state's random id.- Single-use, ``OAUTH_HANDSHAKE_TTL_SECONDS`` TTL. Written atomically with- owner-only permissions under the runtime dir. Invalid ids are ignored.+ Single-use, ``OAUTH_HANDSHAKE_TTL_SECONDS`` TTL. 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- directory = _oauth_handshake_dir()- payload = {+ now = int(time.time())+ record = {"nonce": nonce,"code_verifier": code_verifier,"next": next_target,"device_hash": device_hash,- "exp": int(time.time()) + OAUTH_HANDSHAKE_TTL_SECONDS,+ "exp": now + OAUTH_HANDSHAKE_TTL_SECONDS,}- final = directory / f"{rid}.json"- tmp = directory / f".{rid}.{os.getpid()}.{secrets.token_hex(6)}.tmp"- # Hold the lock across prune + capacity-check + write so admission is atomic:- # otherwise a concurrent burst could all pass the check and blow past the cap.with _OAUTH_STORE_LOCK:- try:- directory.mkdir(parents=True, exist_ok=True)- directory.chmod(0o700)- except OSError:- pass- # Prune expired records first; if the store is still at capacity (i.e. a- # flood of fresh entries), shed this write rather than grow unbounded.- if _prune_oauth_handshakes(directory) >= OAUTH_HANDSHAKE_MAX_ENTRIES:+ _prune_oauth_handshakes(now)+ # At capacity (a flood of fresh entries): shed this one rather than grow+ # unbounded, but keep in-flight logins. Re-storing an existing id is allowed+ # (it doesn't grow the store).+ if len(_oauth_handshakes) >= OAUTH_HANDSHAKE_MAX_ENTRIES and rid not in _oauth_handshakes:_warn_oauth_store_at_capacity()return- 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+ _oauth_handshakes[rid] = recorddef 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 remove (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``.+ ``dict.pop`` under the lock is atomic, so concurrent callbacks for the same+ ``rid`` get exactly one winner."""if not rid or not _OAUTH_HANDSHAKE_RID_RE.match(rid):return None- 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 None- try:- raw = claim.read_text(encoding="utf-8")- except OSError:- return None- finally:- try:- claim.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()):+ with _OAUTH_STORE_LOCK:+ record = _oauth_handshakes.pop(rid, None)+ if record is None or record.get("exp", 0) <= int(time.time()):return None- return payload+ return recorddiff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex c125a9a2b..888672b7d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1487,6 +1487,52 @@ def _oauth_callback_error_response(error: str, *, next_target: Any, status: intreturn response+# --- Unauthenticated /auth rate limiting -----------------------------------+#+# The login-start redirect and /auth/callback are reachable without a session, so+# a flood of unauthenticated requests is the *root* of the resource-growth concerns+# on this path. A per-client fixed-window limiter bounds that flood at the door, so+# the downstream handshake store and diagnostics stay bounded without each needing+# its own guard. (The per-store cap and per-log throttles remain as cheap backstops.)+_AUTH_RATELIMIT_WINDOW_SECONDS = 60.0+_AUTH_RATELIMIT_MAX_PER_WINDOW = 60 # a real login spends a handful; this only stops floods+_AUTH_RATELIMIT_MAX_TRACKED_CLIENTS = 4096+_auth_ratelimit_lock = threading.Lock()+_auth_ratelimit: dict[str, list[float]] = {} # client -> [window_start_monotonic, count]+++def _auth_client_id() -> str:+ """Client identity for rate limiting: the Cloudflare-forwarded IP when present+ (remote traffic always arrives via the tunnel), else the connecting peer."""+ return (request.headers.get("CF-Connecting-IP") or request.remote_addr or "unknown").strip()+++def _auth_rate_limited() -> bool:+ """True when the caller has exceeded the unauthenticated /auth request budget."""+ client = _auth_client_id()+ now = time.monotonic()+ with _auth_ratelimit_lock:+ if len(_auth_ratelimit) > _AUTH_RATELIMIT_MAX_TRACKED_CLIENTS:+ for stale in [c for c, (ws, _c) in _auth_ratelimit.items() if now - ws >= _AUTH_RATELIMIT_WINDOW_SECONDS]:+ _auth_ratelimit.pop(stale, None)+ window_start, count = _auth_ratelimit.get(client, (0.0, 0))+ if now - window_start >= _AUTH_RATELIMIT_WINDOW_SECONDS:+ _auth_ratelimit[client] = [now, 1]+ return False+ if count >= _AUTH_RATELIMIT_MAX_PER_WINDOW:+ return True+ _auth_ratelimit[client] = [window_start, count + 1]+ return False+++def _auth_rate_limit_response():+ """Minimal 429 for an abusive unauthenticated /auth client (no per-request work)."""+ response = Response("Too Many Requests", status=429, mimetype="text/plain; charset=utf-8")+ response.headers["Retry-After"] = str(int(_AUTH_RATELIMIT_WINDOW_SECONDS))+ response.headers["Cache-Control"] = "no-store"+ return response++@app.before_requestdef start_api_request_timer():if request.path.startswith("/api/"):@@ -1528,6 +1574,10 @@ def enforce_remote_access_cookie():g.remote_session_renew = (str(payload.get("email", "")), str(payload.get("sub", "")))return Noneif request.method == "GET":+ # Bound unauthenticated login-start floods at the door (this writes a+ # handshake + sets cookies); a real user spends only a couple per login.+ if _auth_rate_limited():+ return _auth_rate_limit_response()return _redirect_to_vibe_cloud_login(config)return jsonify({"ok": False, "error": "remote_access_login_required"}), 401@@ -2596,6 +2646,9 @@ def remote_access_auth_callback():cloud = config.remote_access.vibe_cloudif not cloud.enabled:return jsonify({"error": "remote_access_disabled"}), 400+ # Unauthenticated endpoint: bound floods before any store lookup / logging.+ if _auth_rate_limited():+ return _auth_rate_limit_response()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)@@ -2619,7 +2672,7 @@ def remote_access_auth_callback():# 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)")+ logger.debug("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")