π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(oidc): redirect relative to the origin the browser is on (#19040)
Innei74d434f4ef10
diff --git a/packages/const/src/url.test.ts b/packages/const/src/url.test.tsnew file mode 100644index 00000000000..f62ef773088--- /dev/null+++ b/packages/const/src/url.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { isOfficialCloudServer } from './url';++describe('isOfficialCloudServer', () => {+ it.each([+ 'https://app.lobehub.com',+ 'https://lobehub.com',+ 'https://lobehub.com/workspace',+ 'https://staging.app.lobehub.com/',+ ])('treats %s as official', (url) => {+ expect(isOfficialCloudServer(url)).toBe(true);+ });++ it.each([+ 'https://lobehub.com.evil.example',+ 'https://notlobehub.com',+ 'https://my-lobehub.internal',+ 'http://localhost:3210',+ 'not a url',+ '',+ undefined,+ ])('treats %s as self-hosted', (url) => {+ expect(isOfficialCloudServer(url)).toBe(false);+ });+});diff --git a/packages/const/src/url.ts b/packages/const/src/url.tsindex b657f02a19e..79cd75af5c6 100644--- a/packages/const/src/url.ts+++ b/packages/const/src/url.ts@@ -4,6 +4,16 @@ export const OFFICIAL_URL = 'https://app.lobehub.com';export const OFFICIAL_SITE = 'https://lobehub.com';export const OFFICIAL_DOMAIN = 'lobehub.com';+export const isOfficialCloudServer = (url?: string): boolean => {+ if (!url) return false;+ try {+ const { hostname } = new URL(url);+ return hostname === OFFICIAL_DOMAIN || hostname.endsWith(`.${OFFICIAL_DOMAIN}`);+ } catch {+ return false;+ }+};+export const OFFICIAL_DEVICE_GATEWAY_URL = 'https://device-gateway.lobehub.com';export const OFFICIAL_AGENT_GATEWAY_URL = 'https://agent-gateway.lobehub.com';diff --git a/src/app/(backend)/oidc/callback/desktop/route.test.ts b/src/app/(backend)/oidc/callback/desktop/route.test.tsnew file mode 100644index 00000000000..2234794f4e9--- /dev/null+++ b/src/app/(backend)/oidc/callback/desktop/route.test.ts@@ -0,0 +1,63 @@+/**+ * @vitest-environment node+ */+import type { NextRequest } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from './route';++const mocks = vi.hoisted(() => ({+ cleanupExpired: vi.fn(),+ create: vi.fn(),+}));++vi.mock('debug', () => ({ default: () => vi.fn() }));++vi.mock('next/server', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ after: vi.fn(),+}));++vi.mock('@/database/server', () => ({ serverDB: {} }));++vi.mock('@/database/models/oauthHandoff', () => ({+ OAuthHandoffModel: class {+ cleanupExpired = mocks.cleanupExpired;+ create = mocks.create;+ },+}));++const createRequest = (search: string) => {+ const url = new URL(+ `https://lobehub-cloud-next-stable.vercel.app/oidc/callback/desktop${search}`,+ );+ return Object.assign(new Request(url), { nextUrl: url }) as unknown as NextRequest;+};++describe('GET /oidc/callback/desktop', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('stores the handoff and redirects to the success page on the current origin', async () => {+ mocks.create.mockResolvedValue(undefined);++ const response = await GET(createRequest('?code=code-1&state=handoff-1'));++ expect(response.status).toBe(307);+ expect(response.headers.get('location')).toBe('/oauth/callback/success');+ expect(mocks.create).toHaveBeenCalledWith({+ client: 'desktop',+ id: 'handoff-1',+ payload: { code: 'code-1', state: 'handoff-1' },+ });+ });++ it('redirects to the error page on the current origin when params are missing', async () => {+ const response = await GET(createRequest(''));++ expect(response.status).toBe(307);+ expect(response.headers.get('location')).toBe('/oauth/callback/error?reason=invalid_request');+ expect(mocks.create).not.toHaveBeenCalled();+ });+});diff --git a/src/app/(backend)/oidc/callback/desktop/route.ts b/src/app/(backend)/oidc/callback/desktop/route.tsindex 119ecd45e70..14ddd62fa5a 100644--- a/src/app/(backend)/oidc/callback/desktop/route.ts+++ b/src/app/(backend)/oidc/callback/desktop/route.ts@@ -4,17 +4,15 @@ import { after, NextResponse } from 'next/server';import { OAuthHandoffModel } from '@/database/models/oauthHandoff';import { serverDB } from '@/database/server';-import { resolveAppOrigin } from '@/libs/oidc-provider/config';const log = debug('lobe-oidc:callback:desktop');const errorPathname = '/oauth/callback/error';-const buildRedirectUrl = (req: NextRequest, pathname: string): URL => {- const url = new URL(resolveAppOrigin(req.headers));- url.pathname = pathname;- log('Redirect target: %s', url.toString());- return url;+const redirectTo = (pathname: string, params?: Record<string, string>) => {+ const location = params ? `${pathname}?${new URLSearchParams(params)}` : pathname;+ log('Redirect target: %s', location);+ return new NextResponse(null, { headers: { location }, status: 307 });};export const GET = async (req: NextRequest) => {@@ -26,11 +24,7 @@ export const GET = async (req: NextRequest) => {if (!code || !state || typeof code !== 'string' || typeof state !== 'string') {log('Missing code or state in form data');- const errorUrl = buildRedirectUrl(req, errorPathname);- errorUrl.searchParams.set('reason', 'invalid_request');-- log('Redirecting to error URL: %s', errorUrl.toString());- return NextResponse.redirect(errorUrl);+ return redirectTo(errorPathname, { reason: 'invalid_request' });}log('Received OIDC callback. state(handoffId): %s', state);@@ -44,14 +38,6 @@ export const GET = async (req: NextRequest) => {await authHandoffModel.create({ client, id, payload });log('Handoff record created successfully for id: %s', id);- const successUrl = buildRedirectUrl(req, '/oauth/callback/success');-- // Add debug logging- log('Request host header: %s', req.headers.get('host'));- log('Request x-forwarded-host: %s', req.headers.get('x-forwarded-host'));- log('Request x-forwarded-proto: %s', req.headers.get('x-forwarded-proto'));- log('Constructed success URL: %s', successUrl.toString());-// cleanup expiredafter(async () => {const cleanedCount = await authHandoffModel.cleanupExpired();@@ -59,18 +45,13 @@ export const GET = async (req: NextRequest) => {log('Cleaned up %d expired handoff records', cleanedCount);});- return NextResponse.redirect(successUrl);+ return redirectTo('/oauth/callback/success');} catch (error) {log('Error in OIDC callback: %O', error);- const errorUrl = buildRedirectUrl(req, errorPathname);- errorUrl.searchParams.set('reason', 'internal_error');-- if (error instanceof Error) {- errorUrl.searchParams.set('errorMessage', error.message);- }-- log('Redirecting to error URL: %s', errorUrl.toString());- return NextResponse.redirect(errorUrl);+ return redirectTo(errorPathname, {+ reason: 'internal_error',+ ...(error instanceof Error && { errorMessage: error.message }),+ });}};diff --git a/src/app/(backend)/oidc/consent/route.test.ts b/src/app/(backend)/oidc/consent/route.test.tsnew file mode 100644index 00000000000..14292bced6f--- /dev/null+++ b/src/app/(backend)/oidc/consent/route.test.ts@@ -0,0 +1,69 @@+/**+ * @vitest-environment node+ */+import type { NextRequest } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { POST } from './route';++const mocks = vi.hoisted(() => ({+ getInteractionDetails: vi.fn(),+ getInteractionResult: vi.fn(),+ getUserAuth: vi.fn(),+}));++vi.mock('debug', () => ({ default: () => vi.fn() }));++vi.mock('@lobechat/utils/server', () => ({ getUserAuth: mocks.getUserAuth }));++vi.mock('@/server/services/oidc', () => ({+ OIDCService: {+ initialize: vi.fn(async () => ({+ getInteractionDetails: mocks.getInteractionDetails,+ getInteractionResult: mocks.getInteractionResult,+ })),+ },+}));++const createRequest = (fields: Record<string, string>) => {+ const body = new FormData();+ for (const [key, value] of Object.entries(fields)) body.set(key, value);+ return new Request('https://lobehub-cloud-next-stable.vercel.app/oidc/consent', {+ body,+ headers: { origin: 'https://lobehub.com' },+ method: 'POST',+ }) as unknown as NextRequest;+};++describe('POST /oidc/consent', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getUserAuth.mockResolvedValue({ userId: 'user-1' });+ mocks.getInteractionDetails.mockResolvedValue({+ params: { client_id: 'lobehub-desktop' },+ prompt: { details: {}, name: 'login' },+ });+ mocks.getInteractionResult.mockResolvedValue(+ 'https://app.lobehub.com/oidc/auth/uid-1?resume=1',+ );+ });++ it('redirects back into the provider on the origin the browser is using', async () => {+ const response = await POST(createRequest({ consent: 'accept', uid: 'uid-1' }));++ expect(response.status).toBe(303);+ expect(response.headers.get('location')).toBe('/oidc/auth/uid-1?resume=1');+ expect(mocks.getInteractionResult).toHaveBeenCalledWith('uid-1', {+ login: { accountId: 'user-1', remember: true },+ });+ });++ it('returns 400 when the interaction session is gone', async () => {+ mocks.getInteractionDetails.mockRejectedValue(new Error('interaction session not found'));++ const response = await POST(createRequest({ consent: 'accept', uid: 'uid-1' }));++ expect(response.status).toBe(400);+ expect(mocks.getInteractionResult).not.toHaveBeenCalled();+ });+});diff --git a/src/app/(backend)/oidc/consent/route.ts b/src/app/(backend)/oidc/consent/route.tsindex 53d3851a38f..180a0cfa33d 100644--- a/src/app/(backend)/oidc/consent/route.ts+++ b/src/app/(backend)/oidc/consent/route.ts@@ -3,7 +3,6 @@ import debug from 'debug';import { type NextRequest } from 'next/server';import { NextResponse } from 'next/server';-import { resolveAppOrigin } from '@/libs/oidc-provider/config';import { OIDCService } from '@/server/services/oidc';const log = debug('lobe-oidc:consent');@@ -115,16 +114,14 @@ export async function POST(request: NextRequest) {const internalRedirectUrlString = await oidcService.getInteractionResult(uid, result);log('OIDC Provider internal redirect URL string: %s', internalRedirectUrlString);- const internalUrl = new URL(internalRedirectUrlString);- const finalRedirectUrl = new URL(resolveAppOrigin(request.headers));- finalRedirectUrl.pathname = internalUrl.pathname;- finalRedirectUrl.search = internalUrl.search;- finalRedirectUrl.hash = internalUrl.hash;+ // The gateway rewrites Host on the way to the origin, so the server cannot tell which+ // public origin the browser is on. A relative Location keeps it on the origin that holds+ // the interaction cookies.+ const { pathname, search, hash } = new URL(internalRedirectUrlString);+ const location = `${pathname}${search}${hash}`;- log('Redirecting to: %s', finalRedirectUrl.toString());- return NextResponse.redirect(finalRedirectUrl, {- status: 303,- });+ log('Redirecting to: %s', location);+ return new NextResponse(null, { headers: { location }, status: 303 });} catch (error) {console.error('Error processing consent:', error);return NextResponse.json(diff --git a/src/features/Billboard/actions.test.ts b/src/features/Billboard/actions.test.tsindex 3e2da839488..32d2fb6e21d 100644--- a/src/features/Billboard/actions.test.ts+++ b/src/features/Billboard/actions.test.ts@@ -98,6 +98,12 @@ describe('resolveBillboardAction', () => {}});+ it('should resolve resetOnboarding on the lobehub.com web origin', () => {+ window.location.href = 'https://lobehub.com/';++ expect(resolveBillboardAction('resetOnboarding')).toBe('resetOnboarding');+ });+it('should not resolve resetOnboarding on a self-hosted web origin', () => {window.location.href = 'https://chat.example.com/';@@ -124,6 +130,21 @@ describe('resolveBillboardAction', () => {}});+ it('should resolve resetOnboarding on desktop synced to a lobehub.com self-host url', async () => {+ electronState.dataSyncConfig = {+ active: true,+ remoteServerUrl: 'https://lobehub.com',+ storageMode: 'selfHost',+ };++ try {+ const desktopActions = await importDesktopActions();+ expect(desktopActions.resolveBillboardAction('resetOnboarding')).toBe('resetOnboarding');+ } finally {+ restoreDesktopMock();+ }+ });+it('should not resolve resetOnboarding on desktop synced to a self-host server', async () => {electronState.dataSyncConfig = {active: true,diff --git a/src/features/Billboard/actions.ts b/src/features/Billboard/actions.tsindex 0814430ce1f..edd622801e0 100644--- a/src/features/Billboard/actions.ts+++ b/src/features/Billboard/actions.ts@@ -1,4 +1,4 @@-import { isDesktop, OFFICIAL_URL } from '@lobechat/const';+import { isDesktop, isOfficialCloudServer, OFFICIAL_URL } from '@lobechat/const';import urlJoin from 'url-join';import { openChangelogModal } from '@/components/ChangelogModal';@@ -22,25 +22,13 @@ export type BillboardAction = (typeof BILLBOARD_ACTIONS)[number];export const isBillboardAction = (value: unknown): value is BillboardAction =>typeof value === 'string' && (BILLBOARD_ACTIONS as readonly string[]).includes(value);-const isOfficialWebOrigin = () => {- if (typeof window === 'undefined') return false;- try {- return window.location.origin === new URL(OFFICIAL_URL).origin;- } catch {- return false;- }-};-const isOnOfficialCloud = () => {const state = getElectronStoreState();- if (- electronSyncSelectors.isSyncActive(state) &&- electronSyncSelectors.storageMode(state) === 'cloud'- ) {+ if (electronSyncSelectors.isSyncActive(state) && electronSyncSelectors.isOfficialServer(state)) {return true;}- return isOfficialWebOrigin();+ return typeof window !== 'undefined' && isOfficialCloudServer(window.location.origin);};type BillboardActionGuard = (action: BillboardAction) => BillboardAction | null;diff --git a/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx b/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsxindex 46e5575ab9d..46ce1877e6e 100644--- a/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx+++ b/src/layout/GlobalProvider/ServerVersionOutdatedAlert.tsx@@ -88,7 +88,7 @@ const ServerVersionOutdatedAlert = () => {const { t } = useTranslation('common');const [dismissed, setDismissed] = useState(false);const isServerVersionOutdated = useGlobalStore((s) => s.isServerVersionOutdated);- const storageMode = useElectronStore(electronSyncSelectors.storageMode);+ const isOfficialServer = useElectronStore(electronSyncSelectors.isOfficialServer);const cssVariables = useMemo<Record<string, string>>(() => ({@@ -98,9 +98,7 @@ const ServerVersionOutdatedAlert = () => {[theme.yellowBorder, theme.yellowBg],);- // Only show alert when using self-hosted server, not cloud- if (storageMode !== 'selfHost') return null;- if (!isServerVersionOutdated || dismissed) return null;+ if (isOfficialServer || !isServerVersionOutdated || dismissed) return null;return (<div className={styles.container}>diff --git a/src/libs/oidc-provider/config.ts b/src/libs/oidc-provider/config.tsindex 93c1a94965c..8a5d3ed60c5 100644--- a/src/libs/oidc-provider/config.ts+++ b/src/libs/oidc-provider/config.ts@@ -10,27 +10,6 @@ const desktopAppOrigins = cloudAppOrigins.includes(new URL(appUrl).origin): [appUrl];const marketBaseUrl = new URL(appEnv.MARKET_BASE_URL ?? 'https://market.lobehub.com').origin;-const allowedAppOrigins = desktopAppOrigins.map((origin) => new URL(origin).origin);--/**- * The apex migration serves the same deployment on two origins, so a redirect must stay on the- * origin the browser is actually using β jumping back to APP_URL drops the user's session cookies.- */-export const resolveAppOrigin = (headers: Headers): string => {- const fallback = new URL(appUrl).origin;- const host = (headers.get('x-forwarded-host') || headers.get('host'))?.split(',')[0].trim();- if (!host) return fallback;-- const protocol = headers.get('x-forwarded-proto')?.split(',')[0].trim() || 'https';-- try {- const origin = new URL(`${protocol}://${host}`).origin;- return allowedAppOrigins.includes(origin) ? origin : fallback;- } catch {- return fallback;- }-};-/*** Default OIDC client configuration*/diff --git a/src/libs/oidc-provider/provider.test.ts b/src/libs/oidc-provider/provider.test.tsindex 14aaa38896d..8580b134640 100644--- a/src/libs/oidc-provider/provider.test.ts+++ b/src/libs/oidc-provider/provider.test.ts@@ -148,54 +148,6 @@ describe('OIDC Provider - Market Client Integration', () => {}, 10000);});- describe('resolveAppOrigin', () => {- const importWithAppUrl = async (APP_URL: string) => {- vi.doMock('@/envs/app', () => ({ appEnv: { APP_URL, MARKET_BASE_URL: undefined } }));- const module = await import('./config');- vi.doUnmock('@/envs/app');- return module;- };-- it('should keep the apex origin the browser is using', async () => {- const { resolveAppOrigin } = await importWithAppUrl('https://app.lobehub.com');-- expect(- resolveAppOrigin(new Headers({ 'host': 'lobehub.com', 'x-forwarded-proto': 'https' })),- ).toBe('https://lobehub.com');- expect(resolveAppOrigin(new Headers({ 'x-forwarded-host': 'app.lobehub.com' }))).toBe(- 'https://app.lobehub.com',- );- });-- it('should fall back to APP_URL for unknown or missing hosts', async () => {- const { resolveAppOrigin } = await importWithAppUrl('https://app.lobehub.com');-- expect(resolveAppOrigin(new Headers({ host: 'evil.example.com' }))).toBe(- 'https://app.lobehub.com',- );- expect(resolveAppOrigin(new Headers())).toBe('https://app.lobehub.com');- expect(resolveAppOrigin(new Headers({ host: 'not a host' }))).toBe('https://app.lobehub.com');- });-- it('should normalize host casing and ignore an empty forwarded host', async () => {- const { resolveAppOrigin } = await importWithAppUrl('https://app.lobehub.com');-- expect(resolveAppOrigin(new Headers({ host: 'LobeHub.com' }))).toBe('https://lobehub.com');- expect(resolveAppOrigin(new Headers({ 'host': 'lobehub.com', 'x-forwarded-host': '' }))).toBe(- 'https://lobehub.com',- );- });-- it('should only allow the configured origin for self-hosted deployments', async () => {- const { resolveAppOrigin } = await importWithAppUrl('http://localhost:3210');-- expect(- resolveAppOrigin(new Headers({ 'host': 'localhost:3210', 'x-forwarded-proto': 'http' })),- ).toBe('http://localhost:3210');- expect(resolveAppOrigin(new Headers({ host: 'lobehub.com' }))).toBe('http://localhost:3210');- });- });-describe('Name Resolution Priority', () => {it('should prioritize fullName over firstName+lastName', () => {const priorities = ['fullName', 'firstName + lastName', 'username', 'id'];diff --git a/src/store/electron/selectors/__tests__/sync.test.ts b/src/store/electron/selectors/__tests__/sync.test.tsnew file mode 100644index 00000000000..14d8a59bd20--- /dev/null+++ b/src/store/electron/selectors/__tests__/sync.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { type ElectronState, initialState } from '../../initialState';+import { electronSyncSelectors } from '../sync';++const withConfig = (dataSyncConfig: ElectronState['dataSyncConfig']): ElectronState => ({+ ...initialState,+ dataSyncConfig,+});++describe('electronSyncSelectors.isOfficialServer', () => {+ it('is official in cloud mode regardless of remoteServerUrl', () => {+ expect(+ electronSyncSelectors.isOfficialServer(+ withConfig({ remoteServerUrl: 'http://localhost:3210', storageMode: 'cloud' }),+ ),+ ).toBe(true);+ });++ it('is official when self-hosting on a lobehub.com origin', () => {+ expect(+ electronSyncSelectors.isOfficialServer(+ withConfig({ remoteServerUrl: 'https://lobehub.com', storageMode: 'selfHost' }),+ ),+ ).toBe(true);+ });++ it('is not official for a third-party self-hosted server', () => {+ expect(+ electronSyncSelectors.isOfficialServer(+ withConfig({ remoteServerUrl: 'https://chat.example.com', storageMode: 'selfHost' }),+ ),+ ).toBe(false);+ });+});diff --git a/src/store/electron/selectors/sync.ts b/src/store/electron/selectors/sync.tsindex f7c0af9cfc8..a082c87049f 100644--- a/src/store/electron/selectors/sync.ts+++ b/src/store/electron/selectors/sync.ts@@ -1,4 +1,4 @@-import { OFFICIAL_URL } from '@lobechat/const';+import { isOfficialCloudServer, OFFICIAL_URL } from '@lobechat/const';import { type ElectronState } from '../initialState';@@ -20,7 +20,10 @@ const remoteServerUrl = (s: ElectronState) =>*/const rawRemoteServerUrl = (s: ElectronState) => s.dataSyncConfig.remoteServerUrl || '';+const isOfficialServer = (s: ElectronState) => isOfficialCloudServer(remoteServerUrl(s));+export const electronSyncSelectors = {+ isOfficialServer,isSyncActive,rawRemoteServerUrl,remoteServerUrl,diff --git a/src/store/global/actions/general.ts b/src/store/global/actions/general.tsindex b330efe367d..3221bf8aed5 100644--- a/src/store/global/actions/general.ts+++ b/src/store/global/actions/general.ts@@ -270,9 +270,7 @@ export class GlobalGeneralActionImpl {useCheckServerVersion = (): SWRResponse<string | null> => {return useOnlyFetchOnceSWR(- isDesktop &&- // only check server version for self-hosted remote server- electronSyncSelectors.storageMode(getElectronStoreState()) !== 'cloud'+ isDesktop && !electronSyncSelectors.isOfficialServer(getElectronStoreState())? globalKeys.serverVersion(): null,async () => globalService.getServerVersion(),