@lenne.tech/nest-server 12.7.0 → 12.7.2

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 (51) hide show
  1. package/.claude/rules/better-auth.md +13 -2
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +1 -1
  4. package/dist/core/common/filters/http-exception-log.filter.js +7 -2
  5. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  6. package/dist/core/common/helpers/server-url.helper.d.ts +2 -0
  7. package/dist/core/common/helpers/server-url.helper.js +10 -0
  8. package/dist/core/common/helpers/server-url.helper.js.map +1 -0
  9. package/dist/core/common/services/email.service.d.ts +1 -0
  10. package/dist/core/common/services/email.service.js +7 -0
  11. package/dist/core/common/services/email.service.js.map +1 -1
  12. package/dist/core/modules/auth/services/core-auth.service.js +0 -1
  13. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +4 -1
  15. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +2 -0
  17. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +33 -10
  18. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  19. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +7 -4
  20. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
  21. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +2 -0
  22. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  23. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -4
  24. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  25. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  27. package/dist/core/modules/better-auth/core-better-auth.service.js +1 -1
  28. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  29. package/dist/index.d.ts +1 -0
  30. package/dist/index.js +1 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/main.js +2 -1
  33. package/dist/main.js.map +1 -1
  34. package/migration-guides/12.5.x-to-12.6.x.md +10 -0
  35. package/migration-guides/12.6.x-to-12.7.x.md +11 -3
  36. package/migration-guides/12.7.0-to-12.7.1.md +99 -0
  37. package/migration-guides/12.7.1-to-12.7.2.md +115 -0
  38. package/package.json +1 -1
  39. package/src/core/common/filters/http-exception-log.filter.ts +8 -2
  40. package/src/core/common/helpers/server-url.helper.ts +27 -0
  41. package/src/core/common/services/email.service.ts +18 -0
  42. package/src/core/modules/auth/services/core-auth.service.ts +1 -1
  43. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +10 -2
  44. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +53 -11
  45. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +23 -5
  46. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +6 -0
  47. package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -4
  48. package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -1
  49. package/src/core/modules/better-auth/core-better-auth.service.ts +3 -1
  50. package/src/index.ts +1 -0
  51. package/src/main.ts +2 -1
@@ -180,10 +180,18 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
180
180
  return;
181
181
  }
182
182
  const caller = req as unknown as {
183
- betterAuthSession?: { user?: { id?: unknown } };
183
+ betterAuthSession?: { session?: { userId?: unknown }; user?: { id?: unknown } };
184
184
  betterAuthUser?: { id?: unknown };
185
185
  };
186
- const userId = caller.betterAuthSession?.user?.id ?? caller.betterAuthUser?.id;
186
+ // The id the sessions are stored under, from the caller's own session (12.7.2, DEV-4133). `user.id` is not it for
187
+ // every user: the session lookup prefers a STORED `id`, and the legacy migration (`migrateAccountToIam()`) writes
188
+ // one of its own next to `_id`, which is what every session references — so a migrated user's sessions were never
189
+ // found and nothing was revoked. The ownership check stays in sessionTokenOfUser().
190
+ const sessionUserId = caller.betterAuthSession?.session?.userId;
191
+ const userId =
192
+ (typeof sessionUserId === 'string' && sessionUserId ? sessionUserId : undefined) ??
193
+ caller.betterAuthSession?.user?.id ??
194
+ caller.betterAuthUser?.id;
187
195
  const token =
188
196
  typeof userId === 'string' && userId
189
197
  ? await this.betterAuthService.sessionTokenOfUser(userId, sessionId)
@@ -289,21 +289,22 @@ export class CoreBetterAuthEmailVerificationService {
289
289
  name: user.name || user.email.split('@')[0],
290
290
  };
291
291
 
