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.

Merge remote-tracking branch 'origin/master' into codex-integrate-org-into-master

cyh2c85869ac84b
diff --cc tests/scenarios/auth_setup/catalog.yaml
index e7d42f00f,3a420df71..5be351712
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@@ -141,76 -141,13 +141,83 @@@ 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-301
+ name: Explicit Organization management sign-in starts an interactive handoff
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_explicit_management_sign_in_starts_interactive_handoff
+ - id: AUTH-SETUP-302
+ name: Silent Organization reauthorization is attempted only once
+ status: covered
+ kind: retry
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_silent_reauthorization_stops_after_login_required
+ - id: AUTH-SETUP-303
+ name: Explicit Organization logout suppresses silent reauthorization
+ status: covered
+ kind: teardown
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_logout_suppresses_silent_reauthorization
+ - id: AUTH-SETUP-304
+ name: Organization management subject mismatch is terminal
+ status: covered
+ kind: negative_path
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_subject_mismatch_is_terminal
+ - id: AUTH-SETUP-305
+ name: Invalid Organization callback state code or token requires manual sign-in
+ status: covered
+ kind: negative_path
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_invalid_callback_token_requires_manual_sign_in
+ - id: AUTH-SETUP-306
+ name: Missing Cloud session or login_required requires explicit sign-in
+ status: covered
+ kind: negative_path
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_silent_reauthorization_stops_after_login_required
+ - id: AUTH-SETUP-307
+ name: Remote Organization callback remains bound to the same subject
+ status: covered
+ kind: authorization
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_remote_callback_keeps_the_bound_subject
+ - id: AUTH-SETUP-308
+ name: Trusted loopback Organization login establishes the first subject
+ status: covered
+ kind: happy_path
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_trusted_loopback_flow_can_establish_the_first_subject
+ - id: AUTH-SETUP-309
+ name: Unbound trusted loopback cannot start silent Organization authorization
+ status: covered
+ kind: authorization
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_unbound_loopback_requires_interactive_sign_in
+ - id: AUTH-SETUP-310
+ name: Organization subject mismatch can re-enter explicit authorization with a clean return path
+ status: covered
+ kind: retry
+ layer: scenario
+ backend: cloud_management
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::OrganizationManagementAuthScenarioTests::test_subject_mismatch_can_reenter_with_clean_return_path
- id: AUTH-SETUP-901
name: Codex setup success refreshes runtime before the next turn
status: covered
diff --cc tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index b80feb6f8,491b04f85..c27fb0b42
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@@ -348,6 -92,203 +356,211 @@@ 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: {
++ def exchange(_config, code, _verifier, redirect_uri=None):
++ return {
+ "claims": {
+ "email": "[email protected]",
+ "sub": "user-1",
+ "nonce": current.retry_nonce,
+ "code": code,
- }
- },
++ },
++ "session_claims": {
++ "vibe_instance_id": current.config.remote_access.vibe_cloud.instance_id,
++ "vibe_instance_role": "owner",
++ "vibe_instance_access_source": "owner",
++ },
++ }
++
++ monkeypatch.setattr(
++ remote_access,
++ "exchange_oauth_code",
++ exchange,
+ )
+ 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 --cc tests/test_ui_remote_access_auth.py
index 322546e2b,816df74bc..1f8aa8246
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@@ -139,130 -150,44 +166,168 @@@ def test_remote_login_endpoint_redirect
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"),
++ remote_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_custom_hostname_uses_remote_auth_until_heartbeat_removes_it(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ responses = iter(
+ [
+ {"ok": True, "active_hostnames": ["max.fileguard.io"]},
+ {"ok": True, "active_hostnames": []},
+ ]
+ )
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: next(responses))
+ client = app.test_client()
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ allowed = client.get(
- "/dashboard",
++ "/auth/login?next=/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert allowed.status_code == 302
+ assert httpx.URL(allowed.headers["Location"]).params["redirect_uri"] == (
+ "https://max.fileguard.io/auth/callback"
+ )
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ removed = client.get(
- "/dashboard",
++ "/auth/login?next=/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert removed.status_code == 503
+ assert removed.get_json()["error"] == "remote_access_host_mismatch"
+
+
+def test_persisted_custom_hostname_is_allowed_before_process_cache_warms(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ remote_access._clear_active_hostnames_cache()
+
+ response = app.test_client().get(
- "/dashboard",
++ "/auth/login?next=/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert remote_access.active_hostnames(config) == frozenset({"max.fileguard.io"})
+
+
+def test_custom_hostname_oauth_flow_reuses_redirect_uri_for_exchange(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ client = app.test_client()
+
+ login = client.get(
- "/dashboard",
++ "/auth/login?next=/dashboard",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+ authorize_params = httpx.URL(login.headers["Location"]).params
+ oauth_cookie_header = next(
+ header
+ for header in login.headers.getlist("Set-Cookie")
+ if header.startswith(f"{ui_server.REMOTE_OAUTH_COOKIE_NAME}=")
+ )
+ oauth_cookie = oauth_cookie_header.split(";", 1)[0].split("=", 1)[1]
+ handshake = ui_server._read_oauth_cookie(config.remote_access.vibe_cloud.session_secret, oauth_cookie)
+ assert handshake is not None
+ state_payload = ui_server._read_oauth_state(
+ config.remote_access.vibe_cloud.session_secret,
+ authorize_params["state"],
+ )
+ assert state_payload is not None
+ stored = remote_access._oauth_handshakes[state_payload["r"]]
+
+ assert authorize_params["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+ assert handshake["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+ assert stored["redirect_uri"] == "https://max.fileguard.io/auth/callback"
+
+ exchanged = {}
+
+ def exchange(cfg, code, verifier, redirect_uri=None):
+ exchanged.update({"code": code, "verifier": verifier, "redirect_uri": redirect_uri})
+ return _oauth_exchange_result(cfg, nonce=handshake["nonce"])
+
+ monkeypatch.setattr(remote_access, "exchange_oauth_code", exchange)
+ client.set_cookie(ui_server.REMOTE_OAUTH_COOKIE_NAME, oauth_cookie, domain="max.fileguard.io")
+
+ callback = client.get(
+ f"/auth/callback?code=test-code&state={authorize_params['state']}",
+ base_url="https://max.fileguard.io",
+ environ_base=_remote_peer(),
+ follow_redirects=False,
+ )
+
+ assert callback.status_code == 302
+ assert callback.headers["Location"] == "/dashboard"
+ assert exchanged == {
+ "code": "test-code",
+ "verifier": handshake["code_verifier"],
+ "redirect_uri": "https://max.fileguard.io/auth/callback",
+ }
+
+
+def test_oauth_redirect_uri_falls_back_for_unlisted_request_host(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path)
+
+ with app.test_request_context("/dashboard", base_url="https://unlisted.example"):
+ response = ui_server._redirect_to_vibe_cloud_login(config)
+
+ params = httpx.URL(response.headers["Location"]).params
+ assert params["redirect_uri"] == config.remote_access.vibe_cloud.redirect_uri
+
+
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
diff --cc ui/src/App.tsx
index eef335e16,ea9379e89..d0a68bfa6
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@@ -94,23 -98,7 +100,19 @@@ import { applyAppTitle } from './lib/do
import { useTranslation } from 'react-i18next';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from './components/ui/card';
import { Button } from './components/ui/button';
+import { OrganizationOverviewPage } from './features/organization/pages/OrganizationOverviewPage';
+import { OrganizationMembersPage } from './features/organization/pages/OrganizationMembersPage';
+import {
+ OrganizationGroupDetailPage,
+ OrganizationGroupsPage,
+} from './features/organization/pages/OrganizationGroupsPages';
+import { OrganizationInstancesPage } from './features/organization/pages/OrganizationInstancesPage';
+import {
+ InstanceAccessPage,
+ InstanceProjectsPage,
+} from './features/organization/pages/OrganizationInstancePages';
+import { OrganizationResourcesPage } from './features/organization/pages/OrganizationResourcesPage';
- // 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();
@@@ -246,8 -235,7 +249,8 @@@ const AuthGuard = ({ children }: { chil
const [guardStatus, setGuardStatus] = useState<GuardStatus>('loading');
const [blockedCode, setBlockedCode] = useState<string | null>(null);
const [authCheckVersion, setAuthCheckVersion] = useState(0);
+ const [authorizationSession, setAuthorizationSession] = useState<SessionInfo | null>(null);
- 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
@@@ -293,18 -281,13 +296,18 @@@
// transition is fine — it's the setup boundary, not every nav.
setGuardStatus('loading');
- getAuthSession().then(session => {
- checkRemoteAuthForPath(location.pathname, getAuthSession).then(({ loginRequired, checkSetup }) => {
++ checkRemoteAuthForPath(location.pathname, getAuthSession).then(({ session, loginRequired, checkSetup }) => {
if (cancelled) return;
+ setAuthorizationSession(session);
- if (session.remote && !session.authenticated) {
+ if (loginRequired) {
setGuardStatus('remote-login-required');
return null;
}
+ if (session.remote && session.authenticated && !session.capabilities.can_manage_instance) {
+ setGuardStatus('ready');
+ return null;
+ }
- if (bypassSetupGuard) {
+ if (!checkSetup) {
setGuardStatus('ready');
return null;
}
@@@ -318,10 -301,9 +321,10 @@@
});
}).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) setAuthorizationSession(session);
- if (session?.remote && !session.authenticated) {
++ if (authCheck?.session) setAuthorizationSession(authCheck.session);
+ if (authCheck?.loginRequired) {
setGuardStatus('remote-login-required');
return;
}
@@@ -361,10 -347,9 +368,11 @@@
if (guardStatus === 'access-blocked') {
return <AccessBlocked code={blockedCode} />;
}
+ if (bypassSetupGuard) return children;
if (guardStatus === 'needs-setup') {
- if (location.pathname === '/setup') return children;
+ if (location.pathname === '/setup' && authorizationSession) {
+ return <InstanceAuthorizationProvider session={authorizationSession}>{children}</InstanceAuthorizationProvider>;
+ }
// A wizard finish navigates from /setup to / before the re-validation
// effect can flip `guardStatus` to loading. Without this render-time
// bridge, the stale setup-required state immediately redirects back to
diff --cc ui/src/lib/apiFetch.test.ts
index 6a08fd71b,a2946c20c..17e90f84e
--- a/ui/src/lib/apiFetch.test.ts
+++ b/ui/src/lib/apiFetch.test.ts
@@@ -1,10 -1,15 +1,13 @@@
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,
-} from './apiFetch';
+import { apiFetch, recoverRemoteAuthFromSessionProbe } from './apiFetch';
describe('apiFetch remote auth recovery', () => {
beforeEach(() => {
@@@ -20,24 -25,37 +23,24 @@@
vi.clearAllMocks();
});
- it('hands an expired remote session to the PWA auth gate', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(async () =>
- Response.json({ error: 'remote_access_login_required' }, { status: 401 }),
- ),
- );
-
- const response = await apiFetch('/api/inbox');
-
- expect(response.status).toBe(401);
- 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.each([
+ 'remote_access_login_required',
+ 'remote_access_authorization_refresh_required',
+ ])(
+ 'hands remote auth recovery error %s to the PWA auth gate',
+ async (error) => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => Response.json({ error }, { status: 401 })),
+ );
+
+ 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('does not start remote auth for an unrelated 401', async () => {
vi.stubGlobal(
@@@ -119,15 -137,4 +122,32 @@@
});
expect(fetchMock).toHaveBeenCalledTimes(3);
});
+
+ it('recovers from a successful session probe that requires authorization refresh', async () => {
+ await recoverRemoteAuthFromSessionProbe(Response.json({
+ remote: true,
+ authenticated: false,
+ authorization_refresh_required: true,
+ }));
+
- expect(deferRemoteAuthRedirect).toHaveBeenCalledOnce();
++ 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');
++ });
});
diff --cc ui/src/lib/applicationRoutes.ts
index 27738ddaf,2f80a53e0..b76fb1c53
--- a/ui/src/lib/applicationRoutes.ts
+++ b/ui/src/lib/applicationRoutes.ts
@@@ -64,6 -58,6 +64,8 @@@ export const APPLICATION_ROUTE_PATHS =
'/remote-access',
'/doctor',
'/doctor/logs',
++ // PWA cold-launch fallback keeps stale extensionless paths inside AuthGuard.
++ '*',
] as const;
export const APPLICATION_DYNAMIC_ROUTE_PATHS = [
diff --cc ui/src/lib/remoteAuth.test.ts
index 6a121aea6,8a5647608..e3296f8c2
--- a/ui/src/lib/remoteAuth.test.ts
+++ b/ui/src/lib/remoteAuth.test.ts
@@@ -36,6 -38,39 +38,44 @@@ 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({
++ session: { remote: true, authenticated: false },
+ 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 });
++ )).resolves.toEqual({
++ session: { remote: true, authenticated: true },
++ loginRequired: false,
++ checkSetup: true,
++ });
+ });
+
it('signals AuthGuard instead of navigating automatically', () => {
platform.isIosDevice.mockReturnValue(true);
platform.isStandalonePwa.mockReturnValue(true);
diff --cc ui/src/lib/remoteAuth.ts
index c717cab9b,293a56e64..76961ee1f
--- a/ui/src/lib/remoteAuth.ts
+++ b/ui/src/lib/remoteAuth.ts
@@@ -13,6 -19,26 +19,27 @@@ export function shouldDeferRemoteAuthRe
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(
++export async function checkRemoteAuthForPath<Session extends RemoteSession>(
+ path: string,
- getSession: () => Promise<RemoteSession>,
-): Promise<{ loginRequired: boolean; checkSetup: boolean }> {
++ getSession: () => Promise<Session>,
++): Promise<{ session: Session; loginRequired: boolean; checkSetup: boolean }> {
+ const session = await getSession();
+ return {
++ session,
+ 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 --cc vibe/ui_server.py
index 71623bcbf,6ea7801ee..6fe4c030c
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@@ -1503,9 -1466,8 +1503,10 @@@ def _remote_auth_exempt_path() -> bool
path = request.path
return (
path == "/health"
+ or path == "/auth/login"
or path == "/auth/callback"
+ or path == "/auth/organization/callback"
+ or path == "/auth/organization/start"
or path == "/auth/logout"
or path == "/api/session"
or path == "/api/cloud/token"
@@@ -2220,24 -2172,17 +2234,26 @@@ def enforce_remote_access_cookie()
return jsonify({"ok": False, "error": "remote_access_session_secret_missing"}), 503
payload = remote_access.parse_session_cookie(config, request.cookies.get(remote_access.SESSION_COOKIE_NAME))
if payload is not None:
+ if remote_access.session_needs_authorization_refresh(payload):
+ if request.method == "GET" and not request.path.startswith("/api/"):
+ if _auth_rate_limited():
+ return _auth_rate_limit_response()
+ return _redirect_to_vibe_cloud_login(config)
+ return jsonify({"ok": False, "error": "remote_access_authorization_refresh_required"}), 401
+ g.authorization_context = context_from_session_payload(payload)
+ g.remote_session_payload = payload
+ g.remote_authorization_refresh_at = remote_access.session_authorization_refresh_deadline(payload)
if remote_access.session_needs_renewal(payload):
- g.remote_session_renew = (str(payload.get("email", "")), str(payload.get("sub", "")))
+ g.remote_session_renew = payload
return None
- if request.method == "GET" and not request.path.startswith("/api/"):
- # 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