@lenne.tech/nest-server 11.45.0 → 11.46.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 (47) hide show
  1. package/.claude/rules/configurable-features.md +2 -1
  2. package/.claude/rules/testing.md +4 -4
  3. package/FRAMEWORK-API.md +2 -2
  4. package/dist/core/common/filters/http-exception-log.filter.js +4 -3
  5. package/dist/core/common/filters/http-exception-log.filter.js.map +1 -1
  6. package/dist/core/common/helpers/swagger.helper.js +6 -0
  7. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  8. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  9. package/dist/core/modules/better-auth/better-auth.config.js +1 -1
  10. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  11. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +2 -2
  12. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  13. package/dist/core/modules/error-code/error-codes.d.ts +18 -0
  14. package/dist/core/modules/error-code/error-codes.js +16 -0
  15. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  16. package/dist/core/modules/system-setup/core-system-setup.controller.d.ts +2 -2
  17. package/dist/core/modules/system-setup/core-system-setup.controller.js +14 -4
  18. package/dist/core/modules/system-setup/core-system-setup.controller.js.map +1 -1
  19. package/dist/core/modules/system-setup/core-system-setup.service.d.ts +18 -0
  20. package/dist/core/modules/system-setup/core-system-setup.service.js +118 -15
  21. package/dist/core/modules/system-setup/core-system-setup.service.js.map +1 -1
  22. package/dist/core/modules/system-setup/system-setup-http-init.helper.d.ts +12 -0
  23. package/dist/core/modules/system-setup/system-setup-http-init.helper.js +60 -0
  24. package/dist/core/modules/system-setup/system-setup-http-init.helper.js.map +1 -0
  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/server/modules/error-code/error-codes.d.ts +2 -0
  29. package/dist/tsconfig.build.tsbuildinfo +1 -1
  30. package/migration-guides/11.45.x-to-11.46.x.md +219 -0
  31. package/migration-guides/11.46.0-to-11.46.1.md +68 -0
  32. package/package.json +3 -3
  33. package/src/core/common/filters/http-exception-log.filter.ts +7 -3
  34. package/src/core/common/helpers/swagger.helper.ts +10 -0
  35. package/src/core/common/interfaces/server-options.interface.ts +60 -3
  36. package/src/core/modules/better-auth/CUSTOMIZATION.md +1 -1
  37. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +4 -0
  38. package/src/core/modules/better-auth/README.md +7 -0
  39. package/src/core/modules/better-auth/better-auth.config.ts +3 -1
  40. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +5 -2
  41. package/src/core/modules/error-code/error-codes.ts +27 -0
  42. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +23 -1
  43. package/src/core/modules/system-setup/README.md +54 -12
  44. package/src/core/modules/system-setup/core-system-setup.controller.ts +30 -8
  45. package/src/core/modules/system-setup/core-system-setup.service.ts +251 -23
  46. package/src/core/modules/system-setup/system-setup-http-init.helper.ts +165 -0
  47. package/src/index.ts +1 -0
