@lenne.tech/nest-server 11.44.2 → 11.46.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 (49) hide show
  1. package/.claude/rules/configurable-features.md +3 -1
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +3 -2
  4. package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
  5. package/dist/core/common/helpers/swagger-enabled.helper.js +13 -0
  6. package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
  7. package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
  8. package/dist/core/common/helpers/swagger.helper.js +16 -3
  9. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  10. package/dist/core/common/interfaces/server-options.interface.d.ts +6 -0
  11. package/dist/core/modules/better-auth/better-auth.config.js +1 -1
  12. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  13. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +2 -2
  14. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  15. package/dist/core/modules/error-code/error-codes.d.ts +18 -0
  16. package/dist/core/modules/error-code/error-codes.js +16 -0
  17. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  18. package/dist/core/modules/system-setup/core-system-setup.controller.d.ts +2 -2
  19. package/dist/core/modules/system-setup/core-system-setup.controller.js +14 -4
  20. package/dist/core/modules/system-setup/core-system-setup.controller.js.map +1 -1
  21. package/dist/core/modules/system-setup/core-system-setup.service.d.ts +18 -0
  22. package/dist/core/modules/system-setup/core-system-setup.service.js +118 -15
  23. package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
  24. package/dist/core/modules/system-setup/system-setup-http-init.helper.d.ts +12 -0
  25. package/dist/core/modules/system-setup/system-setup-http-init.helper.js +60 -0
  26. package/dist/core/modules/system-setup/system-setup-http-init.helper.js.map +1 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +2 -0
  29. package/dist/index.js.map +1 -1
  30. package/dist/server/modules/error-code/error-codes.d.ts +2 -0
  31. package/dist/tsconfig.build.tsbuildinfo +1 -1
  32. package/migration-guides/11.44.x-to-11.45.x.md +111 -0
  33. package/migration-guides/11.45.x-to-11.46.x.md +219 -0
  34. package/package.json +1 -1
  35. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  36. package/src/core/common/helpers/swagger.helper.ts +40 -6
  37. package/src/core/common/interfaces/server-options.interface.ts +79 -3
  38. package/src/core/modules/better-auth/CUSTOMIZATION.md +1 -1
  39. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +4 -0
  40. package/src/core/modules/better-auth/README.md +7 -0
  41. package/src/core/modules/better-auth/better-auth.config.ts +3 -1
  42. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +5 -2
  43. package/src/core/modules/error-code/error-codes.ts +27 -0
  44. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +23 -1
  45. package/src/core/modules/system-setup/README.md +54 -12
  46. package/src/core/modules/system-setup/core-system-setup.controller.ts +30 -8
  47. package/src/core/modules/system-setup/core-system-setup.service.ts +251 -23
  48. package/src/core/modules/system-setup/system-setup-http-init.helper.ts +165 -0
  49. package/src/index.ts +2 -0
