@lobehub/lobehub 2.0.0-next.354 → 2.0.0-next.356

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/.env.desktop +0 -1
  2. package/.env.example +16 -20
  3. package/.env.example.development +1 -4
  4. package/.github/workflows/e2e.yml +10 -11
  5. package/CHANGELOG.md +60 -0
  6. package/Dockerfile +28 -4
  7. package/changelog/v1.json +18 -0
  8. package/docker-compose/local/docker-compose.yml +2 -2
  9. package/docker-compose/local/grafana/docker-compose.yml +2 -2
  10. package/docker-compose/local/logto/docker-compose.yml +2 -2
  11. package/docker-compose/local/zitadel/.env.example +2 -2
  12. package/docker-compose/local/zitadel/.env.zh-CN.example +2 -2
  13. package/docker-compose/production/grafana/docker-compose.yml +2 -2
  14. package/docker-compose/production/logto/.env.example +2 -2
  15. package/docker-compose/production/logto/.env.zh-CN.example +2 -2
  16. package/docker-compose/production/zitadel/.env.example +2 -2
  17. package/docker-compose/production/zitadel/.env.zh-CN.example +2 -2
  18. package/docs/development/basic/add-new-authentication-providers.mdx +144 -136
  19. package/docs/development/basic/add-new-authentication-providers.zh-CN.mdx +146 -136
  20. package/docs/self-hosting/advanced/auth/legacy.mdx +4 -0
  21. package/docs/self-hosting/advanced/auth/legacy.zh-CN.mdx +4 -0
  22. package/docs/self-hosting/advanced/auth/nextauth-to-betterauth.mdx +326 -0
  23. package/docs/self-hosting/advanced/auth/nextauth-to-betterauth.zh-CN.mdx +323 -0
  24. package/docs/self-hosting/advanced/auth.mdx +43 -16
  25. package/docs/self-hosting/advanced/auth.zh-CN.mdx +44 -16
  26. package/docs/self-hosting/advanced/redis/upstash.mdx +69 -0
  27. package/docs/self-hosting/advanced/redis/upstash.zh-CN.mdx +69 -0
  28. package/docs/self-hosting/advanced/redis.mdx +128 -0
  29. package/docs/self-hosting/advanced/redis.zh-CN.mdx +126 -0
  30. package/docs/self-hosting/environment-variables/auth.mdx +15 -1
  31. package/docs/self-hosting/environment-variables/auth.zh-CN.mdx +15 -1
  32. package/docs/self-hosting/environment-variables/basic.mdx +13 -0
  33. package/docs/self-hosting/environment-variables/basic.zh-CN.mdx +13 -0
  34. package/docs/self-hosting/environment-variables/redis.mdx +68 -0
  35. package/docs/self-hosting/environment-variables/redis.zh-CN.mdx +67 -0
  36. package/docs/self-hosting/migration/v2/breaking-changes.mdx +23 -23
  37. package/docs/self-hosting/migration/v2/breaking-changes.zh-CN.mdx +23 -23
  38. package/docs/self-hosting/server-database/docker-compose.mdx +4 -4
  39. package/docs/self-hosting/server-database/docker-compose.zh-CN.mdx +4 -4
  40. package/e2e/CLAUDE.md +5 -6
  41. package/e2e/docs/local-setup.md +9 -12
  42. package/e2e/scripts/setup.ts +9 -15
  43. package/e2e/src/support/webServer.ts +6 -5
  44. package/locales/en-US/plugin.json +3 -0
  45. package/locales/zh-CN/plugin.json +3 -0
  46. package/package.json +4 -6
  47. package/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx +3 -11
  48. package/packages/context-engine/src/engine/messages/MessagesEngine.ts +0 -13
  49. package/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts +0 -25
  50. package/packages/database/src/models/__tests__/topics/topic.create.test.ts +3 -3
  51. package/packages/database/src/schemas/nextauth.ts +7 -2
  52. package/packages/utils/src/server/__tests__/auth.test.ts +1 -63
  53. package/packages/utils/src/server/auth.ts +8 -24
  54. package/scripts/_shared/checkDeprecatedAuth.js +99 -0
  55. package/scripts/clerk-to-betterauth/index.ts +8 -3
  56. package/scripts/nextauth-to-betterauth/_internal/config.ts +41 -0
  57. package/scripts/nextauth-to-betterauth/_internal/db.ts +32 -0
  58. package/scripts/nextauth-to-betterauth/_internal/env.ts +6 -0
  59. package/scripts/nextauth-to-betterauth/index.ts +226 -0
  60. package/scripts/nextauth-to-betterauth/verify.ts +188 -0
  61. package/scripts/prebuild.mts +66 -13
  62. package/scripts/serverLauncher/startServer.js +5 -5
  63. package/src/app/(backend)/api/auth/[...all]/route.ts +5 -23
  64. package/src/app/(backend)/api/webhooks/casdoor/route.ts +5 -5
  65. package/src/app/(backend)/api/webhooks/logto/route.ts +8 -8
  66. package/src/app/(backend)/middleware/auth/index.test.ts +8 -1
  67. package/src/app/(backend)/middleware/auth/index.ts +6 -15
  68. package/src/app/(backend)/middleware/auth/utils.test.ts +0 -32
  69. package/src/app/(backend)/middleware/auth/utils.ts +3 -8
  70. package/src/app/(backend)/webapi/chat/[provider]/route.test.ts +8 -1
  71. package/src/app/(backend)/webapi/create-image/comfyui/route.ts +0 -1
  72. package/src/app/(backend)/webapi/models/[provider]/route.test.ts +8 -1
  73. package/src/app/[variants]/(auth)/signin/SignInEmailStep.tsx +1 -1
  74. package/src/app/[variants]/(auth)/signup/[[...signup]]/page.tsx +4 -17
  75. package/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx +1 -0
  76. package/src/app/[variants]/(main)/agent/cron/[cronId]/features/CronJobContentEditor.tsx +34 -21
  77. package/src/app/[variants]/(main)/agent/features/Conversation/ConversationArea.tsx +4 -0
  78. package/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx +1 -0
  79. package/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx +1 -1
  80. package/src/app/[variants]/(main)/home/_layout/Body/Agent/List/InboxItem.tsx +19 -29
  81. package/src/app/[variants]/(main)/home/_layout/Body/Agent/List/List.tsx +1 -1
  82. package/src/app/[variants]/(main)/home/_layout/Body/Agent/ModalProvider.tsx +1 -1
  83. package/src/app/[variants]/(main)/settings/profile/features/SSOProvidersList/index.tsx +12 -19
  84. package/src/app/[variants]/(main)/settings/profile/index.tsx +8 -14
  85. package/src/components/{NextAuth/AuthIcons.tsx → AuthIcons.tsx} +8 -10
  86. package/src/envs/auth.ts +12 -51
  87. package/src/envs/email.ts +3 -0
  88. package/src/envs/redis.ts +12 -54
  89. package/src/features/ChatInput/ChatInputProvider.tsx +22 -2
  90. package/src/features/ChatInput/InputEditor/index.tsx +14 -3
  91. package/src/features/ChatInput/store/initialState.ts +2 -0
  92. package/src/features/User/__tests__/PanelContent.test.tsx +0 -11
  93. package/src/features/User/__tests__/UserAvatar.test.tsx +1 -16
  94. package/src/layout/AuthProvider/index.tsx +1 -6
  95. package/src/layout/GlobalProvider/StoreInitialization.tsx +2 -4
  96. package/src/libs/better-auth/define-config.ts +2 -0
  97. package/src/libs/better-auth/plugins/email-whitelist.test.ts +120 -0
  98. package/src/libs/better-auth/plugins/email-whitelist.ts +62 -0
  99. package/src/libs/next/config/define-config.ts +13 -1
  100. package/src/libs/next/proxy/define-config.ts +2 -75
  101. package/src/libs/oidc-provider/provider.test.ts +0 -4
  102. package/src/libs/redis/index.ts +0 -1
  103. package/src/libs/redis/manager.test.ts +9 -45
  104. package/src/libs/redis/manager.ts +2 -16
  105. package/src/libs/redis/redis.test.ts +2 -4
  106. package/src/libs/redis/redis.ts +2 -4
  107. package/src/libs/redis/types.ts +2 -24
  108. package/src/libs/redis/utils.test.ts +0 -10
  109. package/src/libs/redis/utils.ts +0 -19
  110. package/src/libs/trpc/lambda/context.test.ts +0 -13
  111. package/src/libs/trpc/lambda/context.ts +21 -59
  112. package/src/libs/trpc/middleware/userAuth.ts +1 -7
  113. package/src/libs/trusted-client/getSessionUser.ts +15 -35
  114. package/src/locales/default/plugin.ts +3 -0
  115. package/src/server/globalConfig/index.ts +1 -3
  116. package/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts +0 -25
  117. package/src/server/routers/lambda/__tests__/user.test.ts +0 -48
  118. package/src/server/routers/lambda/user.ts +1 -12
  119. package/src/server/services/email/impls/nodemailer/index.ts +2 -2
  120. package/src/server/services/webhookUser/index.ts +88 -0
  121. package/src/services/chat/chat.test.ts +19 -19
  122. package/src/services/chat/index.ts +8 -3
  123. package/src/services/chat/mecha/agentConfigResolver.test.ts +72 -55
  124. package/src/services/chat/mecha/agentConfigResolver.ts +28 -4
  125. package/src/services/chat/mecha/contextEngineering.test.ts +21 -14
  126. package/src/services/chat/mecha/contextEngineering.ts +12 -0
  127. package/src/services/chat/types.ts +7 -1
  128. package/src/services/user/index.test.ts +0 -14
  129. package/src/services/user/index.ts +0 -4
  130. package/src/store/chat/agents/createAgentExecutors.ts +15 -4
  131. package/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts +1 -0
  132. package/src/store/chat/slices/aiChat/actions/streamingExecutor.ts +6 -2
  133. package/src/store/user/slices/auth/action.test.ts +22 -126
  134. package/src/store/user/slices/auth/action.ts +32 -65
  135. package/src/store/user/slices/auth/initialState.ts +0 -3
  136. package/src/store/user/slices/auth/selectors.ts +0 -3
  137. package/tests/setup.ts +10 -0
  138. package/scripts/_shared/checkDeprecatedClerkEnv.js +0 -42
  139. package/src/app/(backend)/api/auth/adapter/route.ts +0 -137
  140. package/src/app/[variants]/(auth)/next-auth/error/AuthErrorPage.tsx +0 -40
  141. package/src/app/[variants]/(auth)/next-auth/error/page.tsx +0 -11
  142. package/src/app/[variants]/(auth)/next-auth/signin/AuthSignInBox.tsx +0 -167
  143. package/src/app/[variants]/(auth)/next-auth/signin/page.tsx +0 -11
  144. package/src/app/[variants]/(auth)/reset-password/layout.tsx +0 -12
  145. package/src/app/[variants]/(auth)/signin/layout.tsx +0 -12
  146. package/src/app/[variants]/(auth)/verify-email/layout.tsx +0 -12
  147. package/src/envs/auth.test.ts +0 -47
  148. package/src/layout/AuthProvider/NextAuth/UserUpdater.tsx +0 -44
  149. package/src/layout/AuthProvider/NextAuth/index.tsx +0 -17
  150. package/src/libs/next-auth/adapter/index.ts +0 -177
  151. package/src/libs/next-auth/auth.config.ts +0 -64
  152. package/src/libs/next-auth/index.ts +0 -20
  153. package/src/libs/next-auth/sso-providers/auth0.ts +0 -24
  154. package/src/libs/next-auth/sso-providers/authelia.ts +0 -39
  155. package/src/libs/next-auth/sso-providers/authentik.ts +0 -25
  156. package/src/libs/next-auth/sso-providers/casdoor.ts +0 -50
  157. package/src/libs/next-auth/sso-providers/cloudflare-zero-trust.ts +0 -34
  158. package/src/libs/next-auth/sso-providers/cognito.ts +0 -8
  159. package/src/libs/next-auth/sso-providers/feishu.ts +0 -83
  160. package/src/libs/next-auth/sso-providers/generic-oidc.ts +0 -38
  161. package/src/libs/next-auth/sso-providers/github.ts +0 -23
  162. package/src/libs/next-auth/sso-providers/google.ts +0 -18
  163. package/src/libs/next-auth/sso-providers/index.ts +0 -35
  164. package/src/libs/next-auth/sso-providers/keycloak.ts +0 -22
  165. package/src/libs/next-auth/sso-providers/logto.ts +0 -48
  166. package/src/libs/next-auth/sso-providers/microsoft-entra-id-helper.ts +0 -29
  167. package/src/libs/next-auth/sso-providers/microsoft-entra-id.ts +0 -19
  168. package/src/libs/next-auth/sso-providers/okta.ts +0 -22
  169. package/src/libs/next-auth/sso-providers/sso.config.ts +0 -8
  170. package/src/libs/next-auth/sso-providers/wechat.ts +0 -36
  171. package/src/libs/next-auth/sso-providers/zitadel.ts +0 -21
  172. package/src/libs/redis/upstash.test.ts +0 -158
  173. package/src/libs/redis/upstash.ts +0 -136
  174. package/src/server/services/nextAuthUser/index.ts +0 -318
  175. package/src/server/services/nextAuthUser/utils.ts +0 -62
  176. package/src/types/next-auth.d.ts +0 -26
