@lobehub/chat 1.122.6 → 1.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/changelog/v1.json +18 -0
  3. package/package.json +2 -2
  4. package/packages/model-bank/package.json +1 -0
  5. package/packages/model-bank/src/aiModels/index.ts +3 -1
  6. package/packages/model-bank/src/aiModels/newapi.ts +11 -0
  7. package/packages/model-runtime/src/RouterRuntime/createRuntime.test.ts +60 -0
  8. package/packages/model-runtime/src/RouterRuntime/createRuntime.ts +6 -3
  9. package/packages/model-runtime/src/index.ts +1 -0
  10. package/packages/model-runtime/src/newapi/index.test.ts +618 -0
  11. package/packages/model-runtime/src/newapi/index.ts +245 -0
  12. package/packages/model-runtime/src/runtimeMap.ts +2 -0
  13. package/packages/model-runtime/src/types/type.ts +1 -0
  14. package/packages/types/src/user/settings/keyVaults.ts +1 -0
  15. package/packages/utils/src/server/__tests__/auth.test.ts +1 -1
  16. package/packages/utils/src/server/auth.ts +2 -2
  17. package/src/app/(backend)/api/auth/adapter/route.ts +137 -0
  18. package/src/app/(backend)/api/webhooks/logto/route.ts +9 -0
  19. package/src/app/[variants]/(main)/settings/provider/(detail)/newapi/page.tsx +27 -0
  20. package/src/config/auth.ts +4 -0
  21. package/src/config/modelProviders/index.ts +3 -0
  22. package/src/config/modelProviders/newapi.ts +17 -0
  23. package/src/libs/next-auth/adapter/index.ts +103 -201
  24. package/src/libs/next-auth/auth.config.ts +22 -5
  25. package/src/libs/next-auth/index.ts +11 -24
  26. package/src/libs/trpc/edge/context.ts +2 -2
  27. package/src/libs/trpc/lambda/context.ts +2 -2
  28. package/src/locales/default/modelProvider.ts +26 -0
  29. package/src/middleware.ts +2 -2
  30. package/src/server/routers/lambda/user.test.ts +4 -17
  31. package/src/server/routers/lambda/user.ts +6 -15
  32. package/src/server/services/nextAuthUser/index.ts +282 -6
  33. package/packages/database/src/server/models/__tests__/nextauth.test.ts +0 -556
  34. package/src/libs/next-auth/edge.ts +0 -26
  35. package/src/server/services/nextAuthUser/index.test.ts +0 -108
  36. /package/{.env.development → .env.example.development} +0 -0
  37. /package/src/{libs/next-auth/adapter → server/services/nextAuthUser}/utils.ts +0 -0
@@ -1,18 +1,33 @@
1
+ import { and, eq } from 'drizzle-orm';
2
+ import { Adapter, AdapterAccount } from 'next-auth/adapters';
1
3
  import { NextResponse } from 'next/server';
2
4
 
3
5
  import { UserModel } from '@/database/models/user';
4
- import { UserItem } from '@/database/schemas';
6
+ import {
7
+ UserItem,
8
+ nextauthAccounts,
9
+ nextauthAuthenticators,
10
+ nextauthSessions,
11
+ nextauthVerificationTokens,
12
+ users,
13
+ } from '@/database/schemas';
5
14
  import { LobeChatDatabase } from '@/database/type';
6
15
  import { pino } from '@/libs/logger';
7
- import { LobeNextAuthDbAdapter } from '@/libs/next-auth/adapter';
16
+ import { merge } from '@/utils/merge';
17
+
18
+ import { AgentService } from '../agent';
19
+ import {
20
+ mapAdapterUserToLobeUser,
21
+ mapAuthenticatorQueryResutlToAdapterAuthenticator,
22
+ mapLobeUserToAdapterUser,
23
+ partialMapAdapterUserToLobeUser,
24
+ } from './utils';
8
25
 
