@lenne.tech/nest-server 11.44.0 → 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 (62) hide show
  1. package/.claude/rules/better-auth.md +40 -4
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +1 -1
  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 +1 -0
  8. package/dist/core/modules/auth/services/core-auth.service.js +3 -0
  9. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  10. package/dist/core/modules/better-auth/better-auth.config.js +2 -0
  11. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  12. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
  13. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.d.ts +8 -0
  15. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js +70 -0
  16. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js.map +1 -0
  17. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +2 -1
  18. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  19. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +5 -3
  21. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  22. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
  23. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
  24. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  25. package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
  26. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  27. package/dist/core/modules/better-auth/core-better-auth.module.js +2 -0
  28. package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
  30. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  32. package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
  33. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  34. package/dist/core/modules/better-auth/index.d.ts +1 -0
  35. package/dist/core/modules/better-auth/index.js +1 -0
  36. package/dist/core/modules/better-auth/index.js.map +1 -1
  37. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  38. package/dist/core/modules/error-code/error-codes.js +8 -0
  39. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  40. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  41. package/dist/tsconfig.build.tsbuildinfo +1 -1
  42. package/docs/REQUEST-LIFECYCLE.md +1 -0
  43. package/docs/error-codes.md +14 -0
  44. package/migration-guides/11.44.0-to-11.44.1.md +152 -0
  45. package/package.json +1 -1
  46. package/src/config.env.ts +6 -2
  47. package/src/core/common/interfaces/server-options.interface.ts +15 -0
  48. package/src/core/modules/auth/services/core-auth.service.ts +8 -0
  49. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +3 -0
  50. package/src/core/modules/better-auth/README.md +34 -4
  51. package/src/core/modules/better-auth/better-auth.config.ts +9 -0
  52. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
  53. package/src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts +85 -0
  54. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +5 -2
  55. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +14 -7
  56. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
  57. package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
  58. package/src/core/modules/better-auth/core-better-auth.module.ts +12 -2
  59. package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
  60. package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
  61. package/src/core/modules/better-auth/index.ts +1 -0
  62. package/src/core/modules/error-code/error-codes.ts +9 -0
@@ -64,6 +64,7 @@ Modern OAuth-compatible authentication with plugin architecture:
64
64
  | **Social Login** | OAuth providers: Google, GitHub, Apple, Discord, etc. (plugin) |
65
65
  | **Email Verification** | Configurable email verification flow |
66
66
  | **Sign-Up Validation** | Custom validation hooks for registration |
67
+ | **Path Guard** | `CoreBetterAuthPathGuardMiddleware`, the first middleware under the Better-Auth base path (always registered): a path with a `.` / `..` segment (also `%2e`-encoded), a backslash, an encoded `/` / `\` or a `#` is refused with 400 (`#LTNS_0305`) before the rate limiter, the controller routes or the forwarding read it. Every check there reads the path as sent while Better-Auth routes the resolved one, so without the guard `/iam/callback/../sign-in/email` was skipped by the limiter as a callback and ran as a sign-in (12.2.x) |
67
68
  | **Rate Limiting** | Per-endpoint rate limits (`betterAuth.rateLimit`, configurable). Counters live behind a `RateLimitStore`: `RedisRateLimitStore` when `redis` is configured, so `max` is enforced **exactly across replicas** instead of `max × replicas`; otherwise the process-local `InMemoryRateLimitStore` as before. `check()` / `reset()` / `clear()` are **async** since 11.33.0. On a Redis outage it degrades to the in-memory counter and logs once per transition — never a 500, never "allowed". Counters are keyed on `request.ip`, which Express derives from `X-Forwarded-For` only as far as `trust proxy` allows — set `trustProxy` (§ServerOptions) behind a reverse proxy or every client resolves to the proxy and shares ONE bucket; unset with a limiter enabled logs a boot warning |
68
69
  | **Cross-Subdomain Cookies** | Automatic cookie domain configuration |