@@ -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
@@ -0,0 +1,68 @@
1
+ # Migration Guide: 11.46.0 → 11.46.1
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security: mongodb 7.8.0 closes GHSA-77w5-j825-v4qm (`timeoutMS`) and a flaw in the host-name check of SRV lookups (`mongodb+srv://`) (§1). Error responses of `HttpExceptionLogFilter` no longer contain `options` / `cause` (§2) |
10
+ | **Migration Effort** | Update. A project that pins mongoose / mongodb itself — vendored cores included — raises them (§1) |
11
+
12
+ 11.46.1 is a security patch for 11.46.0 (`latest-11`). Besides the dependency update, one framework fix: error
13
+ responses no longer carry `options` / `cause` (§2). Both changes also ship in 12.8.5 (`latest`; the mongoose / mongodb update already in 12.8.4) and 12.6.8
14
+ (`latest-12.6`).
15
+
16
+ ## Quick Migration
17
+
18
+ ```bash
19
+ pnpm add @lenne.tech/nest-server@11.46.1
20
+ pnpm run update # nest-server-starter based projects
21
+ pnpm run build
22
+ pnpm test
23
+ ```
24
+
25
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual, and raise mongoose / mongodb in the project's own
26
+ `package.json` (§1).
27
+
28
+ ## 1. mongoose 9.12.0 and mongodb 7.8.0 (security)
29
+
30
+ On 11.x mongoose and mongodb are regular dependencies of the framework, so an npm-mode project gets both with the
31
+ update. mongoose 9.12.0 moves to the mongodb driver 7.8.0, which closes two flaws present in every earlier 7.x:
32
+
33
+ - **GHSA-77w5-j825-v4qm / CVE-2026-119179** (high): with `timeoutMS`, a connection-pool desynchronization after an
34
+ operation timeout could hand one user's data to another. Only projects that set `timeoutMS` themselves are affected —
35
+ the framework never sets it. Since 7.8.0 `timeoutMS` is a no-op; use `serverSelectionTimeoutMS`, `socketTimeoutMS`,
36
+ `waitQueueTimeoutMS` and `maxTimeMS` instead.
37
+ - **SRV host-name verification** (mongodb `>= 3.3.3 < 7.8.0`, no GHSA): a host returned by the SRV lookup of a
38
+ `mongodb+srv://` URL was not verified properly, so whoever controlled the DNS answer could redirect the driver to a
39
+ host outside your domain. Projects with `mongodb://host1,host2` URLs are not affected.
40
+
41
+ Neither appears in `pnpm audit`, so the update is the only signal.
42
+
43
+ **What to do:** nothing for an npm-mode project that does not pin mongoose itself. A project that pins mongoose or
44
+ mongodb itself — every vendor-mode project does — sets them to `9.12.0` / `7.8.0`; mongoose 9.11 pins the driver to
45
+ `~7.7`, so raising mongodb alone leaves mongoose's own copy vulnerable:
46
+
47
+ ```bash
48
+ pnpm add mongoose@9.12.0 mongodb@7.8.0
49
+ ```
50
+
51
+ ## 2. Error responses no longer contain `options` / `cause`
52
+
53
+ `HttpExceptionLogFilter` (registered by nest-server-starter's `main.ts` while `logExceptions` is on, its default)
54
+ answered a REST request with every field of the exception — including `options` and the `cause` the throwing code
55
+ passed (`new BadRequestException('…', { cause: dbError })`). An internal error message, a query or a connection
56
+ string could reach the client that way. Error responses now leave `options` and `cause` out; `response`, `status`,
57
+ `message` and `name` stay as before, so frontends reading them need no change. The cause is still logged.
58
+
59
+ ## Troubleshooting
60
+
61
+ | Symptom | Cause | Fix |
62
+ |---|---|---|
63
+ | Two mongodb copies in `pnpm why mongodb` | The project pins mongoose 9.11 or mongodb 7.7 | `pnpm add mongoose@9.12.0 mongodb@7.8.0` |
64
+ | Operations no longer time out after `timeoutMS` | `timeoutMS` is a no-op since mongodb 7.8.0 | `serverSelectionTimeoutMS`, `socketTimeoutMS`, `maxTimeMS` |
65
+
66
+ ## References
67
+
68
+ - `package.json` — `dependencies` (mongodb, mongoose)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.45.0",
3
+ "version": "11.46.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",
@@ -125,8 +125,8 @@
125
125
  "js-sha256": "1.0.0",
126
126
  "json-to-graphql-query": "2.3.0",
127
127
  "lodash": "4.18.1",
128
- "mongodb": "7.7.0",
129
- "mongoose": "9.11.2",
128
+ "mongodb": "7.8.0",
129
+ "mongoose": "9.12.0",
130
130
  "multer": "2.5.0",
131
131
  "node-mailjet": "6.0.11",
132
132
  "nodemailer": "10.1.4",
@@ -21,8 +21,12 @@ export class HttpExceptionLogFilter implements ExceptionFilter {
21
21
  const ctx = host.switchToHttp();
22
22
  const res = ctx.getResponse<Response>();
23
23
  const status = exception.getStatus();
24
- res
25
- .status(status)
26
- .json(exception instanceof ServiceUnavailableException ? ({ ...exception } as any).response : { ...exception });
24
+ // The exception's own fields, minus what it carries for the log: `options` and the `cause` passed to it (an
25
+ // internal error, a query, a connection string) must never reach the client. The shape the frontends read
26
+ // (response, status, message, name) is unchanged.
27
+ const body: Record<string, unknown> = { ...exception };
28
+ delete body.options;
29
+ delete body.cause;
30
+ res.status(status).json(exception instanceof ServiceUnavailableException ? body.response : body);
27
31
  }
28
32
  }
@@ -22,6 +22,11 @@ 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';
@@ -430,6 +435,11 @@ function isSwitchedOffOperation(reference: IHandlerReference, method: string, av
430
435
  ) {
431
436
  return !HUB_AVAILABILITY[handlerName](availability, availability.hub);
432
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
+ }
433
443
  return false;
434
444
  }
435
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
 
@@ -3807,6 +3814,36 @@ export interface ISystemSetup {
3807
3814
  */
3808
3815
  enabled?: boolean;
3809
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
+
3810
3847
  /**
3811
3848
  * Pre-configured initial admin credentials for automatic creation on server start.
3812
3849
  *
@@ -3820,11 +3857,31 @@ export interface ISystemSetup {
3820
3857
  * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3821
3858
  * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME` (optional)
3822
3859
  *
3823
- * 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}.
3824
3862
  */
3825
3863
  initialAdmin?: ISystemSetupInitialAdmin;
3826
3864
  }
