@lenne.tech/nest-server 11.7.2 → 11.7.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.7.2",
3
+ "version": "11.7.3",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -1,8 +1,12 @@
1
- import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
2
- import { Reflector } from '@nestjs/core';
1
+ import { ExecutionContext, Injectable, Logger, Optional, UnauthorizedException } from '@nestjs/common';
2
+ import { ModuleRef, Reflector } from '@nestjs/core';
3
3
  import { GqlExecutionContext } from '@nestjs/graphql';
4
+ import { getConnectionToken } from '@nestjs/mongoose';
5
+ import { Connection, Types } from 'mongoose';
6
+ import { firstValueFrom, isObservable } from 'rxjs';
4
7
 
5
8
  import { RoleEnum } from '../../../common/enums/role.enum';
9
+ import { BetterAuthService } from '../../better-auth/better-auth.service';
6
10
  import { AuthGuardStrategy } from '../auth-guard-strategy.enum';
7
11
  import { ExpiredTokenException } from '../exceptions/expired-token.exception';
8
12
  import { InvalidTokenException } from '../exceptions/invalid-token.exception';
@@ -14,16 +18,305 @@ import { AuthGuard } from './auth.guard';
14
18
  * The RoleGuard is activated by the Role decorator. It checks whether the current user has at least one of the
15
19
  * specified roles or is logged in when the S_USER role is set.
16
20
  * If this is not the case, an UnauthorizedException is thrown.
21
+ *
22
+ * MULTI-TOKEN SUPPORT:
23
+ * This guard supports multiple authentication token types:
24
+ * 1. Legacy JWT tokens (Passport JWT strategy)
25
+ * 2. BetterAuth JWT tokens (verified via BetterAuth service)
26
+ * 3. BetterAuth session tokens (verified via database lookup)
27
+ *
28
+ * When Passport JWT validation fails, the guard falls back to BetterAuth verification:
29
+ * - First tries JWT verification if the JWT plugin is enabled
30
+ * - Then tries session token lookup via MongoDB
31
+ *
32
+ * This enables users who sign in via IAM (/iam/sign-in/email) to access all protected endpoints,
33
+ * regardless of whether they use JWT or session-based authentication.
17
34
  */
18
35
  @Injectable()
19
36
  export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
37
+ private readonly logger = new Logger(RolesGuard.name);
38
+ private betterAuthService: BetterAuthService | null = null;
39
+ private mongoConnection: Connection | null = null;
40
+ private servicesResolved = false;
41
+
20
42
  /**
21
- * Integrate reflector
43
+ * Integrate reflector and moduleRef for lazy service resolution
22
44
  */