69
70
  | **Organization / Multi-Tenant** | Teams and organization management (plugin) |
@@ -346,6 +346,20 @@ All error codes follow the format: `#PREFIX_XXXX: Description`
346
346
  - DE: Die gesendeten Daten sind zu groß und wurden nicht verarbeitet.
347
347
  - EN: The submitted data is too large and was not processed.
348
348
 
349
+ ### LTNS_0305: invalidRequestPath
350
+
351
+ **Message:** Invalid request path
352
+
353
+ **Description:** Answered with HTTP 400 when a request under the Better-Auth base path (`/iam` by default) carries a path segment `.` or `..` (also percent-encoded as `%2e`), a backslash, an encoded `/` or `\` (`%2f`, `%5c`), or a `#`. No route there uses such a path, and the checks in front of Better-Auth would read it as a different route than Better-Auth itself.
354
+
355
+ **Solution:** Send the path in its canonical form. Browsers and HTTP clients do that on their own; the error points at a client that builds paths by hand or sends them unnormalized on purpose.
356
+
357
+ **Parameters:** none
358
+
359
+ **Translations:**
360
+ - DE: Der Anfragepfad ist ungültig.
361
+ - EN: The request path is invalid.
362
+
349
363
  ---
350
364
 
351
365
  ## Resource Errors (LTNS_0400-LTNS_0499)
