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(pwa): keep cold launches out of OAuth sheets (#1238)

Call White9cab489c06bc
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 322eb1b0c..3a420df71 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -141,6 +141,13 @@ scenarios:
layer: scenario
backend: claude
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_claude_startup_cleanup_failure_emits_reset_path
+ - id: AUTH-SETUP-209
+ name: Remote Web cold launch keeps OAuth single-owned and completes one bounded retry
+ status: covered
+ kind: retry
+ layer: scenario
+ backend: web
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_remote_web_oauth_cold_launch_retry_is_single_owner
- id: AUTH-SETUP-901
name: Codex setup success refreshes runtime before the next turn
status: covered
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 1c5907ee0..491b04f85 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -4,10 +4,13 @@ import os
import sys
import tempfile
import unittest
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
+import httpx
+
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
@@ -16,8 +19,11 @@ from config.v2_config import (
ModelHubModelConfig,
ModelHubSourceConfig,
ModelHubSourceStateConfig,
+ PlatformsConfig,
+ RemoteAccessConfig,
RuntimeConfig,
SlackConfig,
+ UiConfig,
V2Config,
)
from core.agent_auth_service import AgentAuthService
@@ -36,6 +42,8 @@ from vibe.claude_config import (
materialize_claude_subprocess_env,
read_claude_settings_env,
)
+from vibe import remote_access, ui_server
+from vibe.ui_server import app
class _FakeNextTurnRuntime:
@@ -84,6 +92,203 @@ class _ReloadingV2ConfigController:
return V2Config.load()
+def _save_remote_web_auth_config() -> V2Config:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ platform="slack",
+ platforms=PlatformsConfig(enabled=["slack"], primary="slack"),
+ slack=SlackConfig(bot_token=""),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ ui=UiConfig(),
+ remote_access=RemoteAccessConfig(),
+ )
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.public_url = "https://alex.avibe.bot"
+ cloud.client_id = "vr_client_123"
+ cloud.instance_id = "inst_123"
+ cloud.session_secret = "session-secret"
+ cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
+ cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"
+ config.save()
+ return config
+
+
+def test_remote_web_oauth_cold_launch_retry_is_single_owner(monkeypatch, tmp_path):
+ """Scenario: AUTH-SETUP-209"""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_remote_web_auth_config()
+ ui_dist = tmp_path / "ui-dist"
+ ui_dist.mkdir()
+ (ui_dist / "index.html").write_text("<html><body>Avibe shell</body></html>", encoding="utf-8")
+ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)
+ with ui_server._auth_ratelimit_lock:
+ ui_server._auth_ratelimit.clear()
+
+ harness = SimpleNamespace(
+ primary=app.test_client(),
+ retry=app.test_client(),
+ base_url="https://alex.avibe.bot",
+ peer={"REMOTE_ADDR": "203.0.113.10"},
+ config=config,
+ )
+ runner = ScenarioRunner(harness)
+
+ def cold_launch(current):
+ response = current.primary.get(
+ "/old-route",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ assert response.status_code == 200
+ assert response.text == "<html><body>Avibe shell</body></html>"
+ assert response.headers.get("Location") is None
+ assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")
+
+ def start_background_providers(current):
+ session = current.primary.get(
+ "/api/session",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ )
+ assert session.get_json() == {"remote": True, "authenticated": False}
+
+ def request(path):
+ return app.test_client().get(
+ path,
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ responses = list(pool.map(request, ("/status", "/api/events", "/api/config")))
+ for response in responses:
+ assert response.status_code == 401
+ assert response.get_json()["error"] == "remote_access_login_required"
+ assert response.headers.get("Location") is None
+ assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")
+
+ def begin_explicit_login(current):
+ response = current.primary.get(
+ "/auth/login?next=/old-route",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ authorize = httpx.URL(response.headers["Location"])
+ current.first_state = authorize.params["state"]
+ state_payload = ui_server._read_oauth_state(
+ current.config.remote_access.vibe_cloud.session_secret,
+ current.first_state,
+ )
+ assert response.status_code == 302
+ assert authorize.host == "backend.test"
+ assert state_payload is not None
+ assert state_payload["next"] == "/old-route"
+ assert state_payload["retry"] is False
+
+ def lose_browser_context_and_retry(current):
+ response = current.retry.get(
+ f"/auth/callback?code=lost-context&state={current.first_state}",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ retry_target = response.headers["Location"]
+ assert response.status_code == 302
+ assert retry_target == f"/old-route?{ui_server.REMOTE_OAUTH_RETRY_PARAM}=1"
+
+ retry_shell = current.retry.get(
+ retry_target,
+ base_url=current.base_url,
+ environ_base=current.peer,
+ headers={"Accept": "text/html"},
+ follow_redirects=False,
+ )
+ assert retry_shell.status_code == 200
+ assert retry_shell.text == "<html><body>Avibe shell</body></html>"
+
+ login = current.retry.get(
+ f"/auth/login?{httpx.QueryParams({'next': retry_target})}",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ authorize = httpx.URL(login.headers["Location"])
+ current.retry_state = authorize.params["state"]
+ current.retry_nonce = authorize.params["nonce"]
+ state_payload = ui_server._read_oauth_state(
+ current.config.remote_access.vibe_cloud.session_secret,
+ current.retry_state,
+ )
+ assert login.status_code == 302
+ assert authorize.host == "backend.test"
+ assert state_payload is not None
+ assert state_payload["next"] == "/old-route"
+ assert state_payload["retry"] is True
+
+ def complete_retry(current):
+ monkeypatch.setattr(
+ remote_access,
+ "exchange_oauth_code",
+ lambda _config, code, _verifier: {
+ "claims": {
+ "email": "[email protected]",
+ "sub": "user-1",
+ "nonce": current.retry_nonce,
+ "code": code,
+ }
+ },
+ )
+ callback = current.retry.get(
+ f"/auth/callback?code=accepted&state={current.retry_state}",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ assert callback.status_code == 302
+ assert callback.headers["Location"] == "/old-route"
+
+ session = current.retry.get(
+ "/api/session",
+ base_url=current.base_url,
+ environ_base=current.peer,
+ )
+ assert session.get_json()["authenticated"] is True
+ shell = current.retry.get(
+ callback.headers["Location"],
+ base_url=current.base_url,
+ environ_base=current.peer,
+ follow_redirects=False,
+ )
+ assert shell.status_code == 200
+ assert shell.text == "<html><body>Avibe shell</body></html>"
+
+ asyncio.run(
+ runner.run(
+ ScenarioStep("cold_launch_unknown_route", cold_launch),
+ ScenarioStep("start_background_providers", start_background_providers),
+ ScenarioStep("begin_explicit_login", begin_explicit_login),
+ ScenarioStep("retry_after_browser_context_loss", lose_browser_context_and_retry),
+ ScenarioStep("complete_retry", complete_retry),
+ )
+ )
+ ScenarioExpect.step_history(
+ runner,
+ [
+ "cold_launch_unknown_route",
+ "start_background_providers",
+ "begin_explicit_login",
+ "retry_after_browser_context_loss",
+ "complete_retry",
+ ],
+ )
+
+
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_claude_oauth_to_explicit_auth_token_reaches_next_turn(self):
"""Scenario: AUTH-SETUP-904"""
diff --git a/tests/test_dock_api.py b/tests/test_dock_api.py
index fc09a6d92..3731885ab 100644
--- a/tests/test_dock_api.py
+++ b/tests/test_dock_api.py
@@ -2,8 +2,8 @@
Mutations are exercised at the ``vibe.api`` layer (like the sibling Show Pages
admin tests); the route layer is covered for the GET round-trip and, crucially,
-for auth parity — a remote request without a session is bounced to login, so a
-``/api/dock`` route can never be an unauthenticated native endpoint.
+for auth parity — a remote request without a session gets the login-required API
+contract, so a ``/api/dock`` route can never be an unauthenticated native endpoint.
"""
import pytest
@@ -11,7 +11,7 @@ import pytest
from core.dock_store import BUILTIN_DOCK_IDS, DockError
from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
from tests.test_ui_remote_access_auth import _remote_peer, _save_config
-from vibe import api
+from vibe import api, ui_server
from vibe.ui_server import app
@@ -440,8 +440,8 @@ def test_dock_route_round_trip_via_client(monkeypatch, tmp_path):
def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):
"""Auth parity: the Dock routes inherit ``enforce_remote_access_cookie`` — a
- remote request without a session is bounced to the OAuth login, never served
- as an unauthenticated native endpoint."""
+ remote request without a session gets the login-required API contract, never
+ an OAuth side effect or an unauthenticated native response."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
@@ -451,8 +451,10 @@ def test_dock_route_blocked_for_remote_without_session(monkeypatch, tmp_path):
environ_base=_remote_peer(),
follow_redirects=False,
)
- assert get_resp.status_code == 302
- assert get_resp.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert get_resp.status_code == 401
+ assert get_resp.get_json()["error"] == "remote_access_login_required"
+ assert get_resp.headers.get("Location") is None
+ assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in get_resp.headers.get("Set-Cookie", "")
# The mutating routes are gated by the same before-request hook.
post_resp = app.test_client().post(
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index fdde9c872..816df74bc 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -5,6 +5,7 @@ import logging
import socket
import asyncio
from collections import namedtuple
+from urllib.parse import urlencode
import httpx
import pytest
@@ -103,12 +104,38 @@ def _cloudflare_headers() -> dict[str, str]:
return {"CF-Connecting-IP": "198.51.100.10", "CF-Ray": "test-ray"}
-def test_remote_host_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):
+def _mock_ui_dist(monkeypatch, tmp_path):
+ ui_dist = tmp_path / "ui-dist"
+ ui_dist.mkdir()
+ (ui_dist / "index.html").write_text("<html><body>Avibe shell</body></html>", encoding="utf-8")
+ monkeypatch.setattr(ui_server, "get_ui_dist_path", lambda: ui_dist)
+ return ui_dist
+
+
[email protected]("path", ["/", "/dashboard", "/chat/session-1"])
+def test_remote_spa_document_serves_shell_without_starting_login(monkeypatch, tmp_path, path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
+
+ response = app.test_client().get(
+ path,
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 200
+ assert response.headers.get("Location") is None
+ assert response.text == "<html><body>Avibe shell</body></html>"
+
+
+def test_remote_login_endpoint_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
response = app.test_client().get(
- "/dashboard",
+ "/auth/login?next=/dashboard",
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
follow_redirects=False,
@@ -123,6 +150,44 @@ def test_remote_host_redirects_to_vibe_cloud_login(monkeypatch, tmp_path):
assert state_payload["retry"] is False
+def test_remote_login_endpoint_sanitizes_external_next_target(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+
+ response = app.test_client().get(
+ "/auth/login?next=https://evil.example/path",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ state = httpx.URL(response.headers["Location"]).params["state"]
+ state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, state)
+ assert state_payload is not None
+ assert state_payload["next"] == "/"
+
+
+def test_remote_login_endpoint_returns_authenticated_session_to_target(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_access.make_session_cookie(config, "[email protected]", "user-1"),
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get(
+ "/auth/login?next=/chat/session-1",
+ base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/chat/session-1"
+
+
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
@@ -159,9 +224,10 @@ def test_login_redirect_sets_stable_device_binding_cookie(monkeypatch, tmp_path)
assert "Secure" in device_cookies[0]
-def test_remote_setup_route_requires_vibe_cloud_login(monkeypatch, tmp_path):
+def test_remote_setup_route_serves_shell_before_login(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
+ _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
response = app.test_client().get(
"/setup",
@@ -170,27 +236,27 @@ def test_remote_setup_route_requires_vibe_cloud_login(monkeypatch, tmp_path):
follow_redirects=False,
)
- assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
- state = httpx.URL(response.headers["Location"]).params["state"]
- state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, state)
- assert state_payload is not None
- assert state_payload["next"] == "/setup"
+ assert response.status_code == 200
+ assert response.headers.get("Location") is None
+ assert "Avibe shell" in response.text
-def test_remote_config_get_without_session_returns_login_required(monkeypatch, tmp_path):
[email protected]("path", ["/api/config", "/status", "/api/events"])
+def test_remote_background_get_without_session_returns_login_required(monkeypatch, tmp_path, path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
response = app.test_client().get(
- "/api/config",
+ path,
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
follow_redirects=False,
)
- assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert response.status_code == 401
+ assert response.get_json()["error"] == "remote_access_login_required"
+ assert response.headers.get("Location") is None
+ assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")
def test_api_config_blocked_host_returns_machine_readable_error(monkeypatch, tmp_path):
@@ -212,43 +278,81 @@ def test_api_config_blocked_host_returns_machine_readable_error(monkeypatch, tmp
assert response.get_json()["error"] == "remote_access_host_mismatch"
-def test_remote_host_strips_retry_marker_from_oauth_next(monkeypatch, tmp_path):
+def test_remote_private_document_routes_through_dedicated_login_endpoint(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
+ _save_config(tmp_path)
response = app.test_client().get(
- f"/show/ses123/?foo=bar&{ui_server.REMOTE_OAUTH_RETRY_PARAM}=1",
+ "/show/ses123/?foo=bar",
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
+ headers={"Accept": "text/html"},
follow_redirects=False,
)
assert response.status_code == 302
- state = httpx.URL(response.headers["Location"]).params["state"]
- state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, state)
+ assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F%3Ffoo%3Dbar"
+ assert ui_server.REMOTE_OAUTH_COOKIE_NAME not in response.headers.get("Set-Cookie", "")
+
+
+def test_remote_login_preserves_callback_retry_budget(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
+ client = app.test_client()
+ state = ui_server._make_oauth_state(
+ config.remote_access.vibe_cloud.session_secret,
+ next_target="/show/ses123/?tab=flow",
+ )
+
+ callback = client.get(
+ f"/auth/callback?code=test-code&state={state}",
+ base_url="https://alex.avibe.bot",
+ follow_redirects=False,
+ )
+ retry_target = callback.headers["Location"]
+ login_entry = client.get(
+ retry_target,
+ base_url="https://alex.avibe.bot",
+ headers={"Accept": "text/html"},
+ follow_redirects=False,
+ )
+ login = client.get(
+ login_entry.headers["Location"],
+ base_url="https://alex.avibe.bot",
+ follow_redirects=False,
+ )
+
+ assert login_entry.status_code == 302
+ assert login_entry.headers["Location"] == f"/auth/login?{urlencode({'next': retry_target})}"
+ assert login.status_code == 302
+ oauth_state = httpx.URL(login.headers["Location"]).params["state"]
+ state_payload = ui_server._read_oauth_state(config.remote_access.vibe_cloud.session_secret, oauth_state)
assert state_payload is not None
- assert state_payload["next"] == "/show/ses123/?foo=bar"
+ assert state_payload["next"] == "/show/ses123/?tab=flow"
assert state_payload["retry"] is True
-def test_remote_host_with_explicit_port_still_requires_login(monkeypatch, tmp_path):
+def test_remote_spa_document_with_explicit_port_still_serves_shell(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
response = app.test_client().get("/dashboard", base_url="https://alex.avibe.bot:443", follow_redirects=False)
- assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert response.status_code == 200
+ assert response.headers.get("Location") is None
-def test_remote_host_with_trailing_dot_still_requires_login(monkeypatch, tmp_path):
+def test_remote_spa_document_with_trailing_dot_still_serves_shell(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
response = app.test_client().get("/dashboard", base_url="https://alex.avibe.bot.", follow_redirects=False)
- assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert response.status_code == 200
+ assert response.headers.get("Location") is None
def test_remote_health_does_not_require_remote_access_cookie(monkeypatch, tmp_path):
@@ -677,6 +781,7 @@ def _forged_session_cookie(config: V2Config, exp: int, *, email: str = "alex@exa
def test_remote_host_does_not_renew_fresh_cookie(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
@@ -695,6 +800,7 @@ def test_remote_host_renews_cookie_past_half_ttl(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
near_exp = int(_time.time()) + (remote_access.SESSION_TTL_SECONDS // 2) - 60
cookie = _forged_session_cookie(config, near_exp)
client = app.test_client()
@@ -833,7 +939,8 @@ def test_cloudflare_forwarded_request_with_loopback_host_fails_closed(monkeypatc
def test_trusted_proxy_forwarded_host_routes_remote_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
monkeypatch.setenv(ui_server.TRUSTED_PROXY_IPS_ENV, "127.0.0.1")
- config = _save_config(tmp_path)
+ _save_config(tmp_path)
+ _mock_ui_dist(monkeypatch, tmp_path)
response = app.test_client().get(
"/dashboard",
@@ -847,8 +954,8 @@ def test_trusted_proxy_forwarded_host_routes_remote_access(monkeypatch, tmp_path
follow_redirects=False,
)
- assert response.status_code == 302
- assert response.headers["Location"].startswith(config.remote_access.vibe_cloud.authorization_endpoint)
+ assert response.status_code == 200
+ assert response.headers.get("Location") is None
def test_ra_tq_026_remote_status_uses_cf_ray_on_paired_public_host(monkeypatch, tmp_path):
@@ -1603,8 +1710,8 @@ def test_oauth_handshake_cap_holds_under_concurrency(monkeypatch, tmp_path):
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.
+ # A flood of explicit login-start requests from one client is 429'd, instead
+ # of each one doing handshake/cookie/log work.
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
_save_config(tmp_path)
monkeypatch.setattr(ui_server, "_AUTH_RATELIMIT_MAX_PER_WINDOW", 3)
@@ -1612,14 +1719,14 @@ def test_unauthenticated_auth_requests_are_rate_limited(monkeypatch, tmp_path):
statuses = [
client.get(
- "/dashboard",
+ "/auth/login?next=/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] == [302, 302, 302] # within budget -> redirect to OAuth
assert statuses[3:] == [429, 429] # over budget -> throttled
@@ -1634,7 +1741,7 @@ def test_auth_rate_limit_ignores_untrusted_forwarded_ip(monkeypatch, tmp_path):
statuses = [
client.get(
- "/dashboard",
+ "/auth/login?next=/dashboard",
base_url="https://alex.avibe.bot",
environ_base={"REMOTE_ADDR": "203.0.113.90"},
headers={"CF-Connecting-IP": f"9.9.9.{i}"}, # rotated each request
@@ -1657,7 +1764,7 @@ def test_auth_rate_limit_keys_trusted_proxy_by_forwarded_client(monkeypatch, tmp
def get_status(client_ip: str) -> int:
return client.get(
- "/dashboard",
+ "/auth/login?next=/dashboard",
base_url="http://127.0.0.1:5123",
environ_base={"REMOTE_ADDR": "127.0.0.1"},
headers={
@@ -1687,7 +1794,7 @@ def test_auth_rate_limit_table_is_bounded(monkeypatch, tmp_path):
for i in range(10): # 10 distinct peers
client.get(
- "/dashboard",
+ "/auth/login?next=/dashboard",
base_url="https://alex.avibe.bot",
environ_base={"REMOTE_ADDR": f"198.51.100.{i}"},
follow_redirects=False,
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index efff86e4d..3b19a59a8 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -323,11 +323,12 @@ def test_private_show_page_requires_remote_login(monkeypatch, tmp_path):
"/show/ses123/",
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
+ headers={"Accept": "text/html"},
follow_redirects=False,
)
assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F"
def test_private_show_page_serves_locally(monkeypatch, tmp_path):
@@ -366,11 +367,12 @@ def test_public_show_page_still_requires_remote_login(monkeypatch, tmp_path):
"/show/ses123/",
base_url="https://alex.avibe.bot",
environ_base=_remote_peer(),
+ headers={"Accept": "text/html"},
follow_redirects=False,
)
assert response.status_code == 302
- assert response.headers["Location"].startswith("https://backend.test/oauth/authorize?")
+ assert response.headers["Location"] == "/auth/login?next=%2Fshow%2Fses123%2F"
def test_offline_show_page_not_served_by_authed_route(monkeypatch, tmp_path):
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index bfcaae949..ea9379e89 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -49,7 +49,13 @@ import { AgentationToggle } from './components/AgentationToggle';
import { PwaLoopbackLinkGuard } from './components/PwaLoopbackLinkGuard';
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
-import { REMOTE_AUTH_REQUIRED_EVENT, shouldDeferRemoteAuthRedirect } from './lib/remoteAuth';
+import {
+ checkRemoteAuthForPath,
+ isSetupCheckBypassed,
+ remoteLoginPath,
+ REMOTE_AUTH_REQUIRED_EVENT,
+ shouldDeferRemoteAuthRedirect,
+} from './lib/remoteAuth';
// Apps layer pages are lazy: they share their chunk with the windowed app bodies
// (registry.tsx) instead of being pulled into the main entry by these routes, so
@@ -93,17 +99,14 @@ import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';
import { Button } from './components/ui/button';
-// Paths that bypass the setup guard so the wizard and diagnostics can show
-// logs / doctor output even before configuration is complete.
-const LOGIN_CHECK_PATHS = new Set(['/admin/logs', '/admin/settings/diagnostics']);
-
const RemoteLoginGate = ({ target }: { target: string }) => {
const { t } = useTranslation();
const requireUserAction = shouldDeferRemoteAuthRedirect();
+ const loginPath = remoteLoginPath(target);
useEffect(() => {
- if (!requireUserAction) window.location.assign(target);
- }, [requireUserAction, target]);
+ if (!requireUserAction) window.location.assign(loginPath);
+ }, [loginPath, requireUserAction]);
if (requireUserAction) {
return (
@@ -114,7 +117,7 @@ const RemoteLoginGate = ({ target }: { target: string }) => {
<CardDescription>{t('remoteLogin.body')}</CardDescription>
</CardHeader>
<CardContent>
- <Button onClick={() => window.location.assign(target)}>{t('remoteLogin.action')}</Button>
+ <Button onClick={() => window.location.assign(loginPath)}>{t('remoteLogin.action')}</Button>
</CardContent>
</Card>
</main>
@@ -232,7 +235,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
const [guardStatus, setGuardStatus] = useState<GuardStatus>('loading');
const [blockedCode, setBlockedCode] = useState<string | null>(null);
const [authCheckVersion, setAuthCheckVersion] = useState(0);
- const bypassSetupGuard = LOGIN_CHECK_PATHS.has(location.pathname);
+ const bypassSetupGuard = isSetupCheckBypassed(location.pathname);
// Re-validate only when crossing the setup boundary, not on every
// route change. The wizard completes by saving config and navigating
// off /setup; that pathname flip re-runs the effect so the stale
@@ -271,10 +274,6 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
useEffect(() => {
let cancelled = false;
- if (bypassSetupGuard) {
- return;
- }
-
// Reset to loading while (re)validating. On the setup-boundary
// re-run this prevents a one-frame bounce: a stale `needs-setup`
// on a non-/setup route would otherwise redirect to /setup before
@@ -282,12 +281,16 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
// transition is fine — it's the setup boundary, not every nav.
setGuardStatus('loading');
- getAuthSession().then(session => {
+ checkRemoteAuthForPath(location.pathname, getAuthSession).then(({ loginRequired, checkSetup }) => {
if (cancelled) return;
- if (session.remote && !session.authenticated) {
+ if (loginRequired) {
setGuardStatus('remote-login-required');
return null;
}
+ if (!checkSetup) {
+ setGuardStatus('ready');
+ return null;
+ }
return getConfig().then(config => {
if (cancelled) return;
const setupState = config?.setup_state;
@@ -298,12 +301,16 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
});
}).catch(async (error) => {
if (cancelled) return;
- const session = await getAuthSession().catch(() => null);
+ const authCheck = await checkRemoteAuthForPath(location.pathname, getAuthSession).catch(() => null);
if (cancelled) return;
- if (session?.remote && !session.authenticated) {
+ if (authCheck?.loginRequired) {
setGuardStatus('remote-login-required');
return;
}
+ if (authCheck && !authCheck.checkSetup) {
+ setGuardStatus('ready');
+ return;
+ }
const blocked = accessBlockedCode(error);
if (blocked) {
// Server is up and the session probe was fine, but it refused
@@ -331,7 +338,6 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
// shell behind the Loading state).
}, [authCheckVersion, bypassSetupGuard, isSetupRoute, getConfig, getAuthSession]);
- if (bypassSetupGuard) return children;
if (guardStatus === 'loading') {
return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
}
@@ -341,6 +347,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
if (guardStatus === 'access-blocked') {
return <AccessBlocked code={blockedCode} />;
}
+ if (bypassSetupGuard) return children;
if (guardStatus === 'needs-setup') {
if (location.pathname === '/setup') return children;
// A wizard finish navigates from /setup to / before the re-validation
@@ -645,6 +652,10 @@ const router = createBrowserRouter(
<Route path="/remote-access" element={<Navigate to="/admin/remote-access" replace />} />
<Route path="/doctor" element={<Navigate to="/admin/settings/diagnostics" replace />} />
<Route path="/doctor/logs" element={<Navigate to="/admin/logs" replace />} />
+ {/* The server intentionally serves the SPA shell for every extensionless
+ path. Keep stale bookmarks and retired push targets inside AuthGuard,
+ then recover authenticated/local clients to the workbench root. */}
+ <Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Route>,
),
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
index 6b342d642..a2946c20c 100644
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@ -1,8 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-const deferRemoteAuthRedirect = vi.hoisted(() => vi.fn());
+const remoteAuth = vi.hoisted(() => ({
+ deferRemoteAuthRedirect: vi.fn(),
+ remoteLoginPath: vi.fn((target: string) => `/auth/login?next=${encodeURIComponent(target)}`),
+}));
-vi.mock('./remoteAuth', () => ({ deferRemoteAuthRedirect }));
+vi.mock('./remoteAuth', () => remoteAuth);
import {
apiFetch,
@@ -10,9 +13,9 @@ import {
describe('apiFetch remote auth recovery', () => {
beforeEach(() => {
- deferRemoteAuthRedirect.mockReturnValue(true);
+ remoteAuth.deferRemoteAuthRedirect.mockReturnValue(true);
vi.stubGlobal('window', {
- location: { href: 'https://alex.avibe.bot/inbox', assign: vi.fn() },
+ location: { pathname: '/inbox', search: '?filter=open', assign: vi.fn() },
});
});
@@ -33,10 +36,27 @@ describe('apiFetch remote auth recovery', () => {
const response = await apiFetch('/api/inbox');
expect(response.status).toBe(401);
- await vi.waitFor(() => expect(deferRemoteAuthRedirect).toHaveBeenCalledOnce());
+ await vi.waitFor(() => expect(remoteAuth.deferRemoteAuthRedirect).toHaveBeenCalledOnce());
expect(window.location.assign).not.toHaveBeenCalled();
});
+ it('uses the dedicated login endpoint outside an iOS standalone PWA', async () => {
+ remoteAuth.deferRemoteAuthRedirect.mockReturnValue(false);
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () =>
+ Response.json({ error: 'remote_access_login_required' }, { status: 401 }),
+ ),
+ );
+
+ await apiFetch('/api/inbox');
+
+ await vi.waitFor(() => expect(window.location.assign).toHaveBeenCalledWith(
+ '/auth/login?next=%2Finbox%3Ffilter%3Dopen',
+ ));
+ expect(remoteAuth.remoteLoginPath).toHaveBeenCalledWith('/inbox?filter=open');
+ });
+
it('does not start remote auth for an unrelated 401', async () => {
vi.stubGlobal(
'fetch',
@@ -46,7 +66,7 @@ describe('apiFetch remote auth recovery', () => {
await apiFetch('/api/inbox');
await new Promise((resolve) => setTimeout(resolve, 0));
- expect(deferRemoteAuthRedirect).not.toHaveBeenCalled();
+ expect(remoteAuth.deferRemoteAuthRedirect).not.toHaveBeenCalled();
});
it('honors the request signal while a shared CSRF request is pending', async () => {
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index bf2380693..edfc77f83 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -1,4 +1,4 @@
-import { deferRemoteAuthRedirect } from './remoteAuth';
+import { deferRemoteAuthRedirect, remoteLoginPath } from './remoteAuth';
const CSRF_COOKIE_NAME = 'vibe_csrf_token';
const CSRF_HEADER_NAME = 'X-Vibe-CSRF-Token';
@@ -149,8 +149,6 @@ async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void
if (deferRemoteAuthRedirect()) return;
redirectingForRemoteAuth = true;
- // Full-page navigation to the current path: enforce_remote_access_cookie
- // redirects an unauthenticated browser request to the Avibe Cloud login
- // (mirrors RemoteLoginRedirect in App.tsx).
- window.location.assign(window.location.href);
+ const target = window.location.pathname + window.location.search;
+ window.location.assign(remoteLoginPath(target));
}
diff --git a/ui/src/lib/remoteAuth.test.ts b/ui/src/lib/remoteAuth.test.ts
index 6a121aea6..8a5647608 100644
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -8,7 +8,9 @@ const platform = vi.hoisted(() => ({
vi.mock('./platform', () => platform);
import {
+ checkRemoteAuthForPath,
deferRemoteAuthRedirect,
+ remoteLoginPath,
REMOTE_AUTH_REQUIRED_EVENT,
shouldDeferRemoteAuthRedirect,
} from './remoteAuth';
@@ -36,6 +38,39 @@ describe('remote auth navigation', () => {
expect(shouldDeferRemoteAuthRedirect(context)).toBe(false);
});
+ it('starts login through the dedicated endpoint while preserving the requested route', () => {
+ expect(remoteLoginPath('/chat/session-1?view=activity')).toBe(
+ '/auth/login?next=%2Fchat%2Fsession-1%3Fview%3Dactivity',
+ );
+ });
+
+ it.each(['https://evil.example/path', '//evil.example/path', 'chat/session-1'])(
+ 'falls back to the app root for an unsafe login target: %s',
+ (target) => {
+ expect(remoteLoginPath(target)).toBe('/auth/login?next=%2F');
+ },
+ );
+
+ it.each(['/admin/logs', '/admin/settings/diagnostics'])(
+ 'keeps remote session authentication enabled while bypassing setup checks for %s',
+ async (path) => {
+ const getSession = vi.fn(async () => ({ remote: true, authenticated: false }));
+
+ await expect(checkRemoteAuthForPath(path, getSession)).resolves.toEqual({
+ loginRequired: true,
+ checkSetup: false,
+ });
+ expect(getSession).toHaveBeenCalledOnce();
+ },
+ );
+
+ it('checks setup after an authenticated remote session on regular app routes', async () => {
+ await expect(checkRemoteAuthForPath(
+ '/inbox',
+ async () => ({ remote: true, authenticated: true }),
+ )).resolves.toEqual({ loginRequired: false, checkSetup: true });
+ });
+
it('signals AuthGuard instead of navigating automatically', () => {
platform.isIosDevice.mockReturnValue(true);
platform.isStandalonePwa.mockReturnValue(true);
diff --git a/ui/src/lib/remoteAuth.ts b/ui/src/lib/remoteAuth.ts
index c717cab9b..293a56e64 100644
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@ -1,18 +1,44 @@
import { isIosDevice, isStandalonePwa } from './platform';
export const REMOTE_AUTH_REQUIRED_EVENT = 'avibe.remote-auth-required';
+const REMOTE_LOGIN_PATH = '/auth/login';
+const SETUP_CHECK_BYPASS_PATHS = new Set(['/admin/logs', '/admin/settings/diagnostics']);
type PwaContext = {
ios: boolean;
standalone: boolean;
};
+type RemoteSession =
+ | { remote: false }
+ | { remote: true; authenticated: boolean };
+
export function shouldDeferRemoteAuthRedirect(
context: PwaContext = { ios: isIosDevice(), standalone: isStandalonePwa() },
): boolean {
return context.ios && context.standalone;
}
+export function remoteLoginPath(target: string): string {
+ const next = target.startsWith('/') && !target.startsWith('//') ? target : '/';
+ return `${REMOTE_LOGIN_PATH}?next=${encodeURIComponent(next)}`;
+}
+
+export function isSetupCheckBypassed(path: string): boolean {
+ return SETUP_CHECK_BYPASS_PATHS.has(path);
+}
+
+export async function checkRemoteAuthForPath(
+ path: string,
+ getSession: () => Promise<RemoteSession>,
+): Promise<{ loginRequired: boolean; checkSetup: boolean }> {
+ const session = await getSession();
+ return {
+ loginRequired: session.remote && !session.authenticated,
+ checkSetup: !isSetupCheckBypassed(path),
+ };
+}
+
export function deferRemoteAuthRedirect(): boolean {
if (!shouldDeferRemoteAuthRedirect() || typeof window === 'undefined') return false;
window.dispatchEvent(new Event(REMOTE_AUTH_REQUIRED_EVENT));
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index efd207735..6ea7801ee 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1466,6 +1466,7 @@ def _remote_auth_exempt_path() -> bool:
path = request.path
return (
path == "/health"
+ or path == "/auth/login"
or path == "/auth/callback"
or path == "/auth/logout"
or path == "/api/session"
@@ -1498,6 +1499,11 @@ def _remote_auth_exempt_before_host_validation() -> bool:
)
+def _is_ui_static_request() -> bool:
+ endpoint = request._request.scope.get("endpoint")
+ return getattr(endpoint, "__name__", "") == "serve_static_compat_endpoint"
+
+
def _oauth_cookie_signature(secret: str, payload: str) -> str:
return hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).hexdigest()
@@ -1626,6 +1632,14 @@ def _strip_oauth_retry_param(value: str) -> str:
return urlunsplit(("", "", parsed.path or "/", query, ""))
+def _oauth_retry_requested(value: Any) -> bool:
+ target = _safe_remote_redirect_target(value)
+ return any(
+ key == REMOTE_OAUTH_RETRY_PARAM and val == "1"
+ for key, val in parse_qsl(urlsplit(target).query, keep_blank_values=True)
+ )
+
+
def _add_oauth_retry_param(value: str) -> str:
target = _strip_oauth_retry_param(value)
parsed = urlsplit(target)
@@ -1638,20 +1652,20 @@ def _oauth_callback_arg(name: str) -> str | None:
return request.args.get(name) or request.args.get(f"amp;{name}")
-def _redirect_to_vibe_cloud_login(config: V2Config):
+def _redirect_to_vibe_cloud_login(config: V2Config, *, next_target: Any | None = None):
from vibe import remote_access
cloud = config.remote_access.vibe_cloud
code_verifier = secrets.token_urlsafe(48)
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
- raw_next = request.full_path if request.query_string else request.path
+ raw_next = next_target if next_target is not None else (request.full_path if request.query_string else request.path)
next_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",
+ retry=_oauth_retry_requested(raw_next),
rid=rid,
)
nonce = secrets.token_urlsafe(24)
@@ -2161,12 +2175,14 @@ def enforce_remote_access_cookie():
if remote_access.session_needs_renewal(payload):
g.remote_session_renew = (str(payload.get("email", "")), str(payload.get("sub", "")))
return None
- if 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)
+ # The SPA shell is non-sensitive and its APIs remain protected. Serving it
+ # lets AuthGuard keep an iOS Home-Screen cold launch on the installed app's
+ # origin instead of automatically crossing into an OAuth browser sheet.
+ if _is_ui_static_request():
+ return None
+ if request.method == "GET" and "text/html" in request.headers.get("Accept", ""):
+ target = request.full_path if request.query_string else request.path
+ return redirect(f"/auth/login?{urlencode({'next': _safe_remote_redirect_target(target)})}")
return jsonify({"ok": False, "error": "remote_access_login_required"}), 401
@@ -4902,6 +4918,28 @@ async def remote_access_diagnostics():
return jsonify(result), 200 if result.get("ok") else 409
[email protected]("/auth/login", methods=["GET"])
+def remote_access_login():
+ from vibe import remote_access
+
+ config = _load_remote_access_config()
+ if config is None or not _is_remote_access_request(config):
+ return jsonify({"error": "remote_access_not_enabled"}), 400
+ cloud = config.remote_access.vibe_cloud
+ if not cloud.enabled:
+ return jsonify({"error": "remote_access_disabled"}), 503
+ if not cloud.session_secret:
+ return jsonify({"error": "remote_access_session_secret_missing"}), 503
+
+ next_target = _safe_remote_redirect_target(request.args.get("next"))
+ session = remote_access.parse_session_cookie(config, request.cookies.get(remote_access.SESSION_COOKIE_NAME))
+ if session is not None:
+ return redirect(next_target)
+ if _auth_rate_limited():
+ return _auth_rate_limit_response()
+ return _redirect_to_vibe_cloud_login(config, next_target=next_target)
+
+
@app.route("/auth/callback", methods=["GET"])
def remote_access_auth_callback():
from vibe import remote_access