@lenne.tech/nest-server 11.44.1 → 11.45.0

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 (43) hide show
  1. package/.claude/rules/better-auth.md +10 -0
  2. package/.claude/rules/configurable-features.md +2 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/FRAMEWORK-API.md +2 -1
  5. package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
  6. package/dist/core/common/helpers/swagger-enabled.helper.js +13 -0
  7. package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
  8. package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
  9. package/dist/core/common/helpers/swagger.helper.js +10 -3
  10. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  11. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  12. package/dist/core/modules/better-auth/better-auth.config.js +30 -4
  13. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +1 -0
  15. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +5 -1
  16. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  17. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.d.ts +2 -0
  18. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +12 -0
  19. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +2 -0
  21. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +23 -1
  22. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  23. package/dist/core/modules/user/core-user.service.js +5 -1
  24. package/dist/core/modules/user/core-user.service.js.map +1 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/tsconfig.build.tsbuildinfo +1 -1
  29. package/migration-guides/11.41.7-to-11.41.8.md +1 -1
  30. package/migration-guides/11.44.0-to-11.44.1.md +2 -2
  31. package/migration-guides/11.44.1-to-11.44.2.md +125 -0
  32. package/migration-guides/11.44.x-to-11.45.x.md +111 -0
  33. package/package.json +1 -1
  34. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  35. package/src/core/common/helpers/swagger.helper.ts +30 -6
  36. package/src/core/common/interfaces/server-options.interface.ts +21 -1
  37. package/src/core/modules/better-auth/README.md +2 -2
  38. package/src/core/modules/better-auth/better-auth.config.ts +63 -5
  39. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +18 -1
  40. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +23 -0
  41. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +44 -3
  42. package/src/core/modules/user/core-user.service.ts +10 -2
  43. package/src/index.ts +1 -0
