🤯 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: betterauth public url auto detect from VERCEL_URL (#10493)
YuTengjingb5bf8ad4077b
diff --git a/docs/self-hosting/advanced/auth.mdx b/docs/self-hosting/advanced/auth.mdxindex 5a90330c09c..11290b5a057 100644--- a/docs/self-hosting/advanced/auth.mdx+++ b/docs/self-hosting/advanced/auth.mdx@@ -39,12 +39,18 @@ By setting the environment variables `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLTo enable Better Auth in LobeChat, set the following environment variables:-| Environment Variable | Type | Description |-| -------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------- |-| `NEXT_PUBLIC_ENABLE_BETTER_AUTH` | Required | Set to `1` to enable Better Auth service |-| `AUTH_SECRET` | Required | Key used to encrypt session tokens. Generate using: `openssl rand -base64 32` |-| `NEXT_PUBLIC_AUTH_URL` | Optional | The URL accessible from the browser for Better Auth callbacks. Only set this if the default generated URL is incorrect |-| `AUTH_SSO_PROVIDERS` | Optional | Comma-separated list of enabled SSO providers, e.g., `google,github,microsoft` |+| Environment Variable | Type | Description |+| -------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `NEXT_PUBLIC_ENABLE_BETTER_AUTH` | Required | Set to `1` to enable Better Auth service |+| `AUTH_SECRET` | Required | Key used to encrypt session tokens. Generate using: `openssl rand -base64 32` |+| `NEXT_PUBLIC_AUTH_URL` | Required | The browser-accessible base URL for Better Auth (e.g., `http://localhost:3010`, `https://lobechat.com`). Optional for Vercel deployments (auto-detected from `VERCEL_URL`) |+| `AUTH_SSO_PROVIDERS` | Optional | Comma-separated list of enabled SSO providers, e.g., `google,github,microsoft` |++<Callout type={'error'}>+ **Important**: Better Auth is currently only suitable for **fresh deployments**. If you are already using NextAuth or Clerk and have existing user data in your database, **do not switch to Better Auth yet**, otherwise existing users will not be able to log in.++ We are developing user data migration tools from NextAuth/Clerk to Better Auth. Documentation will be updated once the migration solution is complete. For progress updates, please follow [GitHub Issue #10456](https://github.com/lobehub/lobe-chat/issues/10456).+</Callout><Callout type={'warning'}>If you build/deploy with the official Docker image, the defaults keep **NextAuth enabled** and **Betterdiff --git a/docs/self-hosting/advanced/auth.zh-CN.mdx b/docs/self-hosting/advanced/auth.zh-CN.mdxindex b6a7abec6f7..7f950b1ebd5 100644--- a/docs/self-hosting/advanced/auth.zh-CN.mdx+++ b/docs/self-hosting/advanced/auth.zh-CN.mdx@@ -37,12 +37,18 @@ LobeChat 与 Clerk 做了深度集成,能够为用户提供一个更加安全要在 LobeChat 中启用 Better Auth,请设置以下环境变量:-| 环境变量 | 类型 | 描述 |-| -------------------------------- | -- | ------------------------------------------------ |-| `NEXT_PUBLIC_ENABLE_BETTER_AUTH` | 必选 | 设置为 `1` 以启用 Better Auth 服务 |-| `AUTH_SECRET` | 必选 | 用于加密会话令牌的密钥。使用以下命令生成:`openssl rand -base64 32` |-| `NEXT_PUBLIC_AUTH_URL` | 可选 | 浏览器可访问的 Better Auth 回调 URL。仅在默认生成的 URL 不正确时设置 |-| `AUTH_SSO_PROVIDERS` | 可选 | 启用的 SSO 提供商列表,以逗号分隔,例如 `google,github,microsoft` |+| 环境变量 | 类型 | 描述 |+| -------------------------------- | -- | ---------------------------------------------------------------------------------------------------------------- |+| `NEXT_PUBLIC_ENABLE_BETTER_AUTH` | 必选 | 设置为 `1` 以启用 Better Auth 服务 |+| `AUTH_SECRET` | 必选 | 用于加密会话令牌的密钥。使用以下命令生成:`openssl rand -base64 32` |+| `NEXT_PUBLIC_AUTH_URL` | 必选 | 浏览器可访问的 Better Auth 基础 URL(例如 `http://localhost:3010`、`https://lobechat.com`)。Vercel 部署时可选(会自动从 `VERCEL_URL` 获取) |+| `AUTH_SSO_PROVIDERS` | 可选 | 启用的 SSO 提供商列表,以逗号分隔,例如 `google,github,microsoft` |++<Callout type={'error'}>+ **重要提示**:Better Auth 目前仅适用于**全新部署**的场景。如果你已经使用 NextAuth 或 Clerk 并且数据库中存在用户数据,**请暂时不要切换到 Better Auth**,否则现有用户将无法登录。++ 我们正在开发从 NextAuth/Clerk 到 Better Auth 的用户数据迁移工具,迁移方案完成后会更新文档。相关进度请关注 [GitHub Issue #10456](https://github.com/lobehub/lobe-chat/issues/10456)。+</Callout><Callout type={'warning'}>若使用官方 Docker 镜像构建 / 部署,默认是 **开启 NextAuth、关闭 Better Auth**diff --git a/packages/const/src/auth.ts b/packages/const/src/auth.tsindex 6e676ee30ff..9d15fc2a74d 100644--- a/packages/const/src/auth.ts+++ b/packages/const/src/auth.ts@@ -1,4 +1,7 @@-export const enableClerk = !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY;+export const enableClerk =+ process.env.NEXT_PUBLIC_ENABLE_CLERK_AUTH === '1'+ ? true+ : !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY;export const enableBetterAuth = process.env.NEXT_PUBLIC_ENABLE_BETTER_AUTH === '1';export const enableNextAuth = process.env.NEXT_PUBLIC_ENABLE_NEXT_AUTH === '1';export const enableAuth = enableClerk || enableBetterAuth || enableNextAuth || false;diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.tsindex 0d77cc60d7e..019fe6924f3 100644--- a/packages/ssrf-safe-fetch/index.ts+++ b/packages/ssrf-safe-fetch/index.ts@@ -4,6 +4,8 @@ import { RequestFilteringAgentOptions, useAgent as ssrfAgent } from 'request-fil/*** SSRF-safe fetch implementation for server-side use* Uses request-filtering-agent to prevent requests to private IP addresses+ *+ * @see https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address*/// eslint-disable-next-line no-undefexport const ssrfSafeFetch = async (url: string, options?: RequestInit): Promise<Response> => {@@ -31,7 +33,8 @@ export const ssrfSafeFetch = async (url: string, options?: RequestInit): Promise} catch (error) {console.error('SSRF-safe fetch error:', error);throw new Error(- `SSRF-safe fetch failed: ${error instanceof Error ? error.message : String(error)}`,+ `SSRF-safe fetch failed: ${error instanceof Error ? error.message : String(error)}. ` ++ 'See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',);}};diff --git a/src/auth.ts b/src/auth.tsindex 071c5f79a4e..918d7ac00cf 100644--- a/src/auth.ts+++ b/src/auth.ts@@ -21,6 +21,42 @@ const enableMagicLink = authEnv.NEXT_PUBLIC_ENABLE_MAGIC_LINK;const { socialProviders, genericOAuthProviders } = initBetterAuthSSOProviders();+/**+ * Normalize a URL-like string to an origin with https fallback.+ */+const normalizeOrigin = (url?: string) => {+ if (!url) return undefined;++ try {+ const normalizedUrl = url.startsWith('http') ? url : `https://${url}`;++ return new URL(normalizedUrl).origin;+ } catch {+ return undefined;+ }+};++/**+ * Build trusted origins with env override and Vercel-aware defaults.+ */+const getTrustedOrigins = () => {+ if (authEnv.AUTH_TRUSTED_ORIGINS) {+ const originsFromEnv = authEnv.AUTH_TRUSTED_ORIGINS.split(',')+ .map((item) => normalizeOrigin(item.trim()))+ .filter(Boolean) as string[];++ if (originsFromEnv.length > 0) return Array.from(new Set(originsFromEnv));+ }++ const defaults = [+ authEnv.NEXT_PUBLIC_AUTH_URL,+ normalizeOrigin(process.env.VERCEL_BRANCH_URL),+ normalizeOrigin(process.env.VERCEL_URL),+ ].filter(Boolean) as string[];++ return defaults.length > 0 ? Array.from(new Set(defaults)) : undefined;+};+export const auth = betterAuth({account: {accountLinking: {@@ -32,6 +68,7 @@ export const auth = betterAuth({// Use renamed env vars (fallback to next-auth vars is handled in src/envs/auth.ts)baseURL: authEnv.NEXT_PUBLIC_AUTH_URL,secret: authEnv.AUTH_SECRET,+ trustedOrigins: getTrustedOrigins(),database: drizzleAdapter(serverDB, {provider: 'pg',diff --git a/src/envs/auth.ts b/src/envs/auth.tsindex 410be92e4b2..5a77ed2e69e 100644--- a/src/envs/auth.ts+++ b/src/envs/auth.ts@@ -2,6 +2,37 @@import { createEnv } from '@t3-oss/env-nextjs';import { z } from 'zod';+import { enableBetterAuth, enableClerk, enableNextAuth } from '@/const/auth';++/**+ * Resolve public auth URL with compatibility fallbacks for NextAuth and Vercel deployments.+ */+const resolvePublicAuthUrl = () => {+ if (process.env.NEXT_PUBLIC_AUTH_URL) return process.env.NEXT_PUBLIC_AUTH_URL;++ if (process.env.NEXTAUTH_URL) {+ try {+ return new URL(process.env.NEXTAUTH_URL).origin;+ } catch {+ // ignore invalid NEXTAUTH_URL+ }+ }++ if (process.env.VERCEL_URL) {+ try {+ const normalizedVercelUrl = process.env.VERCEL_URL.startsWith('http')+ ? process.env.VERCEL_URL+ : `https://${process.env.VERCEL_URL}`;++ return new URL(normalizedVercelUrl).origin;+ } catch {+ // ignore invalid Vercel URL+ }+ }++ return undefined;+};+declare global {// eslint-disable-next-line @typescript-eslint/no-namespacenamespace NodeJS {@@ -16,6 +47,7 @@ declare global {NEXT_PUBLIC_AUTH_URL?: string;NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION?: string;AUTH_SSO_PROVIDERS?: string;+ AUTH_TRUSTED_ORIGINS?: string;// ===== Next Auth ===== //NEXT_AUTH_SECRET?: string;@@ -134,6 +166,7 @@ export const getAuthConfig = () => {// ---------------------------------- better auth ----------------------------------AUTH_SECRET: z.string().optional(),AUTH_SSO_PROVIDERS: z.string().optional().default(''),+ AUTH_TRUSTED_ORIGINS: z.string().optional(),// ---------------------------------- next auth ----------------------------------NEXT_AUTH_SECRET: z.string().optional(),@@ -228,23 +261,22 @@ export const getAuthConfig = () => {runtimeEnv: {// Clerk- NEXT_PUBLIC_ENABLE_CLERK_AUTH: !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,+ NEXT_PUBLIC_ENABLE_CLERK_AUTH: enableClerk,NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,CLERK_WEBHOOK_SECRET: process.env.CLERK_WEBHOOK_SECRET,// ---------------------------------- better auth ----------------------------------- NEXT_PUBLIC_ENABLE_BETTER_AUTH: process.env.NEXT_PUBLIC_ENABLE_BETTER_AUTH === '1',- // Fallback to NEXTAUTH_URL origin for seamless migration from next-auth- NEXT_PUBLIC_AUTH_URL:- process.env.NEXT_PUBLIC_AUTH_URL ||- (process.env.NEXTAUTH_URL ? new URL(process.env.NEXTAUTH_URL).origin : undefined),+ NEXT_PUBLIC_ENABLE_BETTER_AUTH: enableBetterAuth,+ // Fallback to NEXTAUTH_URL origin or Vercel deployment domain for seamless migration from next-auth+ NEXT_PUBLIC_AUTH_URL: resolvePublicAuthUrl(),NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION: process.env.NEXT_PUBLIC_AUTH_EMAIL_VERIFICATION === '1',NEXT_PUBLIC_ENABLE_MAGIC_LINK: process.env.NEXT_PUBLIC_ENABLE_MAGIC_LINK === '1',// Fallback to NEXT_AUTH_SECRET for seamless migration from next-authAUTH_SECRET: process.env.AUTH_SECRET || process.env.NEXT_AUTH_SECRET,// Fallback to NEXT_AUTH_SSO_PROVIDERS for seamless migration from next-authAUTH_SSO_PROVIDERS: process.env.AUTH_SSO_PROVIDERS || process.env.NEXT_AUTH_SSO_PROVIDERS,+ AUTH_TRUSTED_ORIGINS: process.env.AUTH_TRUSTED_ORIGINS,// better-auth env for Cognito provider is different from next-auth's oneAUTH_COGNITO_DOMAIN: process.env.AUTH_COGNITO_DOMAIN,@@ -252,7 +284,7 @@ export const getAuthConfig = () => {AUTH_COGNITO_USERPOOL_ID: process.env.AUTH_COGNITO_USERPOOL_ID,// ---------------------------------- next auth ----------------------------------- NEXT_PUBLIC_ENABLE_NEXT_AUTH: process.env.NEXT_PUBLIC_ENABLE_NEXT_AUTH === '1',+ NEXT_PUBLIC_ENABLE_NEXT_AUTH: enableNextAuth,NEXT_AUTH_SSO_PROVIDERS: process.env.NEXT_AUTH_SSO_PROVIDERS,NEXT_AUTH_SECRET: process.env.NEXT_AUTH_SECRET,NEXT_AUTH_DEBUG: !!process.env.NEXT_AUTH_DEBUG,diff --git a/src/libs/better-auth/sso/index.ts b/src/libs/better-auth/sso/index.tsindex 10c1e698de1..50ccc4282f8 100644--- a/src/libs/better-auth/sso/index.ts+++ b/src/libs/better-auth/sso/index.ts@@ -104,7 +104,7 @@ export const initBetterAuthSSOProviders = () => {if (config) {// the generic oidc callback url is /api/auth/oauth2/callback/{providerId}// different from builtin providers' /api/auth/callback/{providerId}- config.redirectURI = `${authEnv.NEXT_PUBLIC_AUTH_URL}/api/auth/callback/${definition.id}`;+ config.redirectURI = `${authEnv.NEXT_PUBLIC_AUTH_URL || ''}/api/auth/callback/${definition.id}`;genericOAuthProviders.push(config);}}diff --git a/src/libs/oidc-provider/provider.test.ts b/src/libs/oidc-provider/provider.test.tsindex f7a05007e62..74351faca62 100644--- a/src/libs/oidc-provider/provider.test.ts+++ b/src/libs/oidc-provider/provider.test.ts@@ -5,7 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';// Mock dependenciesvi.mock('@/const/auth', () => ({+ enableBetterAuth: false,enableClerk: false,+ enableNextAuth: false,}));vi.mock('@/envs/app', () => ({diff --git a/src/server/routers/lambda/__tests__/user.test.ts b/src/server/routers/lambda/__tests__/user.test.tsindex 252f7c8e475..2a5b74e3212 100644--- a/src/server/routers/lambda/__tests__/user.test.ts+++ b/src/server/routers/lambda/__tests__/user.test.ts@@ -29,7 +29,9 @@ vi.mock('@/server/modules/S3');vi.mock('@/server/services/user');vi.mock('@/server/services/nextAuthUser');vi.mock('@/const/auth', () => ({+ enableBetterAuth: false,enableClerk: true,+ enableNextAuth: false,}));describe('userRouter', () => {