@@ -36,6 +36,10 @@ By setting the environment variables `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CL
36
36
 
37
37
  ## Next Auth
38
38
 
39
+ <Callout type={'tip'}>
40
+ To migrate from NextAuth to Better Auth, see the [NextAuth Migration Guide](/docs/self-hosting/advanced/auth/nextauth-to-betterauth).
41
+ </Callout>
42
+
39
43
  Before using NextAuth, please set the following variables in LobeChat's environment variables:
40
44
 
41
45
  | Environment Variable | Type | Description |
@@ -34,6 +34,10 @@ LobeChat 与 Clerk 做了深度集成,能够为用户提供安全、便捷的
34
34
 
35
35
  ## Next Auth
36
36
 
37
+ <Callout type={'tip'}>
38
+ 如需从 NextAuth 迁移到 Better Auth,请参阅 [NextAuth 迁移指南](/zh/docs/self-hosting/advanced/auth/nextauth-to-betterauth)。
39
+ </Callout>
40
+
37
41
  在使用 NextAuth 之前,请先在 LobeChat 的环境变量中设置以下变量:
38
42
 
39
43
  | 环境变量 | 类型 | 描述 |
@@ -0,0 +1,326 @@
1
+ ---
2
+ title: Migrating from NextAuth to Better Auth
3
+ description: >-
4
+ Guide for migrating your LobeChat deployment from NextAuth authentication to
5
+ Better Auth, including simple and full migration options.
6
+ tags:
7
+ - Authentication Service
8
+ - Better Auth
9
+ - NextAuth
10
+ - Migration
11
+ ---
12
+
13
+ # Migrating from NextAuth to Better Auth
14
+
15
+ This guide helps you migrate your existing NextAuth-based LobeChat deployment to Better Auth.
16
+
17
+ <Callout type={'info'}>
18
+ Better Auth is the recommended authentication solution for LobeChat. It offers simpler configuration, more SSO providers, and better self-hosting support.
19
+ </Callout>
20
+
21
+ <Callout type={'error'}>
22
+ **Important Notice**:
23
+
24
+ - **Always backup your database first!** For Neon users, create a backup via [Fork Branch](https://neon.tech/docs/manage/branches#create-a-branch)
25
+ - LobeChat is not responsible for any data loss or issues that may occur during the migration process
26
+ - This guide is intended for users with development experience; not recommended for users without technical background
27
+ - If you have any questions, feel free to ask in our [Discord](https://discord.com/invite/AYFPHvv2jT) community or [GitHub Issue](https://github.com/lobehub/lobe-chat/issues)
28
+ </Callout>
29
+
30
+ ## Choose Your Migration Path
31
+
32
+ | Method | Best For | User Impact | Data Preserved |
33
+ | ------------------------------------- | ------------------------------ | ---------------------- | ------------------------------------ |
34
+ | [Simple Migration](#simple-migration) | Small deployments (≤ 10 users) | Users need to re-login | Chat history, settings |
35
+ | [Full Migration](#full-migration) | Large deployments | Seamless for users | Everything including SSO connections |
36
+
37
+ <Callout type={'info'}>
38
+ **Note**: NextAuth never supported email/password login, so there are no password hashes to migrate. The main benefit of full migration is preserving SSO connections (Google, GitHub, etc.).
39
+ </Callout>
40
+
41
+ ## Environment Variable Migration Reference
42
+
43
+ ### General Variables
44
+
45
+ | NextAuth (Old) | Better Auth (New) | Notes |
46
+ | -------------------------------- | -------------------- | -------------------------------------------------------- |
47
+ | `NEXT_PUBLIC_ENABLE_NEXT_AUTH` | *(Deprecated)* | No longer needed, Better Auth auto-enables with database |
48
+ | `NEXT_AUTH_SECRET` | `AUTH_SECRET` | Session encryption key |
49
+ | `AUTH_URL` | `APP_URL` | Application URL (for OAuth callbacks) |
50
+ | `NEXT_AUTH_SSO_PROVIDERS` | `AUTH_SSO_PROVIDERS` | SSO provider list (comma-separated) |
51
+ | `NEXT_AUTH_SSO_SESSION_STRATEGY` | *(Deprecated)* | No longer needed, Better Auth uses DB sessions |
52
+
53
+ ### SSO Provider Variables
54
+
55
+ SSO provider environment variables follow the same format: `AUTH_<PROVIDER>_ID` and `AUTH_<PROVIDER>_SECRET`.
56
+
57
+ | NextAuth (Old) | Better Auth (New) | Notes |
58
+ | -------------------------------- | ----------------------- | ------------------- |
59
+ | `AUTH_GITHUB_ID` | `AUTH_GITHUB_ID` | ✅ Unchanged |
60
+ | `AUTH_GITHUB_SECRET` | `AUTH_GITHUB_SECRET` | ✅ Unchanged |
61
+ | `AUTH_GOOGLE_ID` | `AUTH_GOOGLE_ID` | ✅ Unchanged |
62
+ | `AUTH_GOOGLE_SECRET` | `AUTH_GOOGLE_SECRET` | ✅ Unchanged |
63
+ | `AUTH_AUTH0_ID` | `AUTH_AUTH0_ID` | ✅ Unchanged |
64
+ | `AUTH_AUTH0_SECRET` | `AUTH_AUTH0_SECRET` | ✅ Unchanged |
65
+ | `AUTH_AUTH0_ISSUER` | `AUTH_AUTH0_ISSUER` | ✅ Unchanged |
66
+ | `AUTH_AUTHENTIK_ID` | `AUTH_AUTHENTIK_ID` | ✅ Unchanged |
67
+ | `AUTH_AUTHENTIK_SECRET` | `AUTH_AUTHENTIK_SECRET` | ✅ Unchanged |
68
+ | `AUTH_AUTHENTIK_ISSUER` | `AUTH_AUTHENTIK_ISSUER` | ✅ Unchanged |
69
+ | `microsoft-entra-id` | `microsoft` | ⚠️ Provider renamed |
70
+ | `AUTH_MICROSOFT_ENTRA_ID_ID` | `AUTH_MICROSOFT_ID` | ⚠️ Variable renamed |
71
+ | `AUTH_MICROSOFT_ENTRA_ID_SECRET` | `AUTH_MICROSOFT_SECRET` | ⚠️ Variable renamed |
72
+
73
+ <Callout type={'warning'}>
74
+ **Note**: Microsoft Entra ID provider name changed from `microsoft-entra-id` to `microsoft`, and the environment variable prefix changed from `AUTH_MICROSOFT_ENTRA_ID_` to `AUTH_MICROSOFT_`.
75
+ </Callout>
76
+
77
+ ### New Feature Variables
78
+
79
+ Better Auth supports additional features with these new environment variables:
80
+
81
+ | Environment Variable | Description |
82
+ | ------------------------- | ----------------------------------------- |
83
+ | `AUTH_ALLOWED_EMAILS` | Email whitelist (restrict registration) |
84
+ | `AUTH_EMAIL_VERIFICATION` | Enable email verification (set to `1`) |
85
+ | `ENABLE_MAGIC_LINK` | Enable magic link login (set to `1`) |
86
+ | `EMAIL_SERVICE_PROVIDER` | Email provider (`nodemailer` or `resend`) |
87
+
88
+ ## Simple Migration
89
+
90
+ For small self-hosted deployments, the simplest approach is to let users re-login with their SSO accounts.
91
+
92
+ <Callout type={'warning'}>
93
+ **Limitation**: This method loses SSO connection data. Use [Full Migration](#full-migration) to preserve SSO connections.
94
+
95
+ Although SSO connections will be lost, users can manually re-bind social accounts through the profile page after logging in.
96
+
97
+ **Example scenario**: If your previous account had two SSO accounts linked:
98
+
99
+ - Primary email (Google): `mail1@google.com`
100
+ - Secondary email (Microsoft): `mail2@outlook.com`
101
+
102
+ After migrating, logging in with `mail2@outlook.com` will create a **new user** instead of linking to your existing account.
103
+ </Callout>
104
+
105
+ ### Steps
106
+
107
+ 1. **Update Environment Variables**
108
+
109
+ Remove NextAuth variables and add Better Auth variables:
110
+
111
+ ```bash
112
+ # Remove these
113
+ # NEXT_AUTH_SECRET=xxx
114
+ # AUTH_xxx related NextAuth provider configs
115
+
116
+ # Add these
117
+ AUTH_SECRET=your-secret-key # openssl rand -base64 32
118
+
119
+ # Optional: Enable Google SSO (example)
120
+ AUTH_SSO_PROVIDERS=google
121
+ AUTH_GOOGLE_ID=your-google-client-id
122
+ AUTH_GOOGLE_SECRET=your-google-client-secret
123
+ ```
124
+
125
+ <Callout type={'tip'}>
126
+ See [Authentication Service Configuration](/docs/self-hosting/advanced/auth) for complete environment variables and SSO provider setup.
127
+ </Callout>
128
+
129
+ 2. **Redeploy LobeChat**
130
+
131
+ Deploy the new version with Better Auth enabled.
132
+
133
+ 3. **Notify Users**
134
+
135
+ Inform users to log in again with their previous SSO account. Chat history and settings will be preserved since user IDs remain the same.
136
+
137
+ <Callout type={'tip'}>
138
+ This method is quick and requires minimal setup. Users just need to re-login with their existing SSO provider.
139
+ </Callout>
140
+
141
+ ## Full Migration
142
+
143
+ For larger deployments or when you need to preserve SSO connections, use the migration script. This migrates data from the `nextauth_accounts` table to the Better Auth `accounts` table.
144
+
145
+ <Callout type={'error'}>
146
+ **Important Notice**:
147
+
148
+ - **Always backup your database first!** For Neon users, create a backup via [Fork Branch](https://neon.tech/docs/manage/branches#create-a-branch)
149
+ - Migration scripts must be **run locally after cloning the repository**, not in the deployment environment
150
+ - Due to the high-risk nature of user data migration, **we do not provide automatic migration during deployment**
151
+ - Always use dry-run mode first to verify the script runs successfully before executing
152
+ - Always verify in a test environment before operating on production database
153
+ </Callout>
154
+
155
+ ### Prerequisites
156
+
157
+ **Environment Requirements:**
158
+
159
+ - Node.js 18+
160
+ - Git (for cloning the repository)
161
+ - pnpm (for installing dependencies)
162
+
163
+ **Preparation:**
164
+
165
+ 1. Clone the LobeChat repository and install dependencies:
166
+
167
+ ```bash
168
+ git clone https://github.com/lobehub/lobe-chat.git
169
+ cd lobe-chat
170
+ pnpm install
171
+ ```
172
+
173
+ 2. Prepare the database connection string
174
+
175
+ 3. Ensure database schema is up to date
176
+
177
+ <Callout type={'info'}>
178
+ If you've been on an older version for a while, your database schema may be outdated. Run this in the cloned repository:
179
+
180
+ ```bash
181
+ DATABASE_URL=your-database-url pnpm db:migrate
182
+ ```
183
+ </Callout>
184
+
185
+ ### Step 1: Configure Migration Script Environment Variables
186
+
187
+ Create a `.env` file in the project root (the script will automatically load it) with all environment variables:
188
+
189
+ ```bash
190
+ # ============================================
191
+ # Migration mode: test or prod
192
+ # Recommended: Start with test mode to verify on a test database,
193
+ # then switch to prod after confirming everything works
194
+ # ============================================
195
+ NEXTAUTH_TO_BETTERAUTH_MODE=test
196
+
197
+ # ============================================
198
+ # Database connection (uses corresponding variable based on mode)
199
+ # TEST_ prefix for test environment, PROD_ prefix for production
200
+ # ============================================
201
+ TEST_NEXTAUTH_TO_BETTERAUTH_DATABASE_URL=postgresql://user:pass@test-host:5432/testdb
202
+ PROD_NEXTAUTH_TO_BETTERAUTH_DATABASE_URL=postgresql://user:pass@prod-host:5432/proddb
203
+
204
+ # ============================================
205
+ # Database driver (optional)
206
+ # neon: Neon serverless driver (default)
207
+ # node: node-postgres driver
208
+ # ============================================
209
+ NEXTAUTH_TO_BETTERAUTH_DATABASE_DRIVER=neon
210
+
211
+ # ============================================
212
+ # Batch size (optional)
213
+ # Number of records to process per batch, default is 300
214
+ # ============================================
215
+ NEXTAUTH_TO_BETTERAUTH_BATCH_SIZE=300
216
+
217
+ # ============================================
218
+ # Dry Run mode (optional)
219
+ # Set to 1 to only print logs without modifying the database
220
+ # Recommended: Enable for first run, disable after verification
221
+ # ============================================
222
+ NEXTAUTH_TO_BETTERAUTH_DRY_RUN=1
223
+ ```
224
+
225
+ ### Step 2: Dry-Run Verification (Test Environment)
226
+
227
+ ```bash
228
+ # Run migration (NEXTAUTH_TO_BETTERAUTH_DRY_RUN=1, only logs without modifying database)
229
+ npx tsx scripts/nextauth-to-betterauth/index.ts
230
+ ```
231
+
232
+ Review the output logs, confirm no issues, then proceed to the next step.
233
+
234
+ ### Step 3: Execute Migration and Verify (Test Environment)
235
+
236
+ Update `.env` to set `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` to `0`, then execute:
237
+
238
+ ```bash
239
+ # Execute migration
240
+ npx tsx scripts/nextauth-to-betterauth/index.ts
241
+
242
+ # Verify the migration
243
+ npx tsx scripts/nextauth-to-betterauth/verify.ts
244
+ ```
245
+
246
+ After verifying the test environment migration is successful, proceed to the next step.
247
+
248
+ ### Step 4: Dry-Run Verification (Production Environment)
249
+
250
+ 1. Update `.env` file:
251
+ - Change `NEXTAUTH_TO_BETTERAUTH_MODE` to `prod`
252
+ - Change `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` back to `1`
253
+ 2. Run the script:
254
+
255
+ ```bash
256
+ # Run migration (dry-run mode to verify)
257
+ npx tsx scripts/nextauth-to-betterauth/index.ts
258
+ ```
259
+
260
+ Review the output logs, confirm no issues, then proceed to the next step.
261
+
262
+ ### Step 5: Execute Migration and Verify (Production Environment)
263
+
264
+ Update `.env` to set `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` to `0`, then execute:
265
+
266
+ ```bash
267
+ # Execute migration
268
+ npx tsx scripts/nextauth-to-betterauth/index.ts
269
+
270
+ # Verify the migration
271
+ npx tsx scripts/nextauth-to-betterauth/verify.ts
272
+ ```
273
+
274
+ ### Step 6: Configure Better Auth and Redeploy
275
+
276
+ After migration is complete, follow [Simple Migration - Step 1](#steps) to configure Better Auth environment variables and redeploy.
277
+
278
+ <Callout type={'tip'}>
279
+ For complete Better Auth configuration, see [Authentication Service Configuration](/docs/self-hosting/advanced/auth), including all supported SSO providers and email service configuration.
280
+ </Callout>
281
+
282
+ ## What Gets Migrated
283
+
284
+ | Data | Simple Migration | Full Migration |
285
+ | -------------------------------------- | ---------------- | -------------- |
286
+ | User accounts | ✅ (via re-login) | ✅ |
287
+ | SSO connections (Google, GitHub, etc.) | ❌ | ✅ |
288
+ | Chat history | ✅ | ✅ |
289
+ | User settings | ✅ | ✅ |
290
+
291
+ <Callout type={'info'}>
292
+ **Note**: Sessions and verification tokens are not migrated as they are temporary data. Users will need to log in again after migration.
293
+ </Callout>
294
+
295
+ ## Troubleshooting
296
+
297
+ ### Users can't log in after migration
298
+
299
+ - Check that `AUTH_SECRET` is set correctly
300
+ - Verify database connection is working
301
+ - Ensure SSO provider is configured in `AUTH_SSO_PROVIDERS`
302
+
303
+ ### SSO users can't connect
304
+
305
+ - For simple migration: Users need to log in again with their SSO account
306
+ - For full migration: Verify the SSO provider is configured in `AUTH_SSO_PROVIDERS` with the same provider ID
307
+
308
+ ### Migration script fails
309
+
310
+ - Check database connection string
311
+ - Review script logs for specific errors
312
+ - Ensure the `nextauth_accounts` table exists in your database
313
+
314
+ ### column "xxx" of relation "users" does not exist
315
+
316
+ This error occurs because the database schema is outdated. Run `pnpm db:migrate` to update the database structure before running the migration script.
317
+
318
+ ## Related Reading
319
+
320
+ <Cards>
321
+ <Card href={'/docs/self-hosting/advanced/auth'} title={'Authentication Service Configuration'} />
322
+
323
+ <Card href={'/docs/self-hosting/environment-variables/auth'} title={'Auth Environment Variables'} />
324
+
325
+ <Card href={'/docs/self-hosting/advanced/auth/legacy'} title={'Legacy Authentication (NextAuth & Clerk)'} />
326
+ </Cards>
@@ -0,0 +1,323 @@
1
+ ---
2
+ title: 从 NextAuth 迁移到 Better Auth
3
+ description: 将 LobeChat 部署从 NextAuth 身份验证迁移到 Better Auth 的指南,包括简单迁移和完整迁移选项。
4
+ tags:
5
+ - 身份验证服务
6
+ - Better Auth
7
+ - NextAuth
8
+ - 迁移
9
+ ---
10
+
11
+ # 从 NextAuth 迁移到 Better Auth
12
+
13
+ 本指南帮助您将现有的基于 NextAuth 的 LobeChat 部署迁移到 Better Auth。
14
+
15
+ <Callout type={'info'}>
16
+ Better Auth 是 LobeChat 推荐的身份验证解决方案。它提供更简单的配置、更多的 SSO 提供商支持,以及更好的自托管体验。
17
+ </Callout>
18
+
19
+ <Callout type={'error'}>
20
+ **重要提醒**:
21
+
22
+ - **务必先备份数据库**!如使用 Neon,可通过 [Fork 分支](https://neon.tech/docs/manage/branches#create-a-branch) 创建备份
23
+ - 迁移过程中可能出现的任何数据丢失或问题,LobeChat 概不负责
24
+ - 本指南适合有一定开发背景的用户,不建议无技术经验的用户自行操作
25
+ - 如有任何疑问,欢迎到 [Discord](https://discord.com/invite/AYFPHvv2jT) 社区或 [GitHub Issue](https://github.com/lobehub/lobe-chat/issues) 提问
26
+ </Callout>
27
+
28
+ ## 选择迁移方式
29
+
30
+ | 方式 | 适用场景 | 用户影响 | 数据保留 |
31
+ | ------------- | ------------- | ------- | ------------- |
32
+ | [简单迁移](#简单迁移) | 小型部署(≤ 10 用户) | 用户需重新登录 | 聊天记录、设置 |
33
+ | [完整迁移](#完整迁移) | 大型部署 | 对用户无感知 | 全部数据包括 SSO 连接 |
34
+
35
+ <Callout type={'info'}>
36
+ **注意**:NextAuth 从未支持邮箱密码登录,因此没有密码哈希需要迁移。完整迁移的主要好处是保留 SSO 连接(Google、GitHub 等)。
37
+ </Callout>
38
+
39
+ ## 环境变量迁移对照表
40
+
41
+ ### 通用变量
42
+
43
+ | NextAuth (旧) | Better Auth (新) | 说明 |
44
+ | -------------------------------- | -------------------- | ---------------------------- |
45
+ | `NEXT_PUBLIC_ENABLE_NEXT_AUTH` | *(已废弃)* | 不再需要,Better Auth 在配置数据库后自动启用 |
46
+ | `NEXT_AUTH_SECRET` | `AUTH_SECRET` | 会话加密密钥 |
47
+ | `AUTH_URL` | `APP_URL` | 应用 URL(用于 OAuth 回调) |
48
+ | `NEXT_AUTH_SSO_PROVIDERS` | `AUTH_SSO_PROVIDERS` | SSO 提供商列表(逗号分隔) |
49
+ | `NEXT_AUTH_SSO_SESSION_STRATEGY` | *(已废弃)* | 不再需要,Better Auth 使用数据库会话 |
50
+
51
+ ### SSO 提供商变量
52
+
53
+ SSO 提供商的环境变量格式保持一致:`AUTH_<PROVIDER>_ID` 和 `AUTH_<PROVIDER>_SECRET`。
54
+
55
+ | NextAuth (旧) | Better Auth (新) | 说明 |
56
+ | -------------------------------- | ----------------------- | ---------------- |
57
+ | `AUTH_GITHUB_ID` | `AUTH_GITHUB_ID` | ✅ 保持不变 |
58
+ | `AUTH_GITHUB_SECRET` | `AUTH_GITHUB_SECRET` | ✅ 保持不变 |
59
+ | `AUTH_GOOGLE_ID` | `AUTH_GOOGLE_ID` | ✅ 保持不变 |
60
+ | `AUTH_GOOGLE_SECRET` | `AUTH_GOOGLE_SECRET` | ✅ 保持不变 |
61
+ | `AUTH_AUTH0_ID` | `AUTH_AUTH0_ID` | ✅ 保持不变 |
62
+ | `AUTH_AUTH0_SECRET` | `AUTH_AUTH0_SECRET` | ✅ 保持不变 |
63
+ | `AUTH_AUTH0_ISSUER` | `AUTH_AUTH0_ISSUER` | ✅ 保持不变 |
64
+ | `AUTH_AUTHENTIK_ID` | `AUTH_AUTHENTIK_ID` | ✅ 保持不变 |
65
+ | `AUTH_AUTHENTIK_SECRET` | `AUTH_AUTHENTIK_SECRET` | ✅ 保持不变 |
66
+ | `AUTH_AUTHENTIK_ISSUER` | `AUTH_AUTHENTIK_ISSUER` | ✅ 保持不变 |
67
+ | `microsoft-entra-id` | `microsoft` | ⚠️ provider 名称变更 |
68
+ | `AUTH_MICROSOFT_ENTRA_ID_ID` | `AUTH_MICROSOFT_ID` | ⚠️ 变量名变更 |
69
+ | `AUTH_MICROSOFT_ENTRA_ID_SECRET` | `AUTH_MICROSOFT_SECRET` | ⚠️ 变量名变更 |
70
+
71
+ <Callout type={'warning'}>
72
+ **注意**:Microsoft Entra ID 的 provider 名称从 `microsoft-entra-id` 改为 `microsoft`,相应的环境变量前缀也从 `AUTH_MICROSOFT_ENTRA_ID_` 改为 `AUTH_MICROSOFT_`。
73
+ </Callout>
74
+
75
+ ### 新增功能变量
76
+
77
+ Better Auth 支持更多功能,以下是新增的环境变量:
78
+
79
+ | 环境变量 | 说明 |
80
+ | ------------------------- | -------------------------------- |
81
+ | `AUTH_ALLOWED_EMAILS` | 邮箱白名单(限制注册) |
82
+ | `AUTH_EMAIL_VERIFICATION` | 启用邮箱验证(设为 `1`) |
83
+ | `ENABLE_MAGIC_LINK` | 启用魔法链接登录(设为 `1`) |
84
+ | `EMAIL_SERVICE_PROVIDER` | 邮件服务提供商(`nodemailer` 或 `resend`) |
85
+
86
+ ## 简单迁移
87
+
88
+ 对于小型自托管部署,最简单的方法是让用户使用 SSO 账户重新登录。
89
+
90
+ <Callout type={'warning'}>
91
+ **限制**:此方法会丢失 SSO 连接数据。如需保留 SSO 连接,请使用 [完整迁移](#完整迁移)。
92
+
93
+ 虽然 SSO 连接会丢失,但用户可以在登录后通过个人资料页手动重新绑定社交账号。
94
+
95
+ **示例场景**:假设你之前的账户绑定了两个 SSO 账户:
96
+
97
+ - 主邮箱(Google):`mail1@google.com`
98
+ - 副邮箱(Microsoft):`mail2@outlook.com`
99
+
100
+ 迁移后使用 `mail2@outlook.com` 登录将会**创建新用户**,而非关联到原有账户。
101
+ </Callout>
102
+
103
+ ### 步骤
104
+
105
+ 1. **更新环境变量**
106
+
107
+ 移除 NextAuth 变量并添加 Better Auth 变量:
108
+
109
+ ```bash
110
+ # 移除这些
111
+ # NEXT_AUTH_SECRET=xxx
112
+ # AUTH_xxx 相关的 NextAuth 提供商配置
113
+
114
+ # 添加这些
115
+ AUTH_SECRET=your-secret-key # openssl rand -base64 32
116
+
117
+ # 可选:启用 Google SSO(示例)
118
+ AUTH_SSO_PROVIDERS=google
119
+ AUTH_GOOGLE_ID=your-google-client-id
120
+ AUTH_GOOGLE_SECRET=your-google-client-secret
121
+ ```
122
+
123
+ <Callout type={'tip'}>
124
+ 查阅 [身份验证服务配置](/zh/docs/self-hosting/advanced/auth) 了解完整的环境变量和 SSO 提供商配置。
125
+ </Callout>
126
+
127
+ 2. **重新部署 LobeChat**
128
+
129
+ 部署启用 Better Auth 的新版本。
130
+
131
+ 3. **通知用户**
132
+
133
+ 告知用户使用之前的 SSO 账户重新登录。由于用户 ID 保持不变,聊天记录和设置将被保留。
134
+
135
+ <Callout type={'tip'}>
136
+ 这种方法快速且配置简单。用户只需使用现有的 SSO 提供商重新登录即可。
137
+ </Callout>
138
+
139
+ ## 完整迁移
140
+
141
+ 对于大型部署或需要保留 SSO 连接的情况,请使用迁移脚本。这会将数据从 `nextauth_accounts` 表迁移到 Better Auth 的 `accounts` 表。
142
+
143
+ <Callout type={'error'}>
144
+ **重要说明**:
145
+
146
+ - **务必先备份数据库**!如使用 Neon,可通过 [Fork 分支](https://neon.tech/docs/manage/branches#create-a-branch) 创建备份
147
+ - 迁移脚本需要 **clone 仓库后在本地运行**,不是在部署环境中执行
148
+ - 由于迁移涉及用户数据,风险较高,**官方不提供部署时自动迁移功能**
149
+ - 请务必先使用 dry-run 模式测试脚本能够顺利运行再正式执行
150
+ - 请务必在测试环境验证后再操作生产数据库
151
+ </Callout>
152
+
153
+ ### 前置条件
154
+
155
+ **环境要求:**
156
+
157
+ - Node.js 18+
158
+ - Git(用于 clone 仓库)
159
+ - pnpm(用于安装依赖)
160
+
161
+ **准备工作:**
162
+
163
+ 1. Clone LobeChat 仓库并安装依赖:
164
+
165
+ ```bash
166
+ git clone https://github.com/lobehub/lobe-chat.git
167
+ cd lobe-chat
168
+ pnpm install
169
+ ```
170
+
171
+ 2. 准备数据库连接字符串
172
+
173
+ 3. 确保数据库 schema 为最新版本
174
+
175
+ <Callout type={'info'}>
176
+ 如果你长期停留在旧版本,数据库 schema 可能不是最新的。请在 clone 的仓库中运行:
177
+
178
+ ```bash
179
+ DATABASE_URL=your-database-url pnpm db:migrate
180
+ ```
181
+ </Callout>
182
+
183
+ ### 步骤 1:配置迁移脚本环境变量
184
+
185
+ 在项目根目录创建 `.env` 文件(脚本会自动加载),配置所有环境变量:
186
+
187
+ ```bash
188
+ # ============================================
189
+ # 迁移模式:test 或 prod
190
+ # 建议先用 test 模式在测试数据库验证,确认无误后再切换到 prod
191
+ # ============================================
192
+ NEXTAUTH_TO_BETTERAUTH_MODE=test
193
+
194
+ # ============================================
195
+ # 数据库连接(根据模式使用对应的环境变量)
196
+ # TEST_ 前缀用于测试环境,PROD_ 前缀用于生产环境
197
+ # ============================================
198
+ TEST_NEXTAUTH_TO_BETTERAUTH_DATABASE_URL=postgresql://user:pass@test-host:5432/testdb
199
+ PROD_NEXTAUTH_TO_BETTERAUTH_DATABASE_URL=postgresql://user:pass@prod-host:5432/proddb
200
+
201
+ # ============================================
202
+ # 数据库驱动(可选)
203
+ # neon: Neon serverless 驱动(默认)
204
+ # node: node-postgres 驱动
205
+ # ============================================
206
+ NEXTAUTH_TO_BETTERAUTH_DATABASE_DRIVER=neon
207
+
208
+ # ============================================
209
+ # 批处理大小(可选)
210
+ # 每批处理的记录数,默认为 300
211
+ # ============================================
212
+ NEXTAUTH_TO_BETTERAUTH_BATCH_SIZE=300
213
+
214
+ # ============================================
215
+ # Dry Run 模式(可选)
216
+ # 设为 1 时只打印日志,不实际修改数据库
217
+ # 建议首次运行时启用,验证无误后再关闭
218
+ # ============================================
219
+ NEXTAUTH_TO_BETTERAUTH_DRY_RUN=1
220
+ ```
221
+
222
+ ### 步骤 2:Dry-Run 验证(测试环境)
223
+
224
+ ```bash
225
+ # 运行迁移(NEXTAUTH_TO_BETTERAUTH_DRY_RUN=1,只打印日志不修改数据库)
226
+ npx tsx scripts/nextauth-to-betterauth/index.ts
227
+ ```
228
+
229
+ 检查输出日志,确认无异常后继续下一步。
230
+
231
+ ### 步骤 3:执行迁移并验证(测试环境)
232
+
233
+ 修改 `.env` 将 `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` 改为 `0`,然后执行:
234
+
235
+ ```bash
236
+ # 执行迁移
237
+ npx tsx scripts/nextauth-to-betterauth/index.ts
238
+
239
+ # 验证迁移结果
240
+ npx tsx scripts/nextauth-to-betterauth/verify.ts
241
+ ```
242
+
243
+ 验证测试环境迁移结果无误后,继续下一步。
244
+
245
+ ### 步骤 4:Dry-Run 验证(生产环境)
246
+
247
+ 1. 修改 `.env` 文件:
248
+ - 将 `NEXTAUTH_TO_BETTERAUTH_MODE` 改为 `prod`
249
+ - 将 `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` 改回 `1`
250
+ 2. 运行脚本:
251
+
252
+ ```bash
253
+ # 运行迁移(dry-run 模式验证)
254
+ npx tsx scripts/nextauth-to-betterauth/index.ts
255
+ ```
256
+
257
+ 检查输出日志,确认无异常后继续下一步。
258
+
259
+ ### 步骤 5:执行迁移并验证(生产环境)
260
+
261
+ 修改 `.env` 将 `NEXTAUTH_TO_BETTERAUTH_DRY_RUN` 改为 `0`,然后执行:
262
+
263
+ ```bash
264
+ # 执行迁移
265
+ npx tsx scripts/nextauth-to-betterauth/index.ts
266
+
267
+ # 验证迁移结果
268
+ npx tsx scripts/nextauth-to-betterauth/verify.ts
269
+ ```
270
+
271
+ ### 步骤 6:配置 Better Auth 并重新部署
272
+
273
+ 迁移完成后,参照 [简单迁移 - 步骤 1](#步骤) 配置 Better Auth 环境变量并重新部署。
274
+
275
+ <Callout type={'tip'}>
276
+ 完整的 Better Auth 配置请参阅 [身份验证服务配置](/zh/docs/self-hosting/advanced/auth),包括所有支持的 SSO 提供商和邮件服务配置。
277
+ </Callout>
278
+
279
+ ## 迁移内容对比
280
+
281
+ | 数据 | 简单迁移 | 完整迁移 |
282
+ | ----------------------- | --------- | ---- |
283
+ | 用户账户 | ✅(通过重新登录) | ✅ |
284
+ | SSO 连接(Google、GitHub 等) | ❌ | ✅ |
285
+ | 聊天记录 | ✅ | ✅ |
286
+ | 用户设置 | ✅ | ✅ |
287
+
288
+ <Callout type={'info'}>
289
+ **注意**:Sessions 和 verification tokens 不会被迁移,因为它们是临时数据。迁移后用户需要重新登录。
290
+ </Callout>
291
+
292
+ ## 常见问题
293
+
294
+ ### 迁移后用户无法登录
295
+
296
+ - 检查 `AUTH_SECRET` 是否正确设置
297
+ - 验证数据库连接是否正常
298
+ - 确保 SSO 提供商已在 `AUTH_SSO_PROVIDERS` 中配置
299
+
300
+ ### SSO 用户无法连接
301
+
302
+ - 简单迁移:用户需要使用 SSO 账户重新登录
303
+ - 完整迁移:验证 SSO 提供商已在 `AUTH_SSO_PROVIDERS` 中配置,且使用相同的 provider ID
304
+
305
+ ### 迁移脚本失败
306
+
307
+ - 检查数据库连接字符串
308
+ - 查看脚本日志了解具体错误
309
+ - 确保数据库中存在 `nextauth_accounts` 表
310
+
311
+ ### column "xxx" of relation "users" does not exist
312
+
313
+ 这是因为数据库 schema 未更新。请先运行 `pnpm db:migrate` 更新数据库结构,然后再执行迁移脚本。
314
+
315
+ ## 相关阅读
316
+
317
+ <Cards>
318
+ <Card href={'/zh/docs/self-hosting/advanced/auth'} title={'身份验证服务配置'} />
319
+
320
+ <Card href={'/zh/docs/self-hosting/environment-variables/auth'} title={'认证相关环境变量'} />
321
+
322
+ <Card href={'/zh/docs/self-hosting/advanced/auth/legacy'} title={'旧版身份验证(NextAuth 和 Clerk)'} />
323
+ </Cards>