Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: harden market auth popup handoff and storage fallback (#12863)

Sun13138826a099f8dc7
diff --git a/src/app/[variants]/(auth)/market-auth-callback/page.tsx b/src/app/[variants]/(auth)/market-auth-callback/page.tsx
index 0887435a171..0964c499c89 100644
--- a/src/app/[variants]/(auth)/market-auth-callback/page.tsx
+++ b/src/app/[variants]/(auth)/market-auth-callback/page.tsx
@@ -5,6 +5,8 @@ import { Result } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { persistMarketAuthResult } from '@/layout/AuthProvider/MarketAuth/handoff';
+
type CallbackStatus = 'loading' | 'success' | 'error';
/**
@@ -31,11 +33,18 @@ const MarketAuthCallbackPage = () => {
setStatus('error');
setMessage(t('callback.messages.authFailed', { error: errorDescription || error }));
+ persistMarketAuthResult({
+ error: errorDescription || error,
+ state: state || undefined,
+ type: 'MARKET_AUTH_ERROR',
+ });
+
// Send error message to parent window
if (window.opener) {
window.opener.postMessage(
{
error: errorDescription || error,
+ state,
type: 'MARKET_AUTH_ERROR',
},
window.location.origin,
@@ -49,6 +58,12 @@ const MarketAuthCallbackPage = () => {
setStatus('success');
setMessage(t('callback.messages.successWithRedirect'));
+ persistMarketAuthResult({
+ code,
+ state,
+ type: 'MARKET_AUTH_SUCCESS',
+ });
+
// Send success message to parent window
if (window.opener) {
window.opener.postMessage(
@@ -79,10 +94,17 @@ const MarketAuthCallbackPage = () => {
setStatus('error');
setMessage(t('callback.messages.missingParams'));
+ persistMarketAuthResult({
+ error: 'Missing authorization parameters',
+ state: state || undefined,
+ type: 'MARKET_AUTH_ERROR',
+ });
+
if (window.opener) {
window.opener.postMessage(
{
error: 'Missing authorization parameters',
+ state,
type: 'MARKET_AUTH_ERROR',
},
window.location.origin,
diff --git a/src/layout/AuthProvider/MarketAuth/handoff.test.ts b/src/layout/AuthProvider/MarketAuth/handoff.test.ts
new file mode 100644
index 00000000000..3b02dd39dea
--- /dev/null
+++ b/src/layout/AuthProvider/MarketAuth/handoff.test.ts
@@ -0,0 +1,51 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { clearMarketAuthResult, persistMarketAuthResult, readMarketAuthResult } from './handoff';
+
+describe('MarketAuth handoff storage helpers', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('should swallow storage write failures and return false', () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const setItemSpy = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('storage disabled');
+ });
+
+ expect(
+ persistMarketAuthResult({
+ code: 'auth_code',
+ state: 'state_value',
+ type: 'MARKET_AUTH_SUCCESS',
+ }),
+ ).toBe(false);
+
+ expect(setItemSpy).toHaveBeenCalledOnce();
+ expect(consoleErrorSpy).toHaveBeenCalledOnce();
+ });
+
+ it('should swallow storage read failures and return null', () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const getItemSpy = vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('storage disabled');
+ });
+
+ expect(readMarketAuthResult('state_value')).toBeNull();
+
+ expect(getItemSpy).toHaveBeenCalledOnce();
+ expect(consoleErrorSpy).toHaveBeenCalledOnce();
+ });
+
+ it('should swallow storage clear failures and return false', () => {
+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const removeItemSpy = vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
+ throw new Error('storage disabled');
+ });
+
+ expect(clearMarketAuthResult('state_value')).toBe(false);
+
+ expect(removeItemSpy).toHaveBeenCalledOnce();
+ expect(consoleErrorSpy).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/layout/AuthProvider/MarketAuth/handoff.ts b/src/layout/AuthProvider/MarketAuth/handoff.ts
new file mode 100644
index 00000000000..7bce2107d82
--- /dev/null
+++ b/src/layout/AuthProvider/MarketAuth/handoff.ts
@@ -0,0 +1,90 @@
+interface MarketAuthSuccessHandoffPayload {
+ code: string;
+ state: string;
+ type: 'MARKET_AUTH_SUCCESS';
+}
+
+interface MarketAuthErrorHandoffPayload {
+ error: string;
+ state?: string;
+ type: 'MARKET_AUTH_ERROR';
+}
+
+export type MarketAuthHandoffPayload =
+ | MarketAuthErrorHandoffPayload
+ | MarketAuthSuccessHandoffPayload;
+
+const MARKET_AUTH_RESULT_STORAGE_PREFIX = 'market_auth_result:';
+
+const isBrowser = () => typeof window !== 'undefined';
+
+export const getMarketAuthResultStorageKey = (state: string) =>
+ `${MARKET_AUTH_RESULT_STORAGE_PREFIX}${state}`;
+
+export const resolveMarketAuthHandoffPayload = (
+ value: unknown,
+): MarketAuthHandoffPayload | null => {
+ if (!value || typeof value !== 'object') return null;
+
+ const payload = value as Partial<MarketAuthHandoffPayload>;
+
+ if (payload.type === 'MARKET_AUTH_SUCCESS') {
+ if (typeof payload.code !== 'string' || typeof payload.state !== 'string') return null;
+
+ return {
+ code: payload.code,
+ state: payload.state,
+ type: payload.type,
+ };
+ }
+
+ if (payload.type === 'MARKET_AUTH_ERROR') {
+ if (typeof payload.error !== 'string') return null;
+
+ return {
+ error: payload.error,
+ state: typeof payload.state === 'string' ? payload.state : undefined,
+ type: payload.type,
+ };
+ }
+
+ return null;
+};
+
+export const persistMarketAuthResult = (payload: MarketAuthHandoffPayload): boolean => {
+ if (!isBrowser() || !payload.state) return false;
+
+ try {
+ localStorage.setItem(getMarketAuthResultStorageKey(payload.state), JSON.stringify(payload));
+ return true;
+ } catch (error) {
+ console.error('[MarketAuthHandoff] Failed to persist auth result:', error);
+ return false;
+ }
+};
+
+export const readMarketAuthResult = (state: string): MarketAuthHandoffPayload | null => {
+ if (!isBrowser()) return null;
+
+ try {
+ const rawValue = localStorage.getItem(getMarketAuthResultStorageKey(state));
+ if (!rawValue) return null;
+
+ return resolveMarketAuthHandoffPayload(JSON.parse(rawValue));
+ } catch (error) {
+ console.error('[MarketAuthHandoff] Failed to read auth result:', error);
+ return null;
+ }
+};
+
+export const clearMarketAuthResult = (state: string): boolean => {
+ if (!isBrowser()) return false;
+
+ try {
+ localStorage.removeItem(getMarketAuthResultStorageKey(state));
+ return true;
+ } catch (error) {
+ console.error('[MarketAuthHandoff] Failed to clear auth result:', error);
+ return false;
+ }
+};
diff --git a/src/layout/AuthProvider/MarketAuth/oidc.test.ts b/src/layout/AuthProvider/MarketAuth/oidc.test.ts
index b89f96390e6..605f1fa4db9 100644
--- a/src/layout/AuthProvider/MarketAuth/oidc.test.ts
+++ b/src/layout/AuthProvider/MarketAuth/oidc.test.ts
@@ -1,7 +1,8 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MARKET_OIDC_ENDPOINTS } from '@/services/_url';
+import { getMarketAuthResultStorageKey } from './handoff';
import { MarketOIDC } from './oidc';
describe('MarketOIDC.buildAuthUrl', () => {
@@ -23,7 +24,9 @@ describe('MarketOIDC.buildAuthUrl', () => {
expect(url).toContain('https://market.lobehub.com/lobehub-oidc/auth?');
expect(url).toContain(`client_id=${encodeURIComponent('lobehub-desktop')}`);
- expect(url).toContain(`redirect_uri=${encodeURIComponent('https://market.lobehub.com/lobehub-oidc/callback/desktop')}`);
+ expect(url).toContain(
+ `redirect_uri=${encodeURIComponent('https://market.lobehub.com/lobehub-oidc/callback/desktop')}`,
+ );
expect(url).toContain(`state=${encodeURIComponent('state_value')}`);
expect(url).toContain(`code_challenge=${encodeURIComponent('code_challenge')}`);
@@ -35,4 +38,100 @@ describe('MarketOIDC.buildAuthUrl', () => {
});
});
+describe('MarketOIDC.startAuthorization', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('should reject promptly when popup closes without a handoff result', async () => {
+ const client = new MarketOIDC({
+ baseUrl: 'https://market.lobehub.com',
+ clientId: 'lobechat-com',
+ redirectUri: 'http://localhost:3010/market-auth-callback',
+ scope: 'openid profile email',
+ });
+
+ sessionStorage.setItem('market_state', 'state_value');
+ vi.spyOn(client, 'buildAuthUrl').mockResolvedValue(
+ 'https://market.lobehub.com/lobehub-oidc/auth',
+ );
+
+ let isClosed = false;
+ const popup = {
+ get closed() {
+ return isClosed;
+ },
+ } as Window;
+
+ vi.spyOn(window, 'open').mockReturnValue(popup);
+
+ const authPromise = client.startAuthorization();
+ const rejection = expect(authPromise).rejects.toMatchObject({
+ code: 'popupClosed',
+ name: 'MarketAuthError',
+ });
+
+ isClosed = true;
+ await vi.advanceTimersByTimeAsync(2000);
+
+ await rejection;
+ });
+ it('should resolve from storage handoff when popup closes after callback persistence', async () => {
+ const client = new MarketOIDC({
+ baseUrl: 'https://market.lobehub.com',
+ clientId: 'lobechat-com',
+ redirectUri: 'http://localhost:3010/market-auth-callback',
+ scope: 'openid profile email',
+ });
+ const state = 'state_value';
+ const storageKey = getMarketAuthResultStorageKey(state);
+
+ sessionStorage.setItem('market_state', state);
+ vi.spyOn(client, 'buildAuthUrl').mockResolvedValue(
+ 'https://market.lobehub.com/lobehub-oidc/auth',
+ );
+
+ let isClosed = false;
+ const popup = {
+ get closed() {
+ return isClosed;
+ },
+ } as Window;
+
+ vi.spyOn(window, 'open').mockReturnValue(popup);
+
+ const authPromise = client.startAuthorization();
+
+ isClosed = true;
+ await vi.advanceTimersByTimeAsync(500);
+
+ const payload = JSON.stringify({
+ code: 'auth_code',
+ state,
+ type: 'MARKET_AUTH_SUCCESS',
+ });
+
+ localStorage.setItem(storageKey, payload);
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: storageKey,
+ newValue: payload,
+ storageArea: localStorage,
+ }),
+ );
+
+ await expect(authPromise).resolves.toEqual({
+ code: 'auth_code',
+ state,
+ });
+ expect(localStorage.getItem(storageKey)).toBeNull();
+ });
+});
diff --git a/src/layout/AuthProvider/MarketAuth/oidc.ts b/src/layout/AuthProvider/MarketAuth/oidc.ts
index 48867c13be1..8b3d0f25ada 100644
--- a/src/layout/AuthProvider/MarketAuth/oidc.ts
+++ b/src/layout/AuthProvider/MarketAuth/oidc.ts
@@ -2,6 +2,13 @@ import { isDesktop } from '@/const/version';
import { MARKET_OIDC_ENDPOINTS } from '@/services/_url';
import { MarketAuthError } from './errors';
+import {
+ clearMarketAuthResult,
+ getMarketAuthResultStorageKey,
+ type MarketAuthHandoffPayload,
+ readMarketAuthResult,
+ resolveMarketAuthHandoffPayload,
+} from './handoff';
import { type OIDCConfig, type PKCEParams, type TokenResponse } from './types';
/**
@@ -16,6 +23,12 @@ export class MarketOIDC {
private static readonly DESKTOP_HANDOFF_TIMEOUT = 5 * 60 * 1000; // 5 minutes
+ private static readonly WEB_POPUP_CLOSE_GRACE_PERIOD = 1500;
+
+ private static readonly WEB_POPUP_MONITOR_INTERVAL = 500;
+
+ private static readonly WEB_POPUP_TIMEOUT = 5 * 60 * 1000; // 5 minutes
+
constructor(config: OIDCConfig) {
this.config = config;
}
@@ -226,52 +239,152 @@ export class MarketOIDC {
}
}
+ clearMarketAuthResult(state);
+
return new Promise((resolve, reject) => {
let checkClosed: number | undefined;
+ let fallbackPolling: number | undefined;
+ let popupClosedGraceTimeout: number | undefined;
+
+ const authTimeout = setTimeout(() => {
+ cleanup();
+ reject(
+ new MarketAuthError('handoffTimeout', {
+ message:
+ 'Authorization timeout. Please complete the authorization in the browser and try again.',
+ }),
+ );
+ }, MarketOIDC.WEB_POPUP_TIMEOUT) as unknown as number;
+
+ const cleanup = () => {
+ window.removeEventListener('message', messageHandler);
+ window.removeEventListener('storage', storageHandler);
+ clearTimeout(authTimeout);
+ if (checkClosed) clearInterval(checkClosed);
+ if (fallbackPolling) clearInterval(fallbackPolling);
+ if (popupClosedGraceTimeout) clearTimeout(popupClosedGraceTimeout);
+ clearMarketAuthResult(state);
+ };
- // Listen for message events, waiting for authorization to complete
- const messageHandler = (event: MessageEvent) => {
- console.info('[MarketOIDC] Received message from popup:', event.data);
-
- if (event.data.type === 'MARKET_AUTH_SUCCESS') {
- cleanup();
+ const settle = (payload: MarketAuthHandoffPayload) => {
+ cleanup();
- // Don't close the popup immediately, let the user see the success state
- // The popup will close automatically after 3 seconds
+ if (payload.type === 'MARKET_AUTH_SUCCESS') {
resolve({
- code: event.data.code,
- state: event.data.state,
+ code: payload.code,
+ state: payload.state,
});
- } else if (event.data.type === 'MARKET_AUTH_ERROR') {
- cleanup();
+
+ return;
+ }
+
+ try {
popup?.close();
- reject(
- new MarketAuthError('authorizationFailed', {
- message: event.data.error || 'Authorization failed',
- meta: { error: event.data.error },
- }),
- );
+ } catch {
+ // Ignore close failures from cross-origin popup contexts.
}
+
+ reject(
+ new MarketAuthError('authorizationFailed', {
+ message: payload.error || 'Authorization failed',
+ meta: { error: payload.error },
+ }),
+ );
};
- // Cleanup function
- function cleanup() {
- window.removeEventListener('message', messageHandler);
- if (checkClosed) clearInterval(checkClosed);
- }
+ const handleHandoffPayload = (payload: MarketAuthHandoffPayload | null) => {
+ if (!payload) return false;
+ if (payload.state && payload.state !== state) return false;
+
+ settle(payload);
+ return true;
+ };
+
+ const flushStoredResult = () => handleHandoffPayload(readMarketAuthResult(state));
+
+ const startStoragePolling = () => {
+ if (fallbackPolling) return;
+
+ fallbackPolling = setInterval(() => {
+ flushStoredResult();
+ }, MarketOIDC.WEB_POPUP_MONITOR_INTERVAL) as unknown as number;
+ };
+
+ const rejectPopupClosed = () => {
+ cleanup();
+ reject(new MarketAuthError('popupClosed', { message: 'Authorization popup was closed' }));
+ };
+
+ const handlePopupClosed = () => {
+ if (popupClosedGraceTimeout) return;
+ if (checkClosed) {
+ clearInterval(checkClosed);
+ checkClosed = undefined;
+ }
+
+ if (flushStoredResult()) return;
+
+ startStoragePolling();
+
+ popupClosedGraceTimeout = setTimeout(() => {
+ if (flushStoredResult()) return;
+ rejectPopupClosed();
+ }, MarketOIDC.WEB_POPUP_CLOSE_GRACE_PERIOD) as unknown as number;
+ };
+
+ // Listen for message events, waiting for authorization to complete
+ const messageHandler = (event: MessageEvent) => {
+ if (event.origin !== window.location.origin) return;
+
+ console.info('[MarketOIDC] Received message from popup:', event.data);
+
+ handleHandoffPayload(resolveMarketAuthHandoffPayload(event.data));
+ };
+
+ const storageHandler = (event: StorageEvent) => {
+ if (event.storageArea !== localStorage) return;
+ if (event.key !== getMarketAuthResultStorageKey(state)) return;
+
+ if (!event.newValue) {
+ flushStoredResult();
+ return;
+ }
+
+ try {
+ handleHandoffPayload(resolveMarketAuthHandoffPayload(JSON.parse(event.newValue)));
+ } catch {
+ // Ignore malformed storage payloads and keep waiting for a valid handoff.
+ }
+ };
window.addEventListener('message', messageHandler);
+ window.addEventListener('storage', storageHandler);
- // Check if the popup was closed
+ if (flushStoredResult()) return;
+
+ // Check if the popup was closed. A readable `closed === true` means the
+ // window is genuinely gone, so only wait a short grace period for the
+ // callback page to persist its handoff result. If accessing popup state
+ // throws, assume COOP isolation and keep waiting on storage handoff.
if (popup) {
checkClosed = setInterval(() => {
- if (popup.closed) {
- cleanup();
- reject(
- new MarketAuthError('popupClosed', { message: 'Authorization popup was closed' }),
+ try {
+ if (popup.closed) {
+ handlePopupClosed();
+ }
+ } catch {
+ console.info(
+ '[MarketOIDC] COOP blocked popup monitoring, falling back to storage handoff',
);
+
+ if (checkClosed) {
+ clearInterval(checkClosed);
+ checkClosed = undefined;
+ }
+
+ startStoragePolling();
}
- }, 1000) as unknown as number;
+ }, MarketOIDC.WEB_POPUP_MONITOR_INTERVAL) as unknown as number;
}
});
}