@lenne.tech/nest-server 12.7.3 → 12.8.1
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 +13 -0
- package/.claude/rules/configurable-features.md +3 -0
- package/.claude/rules/testing.md +5 -5
- package/FRAMEWORK-API.md +2 -2
- package/dist/core/common/interfaces/server-options.interface.d.ts +2 -0
- package/dist/core/common/middlewares/string-cookies.middleware.d.ts +12 -0
- package/dist/core/common/middlewares/string-cookies.middleware.js +50 -0
- package/dist/core/common/middlewares/string-cookies.middleware.js.map +1 -0
- package/dist/core/common/pipes/map-and-validate.pipe.d.ts +2 -0
- package/dist/core/common/pipes/map-and-validate.pipe.js +15 -0
- package/dist/core/common/pipes/map-and-validate.pipe.js.map +1 -1
- package/dist/core/modules/auth/services/core-auth.service.js +3 -0
- 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 +2 -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 +6 -1
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
- 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.d.ts +2 -0
- package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -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 +13 -5
- 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 +7 -2
- package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
- package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
- package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
- package/dist/core/modules/error-code/error-codes.d.ts +9 -0
- package/dist/core/modules/error-code/error-codes.js +8 -0
- package/dist/core/modules/error-code/error-codes.js.map +1 -1
- package/dist/core.module.js +2 -0
- package/dist/core.module.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/server/modules/error-code/error-codes.d.ts +1 -0
- package/docs/REQUEST-LIFECYCLE.md +27 -0
- package/migration-guides/12.7.x-to-12.8.x.md +152 -0
- package/migration-guides/12.8.0-to-12.8.1.md +85 -0
- package/package.json +2 -2
- package/src/core/common/interfaces/server-options.interface.ts +45 -4
- package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
- package/src/core/common/pipes/map-and-validate.pipe.ts +40 -0
- package/src/core/modules/auth/services/core-auth.service.ts +8 -0
- package/src/core/modules/better-auth/README.md +9 -3
- package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +44 -9
- package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
- package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
- package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
- package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
- package/src/core/modules/error-code/error-codes.ts +13 -0
- package/src/core.module.ts +5 -0
- package/src/index.ts +1 -0
|
@@ -233,10 +233,8 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
233
233
|
let sent = false;
|
|
234
234
|
|
|
235
235
|
try {
|
|
236
|
-
//
|
|
237
|
-
|
|
238
|
-
url = this.buildFrontendVerificationUrl(token);
|
|
239
|
-
}
|
|
236
|
+
// The app's verification page when callbackURL is configured, Better-Auth's own link otherwise
|
|
237
|
+
url = this.verificationMailUrl({ token, url });
|
|
240
238
|
|
|
241
239
|
this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
|
|
242
240
|
|
|
@@ -731,20 +729,57 @@ export class CoreBetterAuthEmailVerificationService {
|
|
|
731
729
|
}
|
|
732
730
|
}
|
|
733
731
|
|
|
732
|
+
/**
|
|
733
|
+
* The link the verification mail carries: the app's verification page when `callbackURL` is configured and resolves
|
|
734
|
+
* ({@link buildFrontendVerificationUrl}), otherwise the link Better-Auth built (`<baseUrl>/<basePath>/verify-email`,
|
|
735
|
+
* token sealed), which verifies on the API and redirects from there.
|
|
736
|
+
*
|
|
737
|
+
* A relative `callbackURL` with no resolvable app URL keeps Better-Auth's link and warns once — a guessed host
|
|
738
|
+
* would 404 (DEV-4140).
|
|
739
|
+
*/
|
|
740
|
+
protected verificationMailUrl(options: { token: string; url: string }): string {
|
|
741
|
+
if (!this.config.callbackURL) {
|
|
742
|
+
return options.url;
|
|
743
|
+
}
|
|
744
|
+
const frontendUrl = this.buildFrontendVerificationUrl(options.token);
|
|
745
|
+
if (frontendUrl === undefined && !this.warnedAboutMissingAppUrl) {
|
|
746
|
+
this.warnedAboutMissingAppUrl = true;
|
|
747
|
+
this.logger.warn(
|
|
748
|
+
`No app URL resolves for the verification link (callbackURL "${this.config.callbackURL}" is relative, appUrl is ` +
|
|
749
|
+
'unset and baseUrl gives none): the mail links to the API instead of the app page. Set NSC__APP_URL, or ' +
|
|
750
|
+
'NSC__BASE_URL to derive it from.',
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
return frontendUrl ?? options.url;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Whether {@link verificationMailUrl} already warned that no app URL resolves (once per process) */
|
|
757
|
+
protected warnedAboutMissingAppUrl = false;
|
|
758
|
+
|
|
734
759
|
/**
|
|
735
760
|
* Build the frontend verification URL from the configured callbackURL and token.
|
|
736
761
|
*
|
|
737
|
-
* Resolves relative
|
|
762
|
+
* Resolves a relative `callbackURL` against the app URL the rest of the framework uses
|
|
763
|
+
* (`resolveAppUrlFromConfig()`: explicit `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from
|
|
764
|
+
* `baseUrl` unless `cors.deriveAppUrl` is `false`). Appends the token as a query parameter.
|
|
765
|
+
*
|
|
766
|
+
* Until DEV-4140 a relative value was resolved against `appUrl || 'http://localhost:3001'`, so every deployed stage
|
|
767
|
+
* without `NSC__APP_URL` mailed a link to localhost — while the password-reset link next to it already derived the
|
|
768
|
+
* app from `baseUrl`.
|
|
738
769
|
*
|
|
739
770
|
* @param token - The verification token from Better-Auth
|
|
740
|
-
* @returns The full frontend URL with token query parameter
|
|
771
|
+
* @returns The full frontend URL with token query parameter, or `undefined` for a relative `callbackURL` when no app
|
|
772
|
+
* URL resolves (the caller then keeps Better-Auth's own link)
|
|
741
773
|
*/
|
|
742
|
-
protected buildFrontendVerificationUrl(token: string): string {
|
|
774
|
+
protected buildFrontendVerificationUrl(token: string): string | undefined {
|
|
743
775
|
let baseUrl = this.config.callbackURL!;
|
|
744
776
|
|
|
745
|
-
// Resolve relative paths against
|
|
777
|
+
// Resolve relative paths against the app URL — the SAME resolver as the password-reset link
|
|
746
778
|
if (baseUrl.startsWith('/')) {
|
|
747
|
-
const appUrl = this.configService
|
|
779
|
+
const appUrl = resolveAppUrlFromConfig(this.configService);
|
|
780
|
+
if (!appUrl) {
|
|
781
|
+
return undefined;
|
|
782
|
+
}
|
|
748
783
|
baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
|
|
749
784
|
}
|
|
750
785
|
|
|
@@ -241,6 +241,29 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
241
241
|
* @param sessionUser - The Better-Auth session user
|
|
242
242
|
* @returns A mapped user with role capabilities
|
|
243
243
|
*/
|
|
244
|
+
/**
|
|
245
|
+
* The mapped user of a Better-Auth user that is stored nowhere, from its own fields only (12.8.1).
|
|
246
|
+
*
|
|
247
|
+
* The placeholder Better-Auth answers a sign-up for an already registered address with (see
|
|
248
|
+
* `CoreBetterAuthService.isPersistedUser()`) must look like a new user: its own id, no roles, not verified. Looking it
|
|
249
|
+
* up by address, as {@link mapSessionUser} does, found the real account and answered its id and roles.
|
|
250
|
+
*/
|
|
251
|
+
mapUnstoredSessionUser(sessionUser: BetterAuthSessionUser): MappedUser | null {
|
|
252
|
+
if (!sessionUser?.id || !sessionUser?.email) {
|
|
253
|
+
return null;
|
|
254
|
+
}
|
|
255
|
+
return this.createMappedUser({
|
|
256
|
+
email: sessionUser.email,
|
|
257
|
+
emailVerified: sessionUser.emailVerified,
|
|
258
|
+
iamId: sessionUser.id,
|
|
259
|
+
id: sessionUser.id,
|
|
260
|
+
image: sessionUser.image,
|
|
261
|
+
name: sessionUser.name,
|
|
262
|
+
roles: [],
|
|
263
|
+
verified: sessionUser.emailVerified,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
244
267
|
async mapSessionUser(sessionUser: BetterAuthSessionUser): Promise<MappedUser | null> {
|
|
245
268
|
if (!sessionUser?.id || !sessionUser?.email) {
|
|
246
269
|
return null;
|
|
@@ -465,6 +488,24 @@ export class CoreBetterAuthUserMapper implements OnApplicationBootstrap, OnModul
|
|
|
465
488
|
* @param plainPassword - The plain password to hash with bcrypt
|
|
466
489
|
* @returns true if sync was successful, false otherwise
|
|
467
490
|
*/
|
|
491
|
+
/**
|
|
492
|
+
* Spends the time {@link syncPasswordToLegacy} spends on a password, and writes nothing (12.8.1).
|
|
493
|
+
*
|
|
494
|
+
* A sign-up for an already registered address writes nothing (see `CoreBetterAuthService.isPersistedUser()`).
|
|
495
|
+
* Without this it would answer a bcrypt round faster than a real sign-up, and the response time would tell which
|
|
496
|
+
* addresses have an account — the enumeration Better-Auth's placeholder answer exists to prevent.
|
|
497
|
+
*/
|
|
498
|
+
async equalizeLegacyPasswordSync(plainPassword?: string): Promise<void> {
|
|
499
|
+
if (!plainPassword) {
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
await bcrypt.hash(this.normalizePasswordForIam(plainPassword), 10);
|
|
504
|
+
} catch {
|
|
505
|
+
// Timing only — nothing depends on the result
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
468
509
|
async syncPasswordToLegacy(iamUserId: string, userEmail: string, plainPassword?: string): Promise<boolean> {
|
|
469
510
|
const sql = getBetterAuthSqlStore();
|
|
470
511
|
if (sql) {
|
|
@@ -611,17 +611,31 @@ export class CoreBetterAuthController {
|
|
|
611
611
|
}
|
|
612
612
|
|
|
613
613
|
if (hasUser(response)) {
|
|
614
|
-
//
|
|
615
|
-
//
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
614
|
+
// An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
|
|
615
|
+
// like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
|
|
616
|
+
// re-pointed the real account found by address and overwrote its legacy password with the caller's (12.8.1).
|
|
617
|
+
// The answer below stays that of a new sign-up; only the writes are left out.
|
|
618
|
+
const isPlaceholder = !(await this.betterAuthService.isPersistedUser(response.user.id));
|
|
619
|
+
|
|
620
|
+
if (isPlaceholder) {
|
|
621
|
+
// The same bcrypt round as the legacy sync, so the response time does not tell the address exists
|
|
622
|
+
await this.userMapper.equalizeLegacyPasswordSync(input.password);
|
|
623
|
+
} else {
|
|
624
|
+
// Link or create user in our database
|
|
625
|
+
// Pass termsAndPrivacyAccepted to store the acceptance timestamp
|
|
626
|
+
await this.userMapper.linkOrCreateUser(response.user, {
|
|
627
|
+
termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
|
|
628
|
+
});
|
|
629
|
+
|
|
630
|
+
// Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
|
|
631
|
+
// Pass the plain password so it can be hashed with bcrypt for Legacy Auth
|
|
632
|
+
await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
|
|
633
|
+
}
|
|
623
634
|
|
|
624
|
-
|
|
635
|
+
// A new user has no roles yet; the placeholder must not carry those of the account it stands for
|
|
636
|
+
const mappedUser = isPlaceholder
|
|
637
|
+
? this.userMapper.mapUnstoredSessionUser(response.user)
|
|
638
|
+
: await this.userMapper.mapSessionUser(response.user);
|
|
625
639
|
|
|
626
640
|
// Get token: JWT accessToken > top-level token > session.token
|
|
627
641
|
// Without this, no session cookies are set after sign-up, causing 401 on
|
|
@@ -484,10 +484,20 @@ export class CoreBetterAuthResolver {
|
|
|
484
484
|
if (hasUser(response)) {
|
|
485
485
|
const sessionUser: BetterAuthSessionUser = response.user;
|
|
486
486
|
|
|
487
|
+
// An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
|
|
488
|
+
// like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
|
|
489
|
+
// re-pointed the real account found by address, and the answer carried that account's id and roles (12.8.1).
|
|
490
|
+
// The answer stays that of a new sign-up; only the write is left out.
|
|
491
|
+
const isPlaceholder = !(await this.betterAuthService.isPersistedUser(sessionUser.id));
|
|
492
|
+
|
|
487
493
|
// Link or create user in our database
|
|
488
494
|
// Pass termsAndPrivacyAccepted to store the acceptance timestamp
|
|
489
|
-
|
|
490
|
-
|
|
495
|
+
if (!isPlaceholder) {
|
|
496
|
+
await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
|
|
497
|
+
}
|
|
498
|
+
const mappedUser = isPlaceholder
|
|
499
|
+
? this.userMapper.mapUnstoredSessionUser(sessionUser)
|
|
500
|
+
: await this.userMapper.mapSessionUser(sessionUser);
|
|
491
501
|
|
|
492
502
|
// If email verification is enabled, revoke the session and don't return session data
|
|
493
503
|
// The user must verify their email before they can use any session
|
|
@@ -1101,6 +1101,34 @@ export class CoreBetterAuthService implements OnApplicationBootstrap, OnModuleDe
|
|
|
1101
1101
|
}
|
|
1102
1102
|
}
|
|
1103
1103
|
|
|
1104
|
+
/**
|
|
1105
|
+
* Whether Better-Auth has stored the user `userId` — false for the placeholder it answers a sign-up with when the
|
|
1106
|
+
* address is already registered (12.8.1).
|
|
1107
|
+
*
|
|
1108
|
+
* With `emailAndPassword.requireEmailVerification: true` or `autoSignIn: false`, Better-Auth answers a sign-up for a
|
|
1109
|
+
* known address like a new one (enumeration protection): `{ token: null, user: <a generated id, the given address> }`.
|
|
1110
|
+
* That user exists nowhere. The sign-up paths linked it to the app user found by address — the real account then
|
|
1111
|
+
* carried the placeholder's id and `verified: false`, its legacy password became the one the caller chose, and the
|
|
1112
|
+
* answer carried its roles. A sign-up therefore writes only for a user this confirms. Asked through Better-Auth's own
|
|
1113
|
+
* adapter (`internalAdapter.findUserById()`), so it reads wherever Better-Auth keeps its users.
|
|
1114
|
+
*
|
|
1115
|
+
* @returns `false` for an unknown id, an empty id, and a failed lookup — a sign-up that cannot confirm the user writes
|
|
1116
|
+
* nothing rather than guessing
|
|
1117
|
+
*/
|
|
1118
|
+
async isPersistedUser(userId: string): Promise<boolean> {
|
|
1119
|
+
if (typeof userId !== 'string' || !userId) {
|
|
1120
|
+
return false;
|
|
1121
|
+
}
|
|
1122
|
+
try {
|
|
1123
|
+
const context = await (this.getInstance() as { $context?: Promise<any> } | null)?.$context;
|
|
1124
|
+
const user: unknown = await context?.internalAdapter?.findUserById?.(userId);
|
|
1125
|
+
return !!user && String((user as { id?: unknown }).id) === userId;
|
|
1126
|
+
} catch (error) {
|
|
1127
|
+
this.logger.error(`isPersistedUser error: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
|
1128
|
+
return false;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1104
1132
|
/**
|
|
1105
1133
|
* Revokes a specific session (logout for that session)
|
|
1106
1134
|
*
|
|
@@ -503,6 +503,19 @@ export const LtnsErrors = {
|
|
|
503
503
|
},
|
|
504
504
|
},
|
|
505
505
|
|
|
506
|
+
/**
|
|
507
|
+
* An object arrived where the route declares a string, number or boolean (`@Body('token') token: string`) — the
|
|
508
|
+
* shape a MongoDB operator takes (`{ "$ne": null }`). Answered by `MapAndValidatePipe` (12.8.0, DEV-4144).
|
|
509
|
+
*/
|
|
510
|
+
INVALID_PARAMETER_TYPE: {
|
|
511
|
+
code: 'LTNS_0306',
|
|
512
|
+
message: 'Invalid parameter type',
|
|
513
|
+
translations: {
|
|
514
|
+
de: 'Ein Parameter hat einen ungültigen Typ.',
|
|
515
|
+
en: 'A parameter has an invalid type.',
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
|
|
506
519
|
// =====================================================
|
|
507
520
|
// Resource Errors (LTNS_0400-LTNS_0499)
|
|
508
521
|
// =====================================================
|
package/src/core.module.ts
CHANGED
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
} from './core/common/interfaces/server-options.interface.js';
|
|
39
39
|
import { RequestContextMiddleware } from './core/common/middleware/request-context.middleware.js';
|
|
40
40
|
import { SecurityHeadersMiddleware } from './core/common/middlewares/security-headers.middleware.js';
|
|
41
|
+
import { StringCookiesMiddleware } from './core/common/middlewares/string-cookies.middleware.js';
|
|
41
42
|
import { CorePersistenceLifecycle } from './core/common/persistence/core-persistence.lifecycle.js';
|
|
42
43
|
import { CorePersistenceModule } from './core/common/persistence/core-persistence.module.js';
|
|
43
44
|
import {
|
|
@@ -115,6 +116,10 @@ export class CoreModule implements NestModule {
|
|
|
115
116
|
// RequestContext middleware must run for all routes to provide AsyncLocalStorage context
|
|
116
117
|
consumer.apply(RequestContextMiddleware).forRoutes('*');
|
|
117
118
|
|
|
119
|
+
// No non-string values in the parsed cookies (cookie-parser turns `j:{...}` into an object, the shape of a MongoDB
|
|
120
|
+
// operator — DEV-4138 / DEV-4144). Before every other middleware and every guard, so none of them sees one.
|
|
121
|
+
consumer.apply(StringCookiesMiddleware).forRoutes('*');
|
|
122
|
+
|
|
118
123
|
// Security headers on EVERY response, guards' rejections included. Middleware rather than an
|
|
119
124
|
// interceptor for exactly that reason: an interceptor never runs for a request a guard turns
|
|
120
125
|
// away, and those are the ones an attacker generates most of. The middleware itself decides
|
package/src/index.ts
CHANGED
|
@@ -84,6 +84,7 @@ export * from './core/common/interfaces/swagger-setup-options.interface.js';
|
|
|
84
84
|
export * from './core/common/middleware/request-context.middleware.js';
|
|
85
85
|
export * from './core/common/middlewares/to-lower-case.middleware.js';
|
|
86
86
|
export * from './core/common/middlewares/security-headers.middleware.js';
|
|
87
|
+
export * from './core/common/middlewares/string-cookies.middleware.js';
|
|
87
88
|
export * from './core/common/models/core-model.model.js';
|
|
88
89
|
export * from './core/common/models/core-persistence.model.js';
|
|
89
90
|
export * from './core/common/models/pagination-info.model.js';
|