@lenne.tech/nest-server 12.7.1 → 12.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.
Files changed (51) hide show
  1. package/.claude/rules/better-auth.md +11 -1
  2. package/.claude/rules/testing.md +6 -6
  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/better-auth-token.service.d.ts +1 -1
  15. package/dist/core/modules/better-auth/better-auth-token.service.js +2 -1
  16. package/dist/core/modules/better-auth/better-auth-token.service.js.map +1 -1
  17. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +4 -1
  18. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  19. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +2 -0
  20. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +33 -10
  21. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  22. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +2 -0
  23. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  24. package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -4
  25. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -1
  27. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  28. package/dist/core/modules/better-auth/core-better-auth.service.js +2 -1
  29. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/main.js +2 -1
  34. package/dist/main.js.map +1 -1
  35. package/migration-guides/12.6.x-to-12.7.x.md +21 -1
  36. package/migration-guides/12.7.1-to-12.7.2.md +115 -0
  37. package/migration-guides/12.7.2-to-12.7.3.md +49 -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/better-auth-token.service.ts +8 -3
  44. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +10 -2
  45. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +53 -11
  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 +8 -1
  50. package/src/index.ts +1 -0
  51. package/src/main.ts +2 -1
@@ -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 {
@@ -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);
@@ -26,6 +26,7 @@ import {
26
26
  shouldConvertSessionTokenToJwt,
27
27
  } from '../../common/helpers/cookies.helper.js';
28
28
  import { type ExpirySweep, scheduleExpirySweep } from '../../common/persistence/expiry-sweep.js';
29
+ import { isQueryableString } from '../../common/helpers/input.helper.js';
29
30
  import { maskEmail, maskToken } from '../../common/helpers/logging.helper.js';
30
31
  import { type IBetterAuth, ICookiesConfig } from '../../common/interfaces/server-options.interface.js';
31
32
  import { ConfigService } from '../../common/services/config.service.js';
@@ -1203,11 +1204,17 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
1203
1204
  * and returns the associated user. Useful for verifying session tokens
1204
1205
  * passed via Authorization header.
1205
1206
  *
1207
+ * A value that is not a non-empty string finds no session (DEV-4138): `token` reaches a raw `$match` below, so an
1208
+ * object such as `{ $ne: null }` — what cookie-parser makes of a `j:` cookie — would be read as a query operator and
1209
+ * select somebody else's session; on MySQL / MariaDB a number (`j:7`) is compared numerically and matches every token
1210
+ * starting with `7`. The check sits here, before both branches, because projects call this method with cookie values
1211
+ * of their own.
1212
+ *
1206
1213
  * @param token - The session token to look up
1207
1214
  * @returns Session and user data, or null if not found/expired
1208
1215
  */
1209
1216
  async getSessionByToken(token: string): Promise<SessionResult> {
1210
- if (!this.isEnabled()) {
1217
+ if (!isQueryableString(token) || !this.isEnabled()) {
1211
1218
  return { session: null, user: null };
1212
1219
  }
1213
1220
  const sql = getBetterAuthSqlStore();
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) {