@@ -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"
@@ -0,0 +1,219 @@
1
+ # Migration Guide: 11.45.x → 11.46.x
2
+
3
+ ## 11.46.0 changes behaviour
4
+
5
+ The version number moves only the MINOR digit (the MAJOR follows NestJS). Read §1 before you update: a deployed
6
+ instance that creates its first administrator through `POST /system-setup/init` (a setup page in the frontend) is
7
+ refused from now on until it is configured. And §4: the e-mail verification link no longer signs the user in. Both
8
+ are 11.x backports (12.4.0 and 12.3.0); 12.x projects have them since then.
9
+
10
+ ## Overview
11
+
12
+ | Category | Details |
13
+ |---|---|
14
+ | **Breaking Changes** | `POST /system-setup/init` is closed outside `local`, `ci` and `e2e` unless `systemSetup.httpInit` opens it (§1). The verification link no longer signs the user in: `autoSignInAfterVerification` defaults to `false` (§4) |
15
+ | **New Features** | `systemSetup.httpInit` (`true` or `{ token }`), the `X-System-Setup-Token` header, `httpInitEnabled` / `httpInitTokenRequired` in `GET /system-setup/status`, error codes `LTNS_0053` / `LTNS_0054`, a boot report for a deployment that cannot be set up (§1) |
16
+ | **Bugfixes** | A deployed instance without users and without `initialAdmin` could be taken over through the anonymous init (§1). A creation that failed after the user was written left a user without the admin role behind and locked the setup for good (§2). An all-digit `initialAdmin` password from the environment crashed the boot, and camelCase ENV names for it were ignored silently (§3). A forwarded verification link signed its recipient in to the sender's account (login CSRF, §4) |
17
+ | **Migration Effort** | None for a deployment that provisions its first admin through `initialAdmin`, none for one whose users already exist, and none locally. A NEW deployed stage set up through the UI: one ENV variable (§1). A frontend whose verify page expects a session afterwards: lead to the sign-in instead (§4) |
18
+
19
+ ## Quick Migration
20
+
21
+ ```bash
22
+ pnpm add @lenne.tech/nest-server@11.46.0
23
+ pnpm run update # nest-server-starter based projects
24
+ pnpm run build
25
+ pnpm test
26
+ ```
27
+
28
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
29
+
30
+ Local development and the e2e suites of a starter-based project keep working without a change: `local`, `ci` and
31
+ `e2e` keep the init open. A deployment whose database already has users is not affected either: the init was locked
32
+ there before, and stays locked.
33
+
34
+ ## 1. The HTTP init is fail-closed outside the local environments
35
+
36
+ `POST /system-setup/init` is anonymous (`S_EVERYONE`). Until 11.46.0 its only guard was "no user exists yet", in every
37
+ environment. So every deployed instance that went live without `systemSetup.initialAdmin` — a new deployment, or one
38
+ whose database was reset — could be taken over by whoever called the route before the first person signed up: an
39
+ administrator account for anybody who found the API.
40
+
41
+ **What changes:** outside `local`, `ci` and `e2e` the init answers **403 `LTNS_0053`** unless `systemSetup.httpInit`
42
+ opens it. The environment is the configured `env` (else `NODE_ENV`); the deployed `develop` and `test` stages of a
43
+ starter-based project, `production` and `staging` count as deployed.
44
+
45
+ **The 11.x local-block fallback is covered.** 11.x loads the `local` block for a `NODE_ENV` without a block of its own
46
+ (boot line `Configured for: local (requested: <name>)`) or an empty one, so such a stage reports `env: 'local'`. The
47
+ init then decides by `NODE_ENV` instead: a configured `env` that is local counts only while `NODE_ENV` is unset or
48
+ local too (`NODE_ENV=test` under vitest / jest excepted). A stage with `NODE_ENV=staging` on the `local` block, or with
49
+ `NODE_ENV=` empty, is therefore closed like any deployed one — `resolveSystemSetupEnv()`.
50
+
51
+ | `systemSetup.httpInit` | `local` / `ci` / `e2e` | every other environment |
52
+ |---|---|---|
53
+ | not set | open | **closed** — 403 `LTNS_0053` |
54
+ | `true` | open | open, without a token |
55
+ | `{ token: '<at least 16 characters>' }` | open, token required | open, token required — 403 `LTNS_0054` without it |
56
+ | `false` / `{ enabled: false }` | closed | closed |
57
+
58
+ `systemSetup.initialAdmin` is not affected: the configured admin is still created at boot in every environment.
59
+
60
+ **How a new 11.x deployment gets its first admin**, preferred first:
61
+
62
+ 1. **Provision the admin via ENV** — created on the next start, no setup page needed:
63
+
64
+ ```bash
65
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
66
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=<strong password>
67
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME=Admin # optional
68
+ ```
69
+
70
+ The admin is created only while no user exists, so the variables can stay; change the password after the first
71
+ sign-in.
72
+
73
+ 2. **Open the init with a token** when the setup must happen through the UI:
74
+
75
+ ```bash
76
+ NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN=<secret of at least 16 characters, with letters>
77
+ ```
78
+
79
+ The frontend sends it in the `X-System-Setup-Token` header. Remove the variable once the admin exists.
80
+
81
+ 3. **Open the init without a token** (`NSC__SYSTEM_SETUP__HTTP_INIT=true`) only where nobody else can reach the API
82
+ before you do: whoever calls it first becomes the administrator. The boot warns about it while no user exists.
83
+
84
+ **A misconfiguration closes, it never opens.** `httpInit: { token: process.env.SETUP_TOKEN }` with the variable unset,
85
+ an empty or short token, or an empty / all-digit `NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN` (the environment reader turns
86
+ it into a number) keep the init closed and log an error at boot naming the problem. A string `"true"` from
87
+ `NEST_SERVER_CONFIG` counts as not set.
88
+
89
+ **Frontend:** `GET /system-setup/status` additionally returns `httpInitEnabled` and `httpInitTokenRequired`, always,
90
+ whatever `needsSetup` says. Show the setup form only when `needsSetup && httpInitEnabled`, with a token field when
91
+ `httpInitTokenRequired`. A backend older than 11.46.0 sends neither field; treat that as "available" (as before).
92
+
93
+ ```typescript
94
+ const { needsSetup, httpInitEnabled = true, httpInitTokenRequired = false } = await status.json();
95
+ if (needsSetup && httpInitEnabled) {
96
+ await fetch('/system-setup/init', {
97
+ body: JSON.stringify({ email, name, password }),
98
+ headers: {
99
+ 'Content-Type': 'application/json',
100
+ ...(httpInitTokenRequired ? { 'X-System-Setup-Token': setupToken } : {}),
101
+ },
102
+ method: 'POST',
103
+ });
104
+ }
105
+ ```
106
+
107
+ **Boot report.** A deployed instance that starts with zero users, no usable `initialAdmin` and a closed init now logs
108
+ an error that names both ways in — before, it stayed silent until somebody tried to sign in.
109
+
110
+ **Swagger:** while the init is closed, `POST /system-setup/init` is left out of the document `setupSwagger()` builds.
111
+
112
+ **A project controller** that extends `CoreSystemSetupController` and overrides `createInitialAdmin()` must call
113
+ `this.systemSetupService.assertHttpInitAllowed(token)` first (the token read with
114
+ `@Headers(SYSTEM_SETUP_TOKEN_HEADER)`); otherwise the override keeps the init open in every environment. A project's
115
+ own endpoint that calls `CoreSystemSetupService.createInitialAdmin()` directly does the same.
116
+
117
+ ## 2. A failed creation no longer leaves a user behind
118
+
119
+ When a step after creating the user failed (linking the credential account, the user sync, the role update, the legacy
120
+ password), only the setup claim was released. The user stayed — without the admin role — so `needsSetup` turned
121
+ `false` and the init was refused for good: a deployment with a user and no administrator, recoverable only by editing
122
+ the database.
123
+
124
+ **What changes:** the partially created user is removed again (`internalAdapter.deleteUser()`: sessions, accounts and
125
+ the `users` document), `needsSetup` stays `true`, and the setup can be retried. The caller still gets 403 `LTNS_0050`,
126
+ and the server log names the original failure. If the removal itself fails, the log says which user to delete by hand.
127
+
128
+ **What to check on an instance that hit this before 11.46.0:** a `users` document without the admin role and no
129
+ administrator anywhere. Delete that document and its `account` documents, then provision the admin as in §1.
130
+
131
+ ## 3. `initialAdmin` from the environment
132
+
133
+ - An all-digit `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD` arrives as a number (the environment reader converts
134
+ numeric strings) and crashed the boot. It is now skipped with a warning naming the cause; use a password with
135
+ letters.
136
+ - A variable with a camelCase segment (`NSC__systemSetup__initialAdmin__email`) is not read: the environment reader
137
+ lowercases every segment it does not split at `_`. The boot now warns about such a variable and names the correct
138
+ spelling (names only, never values). The documented names are the SCREAMING_SNAKE ones in §1.
139
+
140
+ ## 4. No sign-in from the e-mail verification link
141
+
142
+ `betterAuth.emailVerification.autoSignInAfterVerification` defaulted to `true` on 11.x; it is now `false`, which is
143
+ Better-Auth's own default and the 12.x default since 12.3.0.
144
+
145
+ **Why:** with the option on, `GET /iam/verify-email` creates a session for the account the link belongs to in whatever
146
+ browser opens the link. A verification link travels by mail, so it can be forwarded: someone who signs up with their
147
+ own address and sends the unopened link to someone else has that person's browser signed in to the sender's account,
148
+ and what the recipient enters there (payment data, documents, messages) lands with the sender (login CSRF).
149
+
150
+ **How users sign in after verifying:** they click the link, the address is verified (`verified` / `verifiedAt` set as
151
+ before), and they sign in once with their password — or passkey, social login, as configured. Nothing else in the
152
+ sign-up flow changes. `CoreBetterAuthEmailVerificationService.shouldAutoSignIn()` answers `false` accordingly.
153
+
154
+ **What 11.x frontends show:** the nuxt-base-starter's verify page shows "E-Mail bestätigt — Du kannst dich jetzt
155
+ anmelden" with a "Jetzt anmelden" button since February 2026, so projects created from it need nothing. A frontend
156
+ whose verify page assumes a session afterwards (for example a redirect straight into the app) lands the user on a
157
+ signed-out page: send them to the sign-in instead, with a "verified, please sign in" message.
158
+
159
+ **To keep the previous behaviour** — only where a verification link reaches nobody but its owner:
160
+
161
+ ```typescript
162
+ // config.env.ts
163
+ betterAuth: {
164
+ emailVerification: {
165
+ autoSignInAfterVerification: true,
166
+ },
167
+ },
168
+ ```
169
+
170
+ Only the boolean `true` switches it on (`NSC__BETTER_AUTH__EMAIL_VERIFICATION__AUTO_SIGN_IN_AFTER_VERIFICATION=true`
171
+ arrives as a boolean). Any other value — the string `"true"` in `NEST_SERVER_CONFIG`, `1`, `yes` — is read as off, in
172
+ what Better-Auth receives and in what `shouldAutoSignIn()` reports, so the two cannot disagree.
173
+
174
+ ## Compatibility Notes
175
+
176
+ | Pattern | Status |
177
+ |---|---|
178
+ | `systemSetup.initialAdmin` via config or (SCREAMING_SNAKE) ENV | Unchanged |
179
+ | Setup page used locally / in e2e suites (`local`, `ci`, `e2e`) | Unchanged |
180
+ | A deployed stage whose users already exist | Unchanged (the init was locked there before) |
181
+ | Setup page on a NEW deployed stage without configuration | **403 `LTNS_0053`** — see §1 |
182
+ | `systemSetup: { enabled: false }` | Unchanged (no endpoints at all) |
183
+ | `CoreSystemSetupService.createInitialAdmin()` called by project code | Not gated — call `assertHttpInitAllowed()` first on an HTTP path |
184
+ | A frontend reading `GET /system-setup/status` | Two additional fields; existing fields unchanged |
185
+ | Frontend verify page that leads to the sign-in (nuxt-base-starter since February 2026) | Unchanged |
186
+ | Frontend verify page that expects a session after the link | Redirect to the sign-in, or set `autoSignInAfterVerification: true` (§4) |
187
+
188
+ ## Troubleshooting
189
+
190
+ | Symptom | Cause | Fix |
191
+ |---|---|---|
192
+ | 403 `LTNS_0053` on a deployed stage | The init is closed there by default | `initialAdmin` via ENV, or `NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN` (§1) |
193
+ | 403 `LTNS_0054` | Token missing or different | Send the configured value in `X-System-Setup-Token` |
194
+ | Boot error "POST /system-setup/init stays closed" | The token configuration is unusable (missing, empty, short, a number) | Set a token of at least 16 characters with letters |
195
+ | Boot error "No users exist and this instance cannot be set up" | Deployed, no users, no usable `initialAdmin`, init closed | One of the ways in §1 |
196
+ | Boot warning "Environment variable NSC__systemSetup__… is not read" | camelCase ENV names | Rename as in §3 |
197
+ | After clicking the verification link the user is signed out | `autoSignInAfterVerification` is `false` by default (§4) | Lead to the sign-in, or opt in where links reach only their owner |
198
+
199
+ ## Module Documentation
200
+
201
+ ### System Setup
202
+
203
+ - [README](../src/core/modules/system-setup/README.md) — "HTTP init (`systemSetup.httpInit`)"
204
+ - [Integration Checklist](../src/core/modules/system-setup/INTEGRATION-CHECKLIST.md)
205
+
206
+ ### Better-Auth
207
+
208
+ - [README](../src/core/modules/better-auth/README.md) — "Auto sign-in after verification"
209
+ - [Integration Checklist](../src/core/modules/better-auth/INTEGRATION-CHECKLIST.md) — e-mail verification
210
+
211
+ ## References
212
+
213
+ - `src/core/modules/system-setup/system-setup-http-init.helper.ts` — `resolveSystemSetupHttpInit()`, `isSystemSetupTokenValid()`
214
+ - `src/core/modules/system-setup/core-system-setup.service.ts` — `assertHttpInitAllowed()`, `reportSetupReachability()`, `rollbackInitialAdmin()`
215
+ - `src/core/modules/better-auth/better-auth.config.ts` — `buildEmailVerificationConfig()`;
216
+ `core-better-auth-email-verification.service.ts` — `shouldAutoSignIn()`
217
+ - `tests/unit/system-setup-http-init.spec.ts`, `tests/stories/system-setup-http-init.e2e-spec.ts`,
218
+ `tests/unit/better-auth-auto-sign-in.spec.ts`
219
+ - `.claude/rules/configurable-features.md` — "System Setup" row
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.44.2",
3
+ "version": "11.46.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
+ }
@@ -22,12 +22,18 @@ import { CoreBetterAuthService } from '../../modules/better-auth/core-better-aut
22
22
  import { CoreHubActionsController } from '../../modules/hub/core-hub-actions.controller';
