@lenne.tech/nest-server 12.7.1 → 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.
- package/.claude/rules/better-auth.md +4 -1
- package/.claude/rules/testing.md +4 -4
- package/FRAMEWORK-API.md +1 -1
- package/dist/core/common/filters/http-exception-log.filter.js +7 -2
- package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
- package/dist/core/common/helpers/server-url.helper.d.ts +2 -0
- package/dist/core/common/helpers/server-url.helper.js +10 -0
- package/dist/core/common/helpers/server-url.helper.js.map +1 -0
- package/dist/core/common/services/email.service.d.ts +1 -0
- package/dist/core/common/services/email.service.js +7 -0
- package/dist/core/common/services/email.service.js.map +1 -1
- package/dist/core/modules/auth/services/core-auth.service.js +0 -1
- package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +4 -1
- package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +33 -10
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +2 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.controller.js +1 -4
- package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js +1 -1
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/main.js +2 -1
- package/dist/main.js.map +1 -1
- package/migration-guides/12.7.1-to-12.7.2.md +115 -0
- package/package.json +1 -1
- package/src/core/common/filters/http-exception-log.filter.ts +8 -2
- package/src/core/common/helpers/server-url.helper.ts +27 -0
- package/src/core/common/services/email.service.ts +18 -0
- package/src/core/modules/auth/services/core-auth.service.ts +1 -1
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +10 -2
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +53 -11
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +6 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -4
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +1 -1
- package/src/index.ts +1 -0
- package/src/main.ts +2 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lenne.tech/nest-server",
|
|
3
|
-
"version": "12.7.
|
|
3
|
+
"version": "12.7.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
|
|
6
6
|
"keywords": [
|
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
Catch,
|
|
4
4
|
ExceptionFilter,
|
|
5
5
|
HttpException,
|
|
6
|
+
HttpStatus,
|
|
6
7
|
Logger,
|
|
7
8
|
ServiceUnavailableException,
|
|
8
9
|
} from '@nestjs/common';
|
|
@@ -22,8 +23,13 @@ export class HttpExceptionLogFilter implements ExceptionFilter {
|
|
|
22
23
|
* Log exception
|
|
23
24
|
*/
|
|
24
25
|
catch(exception: HttpException, host: ArgumentsHost) {
|
|
25
|
-
// Log
|
|
26
|
-
|
|
26
|
+
// Log. A 404 is an answer, not a failure, so it gets one line without the stack (12.7.2, DEV-4128): the frontends
|
|
27
|
+
// ask `GET /ai/status` on every page, and with the AI module off each of those answers logged a stack trace.
|
|
28
|
+
if (exception.getStatus() === HttpStatus.NOT_FOUND) {
|
|
29
|
+
exceptionLogger.debug(`404 ${exception.message}`);
|
|
30
|
+
} else {
|
|
31
|
+
exceptionLogger.debug(exception.stack);
|
|
32
|
+
}
|
|
27
33
|
|
|
28
34
|
// GraphQL
|
|
29
35
|
const type = host.getType<GqlContextType>();
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { INestApplication } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The address of a listening server, written the way a person opens it in a browser (12.7.2, DEV-4128).
|
|
5
|
+
*
|
|
6
|
+
* `app.getUrl()` reports a server bound to every interface as `http://[::1]:3000` (bound to `::`, Node's default when
|
|
7
|
+
* no host is given) or `http://127.0.0.1:3000` (bound to `0.0.0.0`). Both are loopback addresses of ONE family, and
|
|
8
|
+
* which one a copied address reaches depends on the system — `[::1]` fails where IPv6 loopback is not routed. For a
|
|
9
|
+
* wildcard bind this answers `http://localhost:<port>` instead, which reaches the server on either family. A server
|
|
10
|
+
* bound to one explicit address keeps that address: only it is guaranteed to answer there.
|
|
11
|
+
*
|
|
12
|
+
* Use it for the start message in `main.ts`:
|
|
13
|
+
*
|
|
14
|
+
* ```typescript
|
|
15
|
+
* await server.listen(envConfig.port, envConfig.hostname);
|
|
16
|
+
* console.debug(`Server started at ${await serverDisplayUrl(server)}`);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export async function serverDisplayUrl(app: INestApplication): Promise<string> {
|
|
20
|
+
const url = await app.getUrl();
|
|
21
|
+
const bound = app.getHttpServer?.()?.address?.();
|
|
22
|
+
const host = bound && typeof bound === 'object' ? bound.address : undefined;
|
|
23
|
+
if (host !== '::' && host !== '0.0.0.0') {
|
|
24
|
+
return url;
|
|
25
|
+
}
|
|
26
|
+
return url.replace(/^([a-z][a-z0-9+.-]*:\/\/)(\[::1\]|127\.0\.0\.1)(?=:\d+$)/i, '$1localhost');
|
|
27
|
+
}
|
|
@@ -105,6 +105,24 @@ export class EmailService implements OnModuleDestroy {
|
|
|
105
105
|
return undefined;
|
|
106
106
|
}
|
|
107
107
|
|
|
108
|
+
/**
|
|
109
|
+
* Whether a mail sent with this transport configuration actually leaves the process (12.7.2, DEV-4131).
|
|
110
|
+
*
|
|
111
|
+
* nodemailer's `jsonTransport` and `streamTransport` only RENDER a mail: `sendMail()` resolves like a delivery, and
|
|
112
|
+
* nothing is sent. A starter-based project uses `jsonTransport` locally whenever no `SMTP_HOST` is set, so a caller
|
|
113
|
+
* that logs "sent" after `sendMail()` tells a developer a mail is on its way that never will be. Ask this before
|
|
114
|
+
* claiming a delivery. A send the Hub mailbox captured answers `captured: true` instead — see `sendMail()`.
|
|
115
|
+
*
|
|
116
|
+
* @param smtp - The transport options to judge; defaults to `email.smtp` from the configuration.
|
|
117
|
+
*/
|
|
118
|
+
public deliversMail(smtp: MailTransportOptions = this.configService.get('email.smtp')): boolean {
|
|
119
|
+
if (typeof smtp !== 'object' || smtp === null) {
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
const options = smtp as Record<string, unknown>;
|
|
123
|
+
return !options.jsonTransport && !options.streamTransport;
|
|
124
|
+
}
|
|
125
|
+
|
|
108
126
|
onModuleDestroy(): void {
|
|
109
127
|
if (this.cachedTransporter) {
|
|
110
128
|
this.cachedTransporter.close();
|
|
@@ -538,7 +538,7 @@ export class CoreAuthService {
|
|
|
538
538
|
const migrated = await this.betterAuthUserMapper.migrateAccountToIam(email, plainPassword);
|
|
539
539
|
|
|
540
540
|
if (migrated) {
|
|
541
|
-
|
|
541
|
+
// The mapper logs a real migration itself, with the address masked (12.7.2, DEV-4128)
|
|
542
542
|
|
|
543
543
|
// Refresh user to get updated iamId
|
|
544
544
|
const updatedUser = await this.userService.getViaEmail(email, { force: true });
|
|
@@ -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
|
-
|
|
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.
|
|
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.
|
|
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 (
|
|
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
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
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
|
-
|
|
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]
|
|
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);
|
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
|
|
133
|
+
console.debug(`Server started at ${await serverDisplayUrl(server)}`);
|
|
133
134
|
|
|
134
135
|
// Run command after server init
|
|
135
136
|
if (envConfig.execAfterInit) {
|