@lenne.tech/nest-server 11.43.10 → 11.44.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.
Files changed (85) hide show
  1. package/.claude/rules/better-auth.md +44 -4
  2. package/.claude/rules/configurable-features.md +4 -1
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +2 -2
  5. package/dist/config.env.js +2 -2
  6. package/dist/config.env.js.map +1 -1
  7. package/dist/core/common/interfaces/server-options.interface.d.ts +3 -0
  8. package/dist/core/common/middlewares/string-cookies.middleware.d.ts +12 -0
  9. package/dist/core/common/middlewares/string-cookies.middleware.js +54 -0
  10. package/dist/core/common/middlewares/string-cookies.middleware.js.map +1 -0
  11. package/dist/core/common/pipes/map-and-validate.pipe.d.ts +2 -0
  12. package/dist/core/common/pipes/map-and-validate.pipe.js +16 -0
  13. package/dist/core/common/pipes/map-and-validate.pipe.js.map +1 -1
  14. package/dist/core/modules/auth/services/core-auth.service.js +3 -0
  15. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  16. package/dist/core/modules/better-auth/better-auth.config.js +2 -0
  17. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  18. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
  19. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +7 -1
  21. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
  22. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  23. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.d.ts +8 -0
  24. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js +70 -0
  25. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js.map +1 -0
  26. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +2 -1
  27. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  28. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +5 -3
  30. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
  32. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
  33. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  34. package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
  35. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  36. package/dist/core/modules/better-auth/core-better-auth.module.js +2 -0
  37. package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
  38. package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
  39. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  40. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  41. package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
  42. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  43. package/dist/core/modules/better-auth/index.d.ts +1 -0
  44. package/dist/core/modules/better-auth/index.js +1 -0
  45. package/dist/core/modules/better-auth/index.js.map +1 -1
  46. package/dist/core/modules/error-code/error-codes.d.ts +18 -0
  47. package/dist/core/modules/error-code/error-codes.js +16 -0
  48. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  49. package/dist/core.module.js +2 -0
  50. package/dist/core.module.js.map +1 -1
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/server/modules/error-code/error-codes.d.ts +2 -0
  55. package/dist/tsconfig.build.tsbuildinfo +1 -1
  56. package/docs/REQUEST-LIFECYCLE.md +26 -0
  57. package/docs/error-codes.md +14 -0
  58. package/migration-guides/11.13.x-to-11.14.0.md +5 -5
  59. package/migration-guides/11.43.x-to-11.44.x.md +147 -0
  60. package/migration-guides/11.44.0-to-11.44.1.md +152 -0
  61. package/package.json +2 -2
  62. package/src/config.env.ts +6 -2
  63. package/src/core/common/interfaces/server-options.interface.ts +65 -9
  64. package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
  65. package/src/core/common/pipes/map-and-validate.pipe.ts +38 -0
  66. package/src/core/modules/auth/services/core-auth.service.ts +8 -0
  67. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +3 -0
  68. package/src/core/modules/better-auth/README.md +34 -4
  69. package/src/core/modules/better-auth/better-auth.config.ts +9 -0
  70. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
  71. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +45 -9
  72. package/src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts +85 -0
  73. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +5 -2
  74. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +14 -7
  75. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
  76. package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
  77. package/src/core/modules/better-auth/core-better-auth.module.ts +12 -2
  78. package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
  79. package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
  80. package/src/core/modules/better-auth/index.ts +1 -0
  81. package/src/core/modules/error-code/error-codes.ts +22 -0
  82. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +10 -4
  83. package/src/core/modules/system-setup/README.md +5 -5
  84. package/src/core.module.ts +5 -0
  85. package/src/index.ts +1 -0
@@ -695,15 +695,47 @@ function processNonWhitelistedFields(
695
695
  return forbiddenKeys;
696
696
  }
697
697
 
698
+ /** The declared parameter types a request value must not arrive as an object for */
699
+ const PRIMITIVE_METATYPES: readonly unknown[] = [String, Number, Boolean];
700
+
701
+ /**
702
+ * Whether a request value is an object where the route declares a string, number or boolean (DEV-4144).
703
+ *
704
+ * `@Body('token') token: string` has `metatype === String`, and the pipe used to return a basic-type value unchecked —
705
+ * the declared type is erased at runtime. `{ "token": { "$ne": null } }` therefore reached the service as an object,
706
+ * and a MongoDB filter read it as an operator (DEV-4143: a reset token that set somebody else's password). Only a
707
+ * PLAIN OBJECT is refused: an operator always is one. `null` passes (clearing an optional field is legitimate; the
708
+ * query guards handle it), and so does an array (a repeated query key, `?tag=a&tag=b`, arrives as one and selects
709
+ * nothing in a filter). A parameter typed as a class, as `any` or as a union the compiler emits as `Object` is not
710
+ * covered — its value is validated by its DTO or by the guard at the query. (`tsc` with `strictNullChecks` emits
711
+ * `string | undefined` as `Object`; SWC and `tsc` without it emit `String`, and the parameter is covered.)
712
+ *
713
+ * Exported for tests and for project pipes that replace this one.
714
+ */
715
+ export function receivesObjectForPrimitive(value: unknown, metadata: ArgumentMetadata): boolean {
716
+ return (
717
+ (metadata.type === 'body' || metadata.type === 'query' || metadata.type === 'param') &&
718
+ PRIMITIVE_METATYPES.includes(metadata.metatype) &&
719
+ value !== null &&
720
+ typeof value === 'object' &&
721
+ !Array.isArray(value)
722
+ );
723
+ }
724
+
698
725
  @Injectable()
