Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(remote-access): address codex P2s — bound handshake store + i18n the re-login page

cyhd95b39ea2e9e
diff --git a/docs/plans/pwa-oauth-login-state-desync.md b/docs/plans/pwa-oauth-login-state-desync.md
index 23fc03128..197575ae1 100644
--- a/docs/plans/pwa-oauth-login-state-desync.md
+++ b/docs/plans/pwa-oauth-login-state-desync.md
@@ -98,6 +98,16 @@ while giving the same binding. Its one assumption (iOS keeps the persistent devi
cookie stable across the excursion) is verified on the regression PWA; if that ever
fails, 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.
+- **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-readable
+ locale signal pre-auth; the SPA keeps its language only in localStorage).
+
## Testing
- Unit (`tests/test_ui_remote_access_auth.py`):
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index ea0cc7fe8..15a5f1d20 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -1217,6 +1217,43 @@ def test_oauth_handshake_store_is_single_use_and_expires(monkeypatch, tmp_path):
assert remote_access.pop_oauth_handshake(None) is None
+def test_oauth_handshake_store_caps_entries(monkeypatch, tmp_path):
+ # The store is written on every unauthenticated redirect; a hard cap prevents
+ # unbounded inode growth under a burst. At capacity, new writes are shed and
+ # existing in-flight entries are preserved.
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ monkeypatch.setattr(remote_access, "OAUTH_HANDSHAKE_MAX_ENTRIES", 3)
+
+ for i in range(3):
+ remote_access.store_oauth_handshake(f"rid-{i}", nonce="n", code_verifier="v", next_target="/")
+ remote_access.store_oauth_handshake("rid-overflow", nonce="n", code_verifier="v", next_target="/")
+
+ assert remote_access.pop_oauth_handshake("rid-overflow") is None
+ assert remote_access.pop_oauth_handshake("rid-0") is not None
+
+
+def test_oauth_error_page_localizes_from_accept_language(monkeypatch, tmp_path):
+ # The re-login page copy must come from vibe/i18n and honor the browser's
+ # Accept-Language (the only server-readable locale signal pre-auth).
+ 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",
+ headers={"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8"},
+ )
+
+ assert response.status_code == 400
+ body = response.text
+ assert '<html lang="zh"' in body
+ assert "登录会话已过期" in body # invalid_oauth_state_title (zh)
+ assert "重新登录" in body # sign_in_again (zh)
+ assert "Your sign-in session expired" not in body # not the English copy
+
+
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
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ddd4eb9d8..3215a5788 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -397,5 +397,19 @@
"routingChoosePrefix": "Choose a value for",
"routingSaving": "Saving routing settings...",
"routingCanceled": "Routing update canceled."
+ },
+ "remote_access": {
+ "oauth_error": {
+ "sign_in_again": "Sign in again",
+ "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.",
+ "invalid_oauth_state_title": "Your sign-in session expired",
+ "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.",
+ "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.json
index 9531e31f7..5d54d56df 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -397,5 +397,19 @@
"routingChoosePrefix": "请选择",
"routingSaving": "正在保存 Agent 路由设置...",
"routingCanceled": "已取消更新 Agent 路由设置。"
+ },
+ "remote_access": {
+ "oauth_error": {
+ "sign_in_again": "重新登录",
+ "cookie_hint": "重试后仍然卡住?请确认浏览器允许本站使用 Cookie。",
+ "default_title": "重新登录一下",
+ "default_body": "登录未完成,请重试。",
+ "invalid_oauth_state_title": "登录会话已过期",
+ "invalid_oauth_state_body": "安全登录链接已过期,或无法与当前浏览器匹配。这通常是因为登录链接闲置了几分钟,或在另一个标签页/窗口中打开。重新登录即可继续。",
+ "oauth_exchange_failed_title": "登录未能完成",
+ "oauth_exchange_failed_body": "Avibe Cloud 刚才没能完成登录,这通常是暂时的,请重试。",
+ "invalid_oauth_nonce_title": "无法验证此次登录",
+ "invalid_oauth_nonce_body": "本次登录未能通过验证,为保护你的账户已中止。请重新登录以继续。"
+ }
}
}
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index 7002005d6..fc1358423 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -7,6 +7,7 @@ import hashlib
import hmac
import ipaddress
import json
+import logging
import ntpath
import os
import platform
@@ -32,6 +33,8 @@ from config import paths
from config.v2_config import V2Config
from vibe import api, runtime
+logger = logging.getLogger(__name__)
+
CLOUDFLARED_BASE_URL = "https://github.com/cloudflare/cloudflared/releases/latest/download"
SESSION_COOKIE_NAME = "__Host-vibe_remote_session"
SESSION_TTL_SECONDS = 24 * 60 * 60
@@ -871,6 +874,11 @@ def exchange_oauth_code(config: V2Config, code: str, code_verifier: str) -> dict
# unguessable and single-use; the verifier never leaves the machine.
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.
+OAUTH_HANDSHAKE_MAX_ENTRIES = 2048
_OAUTH_HANDSHAKE_RID_RE = re.compile(r"\A[A-Za-z0-9_-]{1,64}\Z")
@@ -878,18 +886,23 @@ def _oauth_handshake_dir() -> Path:
return paths.get_runtime_dir() / "oauth_handshakes"
-def _prune_oauth_handshakes(directory: Path) -> None:
+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
+ return 0
for entry in entries:
try:
if entry.stat().st_mtime < cutoff:
entry.unlink()
+ else:
+ survivors += 1
except OSError:
pass
+ return survivors
def store_oauth_handshake(
@@ -909,7 +922,11 @@ def store_oauth_handshake(
directory.chmod(0o700)
except OSError:
pass
- _prune_oauth_handshakes(directory)
+ # Prune expired records first; if the store is still at capacity (i.e. flooded
+ # with fresh entries), shed this write rather than grow unbounded on disk.
+ if _prune_oauth_handshakes(directory) >= OAUTH_HANDSHAKE_MAX_ENTRIES:
+ logger.warning("oauth handshake store at capacity (>= %d); skipping write", OAUTH_HANDSHAKE_MAX_ENTRIES)
+ return
payload = {
"nonce": nonce,
"code_verifier": code_verifier,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 099d0705d..dc6407685 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -40,6 +40,7 @@ from core.show_pages import (
)
from core.show_session_events import show_event_payload_session_mismatch
from modules.agents.catalog import AGENT_BACKENDS, supports_runtime_refresh
+from vibe.i18n import get_supported_languages, t
from vibe.runtime import get_ui_dist_path, get_working_dir
from vibe.sentry_integration import init_sentry
@@ -1298,52 +1299,52 @@ 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.",
- ),
-}
+# 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"}
+
+
+def _request_ui_language() -> str:
+ """Best-effort UI language for a pre-auth page, from the Accept-Language header.
+
+ The Web UI persists its language only in localStorage (not a server-readable
+ cookie), so Accept-Language is the available signal here — and it matches what
+ the SPA's own navigator-based detection would pick. Falls back to English.
+ """
+ supported = set(get_supported_languages())
+ for part in (request.headers.get("Accept-Language") or "").split(","):
+ tag = part.split(";")[0].strip().lower()
+ if not tag:
+ continue
+ if tag in supported:
+ return tag
+ primary = tag.split("-")[0]
+ if primary in supported:
+ return primary
+ return "en"
-def _render_oauth_error_html(error: str, *, retry_href: str) -> str:
+def _render_oauth_error_html(error: str, *, retry_href: str, lang: str = "en") -> 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.
+ Replaces the old raw-JSON dead-end: the user sees a plain-language reason and a
+ single re-login button that navigates to ``retry_href`` (a sanitized same-origin
+ path), which re-enters the login flow via the auth gate. Copy is served from
+ ``vibe/i18n`` in ``lang``.
"""
- 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)
+ key = error if error in _OAUTH_ERROR_PAGE_CODES else "default"
+ safe_lang = html.escape(lang, quote=True)
+ safe_title = html.escape(t(f"remote_access.oauth_error.{key}_title", lang))
+ safe_message = html.escape(t(f"remote_access.oauth_error.{key}_body", lang))
+ 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)
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>"
- )
+ hint = f'<p class="oauth-error-hint">{html.escape(t("remote_access.oauth_error.cookie_hint", lang))}</p>'
return f"""<!doctype html>
-<html lang="en">
+<html lang="{safe_lang}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
@@ -1421,7 +1422,7 @@ def _render_oauth_error_html(error: str, *, retry_href: str) -> str:
<p>{safe_message}</p>
{hint}
<div class="oauth-error-actions">
- <a class="oauth-error-button" href="{safe_href}">Sign in again</a>
+ <a class="oauth-error-button" href="{safe_href}">{safe_button}</a>
</div>
<div class="oauth-error-code">{safe_code}</div>
</section>
@@ -1450,7 +1451,7 @@ def _oauth_callback_error_response(error: str, *, next_target: Any, status: int
)
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),
+ _render_oauth_error_html(error, retry_href=retry_href, lang=_request_ui_language()),
status=status,
mimetype="text/html; charset=utf-8",
)