@@ -30,7 +30,7 @@ Vendor-mode projects pick up the core update, and raise the same pins.
30
30
  [GHSA-965c-763c-88jm](https://github.com/better-auth/better-auth/security/advisories/GHSA-965c-763c-88jm)
31
31
  (critical): an OAuth state value can be used as a Magic Link to sign in as another user. It covers
32
32
  `better-auth >= 1.4.0-beta.18, < 1.7.7`; 1.7.7 is fixed. A project is exposed when it registers the
33
- `magicLink` plugin — through `betterAuth.options.plugins` — next to a social or Generic OAuth
33
+ `magicLink` plugin — through `betterAuth.plugins` or `betterAuth.options.plugins` — next to a social or Generic OAuth
34
34
  provider, with OAuth state stored in the database (the default when a database is configured). An
35
35
  attacker who knows a user's email address then gets a normal session for that user, without access
36
36
  to the mailbox.
@@ -129,8 +129,8 @@ betterAuth: {
129
129
 
130
130
  `disableSignUp: true` on a provider closes sign-up for that provider alone, while sign-up stays open elsewhere. Only a
131
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.
132
+ `emailAndPassword.disableSignUp`. Plugins a project registers itself through `betterAuth.plugins` are not
133
+ covered; set their own sign-up options (`magicLink({ disableSignUp: true })`).
134
134
 
135
135
  ## Troubleshooting
136
136
 
@@ -0,0 +1,125 @@
1
+ # Migration Guide: 11.44.1 → 11.44.2
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None. On a stage with `NODE_ENV=test` Better-Auth's origin and CSRF checks now run, as they always did elsewhere (§1) |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security: on a stage with `NODE_ENV=test`, Better-Auth's origin check, CSRF check and `callbackURL` / `redirectTo` validation were off, so a password-reset mail could carry its token to a page the caller chose (§1). Documentation named `betterAuth.options.plugins` for custom plugins, which replaces the built-in ones (§2). A project's `betterAuth.options.user` replaced the framework's `user` block (§3). An address change that differed only in case ended every session (§4). One client could fill the IAM rate limiter's store with paths nobody serves, after which new clients were refused at their first sign-in (§5) |
10
+ | **Migration Effort** | Update. A test stage whose frontend origin is missing from `trustedOrigins` answers 403 `INVALID_ORIGIN` now, as production already does (§1). Plugins registered through `betterAuth.options.plugins` move to `betterAuth.plugins` (§2) |
11
+
12
+ 11.44.2 is a security patch for 11.44.1 (`latest-11`). The same fixes ship in 12.8.2 (`latest`) and 12.6.7 (`latest-12.6`).
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@11.44.2
18
+ pnpm run update # nest-server-starter based projects (release/11.x)
19
+ pnpm run build
20
+ pnpm test
21
+ ```
22
+
23
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
24
+
25
+ ## 1. The origin check runs whatever the environment is called
26
+
27
+ **Why:** Better-Auth decides its origin check itself while `advanced.disableOriginCheck` is unset. Its `isTest()`
28
+ (`NODE_ENV === 'test'`, or a truthy `TEST` variable) switches the check off. With it go:
29
+
30
+ - the CSRF check (Better-Auth keeps them coupled for backward compatibility),
31
+ - the validation of `callbackURL`, `redirectTo`, `errorCallbackURL` and `newUserCallbackURL` against `trustedOrigins`.
32
+
33
+ The nest-server-starter names its deployed test stage `test`, so every such stage ran without these checks. The worst
34
+ consequence: `POST /iam/request-password-reset` is unauthenticated and took any `redirectTo`. The core's reset mail
35
+ (`betterAuth.emailVerification.passwordResetLink`, default since 11.38.0) uses the caller's `redirectTo` because
36
+ Better-Auth normally validates it first. A request for somebody else's address with
37
+ `redirectTo: 'https://attacker.example/reset'` therefore sent that person a genuine mail whose link carried a valid reset
38
+ token to the attacker's page.
39
+
40
+ **What changed:** for every config environment that is not `local`, `ci` or `e2e` (an unknown or missing one
41
+ included), the core passes `advanced.disableOriginCheck: false` to Better-Auth, so `NODE_ENV` no longer decides the check
42
+ there. `local`, `ci` and `e2e` keep Better-Auth's own decision: vitest sets `TEST=true`, so test suites still run without
43
+ the check, as before. A suite that wants it (CSRF, foreign origins, `redirectTo`) sets
44
+ `betterAuth.options.advanced.disableOriginCheck: false` itself, as `tests/better-auth-signin-csrf.e2e-spec.ts` does. A
45
+ project that sets `betterAuth.options.advanced.disableOriginCheck` keeps its own value; an explicitly `undefined` value
46
+ counts as not set. While a project switches the check off (`true`, or a list of paths),
47
+ the core's reset mail no longer takes the caller's `redirectTo` at all and links to the default page
48
+ (`<appUrl>/auth/reset-password`), because nothing validated the URL.
49
+
50
+ **Who was affected:** every project with Better-Auth that ran a deployed stage with `NODE_ENV=test` or a truthy `TEST`
51
+ variable. Stages with `NODE_ENV=develop` or `production` were not affected.
52
+
53
+ **Your project:** update. Then check:
54
+
55
+ - **Frontend origins of the test stage.** A browser request that carries cookies is checked against `trustedOrigins`
56
+ now. If the test stage's frontend runs on an origin the configuration does not name (`appUrl`, `cors.allowedOrigins`,
57
+ `betterAuth.trustedOrigins`), sign-in through Better-Auth's own routes, 2FA and passkeys answer 403 `INVALID_ORIGIN`
58
+ there. Production behaves this way already; add the origin to the same setting.
59
+ - **Password resets on test stages.** A reset link requested while the stage ran an affected version may have carried
60
+ its token to a foreign page. Whoever held the token could set a new password, so ending sessions alone does not
61
+ lock them out again. Where test stages hold accounts that matter, take the time the stage ran an affected version as
62
+ the window, and for every account whose password changed in it:
63
+ - make the password unusable and have the owner set a new one through a reset on the fixed version;
64
+ - remove what was added in the window: passkeys, 2FA enrolments, a changed e-mail address, API tokens;
65
+ - then end its sessions.
66
+
67
+ What shows such a reset: `POST /iam/reset-password` in the access logs, and credential accounts (`account`,
68
+ `providerId: 'credential'`) whose `updatedAt` falls in the window. The `redirectTo` itself is a body field, which
69
+ access logs do not record, and Better-Auth logged nothing for it while the check was off.
70
+
71
+ ## 2. Documentation: custom Better-Auth plugins belong in `betterAuth.plugins`
72
+
73
+ The descriptions of `emailAndPassword.disableSignUp` (interface, README, guide 11.44.0 → 11.44.1) named
74
+ `betterAuth.options.plugins` as the place for a project's own plugins. The framework appends `betterAuth.plugins` to its
75
+ own (JWT, 2FA, passkey). `betterAuth.options` is spread over the generated configuration, so `options.plugins`
76
+ **replaces** that list, and JWT, 2FA and passkey stop working without an error.
77
+
78
+ **Your project:** if you register plugins through `betterAuth.options.plugins`, move them to `betterAuth.plugins`. A
79
+ plugin that creates users itself (Magic Link, Generic OAuth) does not follow `emailAndPassword.disableSignUp`. Give it
80
+ its own option, for example `magicLink({ disableSignUp: true, … })`.
81
+
82
+ ## 3. `betterAuth.options.user` is merged
83
+
84
+ The framework gives Better-Auth `user: { modelName: 'users', additionalFields }`. That is the collection or table it
85
+ shares with the user model, plus the fields `betterAuth.additionalUserFields` declares, among them the `input: false` locks
86
+ on `roles`, `verified` and `twoFactorEnabled`. `betterAuth.options` was spread over that configuration, so a project
87
+ that set `options.user` for its own reason (`changeEmail`, `deleteUser`) replaced the whole block. Better-Auth then read
88
+ and wrote a `user` collection the framework never sees, and knew none of the additional fields.
89
+
90
+ **What changed:** `options.user` is merged. `modelName` stays `users` unless the project names another one. A project
91
+ field of the same name as a framework field does not replace it; change those through `betterAuth.additionalUserFields`.
92
+ A project field under another name that maps to a locked column (`fieldName: 'roles'`) is locked as well.
93
+
94
+ **Your project:** nothing, unless you set `betterAuth.options.user`. Then check whether a `user` collection or table holds
95
+ records written while the options were replaced.
96
+
97
+ ## 4. An address that differs only in case is no change
98
+
99
+ `CoreUserService.update()` syncs an address change to IAM, and that sync ends every session of the account. It compared
100
+ the stored address with the submitted one as typed, while the address is stored trimmed and in lower case. A profile
101
+ form sending `Foo@Example.com` back for `foo@example.com` therefore signed the user out everywhere without changing
102
+ anything. The comparison now uses the stored form. Nothing to do.
103
+
104
+ ## 5. The IAM rate limiter keys its counters by a bounded set of names
105
+
106
+ Only with `betterAuth.rateLimit` configured (the nest-server-starter reads `IAM_RATE_LIMIT_MAX`). Since 11.44.1 a
107
+ counter was keyed by the last segment of the path as sent, and the limiter runs for every path under the base path,
108
+ existing or not. One client sending `/iam/x1`, `/iam/x2`, … created one counter per request, and none of them reached the
109
+ limit. Once the store held `maxEntries` counters (10,000 by default, the Redis store likewise), every new client fell
110
+ into the shared overflow buckets the attacker had filled, and was refused at its first sign-in.
111
+
112
+ **What changed:** a counter is keyed by a route name the base path serves (taken from the running Better-Auth instance and
113
+ the controller, so plugin routes are included), by the matching strict entry for a strict route under an unknown name
114
+ (`/reset-password/<token>`), or by one `other` counter per client for everything else. Real routes keep their counters
115
+ as before: `/sign-in/email` and `/sign-up/email` still share one, `/get-session` and `/two-factor/enable` still have one
116
+ each. Nothing to do.
117
+
118
+ ## References
119
+
120
+ - `src/core/modules/better-auth/better-auth.config.ts`: the `advanced` block of `createBetterAuthInstance()`
121
+ - `src/core/modules/better-auth/core-better-auth-email-verification.service.ts`: `buildPasswordResetUrl()`,
122
+ `readCallbackUrlFromBetterAuthLink()`
123
+ - `tests/unit/better-auth-origin-check-test-env.spec.ts`, `tests/unit/better-auth-user-options-merge.spec.ts`,
124
+ `tests/unit/user-email-change-case.spec.ts`, `tests/unit/better-auth-rate-limit-key-bound.spec.ts`
125
+ - `.claude/rules/better-auth.md`: security checklist
@@ -0,0 +1,111 @@
1
+ # Migration Guide: 11.44.x → 11.45.x
2
+
3
+ ## 11.45.0 changes behaviour
4
+
5
+ The version number moves only the MINOR digit (the MAJOR follows NestJS). This is the 11.x counterpart of the Swagger
6
+ default from 12.7.0 (DEV-4086):
7
+
8
+ - `setupSwagger()` serves the API documentation only in `local`, `ci` and `e2e` unless the new server option
9
+ `swagger` is `true`. On every other stage (`develop`, `test`, `production`, …) `/swagger`, `/api-docs-json` and the
10
+ API-token view answer 404 after the update (§1).
11
+
12
+ Nothing else changes.
13
+
14
+ ## Overview
15
+
16
+ | Category | Details |
17
+ |---|---|
18
+ | **Breaking Changes** | Swagger is off outside `local` / `ci` / `e2e` unless `swagger: true` (§1) |
19
+ | **New Features** | `swagger` server option (`NSC__SWAGGER`); `isSwaggerEnabled()` exported; `setupSwagger()` takes the configuration as an optional third argument |
20
+ | **Bugfixes** | The full API description is no longer public on deployed stages (§1) |
21
+ | **Migration Effort** | Set `swagger: true` on the stages that must keep showing the API documentation (§1); check that every stage loads its own block (§2) |
22
+
23
+ ## Quick Migration
24
+
25
+ ```bash
26
+ pnpm add @lenne.tech/nest-server@11.45.0
27
+ pnpm run update # nest-server-starter based projects (release/11.x)
28
+ pnpm run build
29
+ pnpm test
30
+ ```
31
+
32
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual. A vendored core that closed Swagger in
33
+ `main.ts` or ported the switch by hand can drop its own version: the core now carries it.
34
+
35
+ ## 1. Swagger only where it is switched on
36
+
37
+ **Why:** `setupSwagger()` mounted the Swagger UI and the JSON document on every stage a project called it on,
38
+ production included. The full API description — every route, the roles it requires, every input shape — was public
39
+ there.
40
+
41
+ **What changed:** `setupSwagger()` asks `isSwaggerEnabled()` first (new server option `swagger`):
42
+
43
+ | `swagger` | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
44
+ |---|---|---|
45
+ | not set | served | **off** |
46
+ | `true` | served | served |
47
+ | `false` | off | off |
48
+
49
+ Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and `/api-docs-api-tokens-json`
50
+ (or the paths you gave `setupSwagger()`); they answer 404. One line in the boot log says Swagger is off. A value that
51
+ is not a boolean counts as not set, so the string `'true'` from `NEST_SERVER_CONFIG` does not switch it on;
52
+ `NSC__SWAGGER=true` arrives as a boolean.
53
+
54
+ **Your project:** nothing to do if the documentation should stay local. To keep it on a stage, set it in that
55
+ stage's block of `config.env.ts`, or through the environment:
56
+
57
+ ```typescript
58
+ // config.env.ts — only the stage that should show the documentation
59
+ develop: {
60
+ // …
61
+ swagger: true,
62
+ },
63
+ ```
64
+
65
+ ```bash
66
+ NSC__SWAGGER=true
67
+ ```
68
+
69
+ A client generator that reads `/api-docs-json` from a deployed stage (`openapi-typescript`, `orval`, …) needs the
70
+ switch on that stage, or reads the document from a local or CI run instead.
71
+
72
+ A test that calls `setupSwagger()` under the unit runner (`NODE_ENV=test`, which is no local environment) passes the
73
+ switch itself: `setupSwagger(app, options, { swagger: true })`.
74
+
75
+ ## 2. The environment is the one the loaded block names
76
+
77
+ `isSwaggerEnabled()` reads `env` of the loaded configuration, else `NODE_ENV`. On 11.x a `NODE_ENV` that names no
78
+ block in `config.env.ts` still loads the `local` block (12.7.0 refuses that start; 11.x keeps the old behaviour), and
79
+ the `local` block counts as local — such a stage keeps serving Swagger. Check the boot line of every stage:
80
+
81
+ ```
82
+ Configured for: local (requested: staging)
83
+ ```
84
+
85
+ A `(requested: …)` part means the stage runs on another block than it asked for. Add a block for that `NODE_ENV`, or
86
+ set `swagger: false` in the block it falls back to.
87
+
88
+ ## Compatibility Notes
89
+
90
+ | Pattern | Status |
91
+ |---|---|
92
+ | `setupSwagger(app, options)` in `main.ts` | Unchanged call; serves only where the switch allows it |
93
+ | A `main.ts` that calls `setupSwagger()` only outside production by its own check | Keeps working; the switch closes the other deployed stages too |
94
+ | `buildSwaggerDocument()` / `buildApiTokenSwaggerDocument()` used directly | Unchanged — the switch applies to `setupSwagger()` only |
95
+ | `SwaggerModule.setup()` called directly by the project | Not covered — gate it with `isSwaggerEnabled()` |
96
+ | The Hub's Swagger link on a stage with Swagger off | Answers 404 — set `swagger: true` there if the link should work |
97
+
98
+ ## Troubleshooting
99
+
100
+ | Symptom | Cause | Fix |
101
+ |---|---|---|
102
+ | `/swagger` or `/api-docs-json` answers 404 on a deployed stage after the update | Swagger is off outside `local` / `ci` / `e2e` | `swagger: true` in that stage's block, or `NSC__SWAGGER=true` (§1) |
103
+ | Swagger still answers on a deployed stage | The stage runs on the `local` block (boot line `Configured for: local (requested: …)`) or sets `swagger: true` | Add the missing block, or `swagger: false` (§2) |
104
+ | A unit test that serves Swagger gets 404 | The unit runner is no local environment | Pass `{ swagger: true }` as the third argument of `setupSwagger()` (§1) |
105
+
106
+ ## References
107
+
108
+ - `src/core/common/helpers/swagger-enabled.helper.ts` — `isSwaggerEnabled()`
109
+ - `src/core/common/helpers/swagger.helper.ts` — `setupSwagger()`
110
+ - `tests/unit/swagger-switch.spec.ts`
111
+ - `.claude/rules/configurable-features.md` — row "Swagger"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.44.1",
3
+ "version": "11.45.0",
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",
@@ -0,0 +1,33 @@
1
+ import type { IServerOptions } from '../interfaces/server-options.interface';
2
+ import { ConfigService } from '../services/config.service';
3
+ import { isLocalEnv } from './cookies.helper';
4
+
5
+ /**
6
+ * Whether `setupSwagger()` serves the API documentation (`swagger`, 11.45.0+ — the 12.7.0 rule, backported).
7
+ *
8
+ * | `swagger` | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
9
+ * |-----------|------------------------|---------------------------------------------------------------|
10
+ * | not set | served | **off** — none of the four paths is mounted |
11
+ * | `true` | served | served |
12
+ * | `false` | off | off |
13
+ *
14
+ * Off means nothing is mounted: neither the UI (`/swagger`, `/swagger-api-tokens`) nor the JSON documents
15
+ * (`/api-docs-json`, `/api-docs-api-tokens-json`), so they answer 404 like any unknown route. Before 11.45.0 every
16
+ * project that called `setupSwagger()` published the full API description on every stage, production included.
17
+ *
18
+ * A value that is not a boolean (the string `'true'` from `NEST_SERVER_CONFIG`) counts as not set, so a string
19
+ * cannot switch the documentation on by truthiness; `NSC__SWAGGER=true` arrives as a boolean. The environment is the
20
+ * configured `env`, else `NODE_ENV`, compared with `isLocalEnv()`.
21
+ *
22
+ * @param config - defaults to the running configuration
23
+ * @since 11.45.0
24
+ */
25
+ export function isSwaggerEnabled(
26
+ config: Partial<IServerOptions> | undefined = ConfigService.configFastButReadOnly,
27
+ ): boolean {
28
+ const setting = config?.swagger;
29
+ if (setting === true || setting === false) {
30
+ return setting;
31
+ }
32
+ return isLocalEnv(config?.env ?? process.env.NODE_ENV);
33
+ }
@@ -28,6 +28,7 @@ import { mergeRolesMetadata } from '../../modules/tenant/core-tenant.helpers';
28
28
  import { RoleEnum } from '../enums/role.enum';
29
29
  import { ConfigService } from '../services/config.service';
30
30
  import { isCookiesEnabled } from './cookies.helper';
31
+ import { isSwaggerEnabled } from './swagger-enabled.helper';
31
32
 
32
33
  import type { INestApplication, Type } from '@nestjs/common';
33
34
  import type {
@@ -139,10 +140,28 @@ const logger = new Logger('Swagger');
139
140
  /**
140
141
  * Build the enriched document and serve it — plus the API-token view, when configured. Both documents are
141
142
  * built on the first request, when every module is initialised.
143
+ *
144
+ * Since 11.45.0 only where `swagger` switches it on ({@link isSwaggerEnabled}): by default in `local`, `ci` and `e2e`,
145
+ * everywhere with `swagger: true`. Otherwise nothing is mounted — no UI, no JSON document — and one line in the log
146
+ * says so.
147
+ *
148
+ * @param config - server configuration; the running configuration by default
142
149
  */
143
- export function setupSwagger(app: INestApplication, options: ISwaggerSetupOptions): void {
150
+ export function setupSwagger(
151
+ app: INestApplication,
152
+ options: ISwaggerSetupOptions,
153
+ config: Partial<IServerOptions> = ConfigService.configFastButReadOnly ?? {},
154
+ ): void {
155
+ if (!isSwaggerEnabled(config)) {
156
+ logger.log(
157
+ `Swagger is off in this environment (${config.env ?? process.env.NODE_ENV ?? 'unknown'}): nothing is served at ` +
158
+ `/${options.path ?? 'swagger'} or ${options.jsonDocumentUrl ?? '/api-docs-json'}. Set \`swagger: true\` ` +
159
+ `(NSC__SWAGGER=true) to serve the API documentation here.`,
160
+ );
161
+ return;
162
+ }
144
163
  let document: OpenAPIObject | undefined;