699
726
  export class MapAndValidatePipe implements PipeTransform {
700
727
  private readonly nonWhitelistedFieldsMode: 'strip' | 'error' | false = 'strip';
728
+ private readonly rejectObjectsForPrimitiveTypes: boolean = true;
701
729
 
702
730
  constructor() {
703
731
  const pipeConfig = ConfigService.getFastButReadOnly('security.mapAndValidatePipe');
704
732
  if (typeof pipeConfig === 'object' && pipeConfig?.nonWhitelistedFields !== undefined) {
705
733
  this.nonWhitelistedFieldsMode = pipeConfig.nonWhitelistedFields;
706
734
  }
735
+ // Only an explicit `false` switches the check off — a security default must not fall to a typo or a string
736
+ if (typeof pipeConfig === 'object' && pipeConfig?.rejectObjectsForPrimitiveTypes === false) {
737
+ this.rejectObjectsForPrimitiveTypes = false;
738
+ }
707
739
  }
708
740
 
709
741
  async transform(value: any, metadata: ArgumentMetadata) {
@@ -713,6 +745,12 @@ export class MapAndValidatePipe implements PipeTransform {
713
745
  return value;
714
746
  }
715
747
 
748
+ // An object where the route declares a string, number or boolean is the shape of a MongoDB operator
749
+ // ({ "$ne": null }) and never a value the route can use — refused before anything reaches a query (DEV-4144)
750
+ if (this.rejectObjectsForPrimitiveTypes && receivesObjectForPrimitive(value, metadata)) {
751
+ throw new BadRequestException(`${ErrorCode.INVALID_PARAMETER_TYPE} [${metadata.data ?? metadata.type}]`);
752
+ }
753
+
716
754
  const { metatype } = metadata;
717
755
 
718
756
  if (DEBUG_VALIDATION) {
@@ -591,6 +591,14 @@ export class CoreAuthService {
591
591
 
592
592
  // Link or create Legacy user with iamId
593
593
  const iamUser = response.user as { email: string; id: string; name?: string };
594
+
595
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
596
+ // with a placeholder user it never stored. Linking it re-pointed the real account, overwrote its password with
597
+ // the caller's, and this method then returned that account — the caller got its tokens (11.44.1). The legacy
598
+ // sign-up has always answered a known address with this error, so the IAM path does the same.
599
+ if (!(await this.betterAuthService.isPersistedUser(iamUser.id))) {
600
+ throw new BadRequestException('Email address already in use');
601
+ }
594
602
  const syncedUser = await this.betterAuthUserMapper.linkOrCreateUser(iamUser as any, {
595
603
  firstName: inputAny.firstName,
596
604
  lastName: inputAny.lastName,
@@ -448,6 +448,9 @@ After integration, verify:
448
448
  - [ ] GraphQL `betterAuthSignUp` returns error `LTNS_0026`
449
449
  - [ ] `GET /iam/features` reports `signUpEnabled: false`
450
450
  - [ ] Sign-in still works for existing users
451
+ - [ ] With a social provider: a first social sign-in of an unknown user creates no account (`error=signup_disabled`),
452
+ an existing user still signs in through it. A provider meant for self-registration carries
453
+ `disableSignUp: false` (11.44.1+)
451
454
 
452
455
  ### Additional checks for Migration scenario:
453
456
 
@@ -622,13 +622,31 @@ When disabled:
622
622
  - REST `POST /iam/sign-up/email` returns `400 Bad Request` with error `LTNS_0026`
623
623
  - GraphQL `betterAuthSignUp` mutation returns error `LTNS_0026`
624
624
  - `betterAuthFeatures` reports `signUpEnabled: false`
625
- - Sign-in continues to work for existing users
625
+ - A first sign-in through a social provider creates no account (since 11.44.1, 12.3.0 on 12.x): the OAuth callback redirects with
626
+ `error=signup_disabled`, `/sign-in/social` with an `idToken` answers 401 `signup disabled`
627
+ - Sign-in continues to work for existing users, through e-mail and every social provider
626
628
 
627
629
  **Defense in Depth:** The flag is enforced at two layers:
628
630
 
629
631
  1. **Custom check** (`CoreBetterAuthService.ensureSignUpEnabled()`) runs in Controller/Resolver _before_ any BetterAuth API call and returns a structured `LTNS_0026` error.
630
632
  2. **Native BetterAuth** `emailAndPassword.disableSignUp` acts as a safety net for any direct API access that bypasses the custom check.
631
633
 
634
+ **Social providers:** Better-Auth reads `emailAndPassword.disableSignUp` for `/sign-up/email` only and decides a social
635
+ sign-up per provider, so `buildSocialProviders()` hands every provider the flag as its own `disableSignUp`. One provider
636
+ can deviate on purpose:
637
+
638
+ ```typescript
639
+ socialProviders: {
640
+ google: { clientId: '...', clientSecret: '...', disableSignUp: false }, // new users through Google despite the global flag
641
+ github: { clientId: '...', clientSecret: '...', disableSignUp: true }, // closed for GitHub even while sign-up is open
642
+ },
643
+ ```
644
+
645
+ Only a boolean counts on the provider; any other value follows `emailAndPassword.disableSignUp`, so a string from
646
+ `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.options.plugins`
647
+ (Generic OAuth, Magic Link, …) are not covered and need their own sign-up options. Before 11.44.1 every provider created
648
+ accounts whatever `disableSignUp` said.
649
+
632
650
  **Default:** `false` (sign-up enabled) - fully backward compatible.
633
651
 
634
652
  ### Additional User Fields
@@ -2014,11 +2032,17 @@ When a user is deleted:
2014
2032
  db.account.findOne({ userId: ObjectId('...'), providerId: 'credential' });
2015
2033
  ```
2016
2034
 
2017
- From better-auth 1.7 the row must ALSO carry `issuer: 'local:credential'`. A row matching only
2018
- `providerId` is not usable — better-auth keys accounts by `(issuer, accountId)` and will not find
2019
- it, so sign-in answers 401 while this query happily reports that the account exists:
2035
+ On better-auth 1.7.3 and later (nest-server requires 1.7.16 or later) that query is the whole
2036
+ check: rows carry no `issuer`, and an `issuer` filter finds nothing for every user — that is
2037
+ expected, not the cause of a 401. Do not write `issuer` fields by hand.
2038
+
2039
+ Only on better-auth 1.7.0–1.7.2 (see [Boot-Time Behaviour](#boot-time-behaviour)) must the row ALSO
2040
+ carry `issuer: 'local:credential'`. There a row matching only `providerId` is not usable — those
2041
+ versions key accounts by `(issuer, accountId)` and will not find it, so sign-in answers 401 while
2042
+ the query above reports that the account exists:
2020
2043
 
2021
2044
  ```javascript
2045
+ // better-auth 1.7.0–1.7.2 only
2022
2046
  db.account.findOne({ issuer: 'local:credential', providerId: 'credential', userId: ObjectId('...') });
2023
2047
  ```
2024
2048
 
@@ -2172,6 +2196,12 @@ These endpoints bypass rate limiting entirely:
2172
2196
  - `/session` - Session checks (frequent client-side calls)
2173
2197
  - `/callback` - OAuth callbacks
2174
2198
 
2199
+ Entries match whole path segments of the path the request is served under (dot segments resolved, case-insensitive, as Express routes): `/sign-in` covers
2200
+ `/sign-in/email`, `/session` does not cover `/sessions-export`. A request whose path under the base path carries a
2201
+ `.` or `..` segment (also `%2e`-encoded), a backslash, an encoded `/` or `\`, or a `#` is refused with 400
2202
+ (`#LTNS_0305: Invalid request path`) before the limiter runs — no route needs such a path, and the limiter and
2203
+ Better-Auth would otherwise read it as two different routes.
2204
+
2175
2205
  ### Response Headers
2176
2206
 
2177
2207
  When rate limiting is enabled, the following headers are added to responses:
@@ -386,6 +386,7 @@ interface PasskeyNormalizationResult {
386
386
  interface SocialProviderConfig {
387
387
  clientId: string;
388
388
  clientSecret: string;
389
+ disableSignUp: boolean;
389
390
  }
390
391
 
391
392
  /**
@@ -1021,9 +1022,16 @@ function serverOnlyPlugin<T extends BetterAuthPlugin>(plugin: T): T {
1021
1022
  * Builds the social providers configuration object dynamically.
1022
1023
  * Iterates over all configured providers and includes those that are enabled
1023
1024
  * with valid clientId and clientSecret.
1025
+ *
1026
+ * `emailAndPassword.disableSignUp: true` closes every way to a new account (11.44.1, 12.3.0 on 12.x). Better-Auth reads that flag for
1027
+ * `/sign-up/email` only and decides a social sign-up per provider (`provider.options.disableSignUp`, in the OAuth
1028
+ * callback and in `/sign-in/social` with an `idToken`), so each provider receives it explicitly. A boolean
1029
+ * `disableSignUp` on the provider is the deliberate exception for that provider; any other value follows the global
1030
+ * flag, so a string arriving through `NEST_SERVER_CONFIG` cannot open a closed registration.
1024
1031
  */
1025
1032
  function buildSocialProviders(config: IBetterAuth): Record<string, SocialProviderConfig> {
1026
1033
  const socialProvidersConfig: Record<string, SocialProviderConfig> = {};
1034
+ const signUpClosed = config.emailAndPassword?.disableSignUp === true;
1027
1035
 
1028
1036
  // Iterate over all configured social providers dynamically
1029
1037
  // A provider is enabled by default if it has credentials configured
@@ -1034,6 +1042,7 @@ function buildSocialProviders(config: IBetterAuth): Record<string, SocialProvide
1034
1042
  socialProvidersConfig[name] = {
1035
1043
  clientId: provider.clientId,
1036
1044
  clientSecret: provider.clientSecret,
1045
+ disableSignUp: typeof provider.disableSignUp === 'boolean' ? provider.disableSignUp : signUpClosed,
1037
1046
  };
1038
1047
  }
1039
1048
  }
@@ -8,6 +8,7 @@ import { BetterAuthCookieHelper, createCookieHelper } from './core-better-auth-c
8
8
  import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.helper';
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry';
11
+ import { canonicalRequestPath } from './core-better-auth-path-guard.middleware';
11
12
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper';
12
13
  import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper';
13
14
  import { CoreBetterAuthService } from './core-better-auth.service';
@@ -239,9 +240,13 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
239
240
  }
240
241
 
241
242
  const basePath = this.betterAuthService.getBasePath();
242
- // Use originalUrl to get full path for IAM endpoints, but fallback to req.path
243
- // The originalUrl contains the original request path as sent by client
244
- const requestPath = req.originalUrl?.split('?')[0] || req.path;
243
+ // The path Better-Auth will ROUTE, not the one the client wrote (11.44.1): the forwarded Web Request is built with
244
+ // `new URL(originalUrl, baseUrl)` (toWebRequest()), which resolves `.`, `..` and `%2e` segments. Compared raw,
245
+ // `/iam/sign-up/%2e/email` counted as "not a controller path" while Better-Auth's own sign-up served it — past the
246
+ // controller's checks and every project override. CoreBetterAuthPathGuardMiddleware refuses such a path before this
247
+ // runs; deciding on the canonical path keeps this middleware right where the guard is not registered, as the rate
248
+ // limiter does.
249
+ const requestPath = canonicalRequestPath(req.originalUrl || req.url || req.path);
245
250
 
246
251
  // Only handle requests that start with the Better Auth base path
247
252
  if (!requestPath.startsWith(basePath)) {
@@ -220,10 +220,8 @@ export class CoreBetterAuthEmailVerificationService {
220
220
  let sent = false;
221
221
 
222
222
  try {
223
- // Override URL if callbackURL is configured (frontend-based verification)
224
- if (this.config.callbackURL) {
225
- url = this.buildFrontendVerificationUrl(token, user.email);
226
- }
223
+ // The app's verification page when callbackURL is configured, Better-Auth's own link otherwise
224
+ url = this.verificationMailUrl({ email: user.email, token, url });
227
225
 
228
226
  this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
229
227
 
@@ -707,20 +705,58 @@ export class CoreBetterAuthEmailVerificationService {
707
705
  }
708
706
  }
709
707
 
708
+ /**
709
+ * The link the verification mail carries: the app's verification page when `callbackURL` is configured and resolves
710
+ * ({@link buildFrontendVerificationUrl}), otherwise the link Better-Auth built (`<baseUrl>/<basePath>/verify-email`,
711
+ * token sealed), which verifies on the API and redirects from there.
712
+ *
713
+ * A relative `callbackURL` with no resolvable app URL keeps Better-Auth's link and warns once — a guessed host
714
+ * would 404 (DEV-4140).
715
+ */
716
+ protected verificationMailUrl(options: { email?: string; token: string; url: string }): string {
717
+ if (!this.config.callbackURL) {
718
+ return options.url;
719
+ }
720
+ const frontendUrl = this.buildFrontendVerificationUrl(options.token, options.email);
721
+ if (frontendUrl === undefined && !this.warnedAboutMissingAppUrl) {
722
+ this.warnedAboutMissingAppUrl = true;
723
+ this.logger.warn(
724
+ `No app URL resolves for the verification link (callbackURL "${this.config.callbackURL}" is relative, appUrl is ` +
725
+ 'unset and baseUrl gives none): the mail links to the API instead of the app page. Set NSC__APP_URL, or ' +
726
+ 'NSC__BASE_URL to derive it from.',
727
+ );
728
+ }
729
+ return frontendUrl ?? options.url;
730
+ }
731
+
732
+ /** Whether {@link verificationMailUrl} already warned that no app URL resolves (once per process) */
733
+ protected warnedAboutMissingAppUrl = false;
734
+
710
735
  /**
711
736
  * Build the frontend verification URL from the configured callbackURL and token.
712
737
  *
713
- * Resolves relative paths against `appUrl`. Appends the token as a query parameter.
738
+ * Resolves a relative `callbackURL` against the app URL the rest of the framework uses
739
+ * (`resolveAppUrlFromConfig()`: explicit `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from
740
+ * `baseUrl` unless `cors.deriveAppUrl` is `false`). Appends the token as a query parameter.
741
+ *
742
+ * Until DEV-4140 a relative value was resolved against `appUrl || 'http://localhost:3001'`, so every deployed stage
743
+ * without `NSC__APP_URL` mailed a link to localhost — while the password-reset link next to it already derived the
744
+ * app from `baseUrl`.
714
745
  *
715
746
  * @param token - The verification token from Better-Auth
716
- * @returns The full frontend URL with token query parameter
747
+ * @param email - The recipient's address, appended so the page can offer "send a new email"
748
+ * @returns The full frontend URL with token query parameter, or `undefined` for a relative `callbackURL` when no app
749
+ * URL resolves (the caller then keeps Better-Auth's own link)
717
750
  */
718
- protected buildFrontendVerificationUrl(token: string, email?: string): string {
751
+ protected buildFrontendVerificationUrl(token: string, email?: string): string | undefined {
719
752
  let baseUrl = this.config.callbackURL!;
720
753
 
721
- // Resolve relative paths against appUrl
754
+ // Resolve relative paths against the app URL — the SAME resolver as the password-reset link
722
755
  if (baseUrl.startsWith('/')) {
723
- const appUrl = this.configService.getFastButReadOnly<string>('appUrl') || 'http://localhost:3001';
756
+ const appUrl = resolveAppUrlFromConfig(this.configService);
757
+ if (!appUrl) {
758
+ return undefined;
759
+ }
724
760
  baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
725
761
  }
726
762
 
@@ -0,0 +1,85 @@
1
+ import { BadRequestException, Injectable, NestMiddleware } from '@nestjs/common';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+
4
+ import { ErrorCode } from '../error-code/error-codes';
5
+
6
+ /**
7
+ * Whether a raw request path contains something URL resolution rewrites: a `.` or `..` segment (also
8
+ * percent-encoded), a backslash (a segment separator for WHATWG URLs), an encoded slash or backslash, or a `#`
9
+ * (Express routes the part before it, the forwarding to Better-Auth reads the whole string).
10
+ *
11
+ * Every check in front of Better-Auth (rate limiter, controller routes, password routes) reads the RAW path, while
12
+ * Better-Auth routes the path `new URL()` resolved. A path the two read differently passes those checks as one route
13
+ * and runs as another. No route under the Better-Auth base path needs any of these, so such a request is refused.
14
+ *
15
+ * A loop over segments, no regex over the whole path: the path comes from an unauthenticated request and may be as
16
+ * long as Node's header limit allows.
17
+ */
18
+ export function hasNonCanonicalPathSegments(path: string): boolean {
19
+ if (path.includes('\\') || path.includes('#')) {
20
+ return true;
21
+ }
22
+ for (const segment of path.split('/')) {
23
+ if (segment.includes('%')) {
24
+ const lower = segment.toLowerCase();
25
+ if (lower.includes('%2f') || lower.includes('%5c')) {
26
+ return true;
27
+ }
28
+ }
29
+ // The longest dot segment is `%2e%2e`
30
+ if (segment.length === 0 || segment.length > 6) {
31
+ continue;
32
+ }
33
+ const dots = segment.replace(/%2e/gi, '.');
34
+ if (dots === '.' || dots === '..') {
35
+ return true;
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+
41
+ /**
42
+ * The path as Better-Auth routes it: dot segments resolved (also percent-encoded ones), backslashes read as slashes —
43
+ * what `new URL()` makes of it. Query string and fragment are dropped. A path `new URL()` refuses comes back as given.
44
+ */
45
+ export function canonicalRequestPath(path: string): string {
46
+ try {
47
+ return new URL(path, 'http://canonical.invalid').pathname;
48
+ } catch {
49
+ return path;
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Whether `path` contains the segments of `endpoint` as a contiguous run of WHOLE segments: `/sign-in` matches
55
+ * `/sign-in/email` and `/phone-number/sign-in`, never `/sign-in-legacy`. Segments are compared as they are; pass a
56
+ * {@link canonicalRequestPath} result, so `..` is already resolved.
57
+ */
58
+ export function pathContainsSegments(path: string, endpoint: string): boolean {
59
+ const wanted = endpoint.split('/').filter(Boolean);
60
+ if (wanted.length === 0) {
61
+ return false;
62
+ }
63
+ const segments = path.split('/').filter(Boolean);
64
+ for (let start = 0; start + wanted.length <= segments.length; start++) {
65
+ if (wanted.every((segment, offset) => segments[start + offset] === segment)) {
66
+ return true;
67
+ }
68
+ }
69
+ return false;
70
+ }
71
+
72
+ /**
73
+ * First middleware under the Better-Auth base path: refuses a request whose path is not in canonical form (see
74
+ * {@link hasNonCanonicalPathSegments}) with 400, before any check reads that path.
75
+ */
76
+ @Injectable()
77
+ export class CoreBetterAuthPathGuardMiddleware implements NestMiddleware {
78
+ use(req: Request, _res: Response, next: NextFunction) {
79
+ const path = (req.originalUrl || req.url || '').split('?')[0];
80
+ if (hasNonCanonicalPathSegments(path)) {
81
+ throw new BadRequestException(ErrorCode.INVALID_REQUEST_PATH);
82
+ }
83
+ next();
84
+ }
85
+ }
@@ -50,9 +50,12 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
50
50
  // Get client IP
51
51
  const ip = this.getClientIp(req);
52
52
 
53
- // Get the path relative to basePath
53
+ // The path relative to basePath, read from `originalUrl`: Nest mounts this middleware on `${basePath}/*path`, and
54
+ // Express moves the whole match into `req.baseUrl`, so `req.path` is "/" for every request here. Reading it made
55
+ // every IAM request of one client share a single counter with the full limit — no skip list, no strict limit
54
56
  const basePath = this.betterAuthService.getBasePath();
55
- const path = req.path.startsWith(basePath) ? req.path.substring(basePath.length) : req.path;
57
+ const requestPath = (req.originalUrl || req.url || '').split('?')[0];
58
+ const path = requestPath.startsWith(basePath) ? requestPath.substring(basePath.length) : requestPath;
56
59
 
57
60
  // Check rate limit
58
61
  const result = await this.rateLimiter.check(ip, path);
@@ -2,6 +2,7 @@ import { Injectable, Logger, Optional } from '@nestjs/common';
2
2
 
3
3
  import { IBetterAuthRateLimit } from '../../common/interfaces/server-options.interface';
4
4
  import { CoreRedisService } from '../../common/services/core-redis.service';
5
+ import { canonicalRequestPath, pathContainsSegments } from './core-better-auth-path-guard.middleware';
5
6
  import {
6
7
  InMemoryRateLimitStore,
7
8
  rateLimitKey,
@@ -134,10 +135,10 @@ export class CoreBetterAuthRateLimiter {
134
135
  * Check if a request is allowed under the rate limit
135
136
  *
136
137
  * @param ip - Client IP address
137
- * @param path - Request path (relative to basePath)
138
+ * @param requestPath - Request path (relative to basePath), as sent; dot segments are resolved here
138
139
  * @returns Rate limit check result
139
140
  */
140
- async check(ip: string, path: string): Promise<RateLimitResult> {
141
+ async check(ip: string, requestPath: string): Promise<RateLimitResult> {
141
142
  // If rate limiting is disabled, always allow
142
143
  if (!this.config.enabled) {
143
144
  return {
@@ -149,6 +150,13 @@ export class CoreBetterAuthRateLimiter {
149
150
  };
150
151
  }
151
152
 
153
+ // Decide on the path the request is served under, not the one as sent: `/callback/../sign-in/email` reaches the
154
+ // sign-in handler, so it must not be skipped as a callback (CoreBetterAuthPathGuardMiddleware refuses such paths
155
+ // before they get here; this keeps the limiter correct where that guard is not registered). Lower-cased because
156
+ // Express routes case-insensitively: `/sign-in/EMAIL` is the same sign-in and must share its counter and its
157
+ // strict limit
158
+ const path = canonicalRequestPath(requestPath).toLowerCase();
159
+
152
160
  // Check if this endpoint should skip rate limiting
153
161
  if (this.shouldSkip(path)) {
154
162
  return {
@@ -249,10 +257,11 @@ export class CoreBetterAuthRateLimiter {
249
257
  }
250
258
 
251
259
  /**
252
- * Determine if an endpoint should skip rate limiting
260
+ * Determine if an endpoint should skip rate limiting: an entry matches whole path segments, so `/session` skips
261
+ * `/session` but not `/sessions-export`
253
262
  */
254
263
  private shouldSkip(path: string): boolean {
255
- return this.config.skipEndpoints.some((skip) => path === skip || path.endsWith(skip) || path.includes(skip));
264
+ return this.config.skipEndpoints.some((skip) => pathContainsSegments(path, skip.toLowerCase()));
256
265
  }
257
266
 
258
267
  /**
@@ -260,9 +269,7 @@ export class CoreBetterAuthRateLimiter {
260
269
  * Strict endpoints get half the normal limit
261
270
  */
262
271
  private getLimit(path: string): number {
263
- const isStrict = this.config.strictEndpoints.some(
264
- (strict) => path === strict || path.endsWith(strict) || path.includes(strict),
265
- );
272
+ const isStrict = this.config.strictEndpoints.some((strict) => pathContainsSegments(path, strict.toLowerCase()));
266
273
 
267
274
  return isStrict ? Math.ceil(this.config.max / 2) : this.config.max;
268
275
  }
@@ -166,6 +166,29 @@ export class CoreBetterAuthUserMapper {
166
166
  * @param sessionUser - The Better-Auth session user
167
167
  * @returns A mapped user with role capabilities
168
168
  */
169
+ /**
170
+ * The mapped user of a Better-Auth user that is stored nowhere, from its own fields only (11.44.1).
171
+ *
172
+ * The placeholder Better-Auth answers a sign-up for an already registered address with (see
173
+ * `CoreBetterAuthService.isPersistedUser()`) must look like a new user: its own id, no roles, not verified. Looking it
174
+ * up by address, as {@link mapSessionUser} does, found the real account and answered its id and roles.
175
+ */
176
+ mapUnstoredSessionUser(sessionUser: BetterAuthSessionUser): MappedUser | null {
177
+ if (!sessionUser?.id || !sessionUser?.email) {
178
+ return null;
179
+ }
180
+ return this.createMappedUser({
181
+ email: sessionUser.email,
182
+ emailVerified: sessionUser.emailVerified,
183
+ iamId: sessionUser.id,
184
+ id: sessionUser.id,
185
+ image: sessionUser.image,
186
+ name: sessionUser.name,
187
+ roles: [],
188
+ verified: sessionUser.emailVerified,
189
+ });
190
+ }
191
+
169
192
  async mapSessionUser(sessionUser: BetterAuthSessionUser): Promise<MappedUser | null> {
170
193
  if (!sessionUser?.id || !sessionUser?.email) {
171
194
  return null;
@@ -332,6 +355,24 @@ export class CoreBetterAuthUserMapper {
332
355
  * @param plainPassword - The plain password to hash with bcrypt
333
356
  * @returns true if sync was successful, false otherwise
334
357
  */
358
+ /**
359
+ * Spends the time {@link syncPasswordToLegacy} spends on a password, and writes nothing (11.44.1).
360
+ *
361
+ * A sign-up for an already registered address writes nothing (see `CoreBetterAuthService.isPersistedUser()`).
362
+ * Without this it would answer a bcrypt round faster than a real sign-up, and the response time would tell which
363
+ * addresses have an account — the enumeration Better-Auth's placeholder answer exists to prevent.
364
+ */
365
+ async equalizeLegacyPasswordSync(plainPassword?: string): Promise<void> {
366
+ if (!plainPassword) {
367
+ return;
368
+ }
369
+ try {
370
+ await bcrypt.hash(this.normalizePasswordForIam(plainPassword), 10);
371
+ } catch {
372
+ // Timing only — nothing depends on the result
373
+ }
374
+ }
375
+
335
376
  async syncPasswordToLegacy(iamUserId: string, userEmail: string, plainPassword?: string): Promise<boolean> {
336
377
  if (!this.connection) {
337
378
  this.logger.warn('No database connection available - cannot sync password to legacy');
@@ -584,17 +584,31 @@ export class CoreBetterAuthController {
584
584
  }
585
585
 
586
586
  if (hasUser(response)) {
587
- // Link or create user in our database
588
- // Pass termsAndPrivacyAccepted to store the acceptance timestamp
589
- await this.userMapper.linkOrCreateUser(response.user, {
590
- termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
591
- });
592
-
593
- // Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
594
- // Pass the plain password so it can be hashed with bcrypt for Legacy Auth
595
- await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
587
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
588
+ // like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
589
+ // re-pointed the real account found by address and overwrote its legacy password with the caller's (11.44.1).
590
+ // The answer below stays that of a new sign-up; only the writes are left out.
591
+ const isPlaceholder = !(await this.betterAuthService.isPersistedUser(response.user.id));
592
+
593
+ if (isPlaceholder) {
594
+ // The same bcrypt round as the legacy sync, so the response time does not tell the address exists
595
+ await this.userMapper.equalizeLegacyPasswordSync(input.password);
596
+ } else {
597
+ // Link or create user in our database
598
+ // Pass termsAndPrivacyAccepted to store the acceptance timestamp
599
+ await this.userMapper.linkOrCreateUser(response.user, {
600
+ termsAndPrivacyAccepted: input.termsAndPrivacyAccepted,
601
+ });
602
+
603
+ // Sync password to legacy (enables IAM Sign-Up → Legacy Sign-In)
604
+ // Pass the plain password so it can be hashed with bcrypt for Legacy Auth
605
+ await this.userMapper.syncPasswordToLegacy(response.user.id, response.user.email, input.password);
606
+ }
596
607
 
597
- const mappedUser = await this.userMapper.mapSessionUser(response.user);
608
+ // A new user has no roles yet; the placeholder must not carry those of the account it stands for
609
+ const mappedUser = isPlaceholder
610
+ ? this.userMapper.mapUnstoredSessionUser(response.user)
611
+ : await this.userMapper.mapSessionUser(response.user);
598
612
 
599
613
  // Get token: JWT accessToken > top-level token > session.token
600
614
  // Without this, no session cookies are set after sign-up, causing 401 on
@@ -32,6 +32,7 @@ import { DefaultBetterAuthResolver } from './better-auth.resolver';
32
32
  import { CoreBetterAuthApiMiddleware } from './core-better-auth-api.middleware';
33
33
  import { CoreBetterAuthChallengeService } from './core-better-auth-challenge.service';
34
34
  import { CoreBetterAuthEmailVerificationService } from './core-better-auth-email-verification.service';
35
+ import { CoreBetterAuthPathGuardMiddleware } from './core-better-auth-path-guard.middleware';
35
36
  import { CoreBetterAuthRateLimitMiddleware } from './core-better-auth-rate-limit.middleware';
36
37
  import { CoreBetterAuthRateLimiter } from './core-better-auth-rate-limiter.service';
37
38
  import { revokeApiTokensOfUser } from '../api-token/core-api-token.registry';
@@ -422,8 +423,10 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
422
423
  * 1. CoreBetterAuthMiddleware - Session validation and user mapping for all routes
423
424
  * Must run FIRST so that req.betterAuthSession is available for downstream middleware.
424
425
  * In JWT mode, this resolves the JWT to a real DB session (via getActiveSessionForUser).
425
- * 2. CoreBetterAuthRateLimitMiddleware - Rate limiting for auth endpoints
426
- * 3. CoreBetterAuthApiMiddleware - Forwards plugin endpoints (passkey, 2FA, etc.) to Better Auth's native handler
426
+ * 2. CoreBetterAuthPathGuardMiddleware - Refuses a non-canonical path under the base path (400), before
427
+ * anything below reads it
428
+ * 3. CoreBetterAuthRateLimitMiddleware - Rate limiting for auth endpoints
429
+ * 4. CoreBetterAuthApiMiddleware - Forwards plugin endpoints (passkey, 2FA, etc.) to Better Auth's native handler
427
430
  * Runs AFTER session middleware so it can use req.betterAuthSession.session.token
428
431
  * to authenticate requests in JWT mode.
429
432
  */
@@ -442,6 +445,13 @@ export class CoreBetterAuthModule implements NestModule, OnModuleInit {
442
445
  consumer.apply(CoreBetterAuthMiddleware).forRoutes('(.*)'); // New path-to-regexp syntax for wildcard
443
446
  CoreBetterAuthModule.logger.debug('CoreBetterAuthMiddleware registered for all routes');
444
447
 
448
+ // Refuse a non-canonical path (`.` / `..` segments, also encoded, backslashes, encoded slashes) before anything
449
+ // under the base path reads it: every check below reads the path as SENT, while Better-Auth routes the one
450
+ // `new URL()` resolved — `/callback/../sign-in/email` would pass the rate limiter as a callback and run as a
451
+ // sign-in. Registered unconditionally and FIRST, so it guards the limiter, the controller routes and the
452
+ // forwarding alike.
453
+ consumer.apply(CoreBetterAuthPathGuardMiddleware).forRoutes(`${basePath}/*path`);
454
+
445
455
  // Apply rate limiting to Better-Auth endpoints only.
446
456
  // Mirrors the "presence implies enabled" contract `CoreBetterAuthRateLimiter.configure()`
447
457
  // implements. Gating the MOUNT on `.enabled` alone made that fix unobservable: the limiter
@@ -483,10 +483,20 @@ export class CoreBetterAuthResolver {
483
483
  if (hasUser(response)) {
484
484
  const sessionUser: BetterAuthSessionUser = response.user;
485
485
 
486
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
487
+ // like a new sign-up, with a placeholder user it never stored (enumeration protection). Linking that user
488
+ // re-pointed the real account found by address, and the answer carried that account's id and roles (11.44.1).
489
+ // The answer stays that of a new sign-up; only the write is left out.
490
+ const isPlaceholder = !(await this.betterAuthService.isPersistedUser(sessionUser.id));
491
+
486
492
  // Link or create user in our database
487
493
  // Pass termsAndPrivacyAccepted to store the acceptance timestamp
488
- await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
489
- const mappedUser = await this.userMapper.mapSessionUser(sessionUser);
494
+ if (!isPlaceholder) {
495
+ await this.userMapper.linkOrCreateUser(sessionUser, { termsAndPrivacyAccepted });
496
+ }
497
+ const mappedUser = isPlaceholder
498
+ ? this.userMapper.mapUnstoredSessionUser(sessionUser)
499
+ : await this.userMapper.mapSessionUser(sessionUser);
490
500
 
491
501
  // If email verification is enabled, revoke the session and don't return session data
492
502
  // The user must verify their email before they can use any session