🤯 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
👷 build: Revert "♻️ refactor: make LobeNextAuthDBAdapter Edge Compatible" (#9086)
Arvin Xu7bd25d96fe54
diff --git a/packages/database/src/server/models/__tests__/nextauth.test.ts b/packages/database/src/server/models/__tests__/nextauth.test.tsnew file mode 100644index 00000000000..caff53501f2--- /dev/null+++ b/packages/database/src/server/models/__tests__/nextauth.test.ts@@ -0,0 +1,556 @@+import type {+ AdapterAccount,+ AdapterAuthenticator,+ AdapterSession,+ AdapterUser,+ VerificationToken,+} from '@auth/core/adapters';+import { eq } from 'drizzle-orm';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';++import { getTestDBInstance } from '../../../core/dbForTest';+import {+ nextauthAccounts,+ nextauthAuthenticators,+ nextauthSessions,+ nextauthVerificationTokens,+ users,+} from '../../../schemas';++let serverDB = await getTestDBInstance();++let nextAuthAdapter = LobeNextAuthDbAdapter(serverDB);++const userId = 'user-db';+const user: AdapterUser = {+ id: userId,+ name: 'John Doe',+ email: '[email protected]',+ emailVerified: new Date(),+ image: 'https://example.com/avatar.jpg',+};++const sessionToken = 'session-token';++beforeAll(async () => {+ await serverDB.delete(users);+ await serverDB.delete(nextauthAccounts);+ await serverDB.delete(nextauthAuthenticators);+ await serverDB.delete(nextauthSessions);+ await serverDB.delete(nextauthVerificationTokens);+});++beforeEach(async () => {+ process.env.KEY_VAULTS_SECRET = 'ofQiJCXLF8mYemwfMWLOHoHimlPu91YmLfU7YZ4lreQ=';+ // insert a user+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser(user);+});++afterEach(async () => {+ await serverDB.delete(users);+});++afterAll(async () => {+ await serverDB.delete(users);+ await serverDB.delete(nextauthAccounts);+ await serverDB.delete(nextauthAuthenticators);+ await serverDB.delete(nextauthSessions);+ await serverDB.delete(nextauthVerificationTokens);+ process.env.KEY_VAULTS_SECRET = undefined;+});++/**+ * The tests below only test the database operation functionality,+ * the mock values might not represent the actual value+ */+describe('LobeNextAuthDbAdapter', () => {+ describe('users', () => {+ describe('createUser', () => {+ it('should create a new user', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createUser).toBeDefined();+ const anotherUserId = 'user-db-2';+ const anotherUserName = 'John Doe 2';+ const anotherEmail = '[email protected]';+ // @ts-expect-error: createUser is defined+ const createdUser = await nextAuthAdapter.createUser({+ ...user,+ id: anotherUserId,+ name: anotherUserName,+ email: anotherEmail,+ });+ expect(createdUser).toBeDefined();+ expect(createdUser.id).toBe(anotherUserId);+ expect(createdUser.name).toBe(anotherUserName);+ expect(createdUser.email).toBe(anotherEmail);+ expect(createdUser.emailVerified).toBe(user.emailVerified);+ expect(createdUser.image).toBe(user.image);+ });++ it('should not create a user if it already exists', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createUser).toBeDefined();+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser(user);+ // Should not create a new user if it already exists+ expect(+ await serverDB.query.users.findMany({ where: eq(users.email, user.email) }),+ ).toHaveLength(1);+ });++ it('should not create a user if email exist', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createUser).toBeDefined();+ const anotherUserId = 'user-db-2';+ const anotherUserName = 'John Doe 2';+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser({+ ...user,+ id: anotherUserId,+ name: anotherUserName,+ });+ // Should not create a new user if email already exists+ expect(+ await serverDB.query.users.findMany({ where: eq(users.email, user.email) }),+ ).toHaveLength(1);+ });++ it('should create a user if id not exist and email is null', async () => {+ // In previous version, it will link the account to the existing user if the email is null+ // issue: https://github.com/lobehub/lobe-chat/issues/4918+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createUser).toBeDefined();++ const existUserId = 'user-db-1';+ const existUserName = 'John Doe 1';+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser({+ ...user,+ id: existUserId,+ name: existUserName,+ email: '',+ });++ const anotherUserId = 'user-db-2';+ const anotherUserName = 'John Doe 2';+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser({+ ...user,+ id: anotherUserId,+ name: anotherUserName,+ email: '',+ });+ // Should create a new user if id not exists and email is null+ expect(+ await serverDB.query.users.findMany({ where: eq(users.id, anotherUserId) }),+ ).toHaveLength(1);+ });++ it('should create a user if id not exist even email is invalid type', async () => {+ // In previous version, it will link the account to the existing user if the email is null+ // issue: https://github.com/lobehub/lobe-chat/issues/4918+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createUser).toBeDefined();++ const existUserId = 'user-db-1';+ const existUserName = 'John Doe 1';+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser({+ ...user,+ id: existUserId,+ name: existUserName,+ email: Object({}), // assign a non-string value+ });++ const anotherUserId = 'user-db-2';+ const anotherUserName = 'John Doe 2';+ // @ts-expect-error: createUser is defined+ await nextAuthAdapter.createUser({+ ...user,+ id: anotherUserId,+ name: anotherUserName,+ // @ts-expect-error: try to assign undefined value+ email: undefined,+ });++ // Should create a new user if id not exists and email is null+ expect(+ await serverDB.query.users.findMany({ where: eq(users.id, anotherUserId) }),+ ).toHaveLength(1);+ });+ });++ describe('deleteUser', () => {+ it('should delete a user', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.deleteUser).toBeDefined();+ // @ts-expect-error: deleteUser is defined+ await nextAuthAdapter.deleteUser(userId);+ const deletedUser = await serverDB.query.users.findFirst({ where: eq(users.id, userId) });+ expect(deletedUser).toBeUndefined();+ });+ });++ describe('getUser', () => {+ it('should get a user', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.getUser).toBeDefined();+ // @ts-expect-error: getUser is defined+ const fetchedUser = await nextAuthAdapter.getUser(userId);+ expect(fetchedUser).toBeDefined();+ expect(fetchedUser?.id).toBe(user.id);+ expect(fetchedUser?.name).toBe(user.name);+ expect(fetchedUser?.email).toBe(user.email);+ expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);+ expect(fetchedUser?.image).toBe(user.image);+ });+ });++ describe('getUserByEmail', () => {+ it('should get a user by email', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.getUserByEmail).toBeDefined();+ // @ts-expect-error: getUserByEmail is defined+ const fetchedUser = await nextAuthAdapter.getUserByEmail(user.email);+ expect(fetchedUser).toBeDefined();+ expect(fetchedUser?.id).toBe(user.id);+ expect(fetchedUser?.name).toBe(user.name);+ expect(fetchedUser?.email).toBe(user.email);+ expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);+ expect(fetchedUser?.image).toBe(user.image);+ });+ });++ describe('getUserByAccount', () => {+ it('should get a user by account', async () => {+ const account: AdapterAccount = {+ providerAccountId: 'provider-account-id',+ userId: userId,+ provider: 'auth0',+ type: 'email',+ };+ // @ts-expect-error: linkAccount is defined+ await nextAuthAdapter.linkAccount(account);+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.getUserByAccount).toBeDefined();+ // @ts-expect-error: getUserByAccount is defined+ const fetchedUser = await nextAuthAdapter.getUserByAccount(account);+ expect(fetchedUser).toBeDefined();+ expect(fetchedUser?.id).toBe(user.id);+ expect(fetchedUser?.name).toBe(user.name);+ expect(fetchedUser?.email).toBe(user.email);+ expect(fetchedUser?.emailVerified).toEqual(user.emailVerified);+ expect(fetchedUser?.image).toBe(user.image);+ });+ });++ describe('updateUser', () => {+ it('should update a user', async () => {+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.updateUser).toBeDefined();+ const updatedName = 'updated' + user.name;+ const updatedEmail = 'updated' + user.email;+ // @ts-expect-error: updateUser is defined+ const updatedUser = await nextAuthAdapter.updateUser({+ id: userId,+ name: updatedName,+ email: updatedEmail,+ });+ expect(updatedUser).toBeDefined();+ expect(updatedUser.id).toBe(userId);+ expect(updatedUser.name).toBe(updatedName);+ expect(updatedUser.email).toBe(updatedEmail);+ });+ });+ });++ describe('authenticators', () => {+ describe('createAuthenticator', () => {+ it('should create a new authenticator', async () => {+ // Create an authenticator and link to the exists user+ const params: AdapterAuthenticator = {+ credentialBackedUp: false,+ credentialDeviceType: 'type',+ credentialID: 'some-id',+ credentialPublicKey: 'some-key',+ userId: userId,+ providerAccountId: 'provider-account-id',+ counter: 1,+ };+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createAuthenticator).toBeDefined();+ // @ts-expect-error: createAuthenticator is defined+ const authenticator = await nextAuthAdapter.createAuthenticator(params);++ expect(authenticator).toBeDefined();+ expect(authenticator.userId).toBe(params.userId);+ expect(authenticator.providerAccountId).toBe(params.providerAccountId);+ });+ });++ describe('getAuthenticator', () => {+ it('should get an authenticator', async () => {+ // Create an authenticator and link to the exists user+ const params: AdapterAuthenticator = {+ credentialBackedUp: false,+ credentialDeviceType: 'type',+ credentialID: 'some-id',+ credentialPublicKey: 'some-key',+ userId: userId,+ providerAccountId: 'provider-account-id',+ counter: 1,+ };+ // @ts-expect-error: createAuthenticator is defined+ await nextAuthAdapter.createAuthenticator(params);+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.getAuthenticator).toBeDefined();+ // @ts-expect-error: getAuthenticator is defined+ const fetchedAuthenticator = await nextAuthAdapter.getAuthenticator(params.credentialID);+ expect(fetchedAuthenticator).toBeDefined();+ expect(fetchedAuthenticator?.userId).toBe(params.userId);+ expect(fetchedAuthenticator?.providerAccountId).toBe(params.providerAccountId);+ });+ });++ describe('updateAuthenticatorCounter', () => {+ it('should update an authenticator counter', async () => {+ // Create an authenticator and link to the exists user+ const params: AdapterAuthenticator = {+ credentialBackedUp: false,+ credentialDeviceType: 'type',+ credentialID: 'some-id',+ credentialPublicKey: 'some-key',+ userId: userId,+ providerAccountId: 'provider-account-id',+ counter: 1,+ };+ // @ts-expect-error: createAuthenticator is defined+ await nextAuthAdapter.createAuthenticator(params);+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.updateAuthenticatorCounter).toBeDefined();+ // @ts-expect-error: updateAuthenticatorCounter is defined+ const updatedAuthenticator = await nextAuthAdapter.updateAuthenticatorCounter(+ params.credentialID,+ 2,+ );+ expect(updatedAuthenticator).toBeDefined();+ expect(updatedAuthenticator.counter).toBe(2);+ });+ });++ describe('listAuthenticatorsByUserId', () => {+ it('should list authenticators by user id', async () => {+ // Create an authenticator and link to the exists user+ const params: AdapterAuthenticator = {+ credentialBackedUp: false,+ credentialDeviceType: 'type',+ credentialID: 'some-id',+ credentialPublicKey: 'some-key',+ userId: userId,+ providerAccountId: 'provider-account-id',+ counter: 1,+ };+ // @ts-expect-error: createAuthenticator is defined+ await nextAuthAdapter.createAuthenticator(params);+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.listAuthenticatorsByUserId).toBeDefined();+ // @ts-expect-error: listAuthenticatorsByUserId is defined+ const authenticators = await nextAuthAdapter.listAuthenticatorsByUserId(userId);+ expect(authenticators).toBeDefined();+ expect(authenticators.length).toBeGreaterThan(0);+ expect(authenticators[0].userId).toBe(params.userId);+ expect(authenticators[0].providerAccountId).toBe(params.providerAccountId);+ });+ });+ });++ describe('session', () => {+ describe('createSession', () => {+ it('should create a new session', async () => {+ const data: AdapterSession = {+ sessionToken,+ userId: userId,+ expires: new Date(),+ };+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.createSession).toBeDefined();++ // @ts-expect-error: createSession is defined+ const session = await nextAuthAdapter.createSession(data);++ expect(session).toBeDefined();+ expect(session.sessionToken).toBe(data.sessionToken);+ expect(session.userId).toBe(data.userId);+ expect(session.expires).toEqual(data.expires);+ });+ });++ describe('updateSession', () => {+ it('should update a session', async () => {+ const data: AdapterSession = {+ sessionToken,+ userId: userId,+ expires: new Date(),+ };+ // @ts-expect-error: createSession is defined+ await nextAuthAdapter.createSession(data);+ const updatedExpires = new Date();+ expect(nextAuthAdapter).toBeDefined();+ expect(nextAuthAdapter.updateSession).toBeDefined();+ // @ts-expect-error: updateSession is defined+ const updatedSession = await nextAuthAdapter.updateSession({+ sessionToken,+ expires: updatedExpires,+ });+ expect(updatedSession).toBeDefined();+ expect(updatedSession?.sessionToken).toBe(data.sessionToken);+ expect(updatedSession?.expires).toEqual(updatedExpires);+ });+ });++ describe('getSessionAndUser', () => {+ it('should get a session and user', async () => {+ // create session+ const data = {+ sessionToken,+ userId: userId,+ expires: new Date(),+ };+ // @ts-expect-error: createSession is defined+ await nextAuthAdapter.createSession(data);++ // @ts-expect-error: getSessionAndUser is defined+ const sessionAndUser = await nextAuthAdapter.getSessionAndUser(sessionToken);+ expect(sessionAndUser?.session.sessionToken).toBe(sessionToken);+ expect(sessionAndUser?.user.id).toBe(user.id);+ });+ });++ describe('deleteSession', () => {+ it('should delete a session', async () => {+ const data = {+ sessionToken,+ userId: userId,+ expires: new Date(),+ };+ // @ts-expect-error: createSession is defined+ await nextAuthAdapter.createSession(data);++ // @ts-expect-error: deleteSession is defined+ await nextAuthAdapter.deleteSession(sessionToken);+ const session = await serverDB.query.nextauthSessions.findFirst({+ where: eq(nextauthSessions.sessionToken, sessionToken),+ });+ expect(session).toBeUndefined();+ });+ });+ });++ describe('verificationToken', () => {+ describe('createVerificationToken', () => {+ it('should create a new verification token', async () => {+ const token: VerificationToken = {+ identifier: 'identifier',+ expires: new Date(),+ token: 'token',+ };+ // @ts-expect-error: createVerificationToken is defined+ const createdToken = await nextAuthAdapter.createVerificationToken(token);+ expect(createdToken).toBeDefined();+ expect(createdToken?.identifier).toBe(token.identifier);+ expect(createdToken?.expires).toEqual(token.expires);+ expect(createdToken?.token).toBe(token.token);+ });+ });++ describe('useVerificationToken', () => {+ it('should use a verification token if exist', async () => {+ const token: VerificationToken = {+ identifier: 'identifier',+ expires: new Date(),+ token: 'token2',+ };+ // @ts-expect-error: createVerificationToken is defined+ await nextAuthAdapter.createVerificationToken(token);+ // @ts-expect-error: useVerificationToken is defined+ await nextAuthAdapter.useVerificationToken(token.token);+ });++ it('should return null if the token does not exist', async () => {+ const token: VerificationToken = {+ identifier: 'identifier',+ expires: new Date(),+ token: 'token-not-exist',+ };+ // @ts-expect-error: useVerificationToken is defined+ const result = await nextAuthAdapter.useVerificationToken(token.token);+ expect(result).toBeNull();+ });+ });+ });++ describe('accounts', () => {+ describe('linkAccount', () => {+ it('should link an account', async () => {+ const account: AdapterAccount = {+ providerAccountId: 'provider-account-id',+ userId: userId,+ provider: 'auth0',+ type: 'email',+ };+ // @ts-expect-error: linkAccount is defined+ const insertedAccount = await nextAuthAdapter.linkAccount(account);+ expect(insertedAccount).toBeDefined();+ expect(insertedAccount?.providerAccountId).toBe(account.providerAccountId);+ expect(insertedAccount?.userId).toBe(userId);+ expect(insertedAccount?.provider).toBe(account.provider);+ expect(insertedAccount?.type).toBe(account.type);+ });+ });++ describe('getAccount', () => {+ it('should get an account', async () => {+ const account: AdapterAccount = {+ providerAccountId: 'provider-account-id',+ userId: userId,+ provider: 'auth0',+ type: 'email',+ };+ // @ts-expect-error: linkAccount is defined+ await nextAuthAdapter.linkAccount(account);+ // @ts-expect-error: getAccount is defined+ const fetchedAccount = await nextAuthAdapter.getAccount(+ account.providerAccountId,+ account.provider,+ );+ expect(fetchedAccount).toBeDefined();+ expect(fetchedAccount?.providerAccountId).toBe(account.providerAccountId);+ expect(fetchedAccount?.userId).toBe(userId);+ expect(fetchedAccount?.provider).toBe(account.provider);+ expect(fetchedAccount?.type).toBe(account.type);+ });+ });++ describe('unlinkAccount', () => {+ it('should unlink an account', async () => {+ const account: AdapterAccount = {+ providerAccountId: 'provider-account-id',+ userId: userId,+ provider: 'auth0',+ type: 'email',+ };+ // @ts-expect-error: linkAccount is defined+ await nextAuthAdapter.linkAccount(account);+ // @ts-expect-error: unlinkAccount is defined+ await nextAuthAdapter.unlinkAccount(account);+ const fetchedAccount = await serverDB.query.nextauthAccounts.findFirst({+ where: eq(nextauthAccounts.providerAccountId, account.providerAccountId),+ });+ expect(fetchedAccount).toBeUndefined();+ });+ });+ });+});diff --git a/packages/utils/src/server/__tests__/auth.test.ts b/packages/utils/src/server/__tests__/auth.test.tsindex b819f91a716..80241f9fda0 100644--- a/packages/utils/src/server/__tests__/auth.test.ts+++ b/packages/utils/src/server/__tests__/auth.test.ts@@ -28,7 +28,7 @@ vi.mock('@/libs/clerk-auth', () => ({},}));-vi.mock('@/libs/next-auth', () => ({+vi.mock('@/libs/next-auth/edge', () => ({default: {auth: vi.fn().mockResolvedValue({user: {diff --git a/packages/utils/src/server/auth.ts b/packages/utils/src/server/auth.tsindex 1f8981df8fa..6b629b9170a 100644--- a/packages/utils/src/server/auth.ts+++ b/packages/utils/src/server/auth.ts@@ -12,9 +12,9 @@ export const getUserAuth = async () => {}if (enableNextAuth) {- const { default: NextAuth } = await import('@/libs/next-auth');+ const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');- const session = await NextAuth.auth();+ const session = await NextAuthEdge.auth();const userId = session?.user.id;diff --git a/src/app/(backend)/api/auth/adapter/route.ts b/src/app/(backend)/api/auth/adapter/route.tsdeleted file mode 100644index 15a5e09bdbf..00000000000--- a/src/app/(backend)/api/auth/adapter/route.ts+++ /dev/null@@ -1,137 +0,0 @@-import debug from 'debug';-import { NextRequest, NextResponse } from 'next/server';--import { serverDBEnv } from '@/config/db';-import { serverDB } from '@/database/server';-import { dateKeys } from '@/libs/next-auth/adapter';-import { NextAuthUserService } from '@/server/services/nextAuthUser';--const log = debug('lobe-next-auth:api:auth:adapter');--/**- * @description Process the db query for the NextAuth adapter.- * Returns the db query result directly and let NextAuth handle the raw results.- * @returns {- * success: boolean; // Only return false if the database query fails or the action is invalid.- * data?: any;- * error?: string;- * }- */-export async function POST(req: NextRequest) {- try {- // try validate the request- if (- !req.headers.get('Authorization') ||- req.headers.get('Authorization')?.trim() !== `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`- ) {- log('Unauthorized request, missing or invalid Authorization header');- return NextResponse.json({ error: 'Unauthorized', success: false }, { status: 401 });- }-- // Parse the request body- const data = await req.json();- log('Received request data:', data);- // Preprocess- if (data?.data) {- for (const key of dateKeys) {- if (data?.data && data.data[key]) {- data.data[key] = new Date(data.data[key]);- continue;- }- }- }- const service = new NextAuthUserService(serverDB);- let result;- switch (data.action) {- case 'createAuthenticator': {- result = await service.createAuthenticator(data.data);- break;- }- case 'createSession': {- result = await service.createSession(data.data);- break;- }- case 'createUser': {- result = await service.createUser(data.data);- break;- }- case 'createVerificationToken': {- result = await service.createVerificationToken(data.data);- break;- }- case 'deleteSession': {- result = await service.deleteSession(data.data);- break;- }- case 'deleteUser': {- result = await service.deleteUser(data.data);- break;- }- case 'getAccount': {- result = await service.getAccount(data.data.providerAccountId, data.data.provider);- break;- }- case 'getAuthenticator': {- result = await service.getAuthenticator(data.data);- break;- }- case 'getSessionAndUser': {- result = await service.getSessionAndUser(data.data);- break;- }- case 'getUser': {- result = await service.getUser(data.data);- break;- }- case 'getUserByAccount': {- result = await service.getUserByAccount(data.data);- break;- }- case 'getUserByEmail': {- result = await service.getUserByEmail(data.data);- break;- }- case 'linkAccount': {- result = await service.linkAccount(data.data);- break;- }- case 'listAuthenticatorsByUserId': {- result = await service.listAuthenticatorsByUserId(data.data);- break;- }- case 'unlinkAccount': {- result = await service.unlinkAccount(data.data);- break;- }- case 'updateAuthenticatorCounter': {- result = await service.updateAuthenticatorCounter(- data.data.credentialID,- data.data.counter,- );- break;- }- case 'updateSession': {- result = await service.updateSession(data.data);- break;- }- case 'updateUser': {- result = await service.updateUser(data.data);- break;- }- case 'useVerificationToken': {- result = await service.useVerificationToken(data.data);- break;- }- default: {- return NextResponse.json({ error: 'Invalid action', success: false }, { status: 400 });- }- }- return NextResponse.json({ data: result, success: true });- } catch (error) {- log('Error processing request:');- log(error);- return NextResponse.json({ error, success: false }, { status: 400 });- }-}--export const runtime = 'nodejs';diff --git a/src/app/(backend)/api/webhooks/logto/route.ts b/src/app/(backend)/api/webhooks/logto/route.tsindex e5cd6feb237..39bddd15ed1 100644--- a/src/app/(backend)/api/webhooks/logto/route.ts+++ b/src/app/(backend)/api/webhooks/logto/route.ts@@ -36,15 +36,6 @@ export const POST = async (req: Request): Promise<NextResponse> => {},);}- case 'User.SuspensionStatus.Updated': {- if (data.isSuspended) {- return nextAuthUserService.safeSignOutUser({- provider: 'logto',- providerAccountId: data.id,- });- }- return NextResponse.json({ message: 'user reactivated', success: true }, { status: 200 });- }default: {pino.warn(diff --git a/src/config/auth.ts b/src/config/auth.tsindex d3529013ffe..adee4abfb04 100644--- a/src/config/auth.ts+++ b/src/config/auth.ts@@ -18,8 +18,6 @@ declare global {NEXT_AUTH_DEBUG?: string;- NEXT_AUTH_SSO_SESSION_STRATEGY?: string;-AUTH0_CLIENT_ID?: string;AUTH0_CLIENT_SECRET?: string;AUTH0_ISSUER?: string;@@ -161,7 +159,6 @@ export const getAuthConfig = () => {NEXT_AUTH_SECRET: z.string().optional(),NEXT_AUTH_SSO_PROVIDERS: z.string().optional().default('auth0'),NEXT_AUTH_DEBUG: z.boolean().optional().default(false),- NEXT_AUTH_SSO_SESSION_STRATEGY: z.enum(['jwt', 'database']).optional().default('jwt'),// Auth0AUTH0_CLIENT_ID: z.string().optional(),@@ -224,7 +221,6 @@ export const getAuthConfig = () => {NEXT_AUTH_SSO_PROVIDERS: process.env.NEXT_AUTH_SSO_PROVIDERS,NEXT_AUTH_SECRET: process.env.NEXT_AUTH_SECRET,NEXT_AUTH_DEBUG: !!process.env.NEXT_AUTH_DEBUG,- NEXT_AUTH_SSO_SESSION_STRATEGY: process.env.NEXT_AUTH_SSO_SESSION_STRATEGY || 'jwt',// Auth0AUTH0_CLIENT_ID: process.env.AUTH0_CLIENT_ID,diff --git a/src/libs/next-auth/adapter/index.ts b/src/libs/next-auth/adapter/index.tsindex df91c3a4739..0c5dd6bab20 100644--- a/src/libs/next-auth/adapter/index.ts+++ b/src/libs/next-auth/adapter/index.ts@@ -4,175 +4,273 @@ import type {AdapterUser,VerificationToken,} from '@auth/core/adapters';-import debug from 'debug';+import { and, eq } from 'drizzle-orm';+import type { NeonDatabase } from 'drizzle-orm/neon-serverless';import { Adapter, AdapterAccount } from 'next-auth/adapters';-import urlJoin from 'url-join';-import { serverDBEnv } from '@/config/db';-import { appEnv } from '@/envs/app';+import { UserModel } from '@/database/models/user';+import * as schema from '@/database/schemas';+import { AgentService } from '@/server/services/agent';+import { merge } from '@/utils/merge';-const log = debug('lobe-next-auth:adapter');+import {+ mapAdapterUserToLobeUser,+ mapAuthenticatorQueryResutlToAdapterAuthenticator,+ mapLobeUserToAdapterUser,+ partialMapAdapterUserToLobeUser,+} from './utils';-interface BackendAdapterResponse {- data?: any;- error?: string;- success: boolean;-}--// Due to use direct HTTP Post, the date string cannot parse automatically-export const dateKeys = ['expires', 'emailVerified'];+const {+ nextauthAccounts,+ nextauthAuthenticators,+ nextauthSessions,+ nextauthVerificationTokens,+ users,+} = schema;/*** @description LobeNextAuthDbAdapter is implemented to handle the database operations* for NextAuth, this function do the same things as `src/app/api/webhooks/clerk/route.ts`* @returns {Adapter}*/-export function LobeNextAuthDbAdapter(): Adapter {- const baseUrl = appEnv.APP_URL;-- // Ensure the baseUrl is set, otherwise throw an error- if (!baseUrl) {- throw new Error('LobeNextAuthDbAdapter: APP_URL is not set in environment variables');- }- const interactionUrl = urlJoin(baseUrl, '/api/auth/adapter');- log(`LobeNextAuthDbAdapter initialized with url: ${interactionUrl}`);-- // Ensure serverDBEnv.KEY_VAULTS_SECRET is set, otherwise throw an error- if (!serverDBEnv.KEY_VAULTS_SECRET) {- throw new Error('LobeNextAuthDbAdapter: KEY_VAULTS_SECRET is not set in environment variables');- }-- const fetcher = (action: string, data: any) =>- fetch(interactionUrl, {- body: JSON.stringify({ action, data }),- headers: {- 'Authorization': `Bearer ${serverDBEnv.KEY_VAULTS_SECRET}`,- 'Content-Type': 'application/json',- },- method: 'POST',- });- const postProcessor = async (res: Response) => {- const data = (await res.json()) as BackendAdapterResponse;- log('LobeNextAuthDbAdapter: postProcessor called with data:', data);- if (!data.success) {- log('LobeNextAuthDbAdapter: Error in postProcessor:');- log(data);- throw new Error(`LobeNextAuthDbAdapter: ${data.error}`);- }- if (data?.data) {- for (const key of dateKeys) {- if (data.data[key]) {- data.data[key] = new Date(data.data[key]);- continue;- }- }- }- return data.data;- };-+export function LobeNextAuthDbAdapter(serverDB: NeonDatabase<typeof schema>): Adapter {return {async createAuthenticator(authenticator): Promise<AdapterAuthenticator> {- const data = await fetcher('createAuthenticator', authenticator);- return await postProcessor(data);+ const result = await serverDB+ .insert(nextauthAuthenticators)+ .values(authenticator)+ .returning()+ .then((res) => res[0] ?? undefined);+ if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to create authenticator');+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);},- async createSession(session): Promise<AdapterSession> {- const data = await fetcher('createSession', session);- return await postProcessor(data);+ async createSession(data): Promise<AdapterSession> {+ return serverDB+ .insert(nextauthSessions)+ .values(data)+ .returning()+ .then((res) => res[0]);},async createUser(user): Promise<AdapterUser> {- const data = await fetcher('createUser', user);- return await postProcessor(data);+ const { id, name, email, emailVerified, image, providerAccountId } = user;+ // return the user if it already exists+ let existingUser =+ email && typeof email === 'string' && email.trim()+ ? await UserModel.findByEmail(serverDB, email)+ : undefined;+ // If the user is not found by email, try to find by providerAccountId+ if (!existingUser && providerAccountId) {+ existingUser = await UserModel.findById(serverDB, providerAccountId);+ }+ if (existingUser) {+ const adapterUser = mapLobeUserToAdapterUser(existingUser);+ return adapterUser;+ }++ // create a new user if it does not exist+ // Use id from provider if it exists, otherwise use id assigned by next-auth+ // ref: https://github.com/lobehub/lobe-chat/pull/2935+ const uid = providerAccountId ?? id;+ await UserModel.createUser(+ serverDB,+ mapAdapterUserToLobeUser({+ email,+ emailVerified,+ // Use providerAccountId as userid to identify if the user exists in a SSO provider+ id: uid,+ image,+ name,+ }),+ );++ // 3. Create an inbox session for the user+ const agentService = new AgentService(serverDB, uid);+ await agentService.createInbox();++ return { ...user, id: uid };},async createVerificationToken(data): Promise<VerificationToken | null | undefined> {- const result = await fetcher('createVerificationToken', data);- return await postProcessor(result);+ return serverDB+ .insert(nextauthVerificationTokens)+ .values(data)+ .returning()+ .then((res) => res[0]);},async deleteSession(sessionToken): Promise<AdapterSession | null | undefined> {- const result = await fetcher('deleteSession', sessionToken);- await postProcessor(result);+ await serverDB+ .delete(nextauthSessions)+ .where(eq(nextauthSessions.sessionToken, sessionToken));return;},async deleteUser(id): Promise<AdapterUser | null | undefined> {- const result = await fetcher('deleteUser', id);- await postProcessor(result);+ const user = await UserModel.findById(serverDB, id);+ if (!user) throw new Error('NextAuth: Delete User not found');++ await UserModel.deleteUser(serverDB, id);return;},async getAccount(providerAccountId, provider): Promise<AdapterAccount | null> {- const data = await fetcher('getAccount', {- provider,- providerAccountId,- });- return await postProcessor(data);+ return serverDB+ .select()+ .from(nextauthAccounts)+ .where(+ and(+ eq(nextauthAccounts.provider, provider),+ eq(nextauthAccounts.providerAccountId, providerAccountId),+ ),+ )+ .then((res) => res[0] ?? null) as Promise<AdapterAccount | null>;},async getAuthenticator(credentialID): Promise<AdapterAuthenticator | null> {- const result = await fetcher('getAuthenticator', credentialID);- return await postProcessor(result);+ const result = await serverDB+ .select()+ .from(nextauthAuthenticators)+ .where(eq(nextauthAuthenticators.credentialID, credentialID))+ .then((res) => res[0] ?? null);+ if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to get authenticator');+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);},async getSessionAndUser(sessionToken): Promise<{session: AdapterSession;user: AdapterUser;} | null> {- const result = await fetcher('getSessionAndUser', sessionToken);- return await postProcessor(result);+ const result = await serverDB+ .select({+ session: nextauthSessions,+ user: users,+ })+ .from(nextauthSessions)+ .where(eq(nextauthSessions.sessionToken, sessionToken))+ .innerJoin(users, eq(users.id, nextauthSessions.userId))+ .then((res) => (res.length > 0 ? res[0] : null));++ if (!result) return null;+ const adapterUser = mapLobeUserToAdapterUser(result.user);+ if (!adapterUser) return null;+ return {+ session: result.session,+ user: adapterUser,+ };},async getUser(id): Promise<AdapterUser | null> {- log('getUser called with id:', id);- const result = await fetcher('getUser', id);- return await postProcessor(result);+ const lobeUser = await UserModel.findById(serverDB, id);+ if (!lobeUser) return null;+ return mapLobeUserToAdapterUser(lobeUser);},async getUserByAccount(account): Promise<AdapterUser | null> {- const data = await fetcher('getUserByAccount', account);- return await postProcessor(data);+ const result = await serverDB+ .select({+ account: nextauthAccounts,+ users,+ })+ .from(nextauthAccounts)+ .innerJoin(users, eq(nextauthAccounts.userId, users.id))+ .where(+ and(+ eq(nextauthAccounts.provider, account.provider),+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),+ ),+ )+ .then((res) => res[0]);++ return result?.users ? mapLobeUserToAdapterUser(result.users) : null;},async getUserByEmail(email): Promise<AdapterUser | null> {- const data = await fetcher('getUserByEmail', email);- return await postProcessor(data);+ const lobeUser =+ email && typeof email === 'string' && email.trim()+ ? await UserModel.findByEmail(serverDB, email)+ : undefined;+ return lobeUser ? mapLobeUserToAdapterUser(lobeUser) : null;},async linkAccount(data): Promise<AdapterAccount | null | undefined> {- const result = await fetcher('linkAccount', data);- return await postProcessor(result);+ const [account] = await serverDB+ .insert(nextauthAccounts)+ .values(data as any)+ .returning();+ if (!account) throw new Error('NextAuthAccountModel: Failed to create account');+ // TODO Update type annotation+ return account as any;},async listAuthenticatorsByUserId(userId): Promise<AdapterAuthenticator[]> {- const result = await fetcher('listAuthenticatorsByUserId', userId);- return await postProcessor(result);+ const result = await serverDB+ .select()+ .from(nextauthAuthenticators)+ .where(eq(nextauthAuthenticators.userId, userId))+ .then((res) => res);+ if (result.length === 0)+ throw new Error('LobeNextAuthDbAdapter: Failed to get authenticator list');+ return result.map((r) => mapAuthenticatorQueryResutlToAdapterAuthenticator(r));},// @ts-ignore: The return type is {Promise<void> | Awaitable<AdapterAccount | undefined>}async unlinkAccount(account): Promise<void | AdapterAccount | undefined> {- const result = await fetcher('unlinkAccount', account);- await postProcessor(result);- return;+ await serverDB+ .delete(nextauthAccounts)+ .where(+ and(+ eq(nextauthAccounts.provider, account.provider),+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),+ ),+ );},async updateAuthenticatorCounter(credentialID, counter): Promise<AdapterAuthenticator> {- const result = await fetcher('updateAuthenticatorCounter', {- counter,- credentialID,- });- return await postProcessor(result);+ const result = await serverDB+ .update(nextauthAuthenticators)+ .set({ counter })+ .where(eq(nextauthAuthenticators.credentialID, credentialID))+ .returning()+ .then((res) => res[0]);+ if (!result) throw new Error('LobeNextAuthDbAdapter: Failed to update authenticator counter');+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);},async updateSession(data): Promise<AdapterSession | null | undefined> {- const result = await fetcher('updateSession', data);- return await postProcessor(result);+ const res = await serverDB+ .update(nextauthSessions)+ .set(data)+ .where(eq(nextauthSessions.sessionToken, data.sessionToken))+ .returning();+ return res[0];},async updateUser(user): Promise<AdapterUser> {- const result = await fetcher('updateUser', user);- return await postProcessor(result);+ const lobeUser = await UserModel.findById(serverDB, user?.id);+ if (!lobeUser) throw new Error('NextAuth: User not found');+ const userModel = new UserModel(serverDB, user.id);++ const updatedUser = await userModel.updateUser({+ ...partialMapAdapterUserToLobeUser(user),+ });+ if (!updatedUser) throw new Error('NextAuth: Failed to update user');++ // merge new user data with old user data+ const newAdapterUser = mapLobeUserToAdapterUser(lobeUser);+ if (!newAdapterUser) {+ throw new Error('NextAuth: Failed to map user data to adapter user');+ }+ return merge(newAdapterUser, user);},async useVerificationToken(identifier_token): Promise<VerificationToken | null> {- const result = await fetcher('useVerificationToken', identifier_token);- return await postProcessor(result);+ return serverDB+ .delete(nextauthVerificationTokens)+ .where(+ and(+ eq(nextauthVerificationTokens.identifier, identifier_token.identifier),+ eq(nextauthVerificationTokens.token, identifier_token.token),+ ),+ )+ .returning()+ .then((res) => (res.length > 0 ? res[0] : null));},};}diff --git a/src/server/services/nextAuthUser/utils.ts b/src/libs/next-auth/adapter/utils.tssimilarity index 100%rename from src/server/services/nextAuthUser/utils.tsrename to src/libs/next-auth/adapter/utils.tsdiff --git a/src/libs/next-auth/auth.config.ts b/src/libs/next-auth/auth.config.tsindex 295d98519bc..6ba7bacf7a3 100644--- a/src/libs/next-auth/auth.config.ts+++ b/src/libs/next-auth/auth.config.ts@@ -1,32 +1,23 @@import type { NextAuthConfig } from 'next-auth';-import { ssoProviders } from './sso-providers';-import { LobeNextAuthDbAdapter } from './adapter';-import { getAuthConfig } from '@/config/auth';+import { authEnv } from '@/config/auth';-const {- NEXT_AUTH_DEBUG,- NEXT_AUTH_SECRET,- NEXT_AUTH_SSO_SESSION_STRATEGY,- NEXT_AUTH_SSO_PROVIDERS,- NEXT_PUBLIC_ENABLE_NEXT_AUTH-} = getAuthConfig();+import { ssoProviders } from './sso-providers';export const initSSOProviders = () => {- return NEXT_PUBLIC_ENABLE_NEXT_AUTH- ? NEXT_AUTH_SSO_PROVIDERS.split(/[,,]/).map((provider) => {- const validProvider = ssoProviders.find((item) => item.id === provider.trim());+ return authEnv.NEXT_PUBLIC_ENABLE_NEXT_AUTH+ ? authEnv.NEXT_AUTH_SSO_PROVIDERS.split(/[,,]/).map((provider) => {+ const validProvider = ssoProviders.find((item) => item.id === provider.trim());- if (validProvider) return validProvider.provider;+ if (validProvider) return validProvider.provider;- throw new Error(`[NextAuth] provider ${provider} is not supported`);- })+ throw new Error(`[NextAuth] provider ${provider} is not supported`);+ }): [];};// Notice this is only an object, not a full Auth.js instanceexport default {- adapter: LobeNextAuthDbAdapter(),callbacks: {// Note: Data processing order of callback: authorize --> jwt --> sessionasync jwt({ token, user }) {@@ -48,15 +39,12 @@ export default {return session;},},- debug: NEXT_AUTH_DEBUG,+ debug: authEnv.NEXT_AUTH_DEBUG,pages: {error: '/next-auth/error',signIn: '/next-auth/signin',},providers: initSSOProviders(),- secret: NEXT_AUTH_SECRET,- session: {- strategy: NEXT_AUTH_SSO_SESSION_STRATEGY,- },+ secret: authEnv.NEXT_AUTH_SECRET,trustHost: process.env?.AUTH_TRUST_HOST ? process.env.AUTH_TRUST_HOST === 'true' : true,} satisfies NextAuthConfig;diff --git a/src/libs/next-auth/edge.ts b/src/libs/next-auth/edge.tsnew file mode 100644index 00000000000..4f20532d974--- /dev/null+++ b/src/libs/next-auth/edge.ts@@ -0,0 +1,26 @@+import NextAuth from 'next-auth';++import authConfig from './auth.config';++/**+ * NextAuth initialization without Database adapter+ *+ * @example+ * ```ts+ * import NextAuthEdge from '@/libs/next-auth/edge';+ * const { auth } = NextAuthEdge;+ * ```+ *+ * @note+ * We currently use `jwt` strategy for session management.+ * So you don't need to import `signIn` or `signOut` from+ * this module, just import from `next-auth` directly.+ *+ * Inside react component+ * @example+ * ```ts+ * import { signOut } from 'next-auth/react';+ * signOut();+ * ```+ */+export default NextAuth(authConfig);diff --git a/src/libs/next-auth/index.ts b/src/libs/next-auth/index.tsindex 70c2490c1fb..807eb61af22 100644--- a/src/libs/next-auth/index.ts+++ b/src/libs/next-auth/index.ts@@ -1,20 +1,33 @@import NextAuth from 'next-auth';-import authConfig from './auth.config';+import { getServerDBConfig } from '@/config/db';+import { serverDB } from '@/database/server';++import { LobeNextAuthDbAdapter } from './adapter';+import config from './auth.config';++const { NEXT_PUBLIC_ENABLED_SERVER_SERVICE } = getServerDBConfig();/**- * NextAuth initialization without Database adapter- *- * @note- * We currently use `jwt` strategy for session management.- * So you don't need to import `signIn` or `signOut` from- * this module, just import from `next-auth` directly.+ * NextAuth initialization with Database adapter*- * Inside react component* @example* ```ts- * import { signOut } from 'next-auth/react';- * signOut();+ * import NextAuthNode from '@/libs/next-auth';+ * const { handlers } = NextAuthNode;* ```+ *+ * @note+ * If you meet the edge runtime compatible problem,+ * you can import from `@/libs/next-auth/edge` which is not initial with the database adapter.+ *+ * The difference and usage of the two different NextAuth modules is can be+ * ref to: https://github.com/lobehub/lobe-chat/pull/2935*/-export default NextAuth(authConfig);+export default NextAuth({+ ...config,+ adapter: NEXT_PUBLIC_ENABLED_SERVER_SERVICE ? LobeNextAuthDbAdapter(serverDB) : undefined,+ session: {+ strategy: 'jwt',+ },+});diff --git a/src/libs/trpc/edge/context.ts b/src/libs/trpc/edge/context.tsindex af7570d39b7..8de438e6d5a 100644--- a/src/libs/trpc/edge/context.ts+++ b/src/libs/trpc/edge/context.ts@@ -54,9 +54,9 @@ export const createEdgeContext = async (request: NextRequest): Promise<EdgeConteif (enableNextAuth) {try {- const { default: NextAuth } = await import('@/libs/next-auth');+ const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');- const session = await NextAuth.auth();+ const session = await NextAuthEdge.auth();if (session && session?.user?.id) {auth = session.user;userId = session.user.id;diff --git a/src/libs/trpc/lambda/context.ts b/src/libs/trpc/lambda/context.tsindex 4b17d7b215f..77c7e3ce871 100644--- a/src/libs/trpc/lambda/context.ts+++ b/src/libs/trpc/lambda/context.ts@@ -161,9 +161,9 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCif (enableNextAuth) {log('Attempting NextAuth authentication');try {- const { default: NextAuth } = await import('@/libs/next-auth');+ const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');- const session = await NextAuth.auth();+ const session = await NextAuthEdge.auth();if (session && session?.user?.id) {auth = session.user;userId = session.user.id;diff --git a/src/middleware.ts b/src/middleware.tsindex aafd4a5c396..854f058da99 100644--- a/src/middleware.ts+++ b/src/middleware.ts@@ -10,7 +10,7 @@ import { OAUTH_AUTHORIZED } from '@/const/auth';import { LOBE_LOCALE_COOKIE } from '@/const/locale';import { LOBE_THEME_APPEARANCE } from '@/const/theme';import { appEnv } from '@/envs/app';-import NextAuth from '@/libs/next-auth';+import NextAuthEdge from '@/libs/next-auth/edge';import { Locales } from '@/locales/resources';import { oidcEnv } from './envs/oidc';@@ -170,7 +170,7 @@ const isProtectedRoute = createRouteMatcher([]);// Initialize an Edge compatible NextAuth middleware-const nextAuthMiddleware = NextAuth.auth((req) => {+const nextAuthMiddleware = NextAuthEdge.auth(async (req) => {logNextAuth('NextAuth middleware processing request: %s %s', req.method, req.url);const response = defaultMiddleware(req);diff --git a/src/server/routers/lambda/user.test.ts b/src/server/routers/lambda/user.test.tsindex 360bcc5d080..1466dd5304e 100644--- a/src/server/routers/lambda/user.test.ts+++ b/src/server/routers/lambda/user.test.ts@@ -6,8 +6,8 @@ import { MessageModel } from '@/database/models/message';import { SessionModel } from '@/database/models/session';import { UserModel, UserNotFoundError } from '@/database/models/user';import { serverDB } from '@/database/server';+import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { NextAuthUserService } from '@/server/services/nextAuthUser';import { UserService } from '@/server/services/user';import { userRouter } from './user';@@ -24,10 +24,10 @@ vi.mock('@/database/server', () => ({vi.mock('@/database/models/message');vi.mock('@/database/models/session');vi.mock('@/database/models/user');+vi.mock('@/libs/next-auth/adapter');vi.mock('@/server/modules/KeyVaultsEncrypt');vi.mock('@/server/modules/S3');vi.mock('@/server/services/user');-vi.mock('@/server/services/nextAuthUser');vi.mock('@/const/auth', () => ({enableClerk: true,}));@@ -221,7 +221,7 @@ describe('userRouter', () => {type: 'oauth',};- vi.mocked(NextAuthUserService).mockReturnValue({+ vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({getAccount: vi.fn().mockResolvedValue(mockAccount),unlinkAccount: vi.fn().mockResolvedValue(undefined),} as any);@@ -237,7 +237,7 @@ describe('userRouter', () => {providerAccountId: '123',};- vi.mocked(NextAuthUserService).mockReturnValue({+ vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({getAccount: vi.fn().mockResolvedValue(null),unlinkAccount: vi.fn(),} as any);@@ -246,6 +246,19 @@ describe('userRouter', () => {userRouter.createCaller({ ...mockCtx }).unlinkSSOProvider(mockInput),).rejects.toThrow('The account does not exist');});++ it('should throw error if adapter methods are not implemented', async () => {+ const mockInput = {+ provider: 'google',+ providerAccountId: '123',+ };++ vi.mocked(LobeNextAuthDbAdapter).mockReturnValue({} as any);++ await expect(+ userRouter.createCaller({ ...mockCtx }).unlinkSSOProvider(mockInput),+ ).rejects.toThrow('The method in LobeNextAuthDbAdapter `unlinkAccount` is not implemented');+ });});describe('updateSettings', () => {diff --git a/src/server/routers/lambda/user.ts b/src/server/routers/lambda/user.tsindex be7217677a9..86aff358cf8 100644--- a/src/server/routers/lambda/user.ts+++ b/src/server/routers/lambda/user.ts@@ -9,12 +9,12 @@ import { SessionModel } from '@/database/models/session';import { UserModel, UserNotFoundError } from '@/database/models/user';import { ClerkAuth } from '@/libs/clerk-auth';import { pino } from '@/libs/logger';+import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { S3 } from '@/server/modules/S3';import { FileService } from '@/server/services/file';-import { NextAuthUserService } from '@/server/services/nextAuthUser';import { UserService } from '@/server/services/user';import {NextAuthAccountSchame,@@ -29,7 +29,7 @@ const userProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, nextctx: {clerkAuth: new ClerkAuth(),fileService: new FileService(ctx.serverDB, ctx.userId),- nextAuthUserService: new NextAuthUserService(ctx.serverDB),+ nextAuthDbAdapter: LobeNextAuthDbAdapter(ctx.serverDB),userModel: new UserModel(ctx.serverDB, ctx.userId),},});@@ -134,10 +134,19 @@ export const userRouter = router({unlinkSSOProvider: userProcedure.input(NextAuthAccountSchame).mutation(async ({ ctx, input }) => {const { provider, providerAccountId } = input;- const account = await ctx.nextAuthUserService.getAccount(providerAccountId, provider);- // The userId can either get from ctx.nextAuth?.id or ctx.userId- if (!account || account.userId !== ctx.userId) throw new Error('The account does not exist');- await ctx.nextAuthUserService.unlinkAccount({ provider, providerAccountId });+ if (+ ctx.nextAuthDbAdapter?.unlinkAccount &&+ typeof ctx.nextAuthDbAdapter.unlinkAccount === 'function' &&+ ctx.nextAuthDbAdapter?.getAccount &&+ typeof ctx.nextAuthDbAdapter.getAccount === 'function'+ ) {+ const account = await ctx.nextAuthDbAdapter.getAccount(providerAccountId, provider);+ // The userId can either get from ctx.nextAuth?.id or ctx.userId+ if (!account || account.userId !== ctx.userId) throw new Error('The account does not exist');+ await ctx.nextAuthDbAdapter.unlinkAccount({ provider, providerAccountId });+ } else {+ throw new Error('The method in LobeNextAuthDbAdapter `unlinkAccount` is not implemented');+ }}),// 服务端上传头像diff --git a/src/server/services/nextAuthUser/index.test.ts b/src/server/services/nextAuthUser/index.test.tsnew file mode 100644index 00000000000..cab84d527bb--- /dev/null+++ b/src/server/services/nextAuthUser/index.test.ts@@ -0,0 +1,108 @@+// @vitest-environment node+import { NextResponse } from 'next/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { UserModel } from '@/database/models/user';+import { UserItem } from '@/database/schemas';+import { serverDB } from '@/database/server';+import { pino } from '@/libs/logger';++import { NextAuthUserService } from './index';++vi.mock('@/libs/logger', () => ({+ pino: {+ info: vi.fn(),+ warn: vi.fn(),+ },+}));++vi.mock('@/database/models/user');+vi.mock('@/database/server');++describe('NextAuthUserService', () => {+ let service: NextAuthUserService;++ beforeEach(async () => {+ vi.clearAllMocks();+ service = new NextAuthUserService(serverDB);+ });++ describe('safeUpdateUser', () => {+ const mockUser = {+ id: 'user-123',+ email: '[email protected]',+ };++ const mockAccount = {+ provider: 'github',+ providerAccountId: '12345',+ };++ const mockUpdateData: Partial<UserItem> = {+ avatar: 'https://example.com/avatar.jpg',+ email: '[email protected]',+ fullName: 'Test User',+ };++ it('should update user when user is found', async () => {+ const mockUserModel = {+ updateUser: vi.fn().mockResolvedValue({}),+ };++ vi.mocked(UserModel).mockImplementation(() => mockUserModel as any);++ // Mock the adapter directly on the service instance+ service.adapter = {+ getUserByAccount: vi.fn().mockResolvedValue(mockUser),+ };++ const response = await service.safeUpdateUser(mockAccount, mockUpdateData);++ expect(pino.info).toHaveBeenCalledWith(+ `updating user "${JSON.stringify(mockAccount)}" due to webhook`,+ );++ expect(service.adapter.getUserByAccount).toHaveBeenCalledWith(mockAccount);+ expect(UserModel).toHaveBeenCalledWith(serverDB, mockUser.id);+ expect(mockUserModel.updateUser).toHaveBeenCalledWith(mockUpdateData);++ expect(response).toBeInstanceOf(NextResponse);+ expect(response.status).toBe(200);+ const data = await response.json();+ expect(data).toEqual({ message: 'user updated', success: true });+ });++ it('should handle case when user is not found', async () => {+ // Mock the adapter directly on the service instance+ service.adapter = {+ getUserByAccount: vi.fn().mockResolvedValue(null),+ };++ const response = await service.safeUpdateUser(mockAccount, mockUpdateData);++ expect(pino.warn).toHaveBeenCalledWith(+ `[${mockAccount.provider}]: Webhooks handler user "${JSON.stringify(mockAccount)}" update for "${JSON.stringify(mockUpdateData)}", but no user was found by the providerAccountId.`,+ );++ expect(UserModel).not.toHaveBeenCalled();++ expect(response).toBeInstanceOf(NextResponse);+ expect(response.status).toBe(200);+ const data = await response.json();+ expect(data).toEqual({ message: 'user updated', success: true });+ });++ it('should handle errors during user update', async () => {+ const mockError = new Error('Database error');++ // Mock the adapter directly on the service instance+ service.adapter = {+ getUserByAccount: vi.fn().mockRejectedValue(mockError),+ };++ await expect(service.safeUpdateUser(mockAccount, mockUpdateData)).rejects.toThrow(mockError);++ expect(UserModel).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/server/services/nextAuthUser/index.ts b/src/server/services/nextAuthUser/index.tsindex bdf45d4f8e7..8f09bff19f1 100644--- a/src/server/services/nextAuthUser/index.ts+++ b/src/server/services/nextAuthUser/index.ts@@ -1,33 +1,18 @@-import { and, eq } from 'drizzle-orm';-import { Adapter, AdapterAccount } from 'next-auth/adapters';import { NextResponse } from 'next/server';import { UserModel } from '@/database/models/user';-import {- UserItem,- nextauthAccounts,- nextauthAuthenticators,- nextauthSessions,- nextauthVerificationTokens,- users,-} from '@/database/schemas';+import { UserItem } from '@/database/schemas';import { LobeChatDatabase } from '@/database/type';import { pino } from '@/libs/logger';-import { merge } from '@/utils/merge';--import { AgentService } from '../agent';-import {- mapAdapterUserToLobeUser,- mapAuthenticatorQueryResutlToAdapterAuthenticator,- mapLobeUserToAdapterUser,- partialMapAdapterUserToLobeUser,-} from './utils';+import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';export class NextAuthUserService {+ adapter;private db: LobeChatDatabase;constructor(db: LobeChatDatabase) {this.db = db;+ this.adapter = LobeNextAuthDbAdapter(db);}safeUpdateUser = async (@@ -36,7 +21,8 @@ export class NextAuthUserService {) => {pino.info(`updating user "${JSON.stringify({ provider, providerAccountId })}" due to webhook`);// 1. Find User by account- const user = await this.getUserByAccount({+ // @ts-expect-error: Already impl in `LobeNextauthDbAdapter`+ const user = await this.adapter.getUserByAccount({provider,providerAccountId,});@@ -58,266 +44,4 @@ export class NextAuthUserService {}return NextResponse.json({ message: 'user updated', success: true }, { status: 200 });};-- safeSignOutUser = async ({- providerAccountId,- provider,- }: {- provider: string;- providerAccountId: string;- }) => {- pino.info(`Signing out user "${JSON.stringify({ provider, providerAccountId })}"`);- const user = await this.getUserByAccount({- provider,- providerAccountId,- });-- // 2. If found, Update user data from provider- if (user?.id) {- // Perform update- await this.db.delete(nextauthSessions).where(eq(nextauthSessions.userId, user.id));- } else {- pino.warn(- `[${provider}]: Webhooks handler user "${JSON.stringify({ provider, providerAccountId })}" to signout", but no user was found by the providerAccountId.`,- );- }- return NextResponse.json({ message: 'user signed out', success: true }, { status: 200 });- };-- createAuthenticator: NonNullable<Adapter['createAuthenticator']> = async (authenticator) => {- return await this.db- .insert(nextauthAuthenticators)- .values(authenticator)- .returning()- .then((res: any) => res[0] ?? undefined);- };-- createSession: NonNullable<Adapter['createSession']> = async (data) => {- return await this.db- .insert(nextauthSessions)- .values(data)- .returning()- .then((res: any) => res[0]);- };-- createUser: NonNullable<Adapter['createUser']> = async (user) => {- const { id, name, email, emailVerified, image, providerAccountId } = user;- // return the user if it already exists- let existingUser =- email && typeof email === 'string' && email.trim()- ? await UserModel.findByEmail(this.db, email)- : undefined;- // If the user is not found by email, try to find by providerAccountId- if (!existingUser && providerAccountId) {- existingUser = await UserModel.findById(this.db, providerAccountId);- }- if (existingUser) {- const adapterUser = mapLobeUserToAdapterUser(existingUser);- return adapterUser;- }-- // create a new user if it does not exist- // Use id from provider if it exists, otherwise use id assigned by next-auth- // ref: https://github.com/lobehub/lobe-chat/pull/2935- const uid = providerAccountId ?? id;- await UserModel.createUser(- this.db,- mapAdapterUserToLobeUser({- email,- emailVerified,- // Use providerAccountId as userid to identify if the user exists in a SSO provider- id: uid,- image,- name,- }),- );-- // 3. Create an inbox session for the user- const agentService = new AgentService(this.db, uid);- await agentService.createInbox();-- return { ...user, id: uid };- };-- createVerificationToken: NonNullable<Adapter['createVerificationToken']> = async (data) => {- return await this.db- .insert(nextauthVerificationTokens)- .values(data)- .returning()- .then((res: any) => res[0]);- };-- deleteSession: NonNullable<Adapter['deleteSession']> = async (sessionToken) => {- await this.db.delete(nextauthSessions).where(eq(nextauthSessions.sessionToken, sessionToken));- };-- deleteUser: NonNullable<Adapter['deleteUser']> = async (id) => {- const user = await UserModel.findById(this.db, id);- if (!user) throw new Error('NextAuth: Delete User not found');- await UserModel.deleteUser(this.db, id);- };-- getAccount: NonNullable<Adapter['getAccount']> = async (providerAccountId, provider) => {- return (await this.db- .select()- .from(nextauthAccounts)- .where(- and(- eq(nextauthAccounts.provider, provider),- eq(nextauthAccounts.providerAccountId, providerAccountId),- ),- )- .then((res: any) => res[0] ?? null)) as Promise<AdapterAccount | null>;- };-- getAuthenticator: NonNullable<Adapter['getAuthenticator']> = async (credentialID) => {- const result = await this.db- .select()- .from(nextauthAuthenticators)- .where(eq(nextauthAuthenticators.credentialID, credentialID))- .then((res) => res[0] ?? null);- if (!result) throw new Error('NextAuthUserService: Failed to get authenticator');- return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);- };-- getSessionAndUser: NonNullable<Adapter['getSessionAndUser']> = async (sessionToken) => {- const result = await this.db- .select({- session: nextauthSessions,- user: users,- })- .from(nextauthSessions)- .where(eq(nextauthSessions.sessionToken, sessionToken))- .innerJoin(users, eq(users.id, nextauthSessions.userId))- .then((res: any) => (res.length > 0 ? res[0] : null));-- if (!result) return null;- const adapterUser = mapLobeUserToAdapterUser(result.user);- if (!adapterUser) return null;- return {- session: result.session,- user: adapterUser,- };- };-- getUser: NonNullable<Adapter['getUser']> = async (id) => {- const lobeUser = await UserModel.findById(this.db, id);- if (!lobeUser) return null;- return mapLobeUserToAdapterUser(lobeUser);- };-- getUserByAccount: NonNullable<Adapter['getUserByAccount']> = async (account) => {- const result = await this.db- .select({- account: nextauthAccounts,- users,- })- .from(nextauthAccounts)- .innerJoin(users, eq(nextauthAccounts.userId, users.id))- .where(- and(- eq(nextauthAccounts.provider, account.provider),- eq(nextauthAccounts.providerAccountId, account.providerAccountId),- ),- )- .then((res: any) => res[0]);-- return result?.users ? mapLobeUserToAdapterUser(result.users) : null;- };-- getUserByEmail: NonNullable<Adapter['getUserByEmail']> = async (email) => {- const lobeUser =- email && typeof email === 'string' && email.trim()- ? await UserModel.findByEmail(this.db, email)- : undefined;- return lobeUser ? mapLobeUserToAdapterUser(lobeUser) : null;- };-- linkAccount: NonNullable<Adapter['linkAccount']> = async (data) => {- const [account] = await this.db- .insert(nextauthAccounts)- .values(data as any)- .returning();- if (!account) throw new Error('NextAuthAccountModel: Failed to create account');- // TODO Update type annotation- return account as any;- };-- listAuthenticatorsByUserId: NonNullable<Adapter['listAuthenticatorsByUserId']> = async (- userId,- ) => {- const result = await this.db- .select()- .from(nextauthAuthenticators)- .where(eq(nextauthAuthenticators.userId, userId))- .then((res: any) => res);- if (result.length === 0)- throw new Error('NextAuthUserService: Failed to get authenticator list');- return result.map((r: any) => mapAuthenticatorQueryResutlToAdapterAuthenticator(r));- };-- unlinkAccount: NonNullable<Adapter['unlinkAccount']> = async (account) => {- await this.db- .delete(nextauthAccounts)- .where(- and(- eq(nextauthAccounts.provider, account.provider),- eq(nextauthAccounts.providerAccountId, account.providerAccountId),- ),- );- };-- updateAuthenticatorCounter: NonNullable<Adapter['updateAuthenticatorCounter']> = async (- credentialID,- counter,- ) => {- const result = await this.db- .update(nextauthAuthenticators)- .set({ counter })- .where(eq(nextauthAuthenticators.credentialID, credentialID))- .returning()- .then((res: any) => res[0]);- if (!result) throw new Error('NextAuthUserService: Failed to update authenticator counter');- return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);- };-- updateSession: NonNullable<Adapter['updateSession']> = async (data) => {- const res = await this.db- .update(nextauthSessions)- .set(data)- .where(eq(nextauthSessions.sessionToken, data.sessionToken))- .returning();- return res[0];- };-- updateUser: NonNullable<Adapter['updateUser']> = async (user) => {- const lobeUser = await UserModel.findById(this.db, user?.id);- if (!lobeUser) throw new Error('NextAuth: User not found');- const userModel = new UserModel(this.db, user.id);-- const updatedUser = await userModel.updateUser({- ...partialMapAdapterUserToLobeUser(user),- });- if (!updatedUser) throw new Error('NextAuth: Failed to update user');-- // merge new user data with old user data- const newAdapterUser = mapLobeUserToAdapterUser(lobeUser);- if (!newAdapterUser) {- throw new Error('NextAuth: Failed to map user data to adapter user');- }- return merge(newAdapterUser, user);- };-- useVerificationToken: NonNullable<Adapter['useVerificationToken']> = async (identifier_token) => {- return await this.db- .delete(nextauthVerificationTokens)- .where(- and(- eq(nextauthVerificationTokens.identifier, identifier_token.identifier),- eq(nextauthVerificationTokens.token, identifier_token.token),- ),- )- .returning()- .then((res: any) => (res.length > 0 ? res[0] : null));- };}