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.

✨ feat(auth): support additional trusted origins (#18925)

YuTengjing1c7a7116313b
diff --git a/Dockerfile b/Dockerfile
index f68ed7e284a..fccffdb7c3e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -172,6 +172,7 @@ ENV KEY_VAULTS_SECRET="" \
ENV AUTH_SECRET="" \
AUTH_SSO_PROVIDERS="" \
AUTH_ALLOWED_EMAILS="" \
+ AUTH_ADDITIONAL_TRUSTED_ORIGINS="" \
AUTH_TRUSTED_ORIGINS="" \
AUTH_DISABLE_EMAIL_PASSWORD="" \
AUTH_EMAIL_VERIFICATION="" \
diff --git a/docs/self-hosting/auth.mdx b/docs/self-hosting/auth.mdx
index dec97cc38f1..4e6080bba03 100644
--- a/docs/self-hosting/auth.mdx
+++ b/docs/self-hosting/auth.mdx
@@ -106,6 +106,18 @@ When configuring OAuth providers, use the following callback URL format:
- **Development**: `http://localhost:3210/api/auth/callback/{provider}`
- **Production**: `https://yourdomain.com/api/auth/callback/{provider}`
+## Additional Trusted Origins
+
+Better Auth validates the origin of callback and redirect URLs. To allow another exact origin while keeping the automatically generated application, Vercel, mobile, and provider origins, configure:
+
+```bash
+AUTH_ADDITIONAL_TRUSTED_ORIGINS=https://gateway.example.com
+```
+
+Separate multiple origins with commas. HTTP(S) values are reduced to their origin, so `https://gateway.example.com/signin` is treated as `https://gateway.example.com`; mobile custom schemes are preserved.
+
+Use `AUTH_TRUSTED_ORIGINS` only when you intend to replace the complete generated list. When using that variable, include every required web origin and mobile custom scheme yourself. Use exact origins instead of wildcards.
+
## Email/Password Options
**Disable email/password login (SSO-only mode):**
diff --git a/docs/self-hosting/auth.zh-CN.mdx b/docs/self-hosting/auth.zh-CN.mdx
index 232be358dc8..2cd6d66555f 100644
--- a/docs/self-hosting/auth.zh-CN.mdx
+++ b/docs/self-hosting/auth.zh-CN.mdx
@@ -104,6 +104,18 @@ LobeHub 支持使用 Better Auth 配置外部身份验证服务,供企业 /
- **开发环境**:`http://localhost:3210/api/auth/callback/{provider}`
- **生产环境**:`https://yourdomain.com/api/auth/callback/{provider}`
+## 追加可信来源
+
+Better Auth 会校验回调和重定向 URL 的来源。如果需要允许另一个精确来源,同时保留自动生成的应用、Vercel、移动端及认证提供商来源,请配置:
+
+```bash
+AUTH_ADDITIONAL_TRUSTED_ORIGINS=https://gateway.example.com
+```
+
+多个来源使用逗号分隔。HTTP 或 HTTPS 地址只保留来源,因此 `https://gateway.example.com/signin` 会按 `https://gateway.example.com` 处理;移动端自定义协议会被完整保留。
+
+仅在确实需要替换完整生成列表时使用 `AUTH_TRUSTED_ORIGINS`。使用该变量时,必须自行包含所有必需的网页来源和移动端自定义协议。请使用精确来源,不要使用通配符。
+
## 邮箱密码选项
**禁用邮箱密码登录(仅 SSO 模式):**
diff --git a/docs/self-hosting/environment-variables/auth.mdx b/docs/self-hosting/environment-variables/auth.mdx
index 7498ec8da37..a35d1307bdf 100644
--- a/docs/self-hosting/environment-variables/auth.mdx
+++ b/docs/self-hosting/environment-variables/auth.mdx
@@ -46,6 +46,20 @@ LobeHub provides a complete authentication service capability when deployed. The
- Default: `-`
- Example: `google,github,microsoft,cognito`
+#### `AUTH_TRUSTED_ORIGINS`
+
+- Type: Optional
+- Description: Replaces Better Auth's automatically generated trusted-origin list with a comma-separated list. Use this only when you need full control and include every required web origin and mobile custom scheme. URL paths are reduced to their origin. Prefer exact origins instead of wildcards.
+- Default: Generated from `APP_URL`, Vercel deployment URLs, the mobile app scheme, the Expo development scheme, and the Apple origin when Apple SSO is enabled.
+- Example: `https://lobe.example.com,com.example.app://`
+
+#### `AUTH_ADDITIONAL_TRUSTED_ORIGINS`
+
+- Type: Optional
+- Description: Comma-separated list of origins to add to the resolved Better Auth trusted-origin list. Use this when an extra callback or redirect origin is required without replacing the application, Vercel, mobile, or provider defaults. URL paths are reduced to their origin, duplicate origins are removed, and custom schemes are preserved. Prefer exact origins instead of wildcards.
+- Default: `-`
+- Example: `https://gateway.example.com`
+
#### `AUTH_ALLOWED_EMAILS`
- Type: Optional
diff --git a/docs/self-hosting/environment-variables/auth.zh-CN.mdx b/docs/self-hosting/environment-variables/auth.zh-CN.mdx
index a474c77196f..1a1113a38a2 100644
--- a/docs/self-hosting/environment-variables/auth.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/auth.zh-CN.mdx
@@ -44,6 +44,20 @@ LobeHub 在部署时提供了完善的身份验证服务能力,以下是相关
- 默认值:`-`
- 示例:`google,github,microsoft,cognito`
+#### `AUTH_TRUSTED_ORIGINS`
+
+- 类型:可选
+- 描述:使用逗号分隔的列表完全替换 Better Auth 自动生成的可信来源。仅在需要完整控制时使用,并确保包含所有必需的网页来源和移动端自定义协议。URL 中的路径会被归一化为来源。请使用精确来源,不要使用通配符。
+- 默认值:根据 `APP_URL`、Vercel 部署地址、移动端应用协议、Expo 开发协议自动生成;启用 Apple SSO 时还会包含 Apple 来源。
+- 示例:`https://lobe.example.com,com.example.app://`
+
+#### `AUTH_ADDITIONAL_TRUSTED_ORIGINS`
+
+- 类型:可选
+- 描述:以逗号分隔,追加到 Better Auth 最终可信来源列表。适用于需要增加额外回调或重定向来源、但不希望替换应用、Vercel、移动端及认证提供商默认值的场景。URL 中的路径会被归一化为来源,重复来源会被去除,自定义协议会保留。请使用精确来源,不要使用通配符。
+- 默认值:`-`
+- 示例:`https://gateway.example.com`
+
#### `AUTH_ALLOWED_EMAILS`
- 类型:可选
diff --git a/packages/env/src/__tests__/auth.test.ts b/packages/env/src/__tests__/auth.test.ts
index c98d3abf7c1..1566cdfcc25 100644
--- a/packages/env/src/__tests__/auth.test.ts
+++ b/packages/env/src/__tests__/auth.test.ts
@@ -17,4 +17,12 @@ describe('getAuthConfig', () => {
expect(getAuthConfig().AUTH_COOKIE_PREFIX).toBe('lobehub-oss');
});
+
+ it('should expose additional trusted origins', async () => {
+ vi.stubEnv('AUTH_ADDITIONAL_TRUSTED_ORIGINS', 'https://gateway.example.com');
+
+ const { getAuthConfig } = await import('../auth');
+
+ expect(getAuthConfig().AUTH_ADDITIONAL_TRUSTED_ORIGINS).toBe('https://gateway.example.com');
+ });
});
diff --git a/packages/env/src/auth.ts b/packages/env/src/auth.ts
index 1bd6f06991b..2ddf8f7488d 100644
--- a/packages/env/src/auth.ts
+++ b/packages/env/src/auth.ts
@@ -5,6 +5,8 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace NodeJS {
interface ProcessEnv {
+ /** Comma-separated origins merged into Better Auth's resolved trusted origins. */
+ AUTH_ADDITIONAL_TRUSTED_ORIGINS?: string;
AUTH_ALLOWED_EMAILS?: string;
AUTH_APPLE_APP_BUNDLE_IDENTIFIER?: string;
AUTH_APPLE_CLIENT_ID?: string;
@@ -114,6 +116,7 @@ export const getAuthConfig = () => {
AUTH_COOKIE_PREFIX: z.string().optional(),
AUTH_SECRET: z.string().optional(),
AUTH_SSO_PROVIDERS: z.string().optional().default(''),
+ AUTH_ADDITIONAL_TRUSTED_ORIGINS: z.string().optional(),
AUTH_TRUSTED_ORIGINS: z.string().optional(),
AUTH_EMAIL_VERIFICATION: z.boolean().optional().default(false),
AUTH_ENABLE_MAGIC_LINK: z.boolean().optional().default(false),
@@ -202,6 +205,7 @@ export const getAuthConfig = () => {
},
runtimeEnv: {
+ AUTH_ADDITIONAL_TRUSTED_ORIGINS: process.env.AUTH_ADDITIONAL_TRUSTED_ORIGINS,
AUTH_COOKIE_PREFIX: process.env.AUTH_COOKIE_PREFIX,
AUTH_EMAIL_VERIFICATION: process.env.AUTH_EMAIL_VERIFICATION === '1',
AUTH_ENABLE_MAGIC_LINK: process.env.AUTH_ENABLE_MAGIC_LINK === '1',
diff --git a/src/libs/better-auth/utils/config.test.ts b/src/libs/better-auth/utils/config.test.ts
new file mode 100644
index 00000000000..b5233a794c5
--- /dev/null
+++ b/src/libs/better-auth/utils/config.test.ts
@@ -0,0 +1,61 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ appEnv: { APP_URL: 'https://app.example.com' },
+ authEnv: {
+ AUTH_ADDITIONAL_TRUSTED_ORIGINS: undefined as string | undefined,
+ AUTH_TRUSTED_ORIGINS: undefined as string | undefined,
+ },
+}));
+
+vi.mock('@/envs/app', () => ({ appEnv: mocks.appEnv }));
+vi.mock('@/envs/auth', () => ({ authEnv: mocks.authEnv }));
+vi.mock('@/envs/redis', () => ({ getRedisConfig: vi.fn() }));
+vi.mock('@/libs/redis', () => ({
+ initializeRedis: vi.fn(),
+ isRedisEnabled: vi.fn(() => false),
+}));
+vi.mock('@/utils/env', () => ({ isDev: false }));
+
+describe('getTrustedOrigins', () => {
+ const originalEnv = process.env;
+
+ beforeEach(() => {
+ mocks.appEnv.APP_URL = 'https://app.example.com';
+ mocks.authEnv.AUTH_ADDITIONAL_TRUSTED_ORIGINS = undefined;
+ mocks.authEnv.AUTH_TRUSTED_ORIGINS = undefined;
+ process.env = { ...originalEnv };
+ delete process.env.VERCEL_BRANCH_URL;
+ delete process.env.VERCEL_URL;
+ });
+
+ afterEach(() => {
+ process.env = originalEnv;
+ });
+
+ it('should append normalized origins to provider-aware defaults', async () => {
+ mocks.authEnv.AUTH_ADDITIONAL_TRUSTED_ORIGINS = [
+ 'https://gateway.example.com/signin',
+ 'gateway.example.com/another-path',
+ ].join(',');
+ const { getTrustedOrigins } = await import('./config');
+
+ expect(getTrustedOrigins(['apple'])).toEqual([
+ 'https://app.example.com',
+ 'com.lobehub.app://',
+ 'https://appleid.apple.com',
+ 'https://gateway.example.com',
+ ]);
+ });
+
+ it('should append origins without changing override semantics', async () => {
+ mocks.authEnv.AUTH_TRUSTED_ORIGINS = 'https://override.example.com/callback';
+ mocks.authEnv.AUTH_ADDITIONAL_TRUSTED_ORIGINS = 'https://gateway.example.com/signin';
+ const { getTrustedOrigins } = await import('./config');
+
+ expect(getTrustedOrigins(['apple'])).toEqual([
+ 'https://override.example.com',
+ 'https://gateway.example.com',
+ ]);
+ });
+});
diff --git a/src/libs/better-auth/utils/config.ts b/src/libs/better-auth/utils/config.ts
index 510866e36c1..7a41a9b2e83 100644
--- a/src/libs/better-auth/utils/config.ts
+++ b/src/libs/better-auth/utils/config.ts
@@ -29,23 +29,29 @@ export const normalizeOrigin = (url?: string) => {
}
};
+const parseTrustedOrigins = (value?: string) =>
+ value
+ ?.split(',')
+ .map((item) => normalizeOrigin(item.trim()))
+ .filter((origin): origin is string => Boolean(origin));
+
+const mergeTrustedOrigins = (...originGroups: Array<string[] | undefined>) => {
+ const mergedOrigins = new Set(originGroups.flatMap((origins) => origins ?? []));
+
+ return mergedOrigins.size > 0 ? Array.from(mergedOrigins) : undefined;
+};
+
/**
- * Build trusted origins with env override and Vercel-aware defaults.
+ * Build trusted origins with Vercel-aware defaults and optional additions.
+ * AUTH_TRUSTED_ORIGINS keeps its replacement semantics, while
+ * AUTH_ADDITIONAL_TRUSTED_ORIGINS is merged into either the override or the defaults.
*/
export const getTrustedOrigins = (enabledSSOProviders: string[]) => {
- if (authEnv.AUTH_TRUSTED_ORIGINS) {
- const originsFromEnv = authEnv.AUTH_TRUSTED_ORIGINS.split(',')
- .map((item) => {
- const trimmed = item.trim();
- // Handle custom schemes directly
- if (trimmed.includes('://') && !trimmed.startsWith('http')) {
- return trimmed;
- }
- return normalizeOrigin(trimmed);
- })
- .filter(Boolean) as string[];
-
- if (originsFromEnv.length > 0) return Array.from(new Set(originsFromEnv));
+ const additionalOrigins = parseTrustedOrigins(authEnv.AUTH_ADDITIONAL_TRUSTED_ORIGINS);
+ const originsFromEnv = parseTrustedOrigins(authEnv.AUTH_TRUSTED_ORIGINS);
+
+ if (originsFromEnv?.length) {
+ return mergeTrustedOrigins(originsFromEnv, additionalOrigins);
}
const defaults = [
@@ -57,14 +63,11 @@ export const getTrustedOrigins = (enabledSSOProviders: string[]) => {
...(isDev ? [EXPO_DEV_SCHEME] : []),
].filter(Boolean) as string[];
- const baseTrustedOrigins = defaults.length > 0 ? Array.from(new Set(defaults)) : undefined;
-
- if (!enabledSSOProviders.includes('apple')) return baseTrustedOrigins;
-
- const mergedOrigins = new Set(baseTrustedOrigins || []);
- mergedOrigins.add(APPLE_TRUSTED_ORIGIN);
+ const providerOrigins = enabledSSOProviders.includes('apple')
+ ? [APPLE_TRUSTED_ORIGIN]
+ : undefined;
- return Array.from(mergedOrigins);
+ return mergeTrustedOrigins(defaults, providerOrigins, additionalOrigins);
};
/**