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(oidc): keep consent redirects on the requesting origin (#19003)

Innei97ab13fdad9d
diff --git a/src/app/(backend)/oidc/callback/desktop/route.ts b/src/app/(backend)/oidc/callback/desktop/route.ts
index f4328c2e195..119ecd45e70 100644
--- a/src/app/(backend)/oidc/callback/desktop/route.ts
+++ b/src/app/(backend)/oidc/callback/desktop/route.ts
@@ -4,33 +4,17 @@ import { after, NextResponse } from 'next/server';
import { OAuthHandoffModel } from '@/database/models/oauthHandoff';
import { serverDB } from '@/database/server';
-import { appEnv } from '@/envs/app';
+import { resolveAppOrigin } from '@/libs/oidc-provider/config';
const log = debug('lobe-oidc:callback:desktop');
const errorPathname = '/oauth/callback/error';
-/**
- * Safely build redirect URL - directly use APP_URL as target
- */
const buildRedirectUrl = (req: NextRequest, pathname: string): URL => {
- // Use unified environment variable management
- if (appEnv.APP_URL) {
- try {
- const baseUrl = new URL(appEnv.APP_URL);
- baseUrl.pathname = pathname;
- log('Using APP_URL for redirect: %s', baseUrl.toString());
- return baseUrl;
- } catch (error) {
- log('Error parsing APP_URL, using fallback: %O', error);
- }
- }
-
- // Fallback: use req.nextUrl
- log('Warning: APP_URL not configured, using req.nextUrl as fallback');
- const fallbackUrl = req.nextUrl.clone();
- fallbackUrl.pathname = pathname;
- return fallbackUrl;
+ const url = new URL(resolveAppOrigin(req.headers));
+ url.pathname = pathname;
+ log('Redirect target: %s', url.toString());
+ return url;
};
export const GET = async (req: NextRequest) => {
diff --git a/src/app/(backend)/oidc/consent/route.ts b/src/app/(backend)/oidc/consent/route.ts
index f852f76b987..53d3851a38f 100644
--- a/src/app/(backend)/oidc/consent/route.ts
+++ b/src/app/(backend)/oidc/consent/route.ts
@@ -3,7 +3,7 @@ import debug from 'debug';
import { type NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
-import { appEnv } from '@/envs/app';
+import { resolveAppOrigin } from '@/libs/oidc-provider/config';
import { OIDCService } from '@/server/services/oidc';
const log = debug('lobe-oidc:consent');
@@ -115,23 +115,14 @@ export async function POST(request: NextRequest) {
const internalRedirectUrlString = await oidcService.getInteractionResult(uid, result);
log('OIDC Provider internal redirect URL string: %s', internalRedirectUrlString);
- // Use APP_URL directly as base
- if (appEnv.APP_URL) {
- const baseUrl = new URL(appEnv.APP_URL);
- const internalUrl = new URL(internalRedirectUrlString);
- baseUrl.pathname = internalUrl.pathname;
- baseUrl.search = internalUrl.search;
- baseUrl.hash = internalUrl.hash;
- const finalRedirectUrl = baseUrl;
- log('Using APP_URL as base for redirect: %s', finalRedirectUrl.toString());
- return NextResponse.redirect(finalRedirectUrl, {
- status: 303,
- });
- }
+ const internalUrl = new URL(internalRedirectUrlString);
+ const finalRedirectUrl = new URL(resolveAppOrigin(request.headers));
+ finalRedirectUrl.pathname = internalUrl.pathname;
+ finalRedirectUrl.search = internalUrl.search;
+ finalRedirectUrl.hash = internalUrl.hash;
- // Fallback: use original internal URL
- log('Using internal redirect URL directly: %s', internalRedirectUrlString);
- return NextResponse.redirect(new URL(internalRedirectUrlString), {
+ log('Redirecting to: %s', finalRedirectUrl.toString());
+ return NextResponse.redirect(finalRedirectUrl, {
status: 303,
});
} catch (error) {
diff --git a/src/libs/oidc-provider/config.ts b/src/libs/oidc-provider/config.ts
index 8a5d3ed60c5..93c1a94965c 100644
--- a/src/libs/oidc-provider/config.ts
+++ b/src/libs/oidc-provider/config.ts
@@ -10,6 +10,27 @@ 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.ts
index 8580b134640..14aaa38896d 100644
--- a/src/libs/oidc-provider/provider.test.ts
+++ b/src/libs/oidc-provider/provider.test.ts
@@ -148,6 +148,54 @@ 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'];