@@ -0,0 +1,152 @@
1
+ # Migration Guide: 11.44.0 → 11.44.1
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None in the API. Non-canonical paths under the Better-Auth base path answer 400, the IAM rate limit counts per route (§2). `emailAndPassword.disableSignUp: true` closes social sign-up too (§3) |
8
+ | **New Features** | `CoreBetterAuthService.isPersistedUser()`, `CoreBetterAuthUserMapper.mapUnstoredSessionUser()` and `equalizeLegacyPasswordSync()` (§1). `socialProviders.<name>.disableSignUp` (§3). `CoreBetterAuthPathGuardMiddleware`, `canonicalRequestPath()`, error code `LTNS_0305` (§2) |
9
+ | **Bugfixes** | Security: a sign-up for an already registered address changed the existing account (§1). Dot segments under the IAM base path bypassed the controller and the rate limiter (§2). Social login created accounts while sign-up was switched off (§3) |
10
+ | **Migration Effort** | Update. Projects that had `requireEmailVerification: true` or `autoSignIn: false` with open sign-up check their accounts (§1). A deployment with a tight `betterAuth.rateLimit.max` checks the value (§2). A project that closed sign-up but wants new users through one social provider sets one flag (§3) |
11
+
12
+ 11.44.1 is a security patch for 11.44.0 (`latest-11`). §1 ships in 12.8.1 and 12.6.6 as well. §2 and §3 are backports
13
+ of 12.3.0, where 12.x has had them since.
14
+
15
+ ## Quick Migration
16
+
17
+ ```bash
18
+ pnpm add @lenne.tech/nest-server@11.44.1
19
+ pnpm run update # nest-server-starter based projects (release/11.x)
20
+ pnpm run build
21
+ pnpm test
22
+ ```
23
+
24
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
25
+
26
+ ## 1. A sign-up for an already registered address changes nothing
27
+
28
+ **Why:** with `emailAndPassword.requireEmailVerification: true` or `emailAndPassword.autoSignIn: false` (set through
29
+ `betterAuth.options`), Better-Auth 1.5.0 and later answers a sign-up for a known address like a new one, so the
30
+ response does not reveal which addresses have an account. That answer carries a placeholder user: a generated id and
31
+ the given address, stored nowhere. The core's sign-up paths took it for the new user:
32
+
33
+ - **REST `POST /iam/sign-up/email`** (`CoreBetterAuthController.signUp()`, also without a project override) linked the
34
+ placeholder to the real account it found by address. That account's `iamId` then pointed at the placeholder, it got
35
+ `verified: false`, its **legacy password was set to the one the caller chose**, and the answer carried its roles.
36
+ - **GraphQL `betterAuthSignUp`** linked it the same way and answered with the real account's id and roles.
37
+ - **The legacy sign-up with IAM enabled** (`/auth/signup`, GraphQL `signUp`) linked it, overwrote the password and
38
+ returned the real account, and the caller received its tokens.
39
+
40
+ With the legacy endpoints open, the overwritten legacy password let the caller sign in as the account owner. For a
41
+ legacy user without an IAM credential account, the next IAM sign-in with that password migrated the account to it.
42
+
43
+ **What changed:** a user Better-Auth returns from a sign-up is written only once `CoreBetterAuthService.isPersistedUser()`
44
+ confirmed it through Better-Auth's own adapter. For a placeholder, nothing is linked and no password is synced. The
45
+ answer stays that of a new sign-up: its own id, no roles, not verified, and the same bcrypt round as a real sign-up,
46
+ so neither the body nor the response time tells the address exists. The legacy sign-up answers a known address with
47
+ `Email address already in use`, as it always did without IAM.
48
+
49
+ **Who was affected:** a project running better-auth 1.5.0 or later (nest-server 11.18.0 and later pin it) whose
50
+ Better-Auth options set `requireEmailVerification: true` or `autoSignIn: false`, with sign-up open
51
+ (`emailAndPassword.disableSignUp: true` refused the request before it reached Better-Auth). Without those options
52
+ Better-Auth answers a known address with an error, and the core answered `EMAIL_ALREADY_EXISTS` without writing.
53
+
54
+ **Your project:** update. If the conditions above applied, the traces an attack leaves on an account do not list every
55
+ affected one: `iamId` no longer matching the account's own id, and `verified: false` next to `emailVerified: true`, are
56
+ written back by the owner's next IAM sign-in, while the overwritten legacy password stays. Take the time the options
57
+ were active as the window and:
58
+
59
+ - **Accounts that still carry a trace:** remove the legacy `password`, end their sessions (IAM sessions and legacy
60
+ refresh tokens) and send a password reset.
61
+ - **Every account with a Better-Auth credential account:** remove the legacy `password`. IAM sign-in does not read it,
62
+ only the legacy endpoints do. Where `auth.legacyEndpoints` keeps those open (closed by default since 11.38.0), send
63
+ these accounts a password reset instead.
64
+ - **Credential accounts created in the window for a user who existed before it:** a legacy user's first IAM sign-in
65
+ creates one with the password used for that sign-in, after an attack the caller's. End those sessions and send a
66
+ password reset.
67
+
68
+ Better-Auth logs a sign-up for a known address ("Sign-up attempt for existing email") only at `logger.level: 'info'` or
69
+ lower. Its default is `warn`, so there is usually no log trail. A project test that stubs `CoreBetterAuthService` for
70
+ the sign-up needs `isPersistedUser`.
71
+
72
+ ## 2. Requests under the Better-Auth base path
73
+
74
+ ### Non-canonical paths answer 400
75
+
76
+ Every check under the base path (`/iam` by default) — rate limiter, controller routes, the forwarding to Better-Auth —
77
+ read the path as sent, while Better-Auth routes the path after `new URL()` resolved it. `/iam/sign-up/%2e/email`
78
+ therefore reached Better-Auth's own sign-up past the controller and every project override, and
79
+ `/iam/callback/../sign-in/email` passed the rate limiter as a skipped OAuth callback and ran as a sign-in.
80
+
81
+ `CoreBetterAuthPathGuardMiddleware` now runs first under the base path and answers **400** (`#LTNS_0305: Invalid
82
+ request path`) for a path with a `.` or `..` segment (also `%2e`-encoded), a backslash, an encoded `/` or `\`, or a
83
+ `#`. No Better-Auth route needs any of them; a client that sends one has a bug. It is registered by
84
+ `CoreBetterAuthModule` itself, so there is nothing to add. `CoreBetterAuthApiMiddleware` and the rate limiter decide on
85
+ the same canonical path (`canonicalRequestPath()`) as well, so they stay right where the guard is not registered.
86
+
87
+ ### The IAM rate limit tells routes apart
88
+
89
+ The rate-limit middleware read `req.path`, which is `/` for a middleware Nest mounts under the base path. So every IAM
90
+ request of a client shared one counter with the full limit, and the skip list (`/session`, `/callback`) and the halved
91
+ limit for sign-in, sign-up and the password routes never applied over HTTP.
92
+
93
+ Now a client IP has one counter per route NAME — the last path segment — so `/sign-in/email` and `/sign-up/email` (both
94
+ `email`) share one counter. `/session` and `/callback` are not counted, and the strict routes (sign-in, sign-up, the
95
+ password reset and change routes) get half of `betterAuth.rateLimit.max`, rounded up. The skip and strict lists match
96
+ whole path segments, case-insensitively, as Express routes.
97
+
98
+ **What to check:** a deployment that set `betterAuth.rateLimit.max` (the nest-server-starter reads it from
99
+ `IAM_RATE_LIMIT_MAX`) gets half of it for the e-mail sign-in and sign-up now, and the two count together: with
100
+ `max: 10`, five attempts per window for both combined. Behind a shared NAT or proxy, sign-ups use up the same budget as
101
+ sign-ins. Raise the value if that is too tight.
102
+
103
+ ## 3. Social login creates no account while sign-up is switched off
104
+
105
+ Only with `betterAuth.emailAndPassword.disableSignUp: true` and at least one social provider. The flag closed
106
+ `/sign-up/email` only. Better-Auth decides a social sign-up per provider, and each provider got only its `clientId` and
107
+ `clientSecret`, so whoever signed in with Google, GitHub etc. for the first time got an account in a project that had
108
+ closed self-registration.
109
+
110
+ **What changes:** every configured provider now receives the flag, so `disableSignUp: true` closes sign-up through
111
+ every social provider as well, unless that provider sets its own `disableSignUp`. A first sign-in through a provider by
112
+ somebody who has no account is refused (the OAuth callback redirects with `error=signup_disabled`, `/sign-in/social`
113
+ with an `idToken` answers 401 `signup disabled`). Users who already have an account keep signing in, also through a
114
+ provider they have not used before: Better-Auth checks the flag only when no user exists for the address.
115
+
116
+ **What to check:** a project that closed sign-up on purpose needs nothing. A project that closed e-mail sign-up but
117
+ wants new users through a provider opens that one deliberately:
118
+
119
+ ```typescript
120
+ // config.env.ts
121
+ betterAuth: {
122
+ emailAndPassword: { disableSignUp: true },
123
+ socialProviders: {
124
+ google: { clientId: '...', clientSecret: '...', disableSignUp: false }, // new users through Google
125
+ github: { clientId: '...', clientSecret: '...' }, // follows disableSignUp: closed
126
+ },
127
+ },
128
+ ```
129
+
130
+ `disableSignUp: true` on a provider closes sign-up for that provider alone, while sign-up stays open elsewhere. Only a
131
+ boolean counts there: any other value, such as the string `"false"` in `NEST_SERVER_CONFIG`, follows
132
+ `emailAndPassword.disableSignUp`. Plugins a project registers itself through `betterAuth.options.plugins` are not
133
+ covered; set their own sign-up options.
134
+
135
+ ## Troubleshooting
136
+
137
+ | Symptom | Cause | Fix |
138
+ |---|---|---|
139
+ | 400 `#LTNS_0305` on an IAM request | The path carries a dot segment, a backslash, an encoded separator or a `#` | Fix the client's URL |
140
+ | 429 on sign-in or sign-up earlier than before | The strict routes get half of `betterAuth.rateLimit.max`, and sign-in and sign-up share one counter (§2) | Raise `betterAuth.rateLimit.max` |
141
+ | New users land on the error page with `error=signup_disabled` after a social login | `disableSignUp: true` covers social providers (§3) | Expected; or set `disableSignUp: false` on the provider |
142
+ | A project test fails with `SIGNUP_FAILED` | Its stub of `CoreBetterAuthService` has no `isPersistedUser` (§1) | Add `isPersistedUser: async () => true` to the stub |
143
+
144
+ ## References
145
+
146
+ - `src/core/modules/better-auth/core-better-auth.service.ts`: `isPersistedUser()`
147
+ - `src/core/modules/better-auth/core-better-auth.controller.ts`, `core-better-auth.resolver.ts`,
148
+ `src/core/modules/auth/services/core-auth.service.ts`: the sign-up paths
149
+ - `src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts`, `core-better-auth-rate-limiter.service.ts`
150
+ - `src/core/modules/better-auth/better-auth.config.ts`: `buildSocialProviders()`
151
+ - `src/core/modules/better-auth/README.md`, `INTEGRATION-CHECKLIST.md`
152
+ - `.claude/rules/better-auth.md`: security checklist
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.44.0",
3
+ "version": "11.44.1",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
package/src/config.env.ts CHANGED
@@ -59,7 +59,9 @@ const config: { [env: string]: IServerOptions } = {
59
59
  rpId: 'localhost',
60
60
  rpName: 'Nest Server Local',
61
61
  },