292
+ let info: unknown;
292
293
  if (resolved.isAbsolute) {
293
294
  // Fallback template from nest-server: render directly via EJS (compiled once)
294
295
  const html = this.renderFrameworkTemplate(resolved.path, templateData);
295
296
 
296
- await this.emailService.sendMail(user.email, this.getEmailSubject(appName), { html });
297
+ info = await this.emailService.sendMail(user.email, this.getEmailSubject(appName), { html });
297
298
  } else {
298
299
  // Project template: use TemplateService (relative path)
299
- await this.emailService.sendMail(user.email, this.getEmailSubject(appName), {
300
+ info = await this.emailService.sendMail(user.email, this.getEmailSubject(appName), {
300
301
  htmlTemplate: resolved.path,
301
302
  templateData,
302
303
  });
303
304
  }
304
305
 
305
306
  sent = true;
306
- this.logger.debug(`Verification email sent to ${this.maskEmail(user.email)}`);
307
+ this.logAuthMailOutcome('Verification', 'EMAIL VERIFICATION', user.email, info);
307
308
  } catch (error) {
308
309
  this.logger.error(
309
310
  `Failed to send verification email to ${this.maskEmail(user.email)}: ${error instanceof Error ? error.message : 'Unknown error'}`,
@@ -424,20 +425,21 @@ export class CoreBetterAuthEmailVerificationService {
424
425
  const resolved = await this.resolveTemplatePath(PASSWORD_RESET_TEMPLATE, this.config.locale);
425
426
  const subject = this.getPasswordResetSubject(appName);
426
427
 
428
+ let info: unknown;
427
429
  if (resolved.isAbsolute) {
428
430
  // nest-server fallback template: render directly via EJS (compiled once, see the helper)
429
431
  const html = this.renderFrameworkTemplate(resolved.path, templateData);
430
- await this.emailService.sendMail(user.email, subject, { html });
432
+ info = await this.emailService.sendMail(user.email, subject, { html });
431
433
  } else {
432
434
  // Project template: use TemplateService (relative path)
433
- await this.emailService.sendMail(user.email, subject, {
435
+ info = await this.emailService.sendMail(user.email, subject, {
434
436
  htmlTemplate: resolved.path,
435
437
  templateData,
436
438
  });
437
439
  }
438
440
 
439
441
  sent = true;
440
- this.logger.debug(`Password-reset email sent to ${this.maskEmail(user.email)}`);
442
+ this.logAuthMailOutcome('Password-reset', 'PASSWORD RESET', user.email, info);
441
443
  } catch (error) {
442
444
  this.logger.error(
443
445
  `Failed to send password-reset email to ${this.maskEmail(user.email)}: ${error instanceof Error ? error.message : 'Unknown error'}`,
@@ -1051,22 +1053,62 @@ export class CoreBetterAuthEmailVerificationService {
1051
1053
  * token into `HubLogBufferService`'s ring buffer, which is readable over HTTP by any ADMIN.
1052
1054
  */
1053
1055
  protected logAuthUrlForDevelopment(label: string, email: string, url: string): void {
1054
- if (process.env.LT_LOG_AUTH_URLS === '0') {
1056
+ if (!this.logsAuthUrlsForDevelopment()) {
1055
1057
  return;
1056
1058
  }
1059
+ const userKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16);
1060
+ // oxlint-disable-next-line no-console
1061
+ console.log(`[${label}] User: ${maskEmail(email)}, UserKey: ${userKey}, URL: ${url}`);
1062
+ }
1063
+
1064
+ /**
1065
+ * Whether {@link logAuthUrlForDevelopment} prints its line in this process (the rules are documented there). Its own
1066
+ * method since 12.7.2, so the outcome line of a send can say where the link is (DEV-4131).
1067
+ */
1068
+ protected logsAuthUrlsForDevelopment(): boolean {
1069
+ if (process.env.LT_LOG_AUTH_URLS === '0') {
1070
+ return false;
1071
+ }
1057
1072
  const env = this.configService?.getFastButReadOnly<string>('env') ?? process.env.NODE_ENV;
1058
1073
  if (!isLocalEnv(env)) {
1059
- return;
1074
+ return false;
1060
1075
  }
1061
1076
  // `!== undefined`, not truthiness: an empty NODE_ENV (`NODE_ENV=${NODE_ENV}` in a compose file on a host without
1062
1077
  // the variable) is read as `local` by getEnvironmentConfig(), and `isLocalEnv('')` is false
1063
1078
  const nodeEnv = process.env.NODE_ENV;
1064
1079
  if (nodeEnv !== undefined && !isLocalEnv(nodeEnv)) {
1080
+ return false;
1081
+ }
1082
+ return true;
1083
+ }
1084
+
1085
+ /**
1086
+ * Logs what became of an auth mail handed to the EmailService (12.7.2, DEV-4131). A transport that only renders mail
1087
+ * (`jsonTransport`, what a starter-based project uses locally without `SMTP_HOST`) resolves like a delivery; logging
1088
+ * "sent" then told a developer to check an inbox no mail would ever reach, with the link lost between debug lines.
1089
+ * Such a send is now a WARN saying that nothing went out and where the link is; a send the Hub mailbox captured says
1090
+ * so; only a real delivery reads "sent".
1091
+ *
1092
+ * @param kind - `Verification` or `Password-reset`
1093
+ * @param label - The label of the development log line that carries the link (`EMAIL VERIFICATION`, `PASSWORD RESET`)
1094
+ * @param info - What `EmailService.sendMail()` answered
1095
+ */
1096
+ protected logAuthMailOutcome(kind: string, label: string, email: string, info: unknown): void {
1097
+ const masked = maskEmail(email);
1098
+ if ((info as { captured?: unknown } | null | undefined)?.captured === true) {
1099
+ this.logger.debug(`${kind} email for ${masked} captured in the Hub mailbox, not delivered`);
1065
1100
  return;
1066
1101
  }
1067
- const userKey = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 16);
1068
- // oxlint-disable-next-line no-console
1069
- console.log(`[${label}] User: ${maskEmail(email)}, UserKey: ${userKey}, URL: ${url}`);
1102
+ if (this.emailService?.deliversMail?.() === false) {
1103
+ const where = this.logsAuthUrlsForDevelopment()
1104
+ ? `Open the link from the [${label}] line above.`
1105
+ : 'Configure email.smtp (SMTP_HOST) to deliver it.';
1106
+ this.logger.warn(
1107
+ `No ${kind.toLowerCase()} email was sent to ${masked}: no mail server is configured, the transport only renders mail (email.smtp.jsonTransport / streamTransport). ${where}`,
1108
+ );
1109
+ return;
1110
+ }
1111
+ this.logger.debug(`${kind} email sent to ${masked}`);
1070
1112
  }
1071
1113
 
1072
1114
  protected getAppName(): string {
@@ -31,8 +31,13 @@ export interface SessionTokenPresentation {
31
31
  * A Better-Auth endpoint that CREATES a session (two-factor verify, passkey verify, OTP and magic-link sign-in, …)
32
32
  * sets this cookie; that is how the token in its body is recognised as the session token rather than some other
33
33
  * value a plugin names `token`. The cookie value is signed (`<token>.<signature>`, URL-encoded).
34
+ *
35
+ * When a response sets the cookie more than once, the LAST one counts, as in the browser: a session refresh during
36
+ * the request (Better-Auth's `getSessionFromCtx()`, once per `updateAge`) sets the current session's cookie first, and
37
+ * an endpoint that then replaces the session (enabling 2FA) sets the new one after it (12.7.1).
34
38
  */
35
39
  export function sessionTokenFromSetCookie(response: globalThis.Response, cookieName: string): string | undefined {
40
+ let token: string | undefined;
36
41
  for (const header of response.headers.getSetCookie?.() ?? []) {
37
42
  if (!header.startsWith(`${cookieName}=`)) {
38
43
  continue;
@@ -44,10 +49,9 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
44
49
  } catch {
45
50
  value = raw;
46
51
  }
47
- const token = value.split('.')[0];
48
- return token || undefined;
52
+ token = value.split('.')[0] || undefined;
49
53
  }
50
- return undefined;
54
+ return token;
51
55
  }
52
56
 
53
57
  /**
@@ -68,6 +72,10 @@ export function sessionTokenFromSetCookie(response: globalThis.Response, cookieN
68
72
  * - Session records (an object with a `token`, a `userId` and an `expiresAt`) lose their `token` in every mode, also
69
73
  * inside an array: `list-sessions` answered every session of the user with its token (12.7.0). The client revokes a
70
74
  * session by its `id` instead (`POST /revoke-session` with `{ sessionId }`).
75
+ * - A response in the shape `{ token, user }` that sets a new session cookie while its body names another opaque token
76
+ * rotated the session (the first verify-totp while enabling 2FA answers with the token of the session it deleted):
77
+ * that token is treated as the session token — removed in cookie mode, replaced by the JWT of the NEW session where
78
+ * the body carries one (12.7.1). A plugin's own `{ token }` next to a refreshed session cookie is not a rotation.
71
79
  * - Untouched: error responses, non-JSON bodies, a JWT (`/token` hands one out on purpose), and a top-level `token`
72
80
  * that is not the session token (another plugin's value).
73
81
  *
@@ -109,10 +117,19 @@ export async function presentSessionTokens(
109
117
  const sessionFieldToken = typeof session?.token === 'string' && session.token ? session.token : undefined;
110
118
  const cookieToken = sessionTokenFromSetCookie(response, options.cookieName);
111
119
  const topToken = typeof record.token === 'string' && record.token ? record.token : undefined;
120
+ // A response that sets a NEW session cookie while its body names another opaque token rotated the session: the
121
+ // body token is the one it just replaced (and deleted). Better-Auth's first verify-totp while enabling 2FA does that.
122
+ // Only in the shape of a session-creating answer, `{ token, user }`: a session refresh sets the cookie on ANY
123
+ // session-protected request, so a plugin's own token (`/one-time-token/generate` answers `{ token }`) can sit next
124
+ // to a session cookie as well, and must stay what it is.
125
+ const answersWithUser = !!record.user && typeof record.user === 'object' && !Array.isArray(record.user);
126
+ const rotatedFrom =
127
+ answersWithUser && !!topToken && !isJwtShaped(topToken) && !!cookieToken && topToken !== cookieToken;
112
128
  const topIsSessionToken =
113
129
  !!topToken &&
114
130
  !isJwtShaped(topToken) &&
115
131
  (topToken === cookieToken ||
132
+ rotatedFrom ||
116
133
  topToken === sessionFieldToken ||
117
134
  (await isLiveSessionToken(topToken, options.isSessionToken)));
118
135
 
@@ -131,8 +148,9 @@ export async function presentSessionTokens(
131
148
  delete next.token;
132
149
  }
133
150
  } else {
134
- // The session token the body should present: the top-level one, else the one this response just set
135
- const source = topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
151
+ // The session token the body should present: the one this response set when it rotated the session, else the
152
+ // top-level one, else the one this response just set
153
+ const source = rotatedFrom ? cookieToken : topIsSessionToken ? topToken : !topToken ? cookieToken : undefined;
136
154
  if (source) {
137
155
  const presented = await options.resolveJwt(source);
138
156
  if (presented) {
@@ -692,6 +692,10 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
692
692
  userId: userMongoId,
693
693
  });
694
694
 
695
+ // Logged HERE, where an account is actually created (12.7.2, DEV-4128): `true` also answers "the credential
696
+ // account exists already" — every sign-in of every user with a synchronised legacy password — and the callers
697
+ // logged "Migrated legacy user" for that, also for users registered a minute earlier
698
+ this.logger.log(`Migrated legacy user ${maskEmail(userEmail)} to IAM`);
695
699
  return true;
696
700
  } catch (error) {
697
701
  this.logger.error(`Error migrating account to IAM: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -1467,6 +1471,8 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
1467
1471
  providerId: 'credential',
1468
1472
  userId: legacyUser.id,
1469
1473
  });
1474
+ // Logged where the account is created, as on MongoDB (12.7.2, DEV-4128)
1475
+ this.logger.log(`Migrated legacy user ${maskEmail(userEmail)} to IAM`);
1470
1476
  return true;
1471
1477
  } catch (error) {
1472
1478
  this.logger.error(`Error migrating account to IAM: ${error instanceof Error ? error.message : 'Unknown error'}`);
@@ -408,11 +408,10 @@ export class CoreBetterAuthController {
408
408
 
409
409
  // Step 1: Try legacy user migration BEFORE Better Auth handles the request
410
410
  // This allows users who exist in legacy system to be migrated automatically
411
+ // `true` also means "already migrated" (every sign-in of a user with a synchronised legacy password); the mapper
412
+ // logs a real migration itself (12.7.2, DEV-4128)
411
413
  try {
412
- const migrated = await this.userMapper.migrateAccountToIam(input.email, input.password);
413
- if (migrated) {
414
- this.logger.debug(`Migrated legacy user ${maskEmail(input.email)} to IAM`);
415
- }
414
+ await this.userMapper.migrateAccountToIam(input.email, input.password);
416
415
  } catch (error) {
417
416
  // Migration failure is not fatal - user might not exist in legacy or already migrated
418
417
  this.logger.debug(`Legacy migration check: ${error instanceof Error ? error.message : 'not needed'}`);
@@ -373,7 +373,7 @@ export class CoreBetterAuthResolver {
373
373
  const migrated = await this.userMapper.migrateAccountToIam(email, password);
374
374
  this.logger.debug(`[SignIn] Migration result for ${maskEmail(email)}: ${migrated}`);
375
375
  if (migrated) {
376
- this.logger.debug(`[SignIn] Migrated legacy user ${maskEmail(email)} to IAM, retrying sign-in`);
376
+ this.logger.debug(`[SignIn] IAM account of ${maskEmail(email)} is ready, retrying sign-in`);
377
377
  // Retry sign-in after migration with normalized password (as migrateAccountToIam stores it)
378
378
  const normalizedPassword = this.userMapper.normalizePasswordForIam(password);
379
379
  return this.attemptSignInDirect(email, normalizedPassword, api);
@@ -1086,7 +1086,9 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1086
1086
  }
1087
1087
  try {
1088
1088
  const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
1089
- const sessions: unknown = await context?.internalAdapter?.listSessions?.(userId);
1089
+ // Active sessions only — the query Better-Auth's own list-sessions runs. Without the filter the adapter's default
1090
+ // cap (100 rows, oldest first) could hide every current session behind expired rows MongoDB never removes.
1091
+ const sessions: unknown = await context?.internalAdapter?.listSessions?.(userId, { onlyActiveSessions: true });
1090
1092
  const match = (Array.isArray(sessions) ? sessions : []).find(
1091
1093
  (session: { id?: unknown; userId?: unknown }) =>
1092
1094
  String(session?.id) === sessionId && String(session?.userId) === String(userId),
package/src/index.ts CHANGED
@@ -56,6 +56,7 @@ export * from './core/common/helpers/process-diagnostics.helper.js';
56
56
  export * from './core/common/helpers/redact-secrets.helper.js';
57
57
  export * from './core/common/helpers/register-enum.helper.js';
58
58
  export * from './core/common/helpers/scim.helper.js';
59
+ export * from './core/common/helpers/server-url.helper.js';
59
60
  export * from './core/common/helpers/service.helper.js';
60
61
  export * from './core/common/helpers/swagger-enabled.helper.js';
61
62
  export * from './core/common/helpers/swagger.helper.js';
package/src/main.ts CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  handleFatalBootstrapError,
14
14
  installProcessDiagnostics,
15
15
  } from './core/common/helpers/process-diagnostics.helper.js';
16
+ import { serverDisplayUrl } from './core/common/helpers/server-url.helper.js';
16
17
  import { setupSwagger } from './core/common/helpers/swagger.helper.js';
17
18
  import { CorePersistenceModel } from './core/common/models/core-persistence.model.js';
18
19
  import { CoreAuthModel } from './core/modules/auth/core-auth.model.js';
@@ -129,7 +130,7 @@ async function bootstrap() {
129
130
 
130
131
  // Start server on configured port
131
132
  await server.listen(envConfig.port, envConfig.hostname);
132
- console.debug(`Server started at ${await server.getUrl()}`);
133
+ console.debug(`Server started at ${await serverDisplayUrl(server)}`);
133
134
 
134
135
  // Run command after server init
135
136
  if (envConfig.execAfterInit) {