23
23
  import { CoreHubController } from '../../modules/hub/core-hub.controller';
24
24
  import { isHubEnabled, normalizeHubConfig } from '../../modules/hub/hub-config.helper';
25
+ import { CoreSystemSetupController } from '../../modules/system-setup/core-system-setup.controller';
26
+ import {
27
+ resolveSystemSetupEnv,
28
+ resolveSystemSetupHttpInit,
29
+ } from '../../modules/system-setup/system-setup-http-init.helper';
25
30
  import { SKIP_TENANT_CHECK_KEY } from '../../modules/tenant/core-tenant.decorators';
26
31
  import { API_METHODS_KEY } from '../decorators/api-methods.decorator';
27
32
  import { mergeRolesMetadata } from '../../modules/tenant/core-tenant.helpers';
28
33
  import { RoleEnum } from '../enums/role.enum';
29
34
  import { ConfigService } from '../services/config.service';
30
35
  import { isCookiesEnabled } from './cookies.helper';
36
+ import { isSwaggerEnabled } from './swagger-enabled.helper';
31
37
 
32
38
  import type { INestApplication, Type } from '@nestjs/common';
33
39
  import type {
@@ -139,10 +145,28 @@ const logger = new Logger('Swagger');
139
145
  /**
140
146
  * Build the enriched document and serve it — plus the API-token view, when configured. Both documents are
141
147
  * built on the first request, when every module is initialised.
148
+ *
149
+ * Since 11.45.0 only where `swagger` switches it on ({@link isSwaggerEnabled}): by default in `local`, `ci` and `e2e`,
150
+ * everywhere with `swagger: true`. Otherwise nothing is mounted — no UI, no JSON document — and one line in the log
151
+ * says so.
152
+ *
153
+ * @param config - server configuration; the running configuration by default
142
154
  */
143
- export function setupSwagger(app: INestApplication, options: ISwaggerSetupOptions): void {
155
+ export function setupSwagger(
156
+ app: INestApplication,
157
+ options: ISwaggerSetupOptions,
158
+ config: Partial<IServerOptions> = ConfigService.configFastButReadOnly ?? {},
159
+ ): void {
160
+ if (!isSwaggerEnabled(config)) {
161
+ logger.log(
162
+ `Swagger is off in this environment (${config.env ?? process.env.NODE_ENV ?? 'unknown'}): nothing is served at ` +
163
+ `/${options.path ?? 'swagger'} or ${options.jsonDocumentUrl ?? '/api-docs-json'}. Set \`swagger: true\` ` +
164
+ `(NSC__SWAGGER=true) to serve the API documentation here.`,
165
+ );
166
+ return;
167
+ }
144
168
  let document: OpenAPIObject | undefined;
145
- const fullDocument = () => (document ??= buildSwaggerDocument(app, options));
169
+ const fullDocument = () => (document ??= buildSwaggerDocument(app, options, config));
146
170
 
147
171
  SwaggerModule.setup(options.path ?? 'swagger', app, fullDocument, {
148
172
  ...options.customOptions,
@@ -154,10 +178,15 @@ export function setupSwagger(app: INestApplication, options: ISwaggerSetupOption
154
178
  return;
155
179
  }
156
180
  let viewDocument: OpenAPIObject | undefined;
157
- SwaggerModule.setup(view.path, app, () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view)), {
158
- ...options.customOptions,
159
- jsonDocumentUrl: view.jsonDocumentUrl,
160
- });
181
+ SwaggerModule.setup(
182
+ view.path,
183
+ app,
184
+ () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view, config)),
185
+ {
186
+ ...options.customOptions,
187
+ jsonDocumentUrl: view.jsonDocumentUrl,
188
+ },
189
+ );
161
190
  }