3827
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
+
3828
3885
  /**
3829
3886
  * System setup configuration interface
3830
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
  /**
@@ -640,6 +640,33 @@ export const LtnsErrors = {
640
640
  },
641
641
  },
642
642
 
643
+ /**
644
+ * `POST /system-setup/init` is closed in this environment (11.46.0+): by default it is open only in `local`, `ci`
645
+ * and `e2e`. A deployment provisions its first admin through `systemSetup.initialAdmin`, or opens the HTTP init
646
+ * explicitly with `systemSetup.httpInit`.
647
+ */
648
+ SYSTEM_SETUP_HTTP_INIT_DISABLED: {
649
+ code: 'LTNS_0053',
650
+ message: 'Initial admin setup over HTTP is not enabled in this environment',
651
+ translations: {
652
+ de: 'Die Ersteinrichtung über die Oberfläche ist in dieser Umgebung nicht freigegeben.',
653
+ en: 'Initial admin setup over HTTP is not enabled in this environment.',
654
+ },
655
+ },
656
+
657
+ /**
658
+ * `POST /system-setup/init` requires the setup token (`systemSetup.httpInit.token`) in the `X-System-Setup-Token`
659
+ * header, and the request sent none or a different one (11.46.0+).
660
+ */
661
+ SYSTEM_SETUP_TOKEN_INVALID: {
662
+ code: 'LTNS_0054',
663
+ message: 'Missing or invalid system setup token',
664
+ translations: {
665
+ de: 'Der Einrichtungs-Token fehlt oder ist falsch.',
666
+ en: 'The system setup token is missing or invalid.',
667
+ },
668
+ },
669
+
643
670
  // =====================================================
644
671
  // AI Errors (LTNS_0600-LTNS_0699)
645
672
  // =====================================================
@@ -10,7 +10,9 @@
10
10
 
11
11
  | Scenario | Action Needed |
12
12
  | ---------------------------------------------------- | ----------------------------------------------- |
13
- | Fresh deployment needs initial admin creation | None - endpoints are available by default |
13
+ | Local development / e2e suites (`local`, `ci`, `e2e`) | None - the init endpoint is open there by default |
14
+ | A deployed stage needs its first admin (11.46.0+) | Set ENV variables (Step 1) - the HTTP init is closed there by default |
15
+ | A deployed stage must be set up through a UI form | Step 1b (setup token) |
14
16
  | Automated deployment (Docker/CI) needs auto-creation | Set ENV variables (Step 1) |
15
17
  | Want to disable system setup | Set `systemSetup: { enabled: false }` in config |
16
18
  | Custom setup logic (extra fields, notifications) | Step 2 (Custom Controller) |
@@ -63,6 +65,22 @@ The admin is created automatically on server start when zero users exist.
63
65
 
64
66
  ---
65
67
 
68
+ ## Step 1b: Open the HTTP init with a token (Optional, 11.46.0+)
69
+
70
+ Outside `local`, `ci` and `e2e`, `POST /system-setup/init` answers 403 `LTNS_0053` unless `systemSetup.httpInit`
71
+ opens it. When a deployed stage must be set up through a form:
72
+
73
+ ```bash
74
+ NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN=<secret of at least 16 characters, with letters>
75
+ ```
76
+
77
+ The frontend sends it in the `X-System-Setup-Token` header (403 `LTNS_0054` without it). `GET /system-setup/status`
78
+ reports `httpInitEnabled` / `httpInitTokenRequired`. Remove the variable once the admin exists.
79
+
80
+ **WHY a token and not `httpInit: true`:** without a token, whoever reaches the API first becomes the administrator.
81
+
82
+ ---
83
+
66
84
  ## Step 2: Custom Controller (Optional)
67
85
 
68
86
  Only needed if you want to add extra validation, logging, or custom fields.
@@ -80,6 +98,9 @@ export class SystemSetupController extends CoreSystemSetupController {
80
98
  }
81
99
  ```
82
100
 
101
+ **An override of `createInitialAdmin()` must call `this.systemSetupService.assertHttpInitAllowed(token)` first** (the
102
+ token read with `@Headers(SYSTEM_SETUP_TOKEN_HEADER)`). Otherwise it keeps the init open in every environment.
103
+
83
104
  > **Note:** The SystemSetup module auto-registers its controller via CoreModule. To use a custom controller, you would need to disable auto-registration and register your own module.
84
105
 
85
106
  ---
@@ -92,6 +113,7 @@ export class SystemSetupController extends CoreSystemSetupController {
92
113
  - [ ] `POST /system-setup/init` creates admin user with correct role
93
114
  - [ ] `GET /system-setup/status` returns `{ needsSetup: false }` after init
94
115
  - [ ] `POST /system-setup/init` returns 403 when users already exist
116
+ - [ ] On a deployed stage without `httpInit`: `POST /system-setup/init` returns 403 `LTNS_0053`
95
117
 
96
118
  ---
97
119