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): prevent surprise iOS browser sheets (#972)

Call White2a45e8be5148
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 442cb35a5..5609813d2 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -45,8 +45,10 @@ import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';
import { ComposerBridgeProvider } from './context/ComposerBridgeContext';
import { UnsavedChangesProvider } from './context/UnsavedChangesProvider';
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';
// 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
@@ -84,12 +86,29 @@ import { Button } from './components/ui/button';
// logs / doctor output even before configuration is complete.
const LOGIN_CHECK_PATHS = new Set(['/admin/logs', '/admin/settings/diagnostics']);
-const RemoteLoginRedirect = ({ target }: { target: string }) => {
+const RemoteLoginGate = ({ target }: { target: string }) => {
const { t } = useTranslation();
+ const requireUserAction = shouldDeferRemoteAuthRedirect();
useEffect(() => {
- window.location.assign(target);
- }, [target]);
+ if (!requireUserAction) window.location.assign(target);
+ }, [requireUserAction, target]);
+
+ if (requireUserAction) {
+ return (
+ <main className="min-h-screen flex items-center justify-center bg-bg text-text p-4">
+ <Card className="max-w-md w-full">
+ <CardHeader>
+ <CardTitle>{t('remoteLogin.title')}</CardTitle>
+ <CardDescription>{t('remoteLogin.body')}</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Button onClick={() => window.location.assign(target)}>{t('remoteLogin.action')}</Button>
+ </CardContent>
+ </Card>
+ </main>
+ );
+ }
return <div className="min-h-screen flex items-center justify-center bg-bg text-text">{t('common.loading')}</div>;
};
@@ -201,6 +220,7 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
const guardTarget = location.pathname + location.search;
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);
// Re-validate only when crossing the setup boundary, not on every
// route change. The wizard completes by saving config and navigating
@@ -214,6 +234,29 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
previousIsSetupRouteRef.current = isSetupRoute;
}, [isSetupRoute]);
+ useEffect(() => {
+ const onRemoteAuthRequired = () => setGuardStatus('remote-login-required');
+ window.addEventListener(REMOTE_AUTH_REQUIRED_EVENT, onRemoteAuthRequired);
+ return () => window.removeEventListener(REMOTE_AUTH_REQUIRED_EVENT, onRemoteAuthRequired);
+ }, []);
+
+ useEffect(() => {
+ if (guardStatus !== 'remote-login-required' || !shouldDeferRemoteAuthRedirect()) return;
+
+ let recheckStarted = false;
+ const recheckAfterLogin = () => {
+ if (document.visibilityState !== 'visible' || recheckStarted) return;
+ recheckStarted = true;
+ setAuthCheckVersion((version) => version + 1);
+ };
+ document.addEventListener('visibilitychange', recheckAfterLogin);
+ window.addEventListener('focus', recheckAfterLogin);
+ return () => {
+ document.removeEventListener('visibilitychange', recheckAfterLogin);
+ window.removeEventListener('focus', recheckAfterLogin);
+ };
+ }, [guardStatus]);
+
useEffect(() => {
let cancelled = false;
@@ -275,14 +318,14 @@ const AuthGuard = ({ children }: { children: ReactNode }) => {
// completion clears the stale needs-setup status, while ordinary
// sidebar navigation never re-runs (which would re-mount the
// shell behind the Loading state).
- }, [bypassSetupGuard, isSetupRoute, getConfig, getAuthSession]);
+ }, [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>;
}
if (guardStatus === 'remote-login-required') {
- return <RemoteLoginRedirect target={guardTarget} />;
+ return <RemoteLoginGate target={guardTarget} />;
}
if (guardStatus === 'access-blocked') {
return <AccessBlocked code={blockedCode} />;
@@ -454,6 +497,7 @@ function RouterRoot() {
<DocumentTitle />
<WebPushNotificationNavigator />
<PwaRouteMemory />
+ <PwaLoopbackLinkGuard />
<Outlet />
</UnsavedChangesProvider>
);
diff --git a/ui/src/components/PwaLoopbackLinkGuard.tsx b/ui/src/components/PwaLoopbackLinkGuard.tsx
new file mode 100644
index 000000000..201b1ae2b
--- /dev/null
+++ b/ui/src/components/PwaLoopbackLinkGuard.tsx
@@ -0,0 +1,35 @@
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useToast } from '@/context/ToastContext';
+import { isIosDevice, isStandalonePwa } from '@/lib/platform';
+import { shouldBlockPwaLoopbackLink } from '@/lib/pwaNavigation';
+
+// iOS opens out-of-scope links from a Home-Screen app in a dismissible browser
+// sheet, and may restore that sheet after evicting the PWA process. A loopback
+// URL in a chat reply can therefore strand the user on a dead "localhost" page:
+// localhost is the iPhone, not the machine running Avibe. Catch every ordinary
+// anchor at the app boundary so individual renderers cannot drift.
+export const PwaLoopbackLinkGuard = () => {
+ const { t } = useTranslation();
+ const { showToast } = useToast();
+
+ useEffect(() => {
+ if (!(isIosDevice() && isStandalonePwa())) return;
+
+ const onClick = (event: MouseEvent) => {
+ if (!(event.target instanceof Element)) return;
+ const anchor = event.target.closest<HTMLAnchorElement>('a[href]');
+ if (!anchor || !shouldBlockPwaLoopbackLink(anchor.href, window.location.href)) return;
+
+ event.preventDefault();
+ event.stopPropagation();
+ showToast(t('common.localLinkUnavailable'), 'warning');
+ };
+
+ document.addEventListener('click', onClick, true);
+ return () => document.removeEventListener('click', onClick, true);
+ }, [showToast, t]);
+
+ return null;
+};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 2533107ce..fde8ec44d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -13,6 +13,11 @@
"retry": "Retry",
"reload": "Reload page"
},
+ "remoteLogin": {
+ "title": "Sign in to continue",
+ "body": "Sign in with Avibe Cloud to continue securely.",
+ "action": "Sign in"
+ },
"preview": {
"title": "Preview",
"unsupported": "This file can't be previewed.",
@@ -78,6 +83,7 @@
"copy": "Copy",
"copied": "Copied",
"copyFailed": "Copy failed, please copy it manually",
+ "localLinkUnavailable": "This local link only opens on the computer running Avibe.",
"remove": "Remove",
"removing": "Removing…",
"delete": "Delete",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 13ae69385..cfb59ec95 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -13,6 +13,11 @@
"retry": "重试",
"reload": "刷新页面"
},
+ "remoteLogin": {
+ "title": "登录后继续",
+ "body": "使用 Avibe Cloud 登录后即可安全地继续访问。",
+ "action": "重新登录"
+ },
"preview": {
"title": "预览",
"unsupported": "此文件无法预览。",
@@ -78,6 +83,7 @@
"copy": "复制",
"copied": "已复制",
"copyFailed": "复制失败,请手动复制",
+ "localLinkUnavailable": "这个本机链接只能在运行 Avibe 的电脑上打开。",
"remove": "移除",
"removing": "移除中…",
"delete": "删除",
diff --git a/ui/src/lib/apiFetch.test.ts b/ui/src/lib/apiFetch.test.ts
new file mode 100644
index 000000000..be044baee
--- /dev/null
+++ b/ui/src/lib/apiFetch.test.ts
@@ -0,0 +1,48 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const deferRemoteAuthRedirect = vi.hoisted(() => vi.fn());
+
+vi.mock('./remoteAuth', () => ({ deferRemoteAuthRedirect }));
+
+import { apiFetch } from './apiFetch';
+
+describe('apiFetch remote auth recovery', () => {
+ beforeEach(() => {
+ deferRemoteAuthRedirect.mockReturnValue(true);
+ vi.stubGlobal('window', {
+ location: { href: 'https://alex.avibe.bot/inbox', assign: vi.fn() },
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ 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(deferRemoteAuthRedirect).toHaveBeenCalledOnce());
+ expect(window.location.assign).not.toHaveBeenCalled();
+ });
+
+ it('does not start remote auth for an unrelated 401', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => Response.json({ error: 'not_allowed' }, { status: 401 })),
+ );
+
+ await apiFetch('/api/inbox');
+
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(deferRemoteAuthRedirect).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/lib/apiFetch.ts b/ui/src/lib/apiFetch.ts
index d213293cb..6936dba98 100644
--- a/ui/src/lib/apiFetch.ts
+++ b/ui/src/lib/apiFetch.ts
@@ -1,3 +1,5 @@
+import { deferRemoteAuthRedirect } from './remoteAuth';
+
const CSRF_COOKIE_NAME = 'vibe_csrf_token';
const CSRF_HEADER_NAME = 'X-Vibe-CSRF-Token';
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
@@ -96,6 +98,11 @@ async function maybeRedirectOnRemoteAuthExpiry(response: Response): Promise<void
if ((payload as { error?: string } | null)?.error !== 'remote_access_login_required') {
return;
}
+ // A cross-origin OAuth redirect from an iOS Home-Screen app opens in a
+ // separate browser sheet. Never raise that sheet automatically: hand control
+ // back to AuthGuard so the PWA can ask for an explicit sign-in action.
+ 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
diff --git a/ui/src/lib/pwaNavigation.test.ts b/ui/src/lib/pwaNavigation.test.ts
new file mode 100644
index 000000000..755c66ffe
--- /dev/null
+++ b/ui/src/lib/pwaNavigation.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from 'vitest';
+
+import { shouldBlockPwaLoopbackLink } from './pwaNavigation';
+
+describe('PWA navigation', () => {
+ const remotePage = 'https://alex-app.avibe.bot/chat/session-123';
+
+ it.each([
+ 'http://localhost:5123',
+ 'http://dev.localhost:5173/path',
+ 'http://127.0.0.1:15130/chat/session-456',
+ 'http://127.12.34.56/path',
+ 'http://[::1]:5123/path',
+ ])('blocks a loopback target from a remote page: %s', (href) => {
+ expect(shouldBlockPwaLoopbackLink(href, remotePage)).toBe(true);
+ });
+
+ it.each([
+ '/chat/session-456',
+ 'https://github.com/avibe-bot/avibe',
+ 'https://192.168.1.20:5123',
+ 'mailto:[email protected]',
+ 'not a url',
+ ])('allows a non-loopback target: %s', (href) => {
+ expect(shouldBlockPwaLoopbackLink(href, remotePage)).toBe(false);
+ });
+
+ it('allows loopback links when Avibe itself is open on loopback', () => {
+ expect(
+ shouldBlockPwaLoopbackLink(
+ 'http://127.0.0.1:15130/chat/session-456',
+ 'http://127.0.0.1:5123/chat/session-123',
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/ui/src/lib/pwaNavigation.ts b/ui/src/lib/pwaNavigation.ts
new file mode 100644
index 000000000..117be5972
--- /dev/null
+++ b/ui/src/lib/pwaNavigation.ts
@@ -0,0 +1,31 @@
+function normalizeHostname(hostname: string): string {
+ return hostname.trim().toLowerCase().replace(/^\[|\]$/g, '').replace(/\.$/, '');
+}
+
+function isLoopbackHostname(hostname: string): boolean {
+ const normalized = normalizeHostname(hostname);
+ if (normalized === 'localhost' || normalized.endsWith('.localhost') || normalized === '::1') {
+ return true;
+ }
+
+ const octets = normalized.split('.');
+ return (
+ octets.length === 4 &&
+ octets[0] === '127' &&
+ octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255)
+ );
+}
+
+export function shouldBlockPwaLoopbackLink(href: string, currentHref: string): boolean {
+ try {
+ const current = new URL(currentHref);
+ const target = new URL(href, current);
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') return false;
+
+ // A loopback link is valid when the app itself is being used on loopback.
+ // From a remote iPhone PWA it points at the phone, not the Avibe host.
+ return !isLoopbackHostname(current.hostname) && isLoopbackHostname(target.hostname);
+ } catch {
+ return false;
+ }
+}
diff --git a/ui/src/lib/remoteAuth.test.ts b/ui/src/lib/remoteAuth.test.ts
new file mode 100644
index 000000000..6a121aea6
--- /dev/null
+++ b/ui/src/lib/remoteAuth.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const platform = vi.hoisted(() => ({
+ isIosDevice: vi.fn(),
+ isStandalonePwa: vi.fn(),
+}));
+
+vi.mock('./platform', () => platform);
+
+import {
+ deferRemoteAuthRedirect,
+ REMOTE_AUTH_REQUIRED_EVENT,
+ shouldDeferRemoteAuthRedirect,
+} from './remoteAuth';
+
+describe('remote auth navigation', () => {
+ beforeEach(() => {
+ platform.isIosDevice.mockReturnValue(false);
+ platform.isStandalonePwa.mockReturnValue(false);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it('requires an explicit action in an iOS standalone PWA', () => {
+ expect(shouldDeferRemoteAuthRedirect({ ios: true, standalone: true })).toBe(true);
+ });
+
+ it.each([
+ { ios: true, standalone: false },
+ { ios: false, standalone: true },
+ { ios: false, standalone: false },
+ ])('keeps automatic login outside an iOS standalone PWA: %o', (context) => {
+ expect(shouldDeferRemoteAuthRedirect(context)).toBe(false);
+ });
+
+ it('signals AuthGuard instead of navigating automatically', () => {
+ platform.isIosDevice.mockReturnValue(true);
+ platform.isStandalonePwa.mockReturnValue(true);
+ const dispatchEvent = vi.fn();
+ vi.stubGlobal('window', { dispatchEvent });
+
+ expect(deferRemoteAuthRedirect()).toBe(true);
+ expect(dispatchEvent).toHaveBeenCalledOnce();
+ expect(dispatchEvent.mock.calls[0]?.[0]).toBeInstanceOf(Event);
+ expect(dispatchEvent.mock.calls[0]?.[0].type).toBe(REMOTE_AUTH_REQUIRED_EVENT);
+ });
+});
diff --git a/ui/src/lib/remoteAuth.ts b/ui/src/lib/remoteAuth.ts
new file mode 100644
index 000000000..c717cab9b
--- /dev/null
+++ b/ui/src/lib/remoteAuth.ts
@@ -0,0 +1,20 @@
+import { isIosDevice, isStandalonePwa } from './platform';
+
+export const REMOTE_AUTH_REQUIRED_EVENT = 'avibe.remote-auth-required';
+
+type PwaContext = {
+ ios: boolean;
+ standalone: boolean;
+};
+
+export function shouldDeferRemoteAuthRedirect(
+ context: PwaContext = { ios: isIosDevice(), standalone: isStandalonePwa() },
+): boolean {
+ return context.ios && context.standalone;
+}
+
+export function deferRemoteAuthRedirect(): boolean {
+ if (!shouldDeferRemoteAuthRedirect() || typeof window === 'undefined') return false;
+ window.dispatchEvent(new Event(REMOTE_AUTH_REQUIRED_EVENT));
+ return true;
+}