162
191
 
163
192
  /**
@@ -406,6 +435,11 @@ function isSwitchedOffOperation(reference: IHandlerReference, method: string, av
406
435
  ) {
407
436
  return !HUB_AVAILABILITY[handlerName](availability, availability.hub);
408
437
  }
438
+ // The anonymous init answers LTNS_0053 to everybody where `systemSetup.httpInit` keeps it closed (11.46.0+)
439
+ if (extendsClass(controller, CoreSystemSetupController) && handlerName === 'createInitialAdmin') {
440
+ const { env, systemSetup } = availability.config;
441
+ return !resolveSystemSetupHttpInit(systemSetup?.httpInit, resolveSystemSetupEnv(env)).enabled;
442
+ }
409
443
  return false;
410
444
  }
411
445
 
@@ -510,8 +510,15 @@ export type IBetterAuth = IBetterAuthWithoutPasskey | IBetterAuthWithPasskey;
510
510
  */
511
511
  export interface IBetterAuthEmailVerificationConfig {
512
512
  /**
513
- * Whether to automatically sign in the user after email verification.
514
- * @default true
513
+ * Whether `GET /iam/verify-email` signs in the browser that opens the verification link.
514
+ *
515
+ * Off by default, as in Better-Auth (11.46.0+, backport of 12.3.0; before, the framework defaulted to `true`).
516
+ * Switching it on signs in WHOEVER opens the link, to the account the link belongs to: someone who signs up with
517
+ * their own address and forwards the unopened link has the recipient's browser signed in to their account, and what
518
+ * the recipient then enters lands there (login CSRF). Only switch it on where verification links reach nobody but
519
+ * their owner.
520
+ *
521
+ * @default false
515
522
  */
516
523
  autoSignInAfterVerification?: boolean;
517
524
 
@@ -3459,6 +3466,25 @@ export interface IServerOptions {
3459
3466
  path?: string;
3460
3467
  };
3461
3468
 
3469
+ /**
3470
+ * Whether `setupSwagger()` serves the API documentation (11.45.0+), decided by `isSwaggerEnabled()`.
3471
+ *
3472
+ * | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
3473
+ * |-------|------------------------|---------------------------------------------------------------|
3474
+ * | not set | served | **off** |
3475
+ * | `true` | served | served |
3476
+ * | `false` | off | off |
3477
+ *
3478
+ * Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and
3479
+ * `/api-docs-api-tokens-json` (or the paths `setupSwagger()` was given) — they answer 404. Before 11.45.0 every
3480
+ * project that called `setupSwagger()` published its full API description on every stage. A value that is not a
3481
+ * boolean counts as not set. Environment variable: `NSC__SWAGGER=true`.
3482
+ *
3483
+ * @default undefined (served only in `local`, `ci` and `e2e`)
3484
+ * @since 11.45.0
3485
+ */
3486
+ swagger?: boolean;
3487
+
3462
3488
  /**
3463
3489
  * System setup configuration for initial admin creation.
3464
3490
  *
@@ -3788,6 +3814,36 @@ export interface ISystemSetup {
3788
3814
  */
3789
3815
  enabled?: boolean;
3790
3816
 
3817
+ /**
3818
+ * Whether the anonymous `POST /system-setup/init` may create the first administrator.
3819
+ *
3820
+ * Fail-closed outside the local environments: whoever reaches an API without users through that route becomes its
3821
+ * administrator, so a deployment provisions the first admin through {@link initialAdmin} and opens the HTTP route
3822
+ * only on purpose.
3823
+ *
3824
+ * | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
3825
+ * |-------|------------------------|---------------------------------------------------------------|
3826
+ * | not set | open | **closed** (403 `LTNS_0053`) |
3827
+ * | `true` | open | open, without a token |
3828
+ * | `{ token: '<at least 16 characters>' }` | open, token required | open, token required |
3829
+ * | `false` / `{ enabled: false, … }` | closed | closed |
3830
+ *
3831
+ * The token is sent in the `X-System-Setup-Token` header; a missing or wrong one answers 403 `LTNS_0054`. An object
3832
+ * whose token is missing, empty, shorter than 16 characters or not a string keeps the route CLOSED and logs an
3833
+ * error at boot — `{ token: process.env.SETUP_TOKEN }` with the variable unset must not open it. A value that is
3834
+ * neither a boolean nor an object (the string `'true'` from `NEST_SERVER_CONFIG`) counts as not set.
3835
+ *
3836
+ * Environment variables: `NSC__SYSTEM_SETUP__HTTP_INIT=true`, or `NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN=<secret>` (a
3837
+ * token of digits only is converted to a number by the environment reader and refused; set one of the two, not
3838
+ * both).
3839
+ *
3840
+ * `GET /system-setup/status` reports the result as `httpInitEnabled` / `httpInitTokenRequired`.
3841
+ *
3842
+ * @default undefined (open only in `local`, `ci` and `e2e`)
3843
+ * @since 11.46.0
3844
+ */
3845
+ httpInit?: boolean | ISystemSetupHttpInit;
3846
+
3791
3847
  /**
3792
3848
  * Pre-configured initial admin credentials for automatic creation on server start.
3793
3849
  *
@@ -3801,11 +3857,31 @@ export interface ISystemSetup {
3801
3857
  * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3802
3858
  * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME` (optional)
3803
3859
  *
3804
- * Security: Same zero-user guard applies - only works when no users exist.
3860
+ * Security: Same zero-user guard applies - only works when no users exist. It is not affected by
3861
+ * {@link httpInit}.
3805
3862
  */
3806
3863
  initialAdmin?: ISystemSetupInitialAdmin;
3807
3864
  }