23
- constructor(protected readonly reflector: Reflector) {
45
+ constructor(
46
+ protected readonly reflector: Reflector,
47
+ @Optional() private readonly moduleRef?: ModuleRef,
48
+ ) {
24
49
  super();
25
50
  }
26
51
 
52
+ /**
53
+ * Lazily resolve BetterAuth service and MongoDB connection
54
+ */
55
+ private resolveServices(): void {
56
+ if (this.servicesResolved || !this.moduleRef) {
57
+ return;
58
+ }
59
+
60
+ try {
61
+ this.betterAuthService = this.moduleRef.get(BetterAuthService, { strict: false });
62
+ } catch {
63
+ // BetterAuth not available - that's fine, we'll use Legacy JWT only
64
+ }
65
+
66
+ try {
67
+ // Get the Mongoose connection to query users directly
68
+ this.mongoConnection = this.moduleRef.get(getConnectionToken(), { strict: false });
69
+ } catch {
70
+ // MongoDB connection not available
71
+ }
72
+
73
+ this.servicesResolved = true;
74
+ }
75
+
76
+ /**
77
+ * Override canActivate to add BetterAuth JWT fallback
78
+ *
79
+ * Flow:
80
+ * 1. Try Passport JWT authentication (Legacy JWT)
81
+ * 2. If that fails, try BetterAuth JWT verification
82
+ * 3. If BetterAuth succeeds, load the user and proceed
83
+ */
84
+ override async canActivate(context: ExecutionContext): Promise<boolean> {
85
+ // Resolve services lazily
86
+ this.resolveServices();
87
+
88
+ // First, try the parent canActivate (Passport JWT)
89
+ try {
90
+ const result = super.canActivate(context);
91
+ return isObservable(result) ? await firstValueFrom(result) : await result;
92
+ } catch (passportError) {
93
+ // Passport JWT validation failed - try BetterAuth token fallback (JWT or session)
94
+ if (!this.betterAuthService?.isEnabled()) {
95
+ // BetterAuth not available - rethrow original error
96
+ throw passportError;
97
+ }
98
+
99
+ // Try to verify the token via BetterAuth (JWT or session token)
100
+ const user = await this.verifyBetterAuthTokenFromContext(context);
101
+ if (!user) {
102
+ // BetterAuth verification also failed - rethrow original Passport error
103
+ throw passportError;
104
+ }
105
+
106
+ // BetterAuth token is valid - set the user on the request
107
+ const request = this.getRequest(context);
108
+ if (request) {
109
+ request.user = user;
110
+ }
111
+
112
+ // Now call handleRequest with the BetterAuth-authenticated user to check roles
113
+ this.handleRequest(null, user, null, context);
114
+
115
+ return true;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Verify BetterAuth token (JWT or session) and load the corresponding user
121
+ *
122
+ * This method tries multiple verification strategies:
123
+ * 1. BetterAuth JWT verification (if JWT plugin is enabled)
124
+ * 2. BetterAuth session token lookup (database lookup)
125
+ *
126
+ * @param context - ExecutionContext to extract request from
127
+ * @returns User object if verification succeeds, null otherwise
128
+ */
129
+ private async verifyBetterAuthTokenFromContext(context: ExecutionContext): Promise<any> {
130
+ if (!this.betterAuthService || !this.mongoConnection) {
131
+ return null;
132
+ }
133
+
134
+ try {
135
+ // Get the raw HTTP request from multiple possible sources
136
+ let authHeader: string | undefined;
137
+
138
+ // Try GraphQL context first
139
+ try {
140
+ const gqlContext = GqlExecutionContext.create(context);
141
+ const ctx = gqlContext.getContext();
142
+ if (ctx?.req?.headers) {
143
+ authHeader = ctx.req.headers.authorization || ctx.req.headers.Authorization;
144
+ }
145
+ } catch {
146
+ // GraphQL context not available
147
+ }
148
+
149
+ // Fallback to HTTP context
150
+ if (!authHeader) {
151
+ try {
152
+ const httpRequest = context.switchToHttp().getRequest();
153
+ if (httpRequest?.headers) {
154
+ authHeader = httpRequest.headers.authorization || httpRequest.headers.Authorization;
155
+ }
156
+ } catch {
157
+ // HTTP context not available
158
+ }
159
+ }
160
+
161
+ let token: string | undefined;
162
+
163
+ if (authHeader?.startsWith('Bearer ')) {
164
+ token = authHeader.substring(7);
165
+ } else if (authHeader?.startsWith('bearer ')) {
166
+ // Handle lowercase 'bearer' as well
167
+ token = authHeader.substring(7);
168
+ }
169
+
170
+ if (!token) {
171
+ return null;
172
+ }
173
+
174
+ // Strategy 1: Try JWT verification (if JWT plugin is enabled)
175
+ if (this.betterAuthService.isJwtEnabled()) {
176
+ try {
177
+ const payload = await this.betterAuthService.verifyJwtToken(token);
178
+ if (payload?.sub) {
179
+ const user = await this.loadUserFromPayload(payload);
180
+ if (user) {
181
+ return user;
182
+ }
183
+ }
184
+ } catch {
185
+ // JWT verification failed - try session token next
186
+ }
187
+ }
188
+
189
+ // Strategy 2: Try session token lookup (database lookup)
190
+ try {
191
+ const sessionResult = await this.betterAuthService.getSessionByToken(token);
192
+ if (sessionResult?.user) {
193
+ return this.loadUserFromSessionResult(sessionResult.user);
194
+ }
195
+ } catch {
196
+ // Session lookup failed
197
+ }
198
+
199
+ return null;
200
+ } catch (error) {
201
+ this.logger.debug(
202
+ `BetterAuth token fallback failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
203
+ );
204
+ return null;
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Load user from JWT payload using direct MongoDB query
210
+ *
211
+ * @param payload - JWT payload with sub (user ID or iamId)
212
+ * @returns User object with hasRole method
213
+ */
214
+ private async loadUserFromPayload(payload: { [key: string]: any; sub: string }): Promise<any> {
215
+ if (!this.mongoConnection) {
216
+ return null;
217
+ }
218
+
219
+ try {
220
+ const usersCollection = this.mongoConnection.collection('users');
221
+ let user: any = null;
222
+
223
+ // Try to find by MongoDB _id first
224
+ if (Types.ObjectId.isValid(payload.sub)) {
225
+ user = await usersCollection.findOne({ _id: new Types.ObjectId(payload.sub) });
226
+ }
227
+
228
+ // If not found, try by iamId
229
+ if (!user) {
230
+ user = await usersCollection.findOne({ iamId: payload.sub });
231
+ }
232
+
233
+ if (!user) {
234
+ return null;
235
+ }
236
+
237
+ // Convert MongoDB document to user-like object with hasRole method
238
+ const userObject = {
239
+ ...user,
240
+ _authenticatedViaBetterAuth: true,
241
+ // Add hasRole method for role checking
242
+ hasRole: (roles: string[]): boolean => {
243
+ if (!user.roles || !Array.isArray(user.roles)) {
244
+ return false;
245
+ }
246
+ return roles.some((role) => user.roles.includes(role));
247
+ },
248
+ id: user._id?.toString(),
249
+ };
250
+
251
+ return userObject;
252
+ } catch (error) {
253
+ this.logger.debug(
254
+ `Failed to load user from payload: ${error instanceof Error ? error.message : 'Unknown error'}`,
255
+ );
256
+ return null;
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Load user from session result (from getSessionByToken)
262
+ *
263
+ * @param sessionUser - User object from session lookup
264
+ * @returns User object with hasRole method
265
+ */
266
+ private async loadUserFromSessionResult(sessionUser: any): Promise<any> {
267
+ if (!this.mongoConnection || !sessionUser) {
268
+ return null;
269
+ }
270
+
271
+ try {
272
+ const usersCollection = this.mongoConnection.collection('users');
273
+
274
+ // The sessionUser might have id (BetterAuth ID) or email
275
+ // We need to find the corresponding user in our users collection
276
+ let user: any = null;
277
+
278
+ // Try to find by email (most reliable)
279
+ if (sessionUser.email) {
280
+ user = await usersCollection.findOne({ email: sessionUser.email });
281
+ }
282
+
283
+ // If not found by email, try by iamId
284
+ if (!user && sessionUser.id) {
285
+ user = await usersCollection.findOne({ iamId: sessionUser.id });
286
+ }
287
+
288
+ // If still not found, try by _id (if the ID looks like a MongoDB ObjectId)
289
+ if (!user && sessionUser.id && Types.ObjectId.isValid(sessionUser.id)) {
290
+ user = await usersCollection.findOne({ _id: new Types.ObjectId(sessionUser.id) });
291
+ }
292
+
293
+ if (!user) {
294
+ return null;
295
+ }
296
+
297
+ // Convert MongoDB document to user-like object with hasRole method
298
+ const userObject = {
299
+ ...user,
300
+ _authenticatedViaBetterAuth: true,
301
+ // Add hasRole method for role checking
302
+ hasRole: (roles: string[]): boolean => {
303
+ if (!user.roles || !Array.isArray(user.roles)) {
304
+ return false;
305
+ }
306
+ return roles.some((role) => user.roles.includes(role));
307
+ },
308
+ id: user._id?.toString(),
309
+ };
310
+
311
+ return userObject;
312
+ } catch (error) {
313
+ this.logger.debug(
314
+ `Failed to load user from session: ${error instanceof Error ? error.message : 'Unknown error'}`,
315
+ );
316
+ return null;
317
+ }
318
+ }
319
+
27
320
  /**
28
321
  * Handle request
29
322
  */
@@ -42,7 +335,7 @@ export class RolesGuard extends AuthGuard(AuthGuardStrategy.JWT) {
42
335
  }
43
336
 
44
337
  // Check roles
45
- if (!roles || !roles.some(value => !!value)) {
338
+ if (!roles || !roles.some((value) => !!value)) {
46
339
  return user;
47
340
  }
48
341
 
@@ -91,6 +91,33 @@ export abstract class CoreUserService<
91
91
  return this.process(async () => dbObject, { dbObject, serviceOptions });
92
92
  }
93
93
 
94
+ /**
95
+ * Get user by MongoDB ID or BetterAuth IAM ID
96
+ *
97
+ * This method is used by RolesGuard to resolve users from BetterAuth JWT tokens.
98
+ * The sub claim in BetterAuth JWTs can contain either:
99
+ * - The MongoDB _id of the user
100
+ * - The BetterAuth iamId
101
+ *
102
+ * @param idOrIamId - MongoDB _id or BetterAuth iamId
103
+ * @returns User object or null if not found
104
+ */
105
+ async getByIdOrIamId(idOrIamId: string): Promise<null | TUser> {
106
+ try {
107
+ // First, try to find by MongoDB _id
108
+ const byId = await this.mainDbModel.findById(idOrIamId).exec();
109
+ if (byId) {
110
+ return byId as TUser;
111
+ }
112
+ } catch {
113
+ // Invalid ObjectId format - try iamId instead
114
+ }
115
+
116
+ // Try to find by iamId
117
+ const byIamId = await this.mainDbModel.findOne({ iamId: idOrIamId }).exec();
118
+ return byIamId as null | TUser;
119
+ }
120
+
94
121
  /**
95
122
  * Get verified state of user by token
96
123
  */