🤯 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
⬆️ chore(auth): upgrade Better Auth to 1.7.16 (#22217)
Bryanabbb94206795
diff --git a/.agents/acceptance/scripts/init-dev-env.sh b/.agents/acceptance/scripts/init-dev-env.shindex 51967b97847..2575b2e06d1 100755--- a/.agents/acceptance/scripts/init-dev-env.sh+++ b/.agents/acceptance/scripts/init-dev-env.sh@@ -478,11 +478,11 @@ const client = new pg.Client({ connectionString: databaseUrl });await client.query(`INSERT INTO accounts (id, user_id, account_id, provider_id, password, created_at, updated_at)VALUES ($1, $2, $3, $4, $5, $6, $6)- ON CONFLICT DO NOTHING`,+ ON CONFLICT (id) DO UPDATE SET account_id = EXCLUDED.account_id, password = EXCLUDED.password`,['agent_testing_account_001',TEST_USER.id,- TEST_USER.email,+ TEST_USER.id,'credential',passwordHash,now,diff --git a/docs/self-hosting/migration/v2/auth/better-auth-1-7.mdx b/docs/self-hosting/migration/v2/auth/better-auth-1-7.mdxnew file mode 100644index 00000000000..b68fbf2650b--- /dev/null+++ b/docs/self-hosting/migration/v2/auth/better-auth-1-7.mdx@@ -0,0 +1,65 @@+---+title: Upgrading Better Auth to 1.7+description: Deployment checks for the Better Auth 1.6.33 to 1.7.16 upgrade, including Microsoft account identifiers and Redis.+tags:+ - Authentication+ - Migration+---++# Upgrading Better Auth to 1.7++This guide covers LobeHub's upgrade from Better Auth **1.6.33 to 1.7.16**. Read the [upstream 1.7 upgrade guide](https://github.com/better-auth/better-auth/blob/v1.7.16/docs/content/docs/guides/1-7-upgrade-guide.mdx) and [1.7.16 release](https://github.com/better-auth/better-auth/releases/tag/v1.7.16) before deployment.++## Before deployment++- Back up the database and record the deployed application version. Rehearse the upgrade against a private copy of the database.+- Upgrade the server and browser assets together. The removed generic OAuth endpoints are not compatible with old clients. Ask users to reload open tabs after deployment.+- Avoid serving authentication callbacks from mixed 1.6 and 1.7 instances. Their OAuth state storage formats differ, so an authorization started on 1.6 cannot finish on 1.7; users with an in-flight login must restart it after the cutover.+- If Redis is enabled, its application credentials must permit `EVAL`, `GET`, `DEL`, `INCR`, and `EXPIRE`, in addition to the existing operations. The adapter now consumes one-time values atomically and creates rate-limit counters without extending an existing counter's TTL.+- Check for duplicate provider identities. Resolve each duplicate by verifying ownership; do not automatically merge users or delete accounts:++```sql+SELECT provider_id, account_id, count(*)+FROM accounts+GROUP BY provider_id, account_id+HAVING count(*) > 1;+```++This direct upgrade does **not** require an `issuer` column or a generic schema migration. The issuer schema introduced in Better Auth 1.7.0–1.7.2 was reverted in 1.7.3. Deployments that installed those intermediate versions need a separate schema review. LobeHub's own OIDC server uses `oidc-provider`, not Better Auth's removed `oidcProvider` plugin.++## Password accounts imported outside LobeHub++Better Auth 1.7 requires a password account's `account_id` to equal its local `user_id`. Normal registration and LobeHub's Clerk migration already follow this contract. Audit custom imports or manually seeded accounts before deployment:++```sql+SELECT id, user_id, account_id+FROM accounts+WHERE provider_id = 'credential' AND account_id IS DISTINCT FROM user_id;+```++If this returns rows, verify their ownership and duplicates before a reviewed repair. An email in `account_id` is no longer accepted for password sign-in. Do not change OAuth provider subjects or bypass this ownership check.++## Microsoft: migrate existing identities before sign-in++The built-in Microsoft provider changes its account identifier from the ID token's `sub` claim to `oid`. This also applies when `AUTH_SSO_PROVIDERS` uses LobeHub's `microsoft-entra-id` alias, which resolves to the built-in `microsoft` provider.++If the `accounts` table contains Microsoft accounts, **do not enable Microsoft sign-in or linking on the upgraded application until their identifiers have been mapped**. Otherwise an existing user may no longer match their account, and automatic linking or a new account can hide the mismatch.++1. Inventory rows with `provider_id = 'microsoft'`. Keep each local `id`, `user_id`, and existing `account_id` in the private migration record.+2. Build a reviewed mapping from each local account ID and old `sub` to its verified Entra `oid`. Establish the tenant and client/application context as well. Use verified identity-provider records or correctly validated tokens. An email address or an unverified decoded JWT is not sufficient proof of identity. Do not put tokens or the identity map in a PR.+3. Check that the mapping covers every affected account exactly once, that each old value still matches the database, and that no new `(provider_id, account_id)` pair collides. Stop for missing or ambiguous identities.+4. Stop Microsoft sign-in and account linking during the cutover, including on old application instances. In a reviewed database transaction, update **only** `accounts.account_id` for the matching local row and old value. Preserve `accounts.id`, `accounts.user_id`, and the other account fields. Check the updated row count before committing.+5. Deploy the upgraded application consistently across instances, then test an existing Microsoft user. Confirm that the same local user and account rows are used, and that no duplicate user or account is created. Test a new user separately before reopening normal traffic.++There is no automatic SQL migration in this change: the application cannot safely derive a trusted `sub` → `oid` mapping from the account identifier alone. For rollback, restore the matching application and account-ID mapping together. If new logins or account links have already occurred, reconcile those new rows before reversing the mapping; restoring an old backup blindly can lose unrelated data.++## Other provider checks++- **Generic OAuth/OIDC:** sign-in and linking now use the common social endpoints. LobeHub already sets `/api/auth/callback/<provider>` explicitly, so its registered callback URLs do not need to change for this upgrade. Verify the actual deployed URL and provider configuration in staging.+- **OIDC discovery:** verify discovery availability, issuer, JWKS, audience, nonce, and ID-token validity with your provider. Do not disable token verification to work around a failed login.+- **Feishu and WeChat:** test sign-in and linking with the existing custom profile/token handling. Their generic provider callbacks continue to return the raw profile; do not replace it with the built-in provider `{ user, data }` shape.+- **Email OTP and magic links:** test an existing verified user and an unverified password account. Upstream now removes unproven credentials/accounts and revokes existing sessions when first establishing verified email ownership. Plan for affected users to sign in again.+- **Sessions and account settings:** check deferred session refresh, sign-out, account listing, linking, and unlinking. Account operations now use the local account row ID, not the provider subject.+- **Passkeys and mobile:** test browser and Android passkeys and mobile deep links. Keep explicit WebAuthn origins and trusted custom schemes. Separately maintained Expo clients must await the now-async `getCookie()` API before sending its value as a header.++These checks require your staging identity providers and client applications. Automated unit/integration tests do not establish that a particular deployment or production identity mapping is safe.diff --git a/docs/self-hosting/migration/v2/auth/better-auth-1-7.zh-CN.mdx b/docs/self-hosting/migration/v2/auth/better-auth-1-7.zh-CN.mdxnew file mode 100644index 00000000000..fc96a71b5aa--- /dev/null+++ b/docs/self-hosting/migration/v2/auth/better-auth-1-7.zh-CN.mdx@@ -0,0 +1,65 @@+---+title: 升级 Better Auth 至 1.7+description: 从 Better Auth 1.6.33 升级至 1.7.16 的部署检查,包括 Microsoft 账号标识迁移与 Redis 要求。+tags:+ - Authentication+ - Migration+---++# 升级 Better Auth 至 1.7++本文适用于 LobeHub 从 Better Auth **1.6.33 升级至 1.7.16**。部署前请阅读[上游 1.7 升级指南](https://github.com/better-auth/better-auth/blob/v1.7.16/docs/content/docs/guides/1-7-upgrade-guide.mdx)与 [1.7.16 发布说明](https://github.com/better-auth/better-auth/releases/tag/v1.7.16)。++## 部署前++- 备份数据库并记录当前应用版本,在私有数据库副本上演练升级。+- 同时更新服务端与浏览器资源。旧客户端使用的通用 OAuth 端点已移除,部署后应让用户刷新已打开的页面。+- 不要让 1.6 与 1.7 实例混合处理鉴权回调。两个版本保存 OAuth state 的格式不同,在 1.6 发起的授权无法由 1.7 完成;切换时仍在登录流程中的用户需要重新发起登录。+- 如果启用 Redis,应用凭据除已有权限外,还需要允许 `EVAL`、`GET`、`DEL`、`INCR` 和 `EXPIRE`。适配器现在原子消费一次性数据,并且只在计数器首次创建时设置 TTL,不延长现有计数窗口。+- 检查重复的第三方身份,逐条核实归属,不能自动合并用户或删除账号:++```sql+SELECT provider_id, account_id, count(*)+FROM accounts+GROUP BY provider_id, account_id+HAVING count(*) > 1;+```++从 1.6.33 直接升级至 1.7.16 **不需要**添加 `issuer` 列或执行通用表结构迁移。1.7.0–1.7.2 引入的 issuer 表结构已在 1.7.3 撤回;曾安装这些中间版本的部署需要另行检查。LobeHub 自己的 OIDC 服务使用 `oidc-provider`,不依赖 Better Auth 已移除的 `oidcProvider` 插件。++## 自定义导入的密码账号++Better Auth 1.7 要求密码账号的 `account_id` 等于本地 `user_id`。正常注册和 LobeHub 的 Clerk 迁移脚本已遵循这一约定。部署前应检查自定义导入或手动填充的账号:++```sql+SELECT id, user_id, account_id+FROM accounts+WHERE provider_id = 'credential' AND account_id IS DISTINCT FROM user_id;+```++如果查询返回记录,应先核实账号归属和重复情况,再经审核修复。密码登录不再接受以邮箱作为 `account_id` 的记录。不要修改 OAuth 第三方身份标识,也不要绕过此归属检查。++## Microsoft:恢复登录前迁移现有身份++内置 Microsoft provider 的账号标识由 ID token 的 `sub` 改为 `oid`。LobeHub 的 `microsoft-entra-id` 别名也会解析为内置 `microsoft` provider,因此同样受影响。++如果 `accounts` 表中已有 Microsoft 账号,**完成标识映射前,不要在新版应用上启用 Microsoft 登录或账号绑定**。否则已有账号可能无法匹配,自动绑定或新建账号还可能掩盖这个问题。++1. 盘点 `provider_id = 'microsoft'` 的记录,在私有迁移记录中保存本地 `id`、`user_id` 和原有 `account_id`。+2. 为每个本地账号 ID 和旧 `sub` 建立经过审核的 Entra `oid` 映射,并核实 tenant 与 client/application 上下文。依据可信身份源记录或经过正确验证的 token,不能仅凭 email 或未验证的 JWT 解码结果关联身份。不要将 token 或身份映射提交到 PR。+3. 确认映射完整且一一对应,旧值仍与数据库一致,新的 `(provider_id, account_id)` 不发生冲突。遇到缺失或歧义必须停止迁移。+4. 切换期间停止 Microsoft 登录与绑定,包括旧应用实例。在经过审核的数据库事务中,按本地行 ID 和旧值匹配,**仅更新** `accounts.account_id`,保留 `accounts.id`、`accounts.user_id` 及其他字段。提交前核对更新行数。+5. 所有实例一致部署新版后,用已有 Microsoft 用户验证仍命中原本的用户与账号行,且没有新增重复记录。再单独测试新用户,最后恢复正常流量。++本次升级不包含自动 SQL 迁移,因为应用无法仅从旧账号标识安全推导出可信的 `sub` → `oid` 映射。回滚时必须同时恢复匹配的应用版本与账号 ID 映射。若上线后已发生新登录或绑定,应先核对新增记录,再反向迁移;直接恢复旧备份可能丢失无关数据。++## 其他登录方式检查++- **通用 OAuth/OIDC:** 登录与绑定改用统一的 social 端点。LobeHub 已显式设置 `/api/auth/callback/<provider>`,此次升级不要求更改已登记的回调 URL,仍应在预发布环境核对实际 URL 与 provider 配置。+- **OIDC discovery:** 验证 discovery 可达性、issuer、JWKS、audience、nonce 和 ID token,不要通过禁用 token 校验绕过登录错误。+- **飞书与微信:** 测试登录、绑定及现有自定义 token/profile 处理。通用 provider 回调仍返回原始 profile,不要改成内置 provider 的 `{ user, data }` 格式。+- **邮件 OTP 与 magic link:** 分别测试已验证用户与未验证的密码账号。上游首次确立邮箱所有权时会清理未经证明的凭据 / 账号并撤销已有会话,相关用户可能需要重新登录。+- **会话与账号设置:** 验证延迟续期、退出、账号列表、绑定和解绑。账号操作现在使用本地账号行 ID,而不是第三方 subject。+- **Passkey 与移动端:** 验证浏览器、Android passkey 和移动端深链,保留明确的 WebAuthn origin 与自定义 scheme 信任配置。独立维护的 Expo 客户端需要先 `await getCookie()`,再把返回值用于请求头。++上述检查需要部署方的预发布身份源和客户端。单元 / 集成测试不能证明某个实际部署或生产身份映射已满足上线要求。diff --git a/e2e/cucumber.config.js b/e2e/cucumber.config.jsindex 2b484266c8b..200f91402d4 100644--- a/e2e/cucumber.config.js+++ b/e2e/cucumber.config.js@@ -23,7 +23,7 @@ export default {parallel: canRunInParallel && !perfRun ? Math.max(1, requestedParallel) : 1,paths: ['src/features/**/*.feature'],publishQuiet: true,- require: ['src/steps/**/!(*.test).ts', 'src/support/**/*.ts'],+ require: ['src/steps/**/!(*.test).ts', 'src/support/**/!(*.test).ts'],requireModule: ['tsx/cjs'],retry: 0,tags: perfRun ? `${perfTags} and not @skip` : 'not @skip and not @perf and not @perf-local',diff --git a/e2e/src/probes/acceptanceSeed.test.ts b/e2e/src/probes/acceptanceSeed.test.tsnew file mode 100644index 00000000000..b02eedac524--- /dev/null+++ b/e2e/src/probes/acceptanceSeed.test.ts@@ -0,0 +1,71 @@+import { readFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { runInNewContext } from 'node:vm';++import bcrypt from 'bcryptjs';+import { describe, expect, it, vi } from 'vitest';++async function captureSeedQueries() {+ const script = await readFile(+ new URL('../../../.agents/acceptance/scripts/init-dev-env.sh', import.meta.url),+ 'utf8',+ );+ const source = script.match(/seed_user\(\) \{[\s\S]*?node <<'NODE'\n([\s\S]*?)\nNODE/);+ expect(+ source,+ 'the acceptance bootstrap must contain its seed-user implementation',+ ).not.toBeNull();++ const query = vi.fn(async () => ({ rowCount: 0 }));+ const require = createRequire(import.meta.url);+ await runInNewContext(source![1], {+ Buffer,+ console: { error: vi.fn(), log: vi.fn() },+ process: {+ env: {+ DATABASE_URL: 'postgresql://localhost/acceptance-fixture',+ KEY_VAULTS_SECRET: Buffer.alloc(32).toString('base64'),+ },+ exit: (code: number) => {+ throw new Error(`seed-user exited with ${code}`);+ },+ },+ require: (name: string) => {+ if (name === 'pg') {+ return {+ Client: class {+ connect = vi.fn();+ end = vi.fn();+ query = query;+ },+ };+ }+ if (name === 'node:fs') return { mkdirSync: vi.fn(), writeFileSync: vi.fn() };+ return require(name);+ },+ });++ return query.mock.calls as unknown as [string, unknown[]][];+}++describe('acceptance bootstrap credentials', () => {+ it('seeds a password account owned by the local user ID', async () => {+ const queries = await captureSeedQueries();+ const user = queries.find(([sql]) => sql.includes('INSERT INTO users'))![1];+ const account = queries.find(([sql]) => sql.includes('INSERT INTO accounts'))![1];++ expect(account[1]).toBe(user[0]);+ expect(account[2]).toBe(user[0]);+ expect(account[3]).toBe('credential');+ expect(await bcrypt.compare('TestPassword123!', account[4] as string)).toBe(true);+ });++ it('repairs existing fixture credentials when the seed is rerun', async () => {+ const queries = await captureSeedQueries();+ const [sql] = queries.find(([statement]) => statement.includes('INSERT INTO accounts'))!;++ expect(sql).toContain('ON CONFLICT (id) DO UPDATE');+ expect(sql).toContain('account_id = EXCLUDED.account_id');+ expect(sql).toContain('password = EXCLUDED.password');+ });+});diff --git a/e2e/src/probes/cucumberConfig.test.ts b/e2e/src/probes/cucumberConfig.test.tsnew file mode 100644index 00000000000..d153143aafe--- /dev/null+++ b/e2e/src/probes/cucumberConfig.test.ts@@ -0,0 +1,15 @@+import { glob } from 'node:fs/promises';++import { loadConfiguration } from '@cucumber/cucumber/api';+import { describe, expect, it } from 'vitest';++describe('Cucumber support discovery', () => {+ it('loads runtime support and steps without importing Vitest test files', async () => {+ const { runConfiguration } = await loadConfiguration({ file: 'cucumber.config.js' });+ const paths = await Array.fromAsync(glob(runConfiguration.support.requirePaths ?? []));++ expect(paths.some((path) => path.endsWith('/support/seedTestUser.ts'))).toBe(true);+ expect(paths.some((path) => path.endsWith('/steps/hooks.ts'))).toBe(true);+ expect(paths.filter((path) => path.endsWith('.test.ts'))).toEqual([]);+ });+});diff --git a/e2e/src/support/seedTestUser.test.ts b/e2e/src/support/seedTestUser.test.tsnew file mode 100644index 00000000000..f0d037b8fc0--- /dev/null+++ b/e2e/src/support/seedTestUser.test.ts@@ -0,0 +1,81 @@+import bcrypt from 'bcryptjs';+import { betterAuth } from 'better-auth';+import { memoryAdapter } from 'better-auth/adapters/memory';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { seedTestUser, TEST_USER } from './seedTestUser';++const { query } = vi.hoisted(() => ({ query: vi.fn() }));++vi.mock('pg', () => ({+ default: {+ Client: class {+ connect = vi.fn();+ end = vi.fn();+ query = query;+ },+ },+}));++afterEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+});++describe('seedTestUser', () => {+ it('seeds credentials that can sign in through Better Auth', async () => {+ vi.stubEnv('DATABASE_URL', 'postgresql://localhost/e2e-fixture');+ await seedTestUser();++ const userValues = query.mock.calls.find(([sql]) => sql.includes('INSERT INTO users'))![1];+ const accountValues = query.mock.calls.find(([sql]) =>+ sql.includes('INSERT INTO accounts'),+ )![1];+ const db = {+ account: [+ {+ accountId: accountValues[2],+ createdAt: new Date(accountValues[5]),+ id: accountValues[0],+ password: accountValues[4],+ providerId: accountValues[3],+ updatedAt: new Date(accountValues[5]),+ userId: accountValues[1],+ },+ ],+ session: [],+ user: [+ {+ createdAt: new Date(userValues[7]),+ email: userValues[1],+ emailVerified: userValues[5],+ id: userValues[0],+ name: userValues[4],+ updatedAt: new Date(userValues[7]),+ },+ ],+ verification: [],+ };+ const auth = betterAuth({+ baseURL: 'http://localhost:3006',+ database: memoryAdapter(db),+ emailAndPassword: {+ enabled: true,+ password: { verify: ({ hash, password }) => bcrypt.compare(password, hash) },+ },+ secret: 'test-secret-test-secret-test-secret',+ });++ const response = await auth.handler(+ new Request('http://localhost:3006/api/auth/sign-in/email', {+ body: JSON.stringify({ email: TEST_USER.email, password: TEST_USER.password }),+ headers: { 'content-type': 'application/json', 'origin': 'http://localhost:3006' },+ method: 'POST',+ }),+ );++ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ user: { id: TEST_USER.id } });+ expect(response.headers.get('set-cookie')).toContain('better-auth.session_token');+ });+});diff --git a/e2e/src/support/seedTestUser.ts b/e2e/src/support/seedTestUser.tsindex d2100697c4b..4e4b3190a69 100644--- a/e2e/src/support/seedTestUser.ts+++ b/e2e/src/support/seedTestUser.ts@@ -80,11 +80,11 @@ export async function seedTestUser(): Promise<void> {await client.query(`INSERT INTO accounts (id, user_id, account_id, provider_id, password, created_at, updated_at)VALUES ($1, $2, $3, $4, $5, $6, $6)- ON CONFLICT DO NOTHING`,+ ON CONFLICT (id) DO UPDATE SET account_id = EXCLUDED.account_id, password = EXCLUDED.password`,[accountId,TEST_USER.id,- TEST_USER.email, // account_id is email for credential provider+ TEST_USER.id, // Better Auth credentials belong to the local user ID, not the email'credential', // provider_idpasswordHash,now,diff --git a/package.json b/package.jsonindex 26d8253203c..c1e679a5cbe 100644--- a/package.json+++ b/package.json@@ -190,7 +190,7 @@"overrides": {"@types/react": "19.2.13","baseline-browser-mapping": "2.10.31",- "better-auth": "1.6.33",+ "better-auth": "1.7.16","drizzle-orm": "^0.45.2","fast-xml-parser": "5.4.2","lexical": "0.42.0",@@ -207,8 +207,8 @@"@aws-sdk/s3-request-presigner": "~3.932.0","@azure-rest/ai-inference": "1.0.0-beta.5","@azure/core-auth": "^1.11.0",- "@better-auth/expo": "1.6.33",- "@better-auth/passkey": "1.6.33",+ "@better-auth/expo": "1.7.16",+ "@better-auth/passkey": "1.7.16","@cfworker/json-schema": "^4.1.1","@chat-adapter/discord": "~4.38.0","@chat-adapter/slack": "~4.38.0",@@ -387,7 +387,7 @@"ahooks": "^3.9.7","async-retry": "^1.3.3","bcryptjs": "^3.0.3",- "better-auth": "1.6.33",+ "better-auth": "1.7.16","brotli-wasm": "^3.0.1","buffer.js": "npm:buffer@^6.0.3","chat": "~4.38.0",diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex c04879f27f3..eea7eec1afa 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -490,6 +490,8 @@ export const OAuthAccountSchema = z.object({* SSO Provider info displayed in profile page*/export interface SSOProvider {+ /** Local Better Auth account row ID, used for account operations (not the provider subject). */+ accountId?: string;email?: string;/** Expiration time - Date for better-auth */expiresAt?: Date | number | null;diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex ee9daedb6e0..87ccde3b43c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -39,6 +39,17 @@ minimumReleaseAgeExclude:- '@lobehub/*'- local-replica+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'+ - '@better-auth/[email protected]'# Build scripts run one at a time. Several peer-variant copies of# @lobehub/editor resolve in this workspace and every copy's postinstalldiff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.tsindex 5f0454f3c78..cd601662cf8 100644--- a/src/features/Auth/SignIn/useSignIn.test.ts+++ b/src/features/Auth/SignIn/useSignIn.test.ts@@ -8,7 +8,6 @@ const mockSearchParamsGet = vi.hoisted(() => vi.fn().mockReturnValue(null));const mockMessageError = vi.hoisted(() => vi.fn());const mockMessageSuccess = vi.hoisted(() => vi.fn());const mockSignInSocial = vi.hoisted(() => vi.fn());-const mockSignInOauth2 = vi.hoisted(() => vi.fn());const mockSignInEmail = vi.hoisted(() => vi.fn());const mockSignInMagicLink = vi.hoisted(() => vi.fn());const mockRequestPasswordReset = vi.hoisted(() => vi.fn());@@ -43,7 +42,6 @@ vi.mock('@/libs/better-auth/auth-client', () => ({signIn: {email: mockSignInEmail,magicLink: mockSignInMagicLink,- oauth2: mockSignInOauth2,social: mockSignInSocial,},}));@@ -419,8 +417,8 @@ describe('useSignIn', () => {expect(mockMessageError).not.toHaveBeenCalled();});- it('should call signIn.oauth2 for custom providers', async () => {- mockSignInOauth2.mockResolvedValue({ url: 'https://custom.com/auth' });+ it('should call signIn.social for custom providers', async () => {+ mockSignInSocial.mockResolvedValue({ url: 'https://custom.com/auth' });const { result } = renderHook(() => useSignIn());@@ -428,10 +426,10 @@ describe('useSignIn', () => {await result.current.handleSocialSignIn('custom-oidc');});- expect(mockSignInOauth2).toHaveBeenCalledWith(+ expect(mockSignInSocial).toHaveBeenCalledWith(expect.objectContaining({newUserCallbackURL: `${originalLocation.origin}/onboarding`,- providerId: 'custom-oidc',+ provider: 'custom-oidc',}),);});diff --git a/src/features/Auth/SignIn/useSignIn.ts b/src/features/Auth/SignIn/useSignIn.tsindex 12728626dd9..75a6abfbde0 100644--- a/src/features/Auth/SignIn/useSignIn.ts+++ b/src/features/Auth/SignIn/useSignIn.ts@@ -11,7 +11,7 @@ import { useAuthAgreement } from '@/features/AuthShell/AuthAgreement';import { useAuthServerConfigStore } from '@/features/AuthShell/AuthServerConfigProvider';import { trackLoginOrSignupClicked } from '@/features/User/UserLoginOrSignup/trackLoginOrSignupClicked';import { requestPasswordReset, signIn } from '@/libs/better-auth/auth-client';-import { isBuiltinProvider, normalizeProviderId } from '@/libs/better-auth/utils/client';+import { normalizeProviderId } from '@/libs/better-auth/utils/client';import {buildOnboardingRedirectUrl,sanitizeRedirectPath,@@ -319,22 +319,12 @@ export const useSignIn = () => {authOrigin,);const additionalData = await getAdditionalData();- const signInWithAdditionalData = async () =>- isBuiltinProvider(normalizedProvider)- ? await signIn.social({- additionalData,- callbackURL,- newUserCallbackURL,- provider: normalizedProvider,- })- : await signIn.oauth2({- additionalData,- callbackURL,- newUserCallbackURL,- providerId: normalizedProvider,- });-- const result = await signInWithAdditionalData();+ const result = await signIn.social({+ additionalData,+ callbackURL,+ newUserCallbackURL,+ provider: normalizedProvider,+ });if (result && 'error' in result && result.error) throw result.error;} catch (error) {diff --git a/src/features/Settings/profile/features/SSOProvidersList/index.tsx b/src/features/Settings/profile/features/SSOProvidersList/index.tsxindex 803901bdc62..f2d1aad3897 100644--- a/src/features/Settings/profile/features/SSOProvidersList/index.tsx+++ b/src/features/Settings/profile/features/SSOProvidersList/index.tsx@@ -7,7 +7,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import AuthIcons from '@/components/AuthIcons';-import { isBuiltinProvider, normalizeProviderId } from '@/libs/better-auth/utils/client';+import { normalizeProviderId } from '@/libs/better-auth/utils/client';import { useServerConfigStore } from '@/store/serverConfig';import { serverConfigSelectors } from '@/store/serverConfig/selectors';import { useUserStore } from '@/store/user';@@ -42,13 +42,13 @@ export const SSOProvidersList = memo(() => {);}, [oAuthSSOProviders, linkedProviderIds]);- const handleUnlinkSSO = async (provider: string) => {+ const handleUnlinkSSO = async (provider: string, accountId?: string) => {// Better-auth link/unlink operations are not available on desktopif (isDesktop) return;// The control is disabled when this is the only login method. Keep the// guard for callers outside the rendered list and for state races.- if (!allowUnlink) return;+ if (!allowUnlink || !accountId) return;confirmModal({content: t('profile.sso.unlink.description', { provider }),okButtonProps: {@@ -56,7 +56,7 @@ export const SSOProvidersList = memo(() => {},onOk: async () => {const { unlinkAccount } = await import('@/libs/better-auth/auth-client');- await unlinkAccount({ providerId: provider });+ await unlinkAccount({ accountId });refreshAuthProviders();},title: <span style={providerNameStyle}>{t('profile.sso.unlink.title', { provider })}</span>,@@ -67,20 +67,11 @@ export const SSOProvidersList = memo(() => {if (!enableAuthActions) return;const normalizedProvider = normalizeProviderId(provider);- const { linkSocial, oauth2 } = await import('@/libs/better-auth/auth-client');-- if (isBuiltinProvider(normalizedProvider)) {- // Use better-auth native linkSocial API for built-in providers- await linkSocial({- callbackURL: '/profile',- provider: normalizedProvider as any,- });- return;- }-- await oauth2.link({+ const { linkSocial } = await import('@/libs/better-auth/auth-client');++ await linkSocial({callbackURL: '/profile',- providerId: normalizedProvider,+ provider: normalizedProvider,});};@@ -115,10 +106,10 @@ export const SSOProvidersList = memo(() => {<Tooltip title={!allowUnlink ? t('profile.sso.unlink.forbidden') : undefined}><span><ActionIcon- disabled={!allowUnlink}+ disabled={!allowUnlink || !item.accountId}icon={Unlink}size={'small'}- onClick={() => handleUnlinkSSO(item.provider)}+ onClick={() => handleUnlinkSSO(item.provider, item.accountId)}/></span></Tooltip>diff --git a/src/libs/better-auth/auth-client.desktop.test.ts b/src/libs/better-auth/auth-client.desktop.test.tsindex 22b181c6993..1fcdd7da1d0 100644--- a/src/libs/better-auth/auth-client.desktop.test.ts+++ b/src/libs/better-auth/auth-client.desktop.test.ts@@ -1,6 +1,13 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { changeEmail, listAccounts } from './auth-client.desktop';+import {+ accountInfo,+ changeEmail,+ linkSocial,+ listAccounts,+ signIn,+ unlinkAccount,+} from './auth-client.desktop';afterEach(() => {vi.unstubAllGlobals();@@ -13,6 +20,29 @@ const requestUrl = (input: RequestInfo | URL) => {};describe('desktop better-auth client', () => {+ it('uses the 1.7 social endpoints for generic providers and local account IDs', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({ status: true }));+ vi.stubGlobal('fetch', fetch);++ await signIn.social({ callbackURL: '/chat', provider: 'custom-oidc' });+ await linkSocial({ callbackURL: '/profile', provider: 'custom-oidc' });+ await accountInfo({ query: { accountId: 'local-account-id' } });+ await unlinkAccount({ accountId: 'local-account-id' });++ expect(fetch.mock.calls.map(([input]) => requestUrl(input))).toEqual([+ '/api/auth/sign-in/social',+ '/api/auth/link-social',+ '/api/auth/account-info?accountId=local-account-id',+ '/api/auth/unlink-account',+ ]);+ expect(JSON.parse(fetch.mock.calls[0][1]!.body as string)).toMatchObject({+ provider: 'custom-oidc',+ });+ expect(JSON.parse(fetch.mock.calls[3][1]!.body as string)).toEqual({+ accountId: 'local-account-id',+ });+ });+it('sends account requests to the renderer instead of the remote server', async () => {const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({ status: true }));vi.stubGlobal('fetch', fetch);diff --git a/src/libs/better-auth/auth-client.desktop.ts b/src/libs/better-auth/auth-client.desktop.tsindex 3ca867dfcfe..aeb79b495e0 100644--- a/src/libs/better-auth/auth-client.desktop.ts+++ b/src/libs/better-auth/auth-client.desktop.ts@@ -1,9 +1,4 @@-import {- adminClient,- genericOAuthClient,- inferAdditionalFields,- magicLinkClient,-} from 'better-auth/client/plugins';+import { adminClient, inferAdditionalFields, magicLinkClient } from 'better-auth/client/plugins';import { createAuthClient } from 'better-auth/react';import { type auth } from '@/auth';@@ -23,12 +18,7 @@ function getClient() {fetchOptions: {customFetchImpl: desktopAuthFetch,},- plugins: [- adminClient(),- inferAdditionalFields<typeof auth>(),- genericOAuthClient(),- magicLinkClient(),- ],+ plugins: [adminClient(), inferAdditionalFields<typeof auth>(), magicLinkClient()],});}return _client;@@ -43,14 +33,14 @@ function lazyProp(key: string): any {get(_t, prop, receiver) {const target = getClient()[key];const value = Reflect.get(target, prop, receiver);- return typeof value === 'function' ? value.bind(target) : value;+ // Nested Better Auth proxies treat `.bind` as an endpoint, not Function.bind.+ return typeof value === 'function' ? Function.prototype.bind.call(value, target) : value;},});}export const changeEmail = lazyProp('changeEmail');export const linkSocial = lazyProp('linkSocial');-export const oauth2 = lazyProp('oauth2');export const accountInfo = lazyProp('accountInfo');export const listAccounts = lazyProp('listAccounts');export const requestPasswordReset = lazyProp('requestPasswordReset');diff --git a/src/libs/better-auth/auth-client.ts b/src/libs/better-auth/auth-client.tsindex 9680315711b..5a64167fa87 100644--- a/src/libs/better-auth/auth-client.ts+++ b/src/libs/better-auth/auth-client.ts@@ -1,10 +1,5 @@import { CLIENT_VERSION_HEADER, CURRENT_VERSION } from '@lobechat/const';-import {- adminClient,- genericOAuthClient,- inferAdditionalFields,- magicLinkClient,-} from 'better-auth/client/plugins';+import { adminClient, inferAdditionalFields, magicLinkClient } from 'better-auth/client/plugins';import { createAuthClient } from 'better-auth/react';import { type auth } from '@/auth';@@ -12,7 +7,6 @@ import { type auth } from '@/auth';export const {changeEmail,linkSocial,- oauth2,accountInfo,listAccounts,requestPasswordReset,@@ -32,7 +26,6 @@ export const {plugins: [adminClient(),inferAdditionalFields<typeof auth>(),- genericOAuthClient(),// Always include magicLinkClient - server will reject if not enabledmagicLinkClient(),],diff --git a/src/libs/better-auth/define-config.test.ts b/src/libs/better-auth/define-config.test.tsindex 8f57518170b..d98eee95743 100644--- a/src/libs/better-auth/define-config.test.ts+++ b/src/libs/better-auth/define-config.test.ts@@ -146,6 +146,15 @@ describe('defineConfig', () => {process.env = originalEnv;});+ it('enables stable database joins without dropping the custom ID generator', async () => {+ const { defineConfig } = await import('./define-config');+ defineConfig({ plugins: [] });+ const options = mocks.betterAuth.mock.calls[0][0];+ expect(options.advanced.database.joins).toBe(true);+ expect(options.advanced.database.generateId({ model: 'users' })).toBe('generated-user-id');+ expect(options.experimental).toBeUndefined();+ });+it('should configure passkeys with the approved origins', async () => {const { defineConfig } = await import('./define-config');diff --git a/src/libs/better-auth/define-config.ts b/src/libs/better-auth/define-config.tsindex eecb1bbd810..b43ad2bcf0f 100644--- a/src/libs/better-auth/define-config.ts+++ b/src/libs/better-auth/define-config.ts@@ -217,17 +217,10 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {session: sessionOptions,database: drizzleAdapter(serverDB, {provider: 'pg',- // experimental joins feature needs schema to pass full relation+ // Joined account/session queries need the complete relation schema.schema,}),secondaryStorage: createSecondaryStorage(),- /**- * Database joins is useful when Better-Auth needs to fetch related data from multiple tables in a single query.- * Endpoints like /get-session, /get-full-organization and many others benefit greatly from this feature,- * seeing upwards of 2x to 3x performance improvements depending on database latency.- * Ref: https://www.better-auth.com/docs/adapters/drizzle#joins-experimental- */- experimental: { joins: true },/*** Run user bootstrap for every newly created account (email, magic link, OAuth/social, etc.).* Using Better Auth database hooks ensures we catch social flows that bypass /sign-up/* routes.@@ -289,6 +282,7 @@ export function defineConfig(customOptions: CustomBetterAuthOptions) {}),...(customOptions.cookiePrefix && { cookiePrefix: customOptions.cookiePrefix }),database: {+ joins: true,/*** Align Better Auth user IDs with our shared idGenerator for consistency.* Other models use the shared nanoid generator (12 chars) to keep IDs consistent project-wide.diff --git a/src/libs/better-auth/sso/__tests__/profileMapping.test.ts b/src/libs/better-auth/sso/__tests__/profileMapping.test.tsnew file mode 100644index 00000000000..b3f85d97ab8--- /dev/null+++ b/src/libs/better-auth/sso/__tests__/profileMapping.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it, vi } from 'vitest';++import Casdoor from '../providers/casdoor';+import CloudflareZeroTrust from '../providers/cloudflare-zero-trust';+import GenericOIDC from '../providers/generic-oidc';+import Logto from '../providers/logto';+import Okta from '../providers/okta';++vi.mock('@/envs/auth', () => ({ authEnv: {} }));++const providers = [+ Casdoor.build({+ AUTH_CASDOOR_ID: 'id',+ AUTH_CASDOOR_ISSUER: 'https://issuer.example',+ AUTH_CASDOOR_SECRET: 'secret',+ }),+ CloudflareZeroTrust.build({+ AUTH_CLOUDFLARE_ZERO_TRUST_ID: 'id',+ AUTH_CLOUDFLARE_ZERO_TRUST_ISSUER: 'https://issuer.example',+ AUTH_CLOUDFLARE_ZERO_TRUST_SECRET: 'secret',+ }),+ GenericOIDC.build({+ AUTH_GENERIC_OIDC_ID: 'id',+ AUTH_GENERIC_OIDC_ISSUER: 'https://issuer.example',+ AUTH_GENERIC_OIDC_SECRET: 'secret',+ }),+ Logto.build({+ AUTH_LOGTO_ID: 'id',+ AUTH_LOGTO_ISSUER: 'https://issuer.example',+ AUTH_LOGTO_SECRET: 'secret',+ }),+ Okta.build({+ AUTH_OKTA_ID: 'id',+ AUTH_OKTA_ISSUER: 'https://issuer.example',+ AUTH_OKTA_SECRET: 'secret',+ }),+];++describe.each(providers)('$providerId profile mapping', (provider) => {+ it('preserves the 1.6 account subject precedence while accepting an empty id', async () => {+ expect(+ await provider.accountSubject!({+ profile: { id: 'legacy-id', sub: 'oidc-subject' },+ tokens: {},+ }),+ ).toBe('legacy-id');+ expect(+ await provider.accountSubject!({+ profile: { id: '', sub: 'oidc-subject' },+ tokens: {},+ }),+ ).toBe('oidc-subject');+ expect(+ await provider.accountSubject!({+ profile: { id: 0, sub: 'oidc-subject' },+ tokens: {},+ }),+ ).toBe(0);+ });++ it('keeps valid names', async () => {+ expect(+ await provider.mapProfileToUser!({ email: '[email protected]', name: 'User' }),+ ).toMatchObject({+ name: 'User',+ });+ });++ it('ignores malformed custom claims and normalizes a numeric subject fallback', async () => {+ const mapped = await provider.mapProfileToUser!({+ avatar: {},+ displayName: {},+ email: null,+ firstName: {},+ id: 42,+ lastName: [],+ name: null,+ preferred_username: {},+ sub: 42,+ username: {},+ });++ expect(mapped.name).toBe('42');+ expect(mapped.email).toBeUndefined();+ expect(mapped.image).toBeUndefined();+ });+});diff --git a/src/libs/better-auth/sso/compatibility.test.ts b/src/libs/better-auth/sso/compatibility.test.tsnew file mode 100644index 00000000000..f13b6f88c17--- /dev/null+++ b/src/libs/better-auth/sso/compatibility.test.ts@@ -0,0 +1,182 @@+// @vitest-environment node+import { betterAuth } from 'better-auth';+import { memoryAdapter } from 'better-auth/adapters/memory';+import { genericOAuth } from 'better-auth/plugins';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { buildOidcConfig } from './helpers';++const BASE_URL = 'http://localhost:3000';+const PROVIDER_ID = 'custom-oauth';++afterEach(() => {+ vi.unstubAllGlobals();+});++const createAuth = () => {+ const db: Record<string, any[]> = { account: [], session: [], user: [], verification: [] };+ const auth = betterAuth({+ baseURL: BASE_URL,+ database: memoryAdapter(db),+ emailAndPassword: { enabled: true },+ plugins: [+ genericOAuth({+ config: [+ {+ authorizationUrl: 'https://provider.example.com/authorize',+ clientId: 'test-client',+ clientSecret: 'test-client-secret',+ getToken: async () => ({ accessToken: 'fixture-access-token' }),+ // Match LobeHub's custom providers: a raw profile, not { user, data }.+ getUserInfo: async () => ({+ email: '[email protected]',+ emailVerified: true,+ id: 'provider-subject',+ name: 'User',+ }),+ pkce: false,+ providerId: PROVIDER_ID,+ redirectURI: `${BASE_URL}/api/auth/callback/${PROVIDER_ID}`,+ },+ ],+ }),+ ],+ secret: 'test-secret-test-secret-test-secret',+ });++ return { auth, db };+};++const cookies = (headers: Headers) =>+ headers+ .getSetCookie()+ .map((value) => value.split(';')[0])+ .join('; ');++const completeOAuth = async (+ auth: ReturnType<typeof createAuth>['auth'],+ endpoint: '/sign-in/social' | '/link-social',+ sessionCookie = '',+) => {+ const response = await auth.handler(+ new Request(`${BASE_URL}/api/auth${endpoint}`, {+ body: JSON.stringify({ callbackURL: `${BASE_URL}/profile`, provider: PROVIDER_ID }),+ headers: { 'content-type': 'application/json', 'cookie': sessionCookie, 'origin': BASE_URL },+ method: 'POST',+ }),+ );+ expect(response.status).toBe(200);+ const authorizationURL = new URL((await response.json()).url);+ expect(authorizationURL.searchParams.get('redirect_uri')).toBe(+ `${BASE_URL}/api/auth/callback/${PROVIDER_ID}`,+ );+ expect(authorizationURL.searchParams.has('code_challenge')).toBe(false);++ const callbackURL = new URL(`${BASE_URL}/api/auth/callback/${PROVIDER_ID}`);+ callbackURL.searchParams.set('code', 'fixture-code');+ callbackURL.searchParams.set('state', authorizationURL.searchParams.get('state')!);+ const callback = await auth.handler(+ new Request(callbackURL, {+ headers: { cookie: [sessionCookie, cookies(response.headers)].filter(Boolean).join('; ') },+ }),+ );+ expect(callback.status).toBe(302);+ expect(callback.headers.get('location')).toBe(`${BASE_URL}/profile`);++ return callback;+};++describe('Better Auth 1.7 generic provider compatibility', () => {+ it('signs in through the social endpoint with the existing callback and raw profile', async () => {+ const { auth, db } = createAuth();++ await completeOAuth(auth, '/sign-in/social');++ expect(db.user).toHaveLength(1);+ expect(db.account).toHaveLength(1);+ expect(db.account[0]).toMatchObject({+ accountId: 'provider-subject',+ providerId: PROVIDER_ID,+ userId: db.user[0].id,+ });+ });++ it('links, reads, and unlinks a generic account using its local row ID', async () => {+ const { auth, db } = createAuth();+ const signUp = await auth.api.signUpEmail({+ body: { email: '[email protected]', name: 'User', password: 'password-123456' },+ returnHeaders: true,+ });+ const sessionCookie = cookies(signUp.headers);++ await completeOAuth(auth, '/link-social', sessionCookie);++ expect(db.user).toHaveLength(1);+ const headers = new Headers({ cookie: sessionCookie, origin: BASE_URL });+ const accounts = await auth.api.listUserAccounts({ headers });+ const account = accounts.find((item) => item.providerId === PROVIDER_ID)!;+ expect(account.id).not.toBe(account.accountId);+ expect(await auth.api.accountInfo({ headers, query: { accountId: account.id } })).toMatchObject(+ {+ user: { email: '[email protected]' },+ },+ );+ await auth.api.unlinkAccount({ body: { accountId: account.id }, headers });+ expect(db.account).toHaveLength(1);+ expect(db.account[0].providerId).toBe('credential');+ });++ it('keeps the legacy account subject for OIDC profiles when discovery metadata is incomplete', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: string | URL | Request) => {+ const url = input instanceof Request ? input.url : input.toString();+ if (url.endsWith('/.well-known/openid-configuration')) {+ return Response.json({+ authorization_endpoint: 'https://provider.example.com/authorize',+ issuer: 'https://provider.example.com',+ });+ }+ throw new Error(`Unexpected fetch: ${url}`);+ }),+ );++ const db: Record<string, any[]> = { account: [], session: [], user: [], verification: [] };+ const auth = betterAuth({+ baseURL: BASE_URL,+ database: memoryAdapter(db),+ plugins: [+ genericOAuth({+ config: [+ buildOidcConfig({+ clientId: 'test-client',+ clientSecret: 'test-client-secret',+ issuer: 'https://provider.example.com',+ overrides: {+ getToken: async () => ({ accessToken: 'fixture-access-token' }),+ getUserInfo: async () => ({+ email: '[email protected]',+ emailVerified: true,+ id: '',+ name: 'User',+ sub: 'provider-subject',+ }),+ },+ pkce: false,+ providerId: PROVIDER_ID,+ }),+ ],+ }),+ ],+ secret: 'test-secret-test-secret-test-secret',+ });++ await completeOAuth(auth, '/sign-in/social');++ expect(db.account).toHaveLength(1);+ expect(db.account[0]).toMatchObject({+ accountId: 'provider-subject',+ providerId: PROVIDER_ID,+ });+ });+});diff --git a/src/libs/better-auth/sso/helpers.ts b/src/libs/better-auth/sso/helpers.tsindex 3a71a6370bf..881e23e1d21 100644--- a/src/libs/better-auth/sso/helpers.ts+++ b/src/libs/better-auth/sso/helpers.ts@@ -1,7 +1,12 @@+import { isTrimmedNonEmptyString } from '@lobechat/utils/object';import { type GenericOAuthConfig } from 'better-auth/plugins';export const DEFAULT_OIDC_SCOPES = ['openid', 'email', 'profile'];+/** Custom OIDC claims are untrusted unknown values, not necessarily strings. */+export const getStringClaim = (...values: unknown[]): string | undefined =>+ values.find(isTrimmedNonEmptyString);+const createDiscoveryUrl = (issuer: string) => {const normalized = issuer.replace(/\/$/, '');return normalized.includes('/.well-known/')@@ -38,6 +43,15 @@ export const buildOidcConfig = ({const discoveryUrl = createDiscoveryUrl(normalizedIssuer);return {+ /**+ * Better Auth 1.6 identified generic providers by `id`, then `sub`. Keep that order so the+ * 1.7 migration neither changes existing account IDs nor rejects OIDC UserInfo responses that+ * expose only the standard `sub` claim when discovery metadata is incomplete.+ */+ accountSubject: ({ profile }) =>+ profile.id === undefined || profile.id === null || profile.id === ''+ ? (profile.sub ?? '')+ : profile.id,clientId,clientSecret,discoveryUrl,diff --git a/src/libs/better-auth/sso/index.ts b/src/libs/better-auth/sso/index.tsindex 84eb425fa1c..e862cd02f32 100644--- a/src/libs/better-auth/sso/index.ts+++ b/src/libs/better-auth/sso/index.ts@@ -105,8 +105,7 @@ export const initBetterAuthSSOProviders = () => {const config = definition.build(env);if (config) {- // the generic oidc callback url is /api/auth/oauth2/callback/{providerId}- // different from builtin providers' /api/auth/callback/{providerId}+ // Better Auth 1.7 uses the same callback path for built-in and generic providers.config.redirectURI = `${appEnv.APP_URL}/api/auth/callback/${definition.id}`;genericOAuthProviders.push(config);}diff --git a/src/libs/better-auth/sso/providers/casdoor.ts b/src/libs/better-auth/sso/providers/casdoor.tsindex 013a3b06891..f370716912a 100644--- a/src/libs/better-auth/sso/providers/casdoor.ts+++ b/src/libs/better-auth/sso/providers/casdoor.ts@@ -1,6 +1,6 @@import { authEnv } from '@/envs/auth';-import { buildOidcConfig } from '../helpers';+import { buildOidcConfig, getStringClaim } from '../helpers';import { type GenericProviderDefinition } from '../types';const provider: GenericProviderDefinition<{@@ -15,18 +15,23 @@ const provider: GenericProviderDefinition<{issuer: env.AUTH_CASDOOR_ISSUER,overrides: {mapProfileToUser: (profile) => {- const composedName = [profile.firstName, profile.lastName]+ const composedName = [getStringClaim(profile.firstName), getStringClaim(profile.lastName)].filter(Boolean).join(' ').trim();const fallbackName = composedName.length > 0 ? composedName : undefined;return {- email: profile.email,+ email: profile.email ?? undefined,emailVerified: Boolean(profile.emailVerified),- image: profile.avatar ?? profile.permanentAvatar,- name:- profile.displayName ?? fallbackName ?? profile.name ?? profile.email ?? profile.id,+ image: getStringClaim(profile.avatar, profile.permanentAvatar),+ name: getStringClaim(+ profile.displayName,+ fallbackName,+ profile.name,+ profile.email,+ profile.id?.toString(),+ ),};},},diff --git a/src/libs/better-auth/sso/providers/cloudflare-zero-trust.ts b/src/libs/better-auth/sso/providers/cloudflare-zero-trust.tsindex f01fa8ffdfe..7f833df815b 100644--- a/src/libs/better-auth/sso/providers/cloudflare-zero-trust.ts+++ b/src/libs/better-auth/sso/providers/cloudflare-zero-trust.ts@@ -1,6 +1,6 @@import { authEnv } from '@/envs/auth';-import { buildOidcConfig } from '../helpers';+import { buildOidcConfig, getStringClaim } from '../helpers';import { type GenericProviderDefinition } from '../types';const provider: GenericProviderDefinition<{@@ -15,8 +15,8 @@ const provider: GenericProviderDefinition<{issuer: env.AUTH_CLOUDFLARE_ZERO_TRUST_ISSUER,overrides: {mapProfileToUser: (profile) => ({- email: profile.email,- name: profile.name ?? profile.email ?? profile.sub,+ email: profile.email ?? undefined,+ name: getStringClaim(profile.name, profile.email, profile.sub?.toString()),}),},providerId: 'cloudflare-zero-trust',diff --git a/src/libs/better-auth/sso/providers/generic-oidc.ts b/src/libs/better-auth/sso/providers/generic-oidc.tsindex e675f07d137..102c06685d0 100644--- a/src/libs/better-auth/sso/providers/generic-oidc.ts+++ b/src/libs/better-auth/sso/providers/generic-oidc.ts@@ -1,6 +1,6 @@import { authEnv } from '@/envs/auth';-import { buildOidcConfig } from '../helpers';+import { buildOidcConfig, getStringClaim } from '../helpers';import { type GenericProviderDefinition } from '../types';const provider: GenericProviderDefinition<{@@ -19,7 +19,12 @@ const provider: GenericProviderDefinition<{* fails with name_is_missing when upstream profiles only expose username/email fields.*/mapProfileToUser: (profile) => ({- name: profile.name ?? profile.username ?? profile.email ?? profile.id,+ name: getStringClaim(+ profile.name,+ profile.username,+ profile.email,+ profile.id?.toString(),+ ),}),},providerId: 'generic-oidc',diff --git a/src/libs/better-auth/sso/providers/logto.ts b/src/libs/better-auth/sso/providers/logto.tsindex b5a2b34862d..3e97d1eff39 100644--- a/src/libs/better-auth/sso/providers/logto.ts+++ b/src/libs/better-auth/sso/providers/logto.ts@@ -1,6 +1,6 @@import { authEnv } from '@/envs/auth';-import { buildOidcConfig } from '../helpers';+import { buildOidcConfig, getStringClaim } from '../helpers';import { type GenericProviderDefinition } from '../types';const provider: GenericProviderDefinition<{@@ -15,8 +15,13 @@ const provider: GenericProviderDefinition<{issuer: env.AUTH_LOGTO_ISSUER,overrides: {mapProfileToUser: (profile) => ({- email: profile.email,- name: profile.name ?? profile.username ?? profile.email ?? profile.sub,+ email: profile.email ?? undefined,+ name: getStringClaim(+ profile.name,+ profile.username,+ profile.email,+ profile.sub?.toString(),+ ),}),},providerId: 'logto',diff --git a/src/libs/better-auth/sso/providers/okta.ts b/src/libs/better-auth/sso/providers/okta.tsindex 2b4789fbcf4..c38d522f5e7 100644--- a/src/libs/better-auth/sso/providers/okta.ts+++ b/src/libs/better-auth/sso/providers/okta.ts@@ -1,6 +1,6 @@import { authEnv } from '@/envs/auth';-import { buildOidcConfig } from '../helpers';+import { buildOidcConfig, getStringClaim } from '../helpers';import { type GenericProviderDefinition } from '../types';const provider: GenericProviderDefinition<{@@ -15,8 +15,13 @@ const provider: GenericProviderDefinition<{issuer: env.AUTH_OKTA_ISSUER,overrides: {mapProfileToUser: (profile) => ({- email: profile.email,- name: profile.name ?? profile.preferred_username ?? profile.email ?? profile.sub,+ email: profile.email ?? undefined,+ name: getStringClaim(+ profile.name,+ profile.preferred_username,+ profile.email,+ profile.sub?.toString(),+ ),}),},providerId: 'okta',diff --git a/src/libs/better-auth/utils/config.test.ts b/src/libs/better-auth/utils/config.test.tsindex 0b733e8107b..e4ac4332953 100644--- a/src/libs/better-auth/utils/config.test.ts+++ b/src/libs/better-auth/utils/config.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { initializeRedis, isRedisEnabled } from '@/server/modules/Redis';+const mocks = vi.hoisted(() => ({appEnv: { APP_URL: 'https://app.example.com' },authEnv: {@@ -17,6 +19,82 @@ vi.mock('@/server/modules/Redis', () => ({}));vi.mock('@/utils/env', () => ({ isDev: false }));+describe('createSecondaryStorage', () => {+ const redis = {+ del: vi.fn(),+ eval: vi.fn(),+ get: vi.fn(),+ set: vi.fn(),+ };++ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(isRedisEnabled).mockReturnValue(true);+ vi.mocked(initializeRedis).mockResolvedValue(redis as any);+ });++ afterEach(() => {+ vi.mocked(isRedisEnabled).mockReturnValue(false);+ });++ it('does not configure secondary storage when Redis is disabled', async () => {+ vi.mocked(isRedisEnabled).mockReturnValue(false);+ const { createSecondaryStorage } = await import('./config');++ expect(createSecondaryStorage()).toBeUndefined();+ expect(initializeRedis).not.toHaveBeenCalled();+ });++ it('consumes a namespaced value in one atomic operation', async () => {+ const { createSecondaryStorage } = await import('./config');+ const storage = createSecondaryStorage()!;+ redis.eval.mockResolvedValueOnce('one-time-value').mockResolvedValueOnce(null);++ expect(await storage.getAndDelete!('verification-token')).toBe('one-time-value');+ expect(await storage.getAndDelete!('verification-token')).toBeNull();++ const [script, keys, key] = redis.eval.mock.calls[0];+ expect(script).toContain("redis.call('GET', KEYS[1])");+ expect(script).toContain("redis.call('DEL', KEYS[1])");+ expect(keys).toBe(1);+ expect(key).toBe('better-auth:verification-token');+ expect(redis.get).not.toHaveBeenCalled();+ expect(redis.del).not.toHaveBeenCalled();+ });++ it('increments atomically in a namespace isolated from legacy JSON values', async () => {+ const { createSecondaryStorage } = await import('./config');+ const storage = createSecondaryStorage()!;+ redis.eval.mockResolvedValueOnce(1).mockResolvedValueOnce(2);++ await storage.set('rate-limit', JSON.stringify({ count: 1, lastRequest: 1 }), 60);+ expect(await storage.increment!('rate-limit', 60)).toBe(1);+ expect(await storage.increment!('rate-limit', 60)).toBe(2);++ expect(redis.set).toHaveBeenCalledWith(+ 'better-auth:rate-limit',+ JSON.stringify({ count: 1, lastRequest: 1 }),+ { ex: 60 },+ );+ expect(redis.eval).toHaveBeenCalledWith(+ expect.stringContaining("if value == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end"),+ 1,+ 'better-auth:counter:v1:rate-limit',+ 60,+ );+ });++ it('fails closed when the enabled Redis client cannot initialize', async () => {+ vi.mocked(initializeRedis).mockResolvedValue(null);+ const { createSecondaryStorage } = await import('./config');+ const storage = createSecondaryStorage()!;++ await expect(storage.getAndDelete!('token')).rejects.toThrow('failed to initialize');+ await expect(storage.increment!('counter', 60)).rejects.toThrow('failed to initialize');+ expect(redis.eval).not.toHaveBeenCalled();+ });+});+describe('getTrustedOrigins', () => {const originalEnv = process.env;diff --git a/src/libs/better-auth/utils/config.ts b/src/libs/better-auth/utils/config.tsindex 7ccf7cb4950..d70be429d7b 100644--- a/src/libs/better-auth/utils/config.ts+++ b/src/libs/better-auth/utils/config.ts@@ -1,3 +1,5 @@+import { type BetterAuthOptions } from 'better-auth/minimal';+import assetLinks from '@/../public/.well-known/assetlinks.json';import { appEnv } from '@/envs/app';import { authEnv } from '@/envs/auth';@@ -113,13 +115,15 @@ export const getTrustedOrigins = (enabledSSOProviders: string[]) => {* Build Better Auth secondaryStorage backed by Redis.* Uses the shared Redis manager to avoid duplicate connections and prefixes keys to prevent clashes.*/-export const createSecondaryStorage = () => {+export const createSecondaryStorage = (): BetterAuthOptions['secondaryStorage'] => {const redisConfig = getRedisConfig();if (!isRedisEnabled(redisConfig)) return undefined;const secondaryStorageKeyPrefix = 'better-auth:';+ const atomicCounterKeyPrefix = `${secondaryStorageKeyPrefix}counter:v1:`;const buildKey = (key: string) => `${secondaryStorageKeyPrefix}${key}`;+ const buildAtomicCounterKey = (key: string) => `${atomicCounterKeyPrefix}${key}`;const getRedisClient = async () => {const redisClient = await initializeRedis(redisConfig);@@ -139,6 +143,32 @@ export const createSecondaryStorage = () => {const redisClient = await getRedisClient();return (await redisClient.get(buildKey(key))) ?? null;},+ getAndDelete: async (key: string) => {+ const redisClient = await getRedisClient();+ // One Lua operation also supports Redis versions without GETDEL.+ return redisClient.eval<string | null>(+ `local value = redis.call('GET', KEYS[1])+ if value then redis.call('DEL', KEYS[1]) end+ return value`,+ 1,+ buildKey(key),+ );+ },+ increment: async (key: string, ttl: number) => {+ const redisClient = await getRedisClient();+ /**+ * Better Auth 1.6 stored rate-limit snapshots as JSON through set(). A separate namespace+ * prevents 1.7's INCR from colliding with those live keys during a rolling deployment.+ */+ return redisClient.eval<number>(+ `local value = redis.call('INCR', KEYS[1])+ if value == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end+ return value`,+ 1,+ buildAtomicCounterKey(key),+ ttl,+ );+ },set: async (key: string, value: string, ttl?: number) => {const redisClient = await getRedisClient();if (typeof ttl === 'number') {diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.tsindex 7ef0486a0b7..d9c410680ac 100644--- a/src/store/user/slices/auth/action.test.ts+++ b/src/store/user/slices/auth/action.test.ts@@ -198,7 +198,7 @@ describe('createAuthSlice', () => {it('should fetch providers from BetterAuth', async () => {mockBetterAuthClient.listAccounts.mockResolvedValueOnce({data: [- { providerId: 'github', accountId: 'gh-123' },+ { id: 'local-github', providerId: 'github', accountId: 'gh-123' },{ providerId: 'credential', accountId: 'cred-1' },],});@@ -215,6 +215,9 @@ describe('createAuthSlice', () => {expect(mockBetterAuthClient.listAccounts).toHaveBeenCalled();expect(result.current.isLoadedAuthProviders).toBe(true);expect(result.current.hasPasswordAccount).toBe(true);+ expect(mockBetterAuthClient.accountInfo).toHaveBeenCalledWith({+ query: { accountId: 'local-github' },+ });});it('should handle fetch error gracefully', async () => {@@ -236,7 +239,7 @@ describe('createAuthSlice', () => {describe('refreshAuthProviders', () => {it('should refresh providers from BetterAuth', async () => {mockBetterAuthClient.listAccounts.mockResolvedValueOnce({- data: [{ providerId: 'google', accountId: 'g-1' }],+ data: [{ id: 'local-google', providerId: 'google', accountId: 'g-1' }],});mockBetterAuthClient.accountInfo.mockResolvedValueOnce({data: { user: { email: '[email protected]' } },@@ -250,7 +253,12 @@ describe('createAuthSlice', () => {expect(mockBetterAuthClient.listAccounts).toHaveBeenCalled();expect(result.current.authProviders).toEqual([- { provider: 'google', email: '[email protected]', providerAccountId: 'g-1' },+ {+ accountId: 'local-google',+ provider: 'google',+ email: '[email protected]',+ providerAccountId: 'g-1',+ },]);});diff --git a/src/store/user/slices/auth/action.ts b/src/store/user/slices/auth/action.tsindex 36c2aeef3fa..92f294583c4 100644--- a/src/store/user/slices/auth/action.ts+++ b/src/store/user/slices/auth/action.ts@@ -22,9 +22,10 @@ const fetchAuthProvidersData = async (): Promise<AuthProvidersData> => {.map(async (account) => {// In theory, the id_token could be decrypted from the accounts table, but I found that better-auth on GitHub does not save the id_tokenconst info = await accountInfo({- query: { accountId: account.accountId },+ query: { accountId: account.id },});return {+ accountId: account.id,email: info.data?.user?.email ?? undefined,provider: account.providerId,providerAccountId: account.accountId,