145
- const fullDocument = () => (document ??= buildSwaggerDocument(app, options));
164
+ const fullDocument = () => (document ??= buildSwaggerDocument(app, options, config));
146
165
 
147
166
  SwaggerModule.setup(options.path ?? 'swagger', app, fullDocument, {
148
167
  ...options.customOptions,
@@ -154,10 +173,15 @@ export function setupSwagger(app: INestApplication, options: ISwaggerSetupOption
154
173
  return;
155
174
  }
156
175
  let viewDocument: OpenAPIObject | undefined;
157
- SwaggerModule.setup(view.path, app, () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view)), {
158
- ...options.customOptions,
159
- jsonDocumentUrl: view.jsonDocumentUrl,
160
- });
176
+ SwaggerModule.setup(
177
+ view.path,
178
+ app,
179
+ () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view, config)),
180
+ {
181
+ ...options.customOptions,
182
+ jsonDocumentUrl: view.jsonDocumentUrl,
183
+ },
184
+ );
161
185
  }
162
186
 
163
187
  /**
@@ -3459,6 +3459,25 @@ export interface IServerOptions {
3459
3459
  path?: string;
3460
3460
  };
3461
3461
 
3462
+ /**
3463
+ * Whether `setupSwagger()` serves the API documentation (11.45.0+), decided by `isSwaggerEnabled()`.
3464
+ *
3465
+ * | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
3466
+ * |-------|------------------------|---------------------------------------------------------------|
3467
+ * | not set | served | **off** |
3468
+ * | `true` | served | served |
3469
+ * | `false` | off | off |
3470
+ *
3471
+ * Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and
3472
+ * `/api-docs-api-tokens-json` (or the paths `setupSwagger()` was given) — they answer 404. Before 11.45.0 every
3473
+ * project that called `setupSwagger()` published its full API description on every stage. A value that is not a
3474
+ * boolean counts as not set. Environment variable: `NSC__SWAGGER=true`.
3475
+ *
3476
+ * @default undefined (served only in `local`, `ci` and `e2e`)
3477
+ * @since 11.45.0
3478
+ */
3479
+ swagger?: boolean;
3480
+
3462
3481
  /**
3463
3482
  * System setup configuration for initial admin creation.
3464
3483
  *
@@ -4212,7 +4231,8 @@ interface IBetterAuthBase {
4212
4231
  * 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
4232
  * `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
4214
4233
  * signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
4215
- * registers itself through `options.plugins` are not covered.
4234
+ * registers itself through `plugins` are not covered; they need their own sign-up option
4235
+ * (`magicLink({ disableSignUp: true })`).
4216
4236
  * The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
4217
4237
  * which would answer `SIGNUP_DISABLED` to every caller.
4218
4238
  * @default false
@@ -643,8 +643,8 @@ socialProviders: {
643
643
  ```
644
644
 
645
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
646
+ `NEST_SERVER_CONFIG` cannot open a closed registration. Plugins a project adds itself through `betterAuth.plugins`
647
+ (Generic OAuth, Magic Link, …) are not covered and need their own sign-up options (`magicLink({ disableSignUp: true })`). Before 11.44.1 every provider created
648
648
  accounts whatever `disableSignUp` said.
649
649
 
650
650
  **Default:** `false` (sign-up enabled) - fully backward compatible.
@@ -7,7 +7,7 @@ import * as crypto from 'crypto';
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
 
10
- import { resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper';
10
+ import { isLocalEnv, resolveServerUrls, strippedApiHostname } from '../../common/helpers/cookies.helper';
11
11
  import { revalidateWsConnectionsOf } from '../../common/helpers/graphql-ws-connection.helper';
12
12
  import { IBetterAuth, ICorsConfig } from '../../common/interfaces/server-options.interface';
13
13
  import { ConfigService } from '../../common/services/config.service';
@@ -559,6 +559,15 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
559
559
  // `Secure` TRANSPORT flag. Only injected on https so http/local and a consumer's
560
560
  // own `options.advanced.useSecureCookies` override are left untouched.
561
561
  ...(secureCookies && { defaultCookieAttributes: { secure: true } }),
562
+ // Better-Auth decides the origin check itself when this is unset: `isTest()` — `NODE_ENV === 'test'` or a
563
+ // truthy `TEST` variable — switches it off, and with it the CSRF check (backward compatibility in
564
+ // origin-check.mjs) and the validation of `callbackURL` / `redirectTo` against `trustedOrigins`. A deployed
565
+ // stage named `test` is exactly that environment, so a password-reset mail carried any `redirectTo` a caller
566
+ // chose — with a valid token, to the caller's page. Pinned for every environment that is not local / ci / e2e
567
+ // (an unknown or missing name included). Those three keep Better-Auth's own decision: vitest sets `TEST=true`,
568
+ // and pinning there would arm the check in every e2e suite of every project at once. A project's own
569
+ // `options.advanced.disableOriginCheck` still wins (see the merge below).
570
+ ...(!isLocalEnv(serverEnv) && { disableOriginCheck: false }),
562
571
  },
563
572
  basePath,
564
573
  baseURL: betterAuthBaseUrl,
@@ -674,10 +683,39 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
674
683
  const {
675
684
  advanced: optionsAdvanced,
676
685
  emailAndPassword: optionsEmailAndPassword,
686
+ user: optionsUser,
677
687
  ...restOptions
678
688
  } = config.options as Record<string, unknown>;
679
689
  finalConfig = { ...betterAuthConfig, ...restOptions };
680
690
 
691
+ // `user` is merged, not replaced. A project that sets `options.user` for its own reason (`changeEmail`,
692
+ // `deleteUser`) would otherwise drop `modelName: 'users'` — Better-Auth then reads and writes a `user` collection
693
+ // or table the framework never sees — and every field `additionalUserFields` declares, the `input: false` locks
694
+ // included. The framework's fields win over a project field of the same name; `betterAuth.additionalUserFields` is
695
+ // where a project changes them.
696
+ if (optionsUser && typeof optionsUser === 'object') {
697
+ const baseUser = betterAuthConfig.user as Record<string, unknown>;
698
+ const overrideUser = optionsUser as Record<string, unknown>;
699
+ // Copies, because the lock below writes to them and the project's options may be the frozen configuration
700
+ const projectFields = Object.fromEntries(
701
+ Object.entries((overrideUser.additionalFields as Record<string, unknown> | undefined) ?? {}).map(
702
+ ([key, field]) => [key, field && typeof field === 'object' ? { ...field } : field],
703
+ ),
704
+ );
705
+ const mergedFields = {
706
+ ...projectFields,
707
+ ...(baseUser.additionalFields as Record<string, unknown>),
708
+ };
709
+ // A project field under another key may still map to a protected column (`fieldName: 'roles'`)
710
+ lockProtectedColumns(mergedFields as Record<string, { fieldName?: string; input?: boolean }>);
711
+ finalConfig.user = {
712
+ ...baseUser,
713
+ ...overrideUser,
714
+ additionalFields: mergedFields,
715
+ modelName: overrideUser.modelName ?? baseUser.modelName,
716
+ };
717
+ }
718
+
681
719
  // `emailAndPassword` needs a DEEP merge, and this one is load-bearing.
682
720
  // The block above carries `password: { hash: nativeScryptHash, verify:
683
721
  // nativeScryptVerify }` — the hashing every stored credential was created
@@ -745,6 +783,11 @@ export function createBetterAuthInstance(options: CreateBetterAuthOptions): Crea
745
783
  | undefined),
746
784
  },
747
785
  }),
786
+ // An explicitly `undefined` value survives the spread as a present key and hands the decision back to
787
+ // Better-Auth's `isTest()`. Only a value the project actually set overrides the pin.
788
+ disableOriginCheck:
789
+ (optionsAdvanced as Record<string, unknown>).disableOriginCheck ??
790
+ (betterAuthConfig.advanced as Record<string, unknown>).disableOriginCheck,
748
791
  };
749
792
  }
750
793
  } else {
@@ -1296,14 +1339,29 @@ function buildUserFields(config: IBetterAuth): Record<string, UserFieldConfig> {
1296
1339
  // it, e.g. `additionalUserFields: { customRoles: { fieldName: 'roles', input: true } }`. Lock any
1297
1340
  // such field too, so no additionalUserFields entry — regardless of its key — can feed client input
1298
1341
  // into a protected column.
1342
+ lockProtectedColumns(coreFields);
1343
+
1344
+ return coreFields;
1345
+ }
1346
+
1347
+ /**
1348
+ * Sets `input: false` on every field that feeds a protected column under another key
1349
+ * (`customRoles: { fieldName: 'roles' }`). Used for `additionalUserFields` and for the fields a project passes through
1350
+ * `options.user.additionalFields`, which the `user` merge in createBetterAuthInstance() adds beside the framework's.
1351
+ */
1352
+ function lockProtectedColumns(fields: Record<string, { fieldName?: string; input?: boolean }>): void {
1299
1353
  const protectedColumns = new Set<string>(PROTECTED_INPUT_FALSE_KEYS);
1300
- for (const [key, field] of Object.entries(coreFields)) {
1301
- if (!protectedColumns.has(key) && field.fieldName && protectedColumns.has(field.fieldName)) {
1354
+ for (const [key, field] of Object.entries(fields)) {
1355
+ if (
1356
+ field &&
1357
+ typeof field === 'object' &&
1358
+ !protectedColumns.has(key) &&
1359
+ field.fieldName &&
1360
+ protectedColumns.has(field.fieldName)
1361
+ ) {
1302
1362
  field.input = false;
1303
1363
  }
1304
1364
  }
1305
-
1306
- return coreFields;
1307
1365
  }
1308
1366
 
1309
1367
  /**
@@ -619,6 +619,16 @@ export class CoreBetterAuthEmailVerificationService {
619
619
  return Math.max(1, Math.round(resolved / 60));
620
620
  }
621
621
 
622
+ /**
623
+ * Whether the project switched Better-Auth's origin check off (`betterAuth.options.advanced.disableOriginCheck`):
624
+ * `true`, or a list of paths, which may name the reset route. The framework itself pins `false` (11.44.2), so only a
625
+ * project's own value counts here.
626
+ */
627
+ protected isOriginCheckDisabled(): boolean {
628
+ const raw = this.configService.getFastButReadOnly<unknown>('betterAuth.options.advanced.disableOriginCheck');
629
+ return raw === true || Array.isArray(raw);
630
+ }
631
+
622
632
  protected buildPasswordResetUrl(options: SendPasswordResetEmailOptions): string {
623
633
  const configured = this.config.passwordResetLink;
624
634
 
@@ -633,7 +643,9 @@ export class CoreBetterAuthEmailVerificationService {
633
643
  // `nuxt-base-starter` sends it on every request (`forgot-password.vue` →
634
644
  // `requestPasswordReset({ email, redirectTo: appUrl('/auth/reset-password', siteUrl) })`), and
635
645
  // a client that names its page is a better authority on that page than a framework default.
636
- if (!target) {
646
+ // Only while Better-Auth's origin check validated it (see readCallbackUrlFromBetterAuthLink): a project that
647
+ // switched the check off gets the default page, never an unvalidated URL with a valid token in it.
648
+ if (!target && !this.isOriginCheckDisabled()) {
637
649
  target = this.readCallbackUrlFromBetterAuthLink(options.url);
638
650
  }
639
651
 
@@ -687,6 +699,11 @@ export class CoreBetterAuthEmailVerificationService {
687
699
  * knowing before anyone widens it. `cors.allowAll` does not widen it (an origin check has no
688
700
  * "allow everything" mode), but an over-broad `allowedOrigins` would.
689
701
  *
702
+ * And it makes the origin check itself load-bearing. Until 11.44.2 Better-Auth switched it off on its
703
+ * own under `NODE_ENV=test` (`isTest()`), which is a deployed stage in starter-based projects; the
704
+ * framework now pins `advanced.disableOriginCheck: false`. A project that switches it off itself
705
+ * gets no caller URL here at all ({@link isOriginCheckDisabled}).
706
+ *
690
707
  * Returns `undefined` for anything unparseable or absent, so the caller falls through to its own
691
708
  * resolution rather than to a half-formed URL.
692
709
  */
@@ -1,6 +1,7 @@
1
1
  import { HttpException, HttpStatus, Injectable, NestMiddleware } from '@nestjs/common';
2
2
  import { NextFunction, Request, Response } from 'express';
3
3
 
4
+ import { CONTROLLER_HANDLED_PATHS } from './core-better-auth-openapi.helper';
4
5
  import { CoreBetterAuthRateLimiter, RateLimitResult } from './core-better-auth-rate-limiter.service';
5
6
  import { CoreBetterAuthService } from './core-better-auth.service';
6
7
 
@@ -57,6 +58,9 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
57
58
  const requestPath = (req.originalUrl || req.url || '').split('?')[0];
58
59
  const path = requestPath.startsWith(basePath) ? requestPath.substring(basePath.length) : requestPath;
59
60
 
61
+ // The route names counters are keyed by, from the running instance (once per instance)
62
+ this.provideKnownEndpoints();
63
+
60
64
  // Check rate limit
61
65
  const result = await this.rateLimiter.check(ip, path);
62
66
 
@@ -94,6 +98,25 @@ export class CoreBetterAuthRateLimitMiddleware implements NestMiddleware {
94
98
  return req.ip || req.socket?.remoteAddress || 'unknown';
95
99
  }
96
100
 
101
+ /** The instance whose routes the limiter knows */
102
+ private knownEndpointsFrom: unknown = null;
103
+
104
+ /**
105
+ * Hands the limiter the routes the base path serves: Better-Auth's own (every endpoint of the running instance,
106
+ * plugins included) and the controller's. Counters are keyed by these names only, so unknown paths cannot create
107
+ * counters (see CoreBetterAuthRateLimiter.normalizeEndpoint()).
108
+ */
109
+ private provideKnownEndpoints(): void {
110
+ // Optional call: a project's stand-in service may not offer it, and the limiter stays bounded without the names
111
+ const instance = this.betterAuthService.getInstance?.() as null | undefined | { api?: Record<string, unknown> };
112
+ if (!instance || instance === this.knownEndpointsFrom) {
113
+ return;
114
+ }
115
+ this.knownEndpointsFrom = instance;
116
+ const routes = Object.values(instance.api ?? {}).map((endpoint) => (endpoint as { path?: unknown })?.path);
117
+ this.rateLimiter.setKnownEndpoints([...routes, ...CONTROLLER_HANDLED_PATHS]);
118
+ }
119
+
97
120
  /**
98
121
  * Add standard rate limit headers to response
99
122
  */