62
- rateLimit: { enabled: true, max: 100, windowSeconds: 60 },
62
+ // 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
63
+ // counted every IAM request of a client on one shared counter of 100
64
+ rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
63
65
  secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
64
66
  // Social providers disabled in local environment (no credentials)
65
67
  socialProviders: {
@@ -368,7 +370,9 @@ const config: { [env: string]: IServerOptions } = {
368
370
  rpId: 'localhost',
369
371
  rpName: 'Nest Server Local',
370
372
  },
371
- rateLimit: { enabled: true, max: 100, windowSeconds: 60 },
373
+ // 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
374
+ // counted every IAM request of a client on one shared counter of 100
375
+ rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
372
376
  secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
373
377
  // Social providers disabled in local environment (no credentials)
374
378
  socialProviders: {
@@ -978,6 +978,17 @@ export interface IBetterAuthSocialProvider {
978
978
  */
979
979
  clientSecret: string;
980
980
 
981
+ /**
982
+ * Whether a first sign-in through this provider may create an account.
983
+ *
984
+ * Unset, the provider follows `betterAuth.emailAndPassword.disableSignUp`: with that set to `true` (since 12.3.0)
985
+ * nobody gets a new account through any provider, while existing users keep signing in. `false` opens sign-up
986
+ * through this provider although `disableSignUp` closes it otherwise; `true` closes it for this provider alone.
987
+ * Only a boolean counts: any other value follows `emailAndPassword.disableSignUp`.
988
+ * @default emailAndPassword.disableSignUp
989
+ */
990
+ disableSignUp?: boolean;
991
+
981
992
  /**
982
993
  * Whether this provider is enabled.
983
994
  * Defaults to true when clientId and clientSecret are provided.
@@ -4198,6 +4209,10 @@ interface IBetterAuthBase {
4198
4209
  * Disable user registration (sign-up) via BetterAuth.
4199
4210
  * Passed through to better-auth's native emailAndPassword.disableSignUp.
4200
4211
  * Custom endpoints (GraphQL + REST) also check this flag early.
4212
+ * Since 11.44.1 (12.3.0 on 12.x) it closes social sign-up too: every configured social provider receives it as its own
4213
+ * `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
4214
+ * signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
4215
+ * registers itself through `options.plugins` are not covered.
4201
4216
  * The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
4202
4217
  * which would answer `SIGNUP_DISABLED` to every caller.
4203
4218
  * @default false
@@ -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)) {
@@ -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');