9
26
  export class NextAuthUserService {
10
- adapter;
11
27
  private db: LobeChatDatabase;
12
28
 
13
29
  constructor(db: LobeChatDatabase) {
14
30
  this.db = db;
15
- this.adapter = LobeNextAuthDbAdapter(db);
16
31
  }
17
32
 
18
33
  safeUpdateUser = async (
@@ -21,8 +36,7 @@ export class NextAuthUserService {
21
36
  ) => {
22
37
  pino.info(`updating user "${JSON.stringify({ provider, providerAccountId })}" due to webhook`);
23
38
  // 1. Find User by account
24
- // @ts-expect-error: Already impl in `LobeNextauthDbAdapter`
25
- const user = await this.adapter.getUserByAccount({
39
+ const user = await this.getUserByAccount({
26
40
  provider,
27
41
  providerAccountId,
28
42
  });
@@ -44,4 +58,266 @@ export class NextAuthUserService {
44
58
  }
45
59
  return NextResponse.json({ message: 'user updated', success: true }, { status: 200 });
46
60
  };
61
+
62
+ safeSignOutUser = async ({
63
+ providerAccountId,
64
+ provider,
65
+ }: {
66
+ provider: string;
67
+ providerAccountId: string;
68
+ }) => {
69
+ pino.info(`Signing out user "${JSON.stringify({ provider, providerAccountId })}"`);
70
+ const user = await this.getUserByAccount({
71
+ provider,
72
+ providerAccountId,
73
+ });
74
+
75
+ // 2. If found, Update user data from provider
76
+ if (user?.id) {
77
+ // Perform update
78
+ await this.db.delete(nextauthSessions).where(eq(nextauthSessions.userId, user.id));
79
+ } else {
80
+ pino.warn(
81
+ `[${provider}]: Webhooks handler user "${JSON.stringify({ provider, providerAccountId })}" to signout", but no user was found by the providerAccountId.`,
82
+ );
83
+ }
84
+ return NextResponse.json({ message: 'user signed out', success: true }, { status: 200 });
85
+ };
86
+
87
+ createAuthenticator: NonNullable<Adapter['createAuthenticator']> = async (authenticator) => {
88
+ return await this.db
89
+ .insert(nextauthAuthenticators)
90
+ .values(authenticator)
91
+ .returning()
92
+ .then((res: any) => res[0] ?? undefined);
93
+ };
94
+
95
+ createSession: NonNullable<Adapter['createSession']> = async (data) => {
96
+ return await this.db
97
+ .insert(nextauthSessions)
98
+ .values(data)
99
+ .returning()
100
+ .then((res: any) => res[0]);
101
+ };
102
+
103
+ createUser: NonNullable<Adapter['createUser']> = async (user) => {
104
+ const { id, name, email, emailVerified, image, providerAccountId } = user;
105
+ // return the user if it already exists
106
+ let existingUser =
107
+ email && typeof email === 'string' && email.trim()
108
+ ? await UserModel.findByEmail(this.db, email)
109
+ : undefined;
110
+ // If the user is not found by email, try to find by providerAccountId
111
+ if (!existingUser && providerAccountId) {
112
+ existingUser = await UserModel.findById(this.db, providerAccountId);
113
+ }
114
+ if (existingUser) {
115
+ const adapterUser = mapLobeUserToAdapterUser(existingUser);
116
+ return adapterUser;
117
+ }
118
+
119
+ // create a new user if it does not exist
120
+ // Use id from provider if it exists, otherwise use id assigned by next-auth
121
+ // ref: https://github.com/lobehub/lobe-chat/pull/2935
122
+ const uid = providerAccountId ?? id;
123
+ await UserModel.createUser(
124
+ this.db,
125
+ mapAdapterUserToLobeUser({
126
+ email,
127
+ emailVerified,
128
+ // Use providerAccountId as userid to identify if the user exists in a SSO provider
129
+ id: uid,
130
+ image,
131
+ name,
132
+ }),
133
+ );
134
+
135
+ // 3. Create an inbox session for the user
136
+ const agentService = new AgentService(this.db, uid);
137
+ await agentService.createInbox();
138
+
139
+ return { ...user, id: uid };
140
+ };
141
+
142
+ createVerificationToken: NonNullable<Adapter['createVerificationToken']> = async (data) => {
143
+ return await this.db
144
+ .insert(nextauthVerificationTokens)
145
+ .values(data)
146
+ .returning()
147
+ .then((res: any) => res[0]);
148
+ };
149
+
150
+ deleteSession: NonNullable<Adapter['deleteSession']> = async (sessionToken) => {
151
+ await this.db.delete(nextauthSessions).where(eq(nextauthSessions.sessionToken, sessionToken));
152
+ };
153
+
154
+ deleteUser: NonNullable<Adapter['deleteUser']> = async (id) => {
155
+ const user = await UserModel.findById(this.db, id);
156
+ if (!user) throw new Error('NextAuth: Delete User not found');
157
+ await UserModel.deleteUser(this.db, id);
158
+ };
159
+
160
+ getAccount: NonNullable<Adapter['getAccount']> = async (providerAccountId, provider) => {
161
+ return (await this.db
162
+ .select()
163
+ .from(nextauthAccounts)
164
+ .where(
165
+ and(
166
+ eq(nextauthAccounts.provider, provider),
167
+ eq(nextauthAccounts.providerAccountId, providerAccountId),
168
+ ),
169
+ )
170
+ .then((res: any) => res[0] ?? null)) as Promise<AdapterAccount | null>;
171
+ };
172
+
173
+ getAuthenticator: NonNullable<Adapter['getAuthenticator']> = async (credentialID) => {
174
+ const result = await this.db
175
+ .select()
176
+ .from(nextauthAuthenticators)
177
+ .where(eq(nextauthAuthenticators.credentialID, credentialID))
178
+ .then((res) => res[0] ?? null);
179
+ if (!result) throw new Error('NextAuthUserService: Failed to get authenticator');
180
+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
181
+ };
182
+
183
+ getSessionAndUser: NonNullable<Adapter['getSessionAndUser']> = async (sessionToken) => {
184
+ const result = await this.db
185
+ .select({
186
+ session: nextauthSessions,
187
+ user: users,
188
+ })
189
+ .from(nextauthSessions)
190
+ .where(eq(nextauthSessions.sessionToken, sessionToken))
191
+ .innerJoin(users, eq(users.id, nextauthSessions.userId))
192
+ .then((res: any) => (res.length > 0 ? res[0] : null));
193
+
194
+ if (!result) return null;
195
+ const adapterUser = mapLobeUserToAdapterUser(result.user);
196
+ if (!adapterUser) return null;
197
+ return {
198
+ session: result.session,
199
+ user: adapterUser,
200
+ };
201
+ };
202
+
203
+ getUser: NonNullable<Adapter['getUser']> = async (id) => {
204
+ const lobeUser = await UserModel.findById(this.db, id);
205
+ if (!lobeUser) return null;
206
+ return mapLobeUserToAdapterUser(lobeUser);
207
+ };
208
+
209
+ getUserByAccount: NonNullable<Adapter['getUserByAccount']> = async (account) => {
210
+ const result = await this.db
211
+ .select({
212
+ account: nextauthAccounts,
213
+ users,
214
+ })
215
+ .from(nextauthAccounts)
216
+ .innerJoin(users, eq(nextauthAccounts.userId, users.id))
217
+ .where(
218
+ and(
219
+ eq(nextauthAccounts.provider, account.provider),
220
+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),
221
+ ),
222
+ )
223
+ .then((res: any) => res[0]);
224
+
225
+ return result?.users ? mapLobeUserToAdapterUser(result.users) : null;
226
+ };
227
+
228
+ getUserByEmail: NonNullable<Adapter['getUserByEmail']> = async (email) => {
229
+ const lobeUser =
230
+ email && typeof email === 'string' && email.trim()
231
+ ? await UserModel.findByEmail(this.db, email)
232
+ : undefined;
233
+ return lobeUser ? mapLobeUserToAdapterUser(lobeUser) : null;
234
+ };
235
+
236
+ linkAccount: NonNullable<Adapter['linkAccount']> = async (data) => {
237
+ const [account] = await this.db
238
+ .insert(nextauthAccounts)
239
+ .values(data as any)
240
+ .returning();
241
+ if (!account) throw new Error('NextAuthAccountModel: Failed to create account');
242
+ // TODO Update type annotation
243
+ return account as any;
244
+ };
245
+
246
+ listAuthenticatorsByUserId: NonNullable<Adapter['listAuthenticatorsByUserId']> = async (
247
+ userId,
248
+ ) => {
249
+ const result = await this.db
250
+ .select()
251
+ .from(nextauthAuthenticators)
252
+ .where(eq(nextauthAuthenticators.userId, userId))
253
+ .then((res: any) => res);
254
+ if (result.length === 0)
255
+ throw new Error('NextAuthUserService: Failed to get authenticator list');
256
+ return result.map((r: any) => mapAuthenticatorQueryResutlToAdapterAuthenticator(r));
257
+ };
258
+
259
+ unlinkAccount: NonNullable<Adapter['unlinkAccount']> = async (account) => {
260
+ await this.db
261
+ .delete(nextauthAccounts)
262
+ .where(
263
+ and(
264
+ eq(nextauthAccounts.provider, account.provider),
265
+ eq(nextauthAccounts.providerAccountId, account.providerAccountId),
266
+ ),
267
+ );
268
+ };
269
+
270
+ updateAuthenticatorCounter: NonNullable<Adapter['updateAuthenticatorCounter']> = async (
271
+ credentialID,
272
+ counter,
273
+ ) => {
274
+ const result = await this.db
275
+ .update(nextauthAuthenticators)
276
+ .set({ counter })
277
+ .where(eq(nextauthAuthenticators.credentialID, credentialID))
278
+ .returning()
279
+ .then((res: any) => res[0]);
280
+ if (!result) throw new Error('NextAuthUserService: Failed to update authenticator counter');
281
+ return mapAuthenticatorQueryResutlToAdapterAuthenticator(result);
282
+ };
283
+
284
+ updateSession: NonNullable<Adapter['updateSession']> = async (data) => {
285
+ const res = await this.db
286
+ .update(nextauthSessions)
287
+ .set(data)
288
+ .where(eq(nextauthSessions.sessionToken, data.sessionToken))
289
+ .returning();
290
+ return res[0];
291
+ };
292
+
293
+ updateUser: NonNullable<Adapter['updateUser']> = async (user) => {
294
+ const lobeUser = await UserModel.findById(this.db, user?.id);
295
+ if (!lobeUser) throw new Error('NextAuth: User not found');
296
+ const userModel = new UserModel(this.db, user.id);
297
+
298
+ const updatedUser = await userModel.updateUser({
299
+ ...partialMapAdapterUserToLobeUser(user),
300
+ });
301
+ if (!updatedUser) throw new Error('NextAuth: Failed to update user');
302
+
303
+ // merge new user data with old user data
304
+ const newAdapterUser = mapLobeUserToAdapterUser(lobeUser);
305
+ if (!newAdapterUser) {
306
+ throw new Error('NextAuth: Failed to map user data to adapter user');
307
+ }
308
+ return merge(newAdapterUser, user);
309
+ };
310
+
311
+ useVerificationToken: NonNullable<Adapter['useVerificationToken']> = async (identifier_token) => {
312
+ return await this.db
313
+ .delete(nextauthVerificationTokens)
314
+ .where(
315
+ and(
316
+ eq(nextauthVerificationTokens.identifier, identifier_token.identifier),
317
+ eq(nextauthVerificationTokens.token, identifier_token.token),
318
+ ),
319
+ )
320
+ .returning()
321
+ .then((res: any) => (res.length > 0 ? res[0] : null));
322
+ };
47
323
  }