3808
3865
 
3866
+ /**
3867
+ * Object form of {@link ISystemSetup.httpInit}: the HTTP init, protected by a setup token
3868
+ *
3869
+ * @since 11.46.0
3870
+ */
3871
+ export interface ISystemSetupHttpInit {
3872
+ /**
3873
+ * `false` keeps the HTTP init closed while the token stays configured
3874
+ * @default true
3875
+ */
3876
+ enabled?: boolean;
3877
+
3878
+ /**
3879
+ * The secret `POST /system-setup/init` must carry in the `X-System-Setup-Token` header. At least 16 characters;
3880
+ * a missing, shorter or non-string value keeps the HTTP init closed.
3881
+ */
3882
+ token?: string;
3883
+ }
3884
+
3809
3885
  /**
3810
3886
  * System setup configuration interface
3811
3887
  *
@@ -472,7 +472,7 @@ const config = {
472
472
  template: 'email-verification', // Default: 'email-verification'
473
473
  expiresIn: 86400, // Default: 86400 (24 hours)
474
474
  callbackURL: '/auth/verify-email', // Frontend verification page
475
- autoSignInAfterVerification: true, // Default: true
475
+ autoSignInAfterVerification: false, // Default: false — true signs in whoever opens the link (see README)
476
476
  resendCooldownSeconds: 60, // Default: 60
477
477
  },
478
478
  },
@@ -273,6 +273,10 @@ Email verification is **enabled by default** via Better-Auth's `emailVerificatio
273
273
  - Users receive a verification email after sign-up
274
274
  - Email contains a verification link with token
275
275
  - After verification, `verifiedAt` is automatically set on the user
276
+ - The user is **not** signed in by the verification link and signs in once afterwards (11.46.0+, as in Better-Auth).
277
+ `emailVerification: { autoSignInAfterVerification: true }` signs in whoever opens the link, to the link owner's
278
+ account — a forwarded link signs its recipient in to the sender's account. Your frontend's verify page should lead
279
+ to the sign-in rather than expect a session
276
280
  - Templates are provided in German and English
277
281
 
278
282
  ### Configuration
@@ -548,6 +548,13 @@ const config = {
548
548
 
549
549
  **Custom Templates:** Create `templates/email-verification-{locale}.ejs` in your project. Available variables: `name`, `link`, `expiresIn`, `appName`.
550
550
 
551
+ **Auto sign-in after verification (`autoSignInAfterVerification`, default `false` since 11.46.0):** with it on,
552
+ `GET /iam/verify-email` signs in the browser that opens the link — to the account the link belongs to, whoever opens
553
+ it. Someone who signs up with their own address and forwards the unopened link then has the recipient's browser signed
554
+ in to their account, and what the recipient enters there lands with them (login CSRF). Off, the user verifies and then
555
+ signs in once, as in Better-Auth's own default. Switch it on (`emailVerification: { autoSignInAfterVerification: true }`)
556
+ only where a verification link reaches nobody but its owner.
557
+
551
558
  **Brevo Integration:** When `brevoTemplateId` is set and Brevo is configured (`config.brevo`), verification emails are sent via Brevo's transactional API instead of SMTP/EJS templates. The same template variables (`name`, `link`, `appName`, `expiresIn`) are passed to the Brevo template.
552
559
 
553
560
  ### Sign-Up Checks (v11.13.0+)
@@ -903,7 +903,9 @@ function buildEmailVerificationConfig(
903
903
  // Get configuration values (with defaults)
904
904
  const configObj = typeof emailVerificationConfig === 'object' ? emailVerificationConfig : {};
905
905
  const expiresIn = configObj.expiresIn ?? 86400; // 24 hours
906
- const autoSignInAfterVerification = configObj.autoSignInAfterVerification ?? true;
906
+ // Off unless switched on, as Better-Auth has it (11.46.0+): on verification Better-Auth signs in the browser that
907
+ // opens the link, to the account the link belongs to — a forwarded link signs its recipient in to the sender's account
908
+ const autoSignInAfterVerification = configObj.autoSignInAfterVerification === true;
907
909
 
908
910
  const result: Record<string, unknown> = {
909
911
  autoSignInAfterVerification,
@@ -37,7 +37,7 @@ type ResolvedEmailVerificationConfig = Pick<
37
37
  * Default configuration for email verification
38
38
  */
39
39
  const DEFAULT_CONFIG: ResolvedEmailVerificationConfig = {
40
- autoSignInAfterVerification: true,
40
+ autoSignInAfterVerification: false,
41
41
  callbackURL: '/auth/verify-email',
42
42
  enabled: true,
43
43
  expiresIn: 86400, // 24 hours in seconds
@@ -191,9 +191,12 @@ export class CoreBetterAuthEmailVerificationService {
191
191
 
192
192
  /**
193
193
  * Check if auto sign-in after verification is enabled
194
+ *
195
+ * `=== true` as in `better-auth.config.ts`, which decides what Better-Auth does: a value arriving as
196
+ * a string in `NEST_SERVER_CONFIG` must not report a sign-in that Better-Auth never performs.
194
197
  */
195
198
  shouldAutoSignIn(): boolean {
196
- return this.config.autoSignInAfterVerification;
199
+ return this.config.autoSignInAfterVerification === true;
197
200
  }
198
201
 
199
202
  /**