@lenne.tech/nest-server 12.6.2 → 12.7.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 (52) hide show
  1. package/.claude/rules/better-auth.md +10 -2
  2. package/.claude/rules/configurable-features.md +3 -2
  3. package/.claude/rules/testing.md +7 -5
  4. package/CLAUDE.md +4 -0
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/helpers/config.helper.js +26 -2
  7. package/dist/core/common/helpers/config.helper.js.map +1 -1
  8. package/dist/core/common/helpers/cookies.helper.js +0 -3
  9. package/dist/core/common/helpers/cookies.helper.js.map +1 -1
  10. package/dist/core/common/helpers/swagger-enabled.helper.d.ts +2 -0
  11. package/dist/core/common/helpers/swagger-enabled.helper.js +10 -0
  12. package/dist/core/common/helpers/swagger-enabled.helper.js.map +1 -0
  13. package/dist/core/common/helpers/swagger.helper.d.ts +1 -1
  14. package/dist/core/common/helpers/swagger.helper.js +10 -3
  15. package/dist/core/common/helpers/swagger.helper.js.map +1 -1
  16. package/dist/core/common/interfaces/server-options.interface.d.ts +1 -0
  17. package/dist/core/modules/ai/core-ai.controller.d.ts +1 -1
  18. package/dist/core/modules/ai/core-ai.controller.js +13 -3
  19. package/dist/core/modules/ai/core-ai.controller.js.map +1 -1
  20. package/dist/core/modules/ai/core-ai.resolver.d.ts +1 -1
  21. package/dist/core/modules/ai/core-ai.resolver.js +8 -3
  22. package/dist/core/modules/ai/core-ai.resolver.js.map +1 -1
  23. package/dist/core/modules/ai/services/core-ai-prompt.service.d.ts +3 -1
  24. package/dist/core/modules/ai/services/core-ai-prompt.service.js +3 -2
  25. package/dist/core/modules/ai/services/core-ai-prompt.service.js.map +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +7 -4
  27. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -1
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.js +1 -0
  30. package/dist/index.js.map +1 -1
  31. package/dist/main.js.map +1 -1
  32. package/docs/REQUEST-LIFECYCLE.md +9 -3
  33. package/migration-guides/12.5.x-to-12.6.x.md +10 -0
  34. package/migration-guides/12.6.x-to-12.7.x.md +307 -0
  35. package/migration-guides/12.7.0-to-12.7.1.md +99 -0
  36. package/package.json +1 -1
  37. package/src/core/common/helpers/config.helper.ts +58 -2
  38. package/src/core/common/helpers/cookies.helper.ts +13 -10
  39. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  40. package/src/core/common/helpers/swagger.helper.ts +30 -6
  41. package/src/core/common/interfaces/server-options.interface.ts +26 -5
  42. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +4 -1
  43. package/src/core/modules/ai/core-ai.controller.ts +18 -3
  44. package/src/core/modules/ai/core-ai.resolver.ts +14 -3
  45. package/src/core/modules/ai/services/core-ai-prompt.service.ts +11 -5
  46. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +2 -2
  47. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +24 -6
  48. package/src/core/modules/better-auth/core-better-auth.service.ts +1 -1
  49. package/src/core/modules/tus/README.md +2 -1
  50. package/src/index.ts +1 -0
  51. package/src/main.ts +3 -2
  52. package/migration-guides/12.6.1-to-12.6.2.md +0 -79
@@ -0,0 +1,307 @@
1
+ # Migration Guide: 12.6.x → 12.7.x
2
+
3
+ ## 12.7.0 contains breaking changes
4
+
5
+ The version number moves only the MINOR digit (the MAJOR follows NestJS). Two defaults change:
6
+
7
+ - `getEnvironmentConfig()` now refuses to load a configuration when `NODE_ENV` is empty or names an environment that
8
+ has no block in `config.env.ts`. Until 12.7.0 both cases silently got the `local` block. A stage or job that relied
9
+ on that stops at startup after the update. That is intended: the `local` block on a deployed stage is the hole this
10
+ release closes (§1).
11
+ - `setupSwagger()` serves the API documentation only in `local`, `ci` and `e2e` unless `swagger: true` is set. A
12
+ deployed stage that showed `/swagger` until now answers 404 there after the update (§4).
13
+ - In JWT mode (`cookies: false`) CORS answers the configured origins with credentials instead of every origin with
14
+ `*`. A browser page on an origin that is neither `appUrl`, `baseUrl` nor in `cors.allowedOrigins` can no longer
15
+ call the API (§5).
16
+ - `GET /iam/list-sessions` names the sessions by `id` and hands out no session token any more; revoke a session with
17
+ `POST /iam/revoke-session` and `{ sessionId }` (§6).
18
+
19
+ ## Overview
20
+
21
+ | Category | Details |
22
+ |---|---|
23
+ | **Breaking Changes** | An empty `NODE_ENV`, or one without a block in `config.env.ts`, throws at startup instead of loading the `local` block (§1). Swagger is off outside `local` / `ci` / `e2e` unless `swagger: true` (§4). JWT mode answers only the configured origins, with credentials, instead of `*` (§5). `list-sessions` hands out no tokens (§6) |
24
+ | **New Features** | `POST /iam/revoke-session` accepts `{ sessionId }` (§6); `swagger` server option (§4); `includeDisabled` for the AI prompt list (§7) |
25
+ | **Bugfixes** | A deployed stage can no longer run on the `local` block by a missing block or an unset host variable (§1). A JWT-mode API on a separate origin can finish a 2FA sign-in in the browser (§5). A disabled AI prompt can be managed again (§7) |
26
+ | **Migration Effort** | Check the boot line of every stage and job before updating and add a block for each `NODE_ENV` that has none (§1); check scripts and process files that set `NODE_ENV` (§2); know what your platform does with a refused start (§3); set `swagger: true` on the stages that must keep showing the API documentation (§4); in JWT mode, list every browser origin that calls the API (§5); a session management screen revokes by `sessionId` (§6); an AI prompt management screen lists with `includeDisabled` (§7) |
27
+
28
+ ## Quick Migration
29
+
30
+ ```bash
31
+ pnpm add @lenne.tech/nest-server@12.7.0
32
+ pnpm run update # nest-server-starter based projects
33
+ pnpm run build
34
+ pnpm test
35
+ ```
36
+
37
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
38
+
39
+ ## 1. A NODE_ENV without a block no longer starts
40
+
41
+ **Why:** `getEnvironmentConfig()` used `config[NODE_ENV || 'local'] || config.local`. A stage started with
42
+ `NODE_ENV=development`, `dev` or `staging` in a project that defines none of them, or with an empty `NODE_ENV`, ran on
43
+ the `local` block. Its `env` then claims `local`, which opens what the framework keeps to laptops: the anonymous
44
+ `POST /system-setup/init`, `GET /config`, private outbound targets for user-entered URLs, the development MCP OAuth
45
+ secret, and the auth links in the log — on top of whatever dummy secrets the `local` block carries.
46
+
47
+ **What changed:**
48
+
49
+ | `NODE_ENV` | Until 12.6.x | From 12.7.0 |
50
+ |---|---|---|
51
+ | unset | the `local` block (or `defaultEnv`) | unchanged |
52
+ | names a block | that block | unchanged |
53
+ | names no block (`staging`, `development`, a typo) | the `local` block | throws `NODE_ENV='<value>' has no block in the configuration (known: …)` |
54
+ | empty or blank (`''`, `' '`) | the `local` block | throws `NODE_ENV is set but empty (known: …)` |
55
+ | `test` with no `test` block, under vitest or jest (`VITEST` / `JEST_WORKER_ID`) | the `local` block | the `local` block, with one warning |
56
+ | `test` with no `test` block, anywhere else | the `local` block | throws |
57
+
58
+ **Am I affected?**
59
+
60
+ - **A stage or job on an env without a block.** Its boot log shows `Configured for: local (requested: <NODE_ENV>)`.
61
+ Look at every place that starts the application or loads `config.env.ts`, not only deployed stages: compose files,
62
+ CI jobs, `package.json` scripts (`migrate:<env>:up`, seeds), cron containers.
63
+ - **An empty `NODE_ENV`.** `NODE_ENV=${NODE_ENV}` in a compose file passes `''` when the host does not set the
64
+ variable. The boot line then reads a plain `Configured for: local`, which looked correct. Check the environment of
65
+ the running container instead (`NODE_ENV` present but empty).
66
+ - **A test suite under vitest or jest without a `test` block** keeps working and prints
67
+ `NODE_ENV='test' has no block in the configuration; a test runner is active, so the local block is used.` once per
68
+ module instance. Add a `test` block to silence it.
69
+
70
+ **What to do, before the update:**
71
+
72
+ - For each `NODE_ENV` without a block, **add a block** rather than renaming `NODE_ENV`. Other libraries read
73
+ `NODE_ENV` themselves (Express and many others switch behaviour on `production` / `development`), so renaming it
74
+ changes them too. In a starter-based project: `staging: deployedConfig('staging', { brandSuffix: 'Staging' }),`.
75
+ A stage that moves off the `local` block needs every variable its new block requires — in a starter-based project
76
+ the ones `.env.example` lists as required — and its `migrate:<env>:up` job too.
77
+ - For an empty `NODE_ENV`, set the value on the host or in the compose file, or remove the line so the variable is
78
+ really unset.
79
+ - Check the scripts that set a `NODE_ENV` of their own, not only the stages (§2): they fail at the first run after the
80
+ update, which may be weeks later.
81
+ - Know what your platform does with a refused start before you deploy the update (§3).
82
+
83
+ **Starter-based projects:** nest-server-starter refuses both cases itself since its 12.6.0 release, before
84
+ `getEnvironmentConfig()` runs (see `12.5.x-to-12.6.x.md` §3). That check lives in your project's own
85
+ `src/config.env.ts`, and `pnpm run update` does not touch that file, so a project created from an earlier starter has
86
+ it only if it was taken over by hand. Check for both messages of the starter's checks:
87
+
88
+ ```bash
89
+ grep -nE "has no block in src/config.env.ts|is set but empty" src/config.env.ts
90
+ ```
91
+
92
+ - Both found: 12.7.0 changes nothing about `NODE_ENV` for you; the starter has a `test` block, so its test runs see no
93
+ warning either.
94
+ - Only `has no block…`: the check of an earlier starter change without the empty-value rule. An empty `NODE_ENV` is
95
+ refused from 12.7.0 on; check your stages for it (§1).
96
+ - Neither: your project is affected like any other, §1–§3 apply in full.
97
+
98
+ ## 2. Scripts and process files that name an environment
99
+
100
+ A refused start is not limited to deployed stages. Every script that sets `NODE_ENV` loads `config.env.ts` the same
101
+ way, and a scan of existing projects found three recurring cases:
102
+
103
+ - **`migrate:preview:up`.** The lt CLI writes it into every project, usually without a `preview` block; until now it
104
+ migrated silently against the local database URI. Take over the `preview` block of nest-server-starter
105
+ (`preview: deployedConfig('preview', { brandSuffix: 'Preview' }),`), or remove the script if nothing runs it.
106
+ - **A pm2 default of `development`.** Many `pm2.config.js` files set `NODE_ENV` to `development` in their default
107
+ `env`. Set it to a block that exists, or add a `development` block if pm2 really runs a development stage.
108
+ - **Block names that differ from the script names.** A project whose blocks are called `dev` or `productive` while its
109
+ scripts set `NODE_ENV=develop` or `NODE_ENV=production` (`migrate:develop:up`, `start:prod`, `migrate:prod:up`) gets
110
+ the `local` block today and a refused start after the update. Make both use the same name: let the script set the
111
+ block's name, or add the name the script uses as a further block (a `production` key next to `productive`). Where a
112
+ deployed stage relies on the value for other libraries (`production`), keep the value and add the block.
113
+
114
+ On a developer machine a missing `NODE_ENV` still means `local`. **One exception, corrected in 12.7.1:** `lt dev up`
115
+ and `lt dev test` start the API server with `NODE_ENV=local`, but a migration step in the project's `start` script
116
+ (`pnpm run migrate:up && …`) runs with the `NODE_ENV` the shell exported. With `NODE_ENV=development` (or any other
117
+ value without a block) exported, that migration now stops. Pin the environment in the script, as nest-server-starter
118
+ 12.7.0 does:
119
+
120
+ ```json
121
+ "start": "cross-env NODE_ENV=local pnpm run migrate:up && pnpm run start:local"
122
+ ```
123
+
124
+ ## 3. What happens on deploy?
125
+
126
+ The refusal is an error thrown while the configuration loads, so the API process exits before it listens. What the
127
+ stage does then depends on the platform:
128
+
129
+ | Platform | Running stage | What you see |
130
+ |---|---|---|
131
+ | TurboOps | The previous version keeps running (start-first update with a health check, `failure_action: rollback`) | The deployment ends `failed` with a completed rollback, the pipeline turns red |
132
+ | STACKIT (Argo Rollouts canary) | The previous version keeps running: the rollout is aborted at its progress deadline | `RolloutAborted` after the deadline (300 s); **the pipeline stays green** |
133
+ | deploy.party | **The stage goes down**: there is no health check and no check after the deploy | **Nothing**: the build reports success |
134
+
135
+ On every platform, the **first** deploy of a new stage goes down, because there is no previous version to keep.
136
+ TurboOps can go down too when an api service runs without a health check or updates stop-first (because of a named
137
+ volume, or `updateOrder` set to stop-first).
138
+
139
+ Before you deploy the update:
140
+
141
+ - **deploy.party:** check the stage's `NODE_ENV` against the blocks of `config.env.ts` first. A refused start goes
142
+ unnoticed there until somebody opens the application.
143
+ - **STACKIT:** look at the rollout status after the deploy rather than at the pipeline, which stays green.
144
+ - **TurboOps:** a red pipeline with a rollback is the signal; the previous version keeps serving.
145
+
146
+ ## 4. Swagger only where it is switched on
147
+
148
+ **Why:** `setupSwagger()` mounted the Swagger UI and the JSON document on every stage a project called it on,
149
+ production included. The full API description — every route, the roles it requires, every input shape — was public
150
+ there.
151
+
152
+ **What changed:** `setupSwagger()` asks `isSwaggerEnabled()` first (new server option `swagger`):
153
+
154
+ | `swagger` | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
155
+ |---|---|---|
156
+ | not set | served | **off** |
157
+ | `true` | served | served |
158
+ | `false` | off | off |
159
+
160
+ Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and `/api-docs-api-tokens-json`
161
+ (or the paths you gave `setupSwagger()`); they answer 404. One line in the boot log says Swagger is off. A value that
162
+ is not a boolean counts as not set.
163
+
164
+ **Your project:** nothing to do if the documentation should stay local. To keep it on a stage, set it in that
165
+ stage's block of `config.env.ts`, or through the environment:
166
+
167
+ ```typescript
168
+ // config.env.ts — only the stage that should show the documentation
169
+ develop: {
170
+ // …
171
+ swagger: true,
172
+ },
173
+ ```
174
+
175
+ ```bash
176
+ NSC__SWAGGER=true
177
+ ```
178
+
179
+ A client generator that reads `/api-docs-json` from a deployed stage (`openapi-typescript`, `orval`, …) needs the
180
+ switch on that stage, or reads the document from a local or CI run instead.
181
+
182
+ ## 5. CORS with credentials in JWT mode
183
+
184
+ **Why:** with `cookies: false` the API answered every origin with `Access-Control-Allow-Origin: *` and no
185
+ credentials. Browsers refuse `*` on a credentialed request, and a JWT-mode frontend makes them: the stack's client
186
+ sends `credentials: 'include'`, and after a second factor it turns the session cookie Better-Auth set into a JWT
187
+ through `/iam/token`. With app and API on separate origins, a 2FA sign-in in JWT mode failed in every browser while
188
+ the server answered 200.
189
+
190
+ **What changed:** `buildCorsConfig()` no longer distinguishes the cookie mode. REST (through `main.ts`), GraphQL and
191
+ the tus uploads answer the same origin list in both modes:
192
+
193
+ | `cookies: false`, origins | Until 12.6.x | From 12.7.0 |
194
+ |---|---|---|
195
+ | `appUrl` / `baseUrl` / `cors.allowedOrigins` resolvable | `*`, no credentials, every origin | those origins, with credentials; any other origin gets no CORS grant |
196
+ | `cors.allowAll: true` | `*`, no credentials | the request origin mirrored, with credentials (as in cookie mode) |
197
+ | nothing resolvable | `*`, no credentials | unchanged |
198
+
199
+ Credentialed CORS decides which origins may READ a credentialed response; it does not change what a browser sends.
200
+ The list is the one cookie mode has always trusted, so no other origin gains anything.
201
+
202
+ **Your project:** nothing to change in `main.ts` — it already applies what `buildCorsConfig()` returns. If browser
203
+ pages on further origins call your JWT-mode API (a second frontend, a partner widget), list them:
204
+
205
+ ```typescript
206
+ cors: {
207
+ allowedOrigins: ['https://admin.example.com'],
208
+ },
209
+ ```
210
+
211
+ Server-to-server calls and native apps send no `Origin` and are not affected.
212
+
213
+ ## 6. list-sessions names sessions by id; revoke-session takes the id
214
+
215
+ **Why:** `GET /iam/list-sessions` answered every session of the user with its `token` — the bearer credential of every
216
+ device the user is signed in on, readable by any script on the page. 12.6.1 took the session token out of the other
217
+ forwarded answers; this was the last one.
218
+
219
+ **What changed:**
220
+
221
+ | | Until 12.6.x | From 12.7.0 |
222
+ |---|---|---|
223
+ | `GET /iam/list-sessions` | `[{ id, token, userId, expiresAt, … }]` | `[{ id, userId, expiresAt, … }]` — no `token`, in every mode |
224
+ | `POST /iam/revoke-session` | `{ token }` | `{ sessionId }` (new) or `{ token }` (unchanged) |
225
+
226
+ `{ sessionId }` is resolved among the sessions of the signed-in user. An unknown id, or the id of another user's
227
+ session, revokes nothing — the answer is the same as for a foreign token, so it discloses nothing. Revoking by
228
+ `token` stays for clients that hold one; nothing in the stack's frontends uses either route directly.
229
+
230
+ **Your frontend:** a "signed-in devices" screen that revokes a session by the `token` from `list-sessions` sends the
231
+ `id` instead:
232
+
233
+ ```typescript
234
+ await fetch(`${api}/iam/revoke-session`, {
235
+ body: JSON.stringify({ sessionId: session.id }),
236
+ credentials: 'include',
237
+ headers: { 'Content-Type': 'application/json' },
238
+ method: 'POST',
239
+ });
240
+ ```
241
+
242
+ Better-Auth's client (`authClient.revokeSession({ token })`) types the body as `{ token }`; send the request yourself
243
+ as above.
244
+
245
+ ## 7. Disabled AI prompts in the management list
246
+
247
+ **Why:** `GET /ai/prompts` (GraphQL `findAiPrompts`) answered enabled prompts only, for every caller. That is right
248
+ for the chat's prompt picker and wrong for the management screen: a prompt saved with "enabled" switched off
249
+ disappeared from it and could no longer be edited or deleted.
250
+
251
+ **What changed:** a new, optional switch. Without it nothing changes.
252
+
253
+ | Call | Lists |
254
+ |---|---|
255
+ | `GET /ai/prompts` · `findAiPrompts` | enabled prompts — the chat picker (unchanged) |
256
+ | `GET /ai/prompts?includeDisabled=true` · `findAiPrompts(includeDisabled: true)` | enabled and disabled prompts — the management screen |
257
+
258
+ Visibility is the same in both: the user's own prompts and the prompts of the user's tenant.
259
+
260
+ **Your frontend:** the screen that edits and deletes prompts adds the parameter; the chat picker keeps its call.
261
+
262
+ ## Compatibility Notes
263
+
264
+ | Pattern | Status |
265
+ |---|---|
266
+ | `NODE_ENV` unset on a developer machine | Unchanged: the `local` block |
267
+ | `lt dev up` / `lt dev test` | They start the API with `NODE_ENV=local`; a `migrate:up` in the `start` script inherits the shell's `NODE_ENV` — pin it (§2, corrected in 12.7.1) |
268
+ | A starter-based project whose `src/config.env.ts` contains both starter 12.6.0 checks (`has no block…`, `is set but empty`) | Already refuses both cases itself; nothing changes |
269
+ | A starter-based project created earlier, without those checks | Affected like any other project: `pnpm run update` does not change `config.env.ts` (§1–§3) |
270
+ | vitest / jest suites without a `test` block | Keep the `local` block, with one warning per module instance |
271
+ | A project that calls `getEnvironmentConfig({ defaultEnv })` | `defaultEnv` still applies when `NODE_ENV` is unset |
272
+ | A `local` `env` from `NSC__ENV`, `NEST_SERVER_CONFIG` or a project's own loader on a deployed stage | Not caught here; the auth-link log line keeps its own `NODE_ENV` check (12.6.0) |
273
+ | `setupSwagger()` in `main.ts` | Unchanged call; it decides itself whether to mount (§4) |
274
+ | A generator fetching `/api-docs-json` from a deployed stage | 404 there unless `swagger: true` on that stage (§4) |
275
+ | JWT mode, frontend on `appUrl` | Works cross-origin with credentials now, 2FA sign-in included (§5) |
276
+ | JWT mode, a browser page on an origin not listed anywhere | Blocked by the browser; list it in `cors.allowedOrigins` (§5) |
277
+ | A client reading `token` from `list-sessions` | Gets none; use `id` and `revoke-session` with `{ sessionId }` (§6) |
278
+ | `revoke-session` with `{ token }` | Unchanged (§6) |
279
+ | `GET /ai/prompts` / `findAiPrompts` without the new parameter | Unchanged: enabled prompts only (§7) |
280
+
281
+ ## Troubleshooting
282
+
283
+ | Symptom | Cause | Fix |
284
+ |---|---|---|
285
+ | `NODE_ENV='<value>' has no block in the configuration (known: …)` at startup | The stage ran on the `local` block until now | Add a block for `<value>` to `config.env.ts` (§1) |
286
+ | `NODE_ENV is set but empty` at startup | An empty variable, often `NODE_ENV=${NODE_ENV}` in a compose file | Set the value or remove the line (§1) |
287
+ | `NODE_ENV='test' has no block in the configuration; a test runner is active` in a test run | vitest sets `NODE_ENV=test` | Nothing to do, or add a `test` block |
288
+ | A job (migration, seed) fails after the update while the application starts | The job runs with its own `NODE_ENV` | Give that `NODE_ENV` a block too (§2) |
289
+ | `lt dev up` stops in the migration step, the server would start | `migrate:up` inherits an exported `NODE_ENV` without a block (`development`) | `cross-env NODE_ENV=local pnpm run migrate:up` in the `start` script (§2) |
290
+ | A deploy.party stage is down after the update, the build was green | The API refused to start; the platform has no health check | Check the stage's `NODE_ENV` and its logs (§3) |
291
+ | A STACKIT pipeline is green but the stage still serves the previous version | The canary was aborted at its progress deadline | Look at the rollout status and the API's logs (§3) |
292
+ | `/swagger` answers 404 on a deployed stage | Swagger is off outside `local` / `ci` / `e2e` | `swagger: true` in that stage's block, or `NSC__SWAGGER=true` (§4) |
293
+ | A browser reports a CORS error for the API in JWT mode after the update | The page's origin is not `appUrl`, `baseUrl` or in `cors.allowedOrigins` | Add it to `cors.allowedOrigins` (§5) |
294
+ | Revoking a device does nothing after the update | The screen sends the `token` from `list-sessions`, which is gone | Send `{ sessionId: session.id }` (§6) |
295
+ | A disabled AI prompt is missing from the management screen | The screen lists without `includeDisabled` | `GET /ai/prompts?includeDisabled=true` (§7) |
296
+
297
+ ## References
298
+
299
+ - `src/core/common/helpers/config.helper.ts` — `getEnvironmentConfig()`, `selectEnvironmentBlock()`
300
+ - `tests/unit/environment-config-node-env.spec.ts`
301
+ - `src/core/common/helpers/swagger-enabled.helper.ts` — `isSwaggerEnabled()`; `swagger.helper.ts` — `setupSwagger()`
302
+ - `tests/unit/swagger-switch.spec.ts`
303
+ - `src/core/common/helpers/cookies.helper.ts` — `buildCorsConfig()`; `tests/unit/cookies-cors-config.spec.ts`,
304
+ `tests/cors-jwt-mode.e2e-spec.ts`
305
+ - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts` — session records;
306
+ `core-better-auth-api.middleware.ts` — `resolveRevokeSessionId()`; `tests/session-token-exposure.e2e-spec.ts`
307
+ - `src/core/modules/ai/services/core-ai-prompt.service.ts` — `listVisible()`; `tests/unit/ai-prompt-list-visible.spec.ts`
@@ -0,0 +1,99 @@
1
+ # Migration Guide: 12.7.0 → 12.7.1
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security: revoking a session by id could leave a live session in place for a user with many stored sessions (§1). The first second-factor check while enabling 2FA answered with the token of the session it had just replaced (§2) |
10
+ | **Documentation** | 12.6.x-to-12.7.x §2: `lt dev up` with an exported `NODE_ENV` (§3). 12.5.x-to-12.6.x: the E2E helper `findVerificationToken()` in project copies (§4) |
11
+ | **Migration Effort** | None on the server. Check a project's `start` script (§3) and its copy of the E2E auth helper (§4) |
12
+
13
+ ## Quick Migration
14
+
15
+ ```bash
16
+ pnpm add @lenne.tech/nest-server@12.7.1
17
+ pnpm run update # nest-server-starter based projects
18
+ pnpm run build
19
+ pnpm test
20
+ ```
21
+
22
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
23
+
24
+ ## 1. `revoke-session` by id looks among the active sessions only
25
+
26
+ **Why:** since 12.7.0, `POST /iam/revoke-session` accepts `{ sessionId }` and resolves the id among the caller's own
27
+ sessions. It asked Better-Auth for every stored session of the user. Better-Auth returns at most 100 rows for such a
28
+ query, and MongoDB keeps expired session rows until something removes them. For a user with more than 100 stored
29
+ sessions, the session to revoke could fall outside the answer. The request then revoked nothing and still answered
30
+ successfully, so a device the user meant to sign out stayed signed in.
31
+
32
+ **What changed:** the id is resolved among the user's **active** sessions only. An expired session has nothing left to
33
+ revoke, and an unknown or foreign id still revokes nothing and discloses nothing.
34
+
35
+ **Your project:** nothing to do. The same fix ships in 12.6.2 and 11.43.8.
36
+
37
+ ## 2. The first second-factor check while enabling 2FA hands out no replaced token
38
+
39
+ **Why:** enabling 2FA rotates the session. The first `POST /iam/two-factor/verify-totp` creates a new session, sets
40
+ its cookie and deletes the old one, and Better-Auth answered with the token of the old session. That token was dead
41
+ by then, so it gave no access, but the rule is that no response body carries an opaque session token. The token policy
42
+ (12.6.1) did not recognise it, because neither the new cookie nor the session store named it any more.
43
+
44
+ **What changed:** a response in Better-Auth's session-creating shape `{ token, user }` that sets a new session cookie
45
+ while its body names another opaque token counts as a session rotation. Cookie mode removes the token. With
46
+ `cookies: false` or `exposeTokenInBody`, the body carries the JWT of the **new** session, as sign-in does. When a
47
+ response sets the session cookie twice (a session refresh during the request sets the current one first), the last
48
+ one counts, as in the browser. A plugin's own token next to a refreshed session cookie, such as the `{ token }` of
49
+ `/one-time-token/generate`, stays untouched.
50
+
51
+ **Your frontend:** nothing to do. In cookie mode the session cookie authenticates after enabling 2FA, as before. In
52
+ token-in-body mode the `token` of this response now belongs to the session the client actually holds.
53
+
54
+ ## 3. Correction in 12.6.x-to-12.7.x §2: `lt dev up` with an exported `NODE_ENV`
55
+
56
+ The 12.7.x guide said that `lt dev up` and `lt dev test` set `NODE_ENV=local`. They do for the API server. A
57
+ `migrate:up` in the project's `start` script runs with whatever `NODE_ENV` the shell exported, so with
58
+ `NODE_ENV=development` exported, that step stops since 12.7.0. Pin the environment in the script, as
59
+ nest-server-starter 12.7.0 does:
60
+
61
+ ```json
62
+ "start": "cross-env NODE_ENV=local pnpm run migrate:up && pnpm run start:local"
63
+ ```
64
+
65
+ ## 4. Addition to 12.5.x-to-12.6.x: the E2E helper `findVerificationToken()`
66
+
67
+ Since 12.6 the verification token is sealed. Projects created from nuxt-base-starter 2.37 or earlier keep their own
68
+ copy of `tests/e2e/helpers/auth-backend.ts` (in a fullstack project under `projects/app/`), and its
69
+ `findVerificationToken()` reads the address out of the token's JWT. It finds no token any more, and every E2E test that
70
+ verifies an address fails or times out. Updating the starter does not reach that copy: replace
71
+ `findVerificationToken()`, `userKey()` and `jwtEmail()` with the versions from nuxt-base-starter 2.38.1, and add the
72
+ import `userKey()` needs at the top of the file, `import { createHash } from 'node:crypto';` (without it the first call
73
+ throws `ReferenceError: createHash is not defined`). Those functions match the development log line by `UserKey` and
74
+ still read the JWT of a server older than 12.6. This affects every project copy.
75
+
76
+ ## Compatibility Notes
77
+
78
+ | Pattern | Status |
79
+ |---|---|
80
+ | `POST /iam/revoke-session` with `{ sessionId }` or `{ token }` | Unchanged API. By id, only an active session is found (§1) |
81
+ | Enabling 2FA in cookie mode | Unchanged: the new session cookie authenticates; the body carries no token (§2) |
82
+ | Enabling 2FA with `cookies: false` / `exposeTokenInBody` | The body's `token` is the JWT of the new session (§2) |
83
+ | A plugin endpoint answering its own `token` (`/one-time-token/generate`) | Unchanged, also when a session refresh sets the session cookie in the same response (§2) |
84
+ | A project subclass of `CoreBetterAuthService` overriding `sessionTokenOfUser()` | Keep the active-sessions restriction (`onlyActiveSessions: true`) |
85
+
86
+ ## Troubleshooting
87
+
88
+ | Symptom | Cause | Fix |
89
+ |---|---|---|
90
+ | `lt dev up` stops in the migration step | `migrate:up` inherits an exported `NODE_ENV` without a block | `cross-env NODE_ENV=local` in the `start` script (§3) |
91
+ | E2E tests that verify an address find no token | The project's copy of the E2E helper still decodes the JWT | Take the helper from nuxt-base-starter 2.38.1, with its `createHash` import (§4) |
92
+ | `ReferenceError: createHash is not defined` in the E2E helper | The new `userKey()` was copied without its import | `import { createHash } from 'node:crypto';` at the top of the file (§4) |
93
+
94
+ ## References
95
+
96
+ - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts`: `presentSessionTokens()`, rotation (§2)
97
+ - `src/core/modules/better-auth/core-better-auth.service.ts`: `sessionTokenOfUser()` (§1)
98
+ - `migration-guides/12.6.x-to-12.7.x.md` §2, `migration-guides/12.5.x-to-12.6.x.md` ("The development log line of auth
99
+ links")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.6.2",
3
+ "version": "12.7.1",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -64,6 +64,60 @@ export function loadLocalConfigFile(
64
64
  return loaded?.default ?? loaded;
65
65
  }
66
66
 
67
+ /** Whether the test-runner fallback for `NODE_ENV=test` has been reported in this module instance */
68
+ let testRunnerFallbackReported = false;
69
+
70
+ /**
71
+ * The block of `config` that `NODE_ENV` selects — or a refusal.
72
+ *
73
+ * Until 12.7.0 a `NODE_ENV` without a block (and an empty one, via `'' || 'local'`) got the `local` block, whose
74
+ * `env` then claimed `local` on a deployed stage: public dummy secrets, the anonymous system setup, `GET /config`,
75
+ * the SSRF guard's private targets and the development MCP OAuth secret, all opened by a typo or a missing block.
76
+ * Now:
77
+ *
78
+ * - `NODE_ENV` unset → `defaultEnv` (`local`), as before.
79
+ * - `NODE_ENV` empty or blank → refused. `NODE_ENV=${NODE_ENV}` in a compose file passes `''` when the host does not
80
+ * set the variable, and that must not read as "local".
81
+ * - `NODE_ENV` without a block → refused, naming the blocks that exist.
82
+ * - The one exception: `NODE_ENV=test` while a test runner is active (`VITEST` or `JEST_WORKER_ID`), because vitest
83
+ * sets that value and many repositories have no `test` block. It keeps the `local` block, with one warning.
84
+ */
85
+ function selectEnvironmentBlock(
86
+ config: Record<string, any>,
87
+ defaultEnv: string,
88
+ // `any`, not `Record<string, any>`: it is what getEnvironmentConfig() returns, and a project spreading that result
89
+ // (`{ ...envConfig, auth }`) loses every other field under the narrower type — a type break in consumer code
90
+ ): { env: string; envConfig: any } {
91
+ const requested = process.env['NODE_ENV'];
92
+ if (requested === undefined) {
93
+ return { env: defaultEnv, envConfig: config[defaultEnv] || config.local || {} };
94
+ }
95
+ const known = Object.keys(config).join(', ') || 'none';
96
+ if (requested.trim() === '') {
97
+ throw new Error(
98
+ `NODE_ENV is set but empty (known: ${known}). Set it to one of them, or unset it for local. ` +
99
+ 'A compose file with NODE_ENV=${NODE_ENV} passes an empty value when the host does not set the variable.',
100
+ );
101
+ }
102
+ if (Object.hasOwn(config, requested) && config[requested]) {
103
+ return { env: requested, envConfig: config[requested] };
104
+ }
105
+ if (requested === 'test' && (process.env['VITEST'] || process.env['JEST_WORKER_ID'])) {
106
+ if (!testRunnerFallbackReported) {
107
+ testRunnerFallbackReported = true;
108
+ console.warn(
109
+ "NODE_ENV='test' has no block in the configuration; a test runner is active, so the local block is used. " +
110
+ 'Add a test block to silence this.',
111
+ );
112
+ }
113
+ return { env: requested, envConfig: config.local || {} };
114
+ }
115
+ throw new Error(
116
+ `NODE_ENV='${requested}' has no block in the configuration (known: ${known}). Add a block for it, or set NODE_ENV ` +
117
+ 'to one of the known environments. Prefer the block: other libraries read NODE_ENV themselves.',
118
+ );
119
+ }
120
+
67
121
  /**
68
122
  * Get environment configuration (deeply merged into config object set via options)
69
123
  *
@@ -71,6 +125,9 @@ export function loadLocalConfigFile(
71
125
  * 1. config[env] (if set)
72
126
  * 2.
73
127
  *
128
+ * `NODE_ENV` must name a block of `config` (12.7.0): an empty value or one without a block throws, except
129
+ * `NODE_ENV=test` under a test runner — see `selectEnvironmentBlock()`.
130
+ *
74
131
  * @param options options for processing
75
132
  * @param options.config config object with different environments as main keys (see config.env.ts) to merge environment configurations into (default: {})
76
133
  * @param options.defaultEnv default environment to use if no NODE_ENV is set (default: 'local')
@@ -92,8 +149,7 @@ export function getEnvironmentConfig(options: { config?: Record<string, any>; de
92
149
  dotenv.config({ quiet: true });
93
150
  }
94
151
 
95
- const env = process.env['NODE_ENV'] || defaultEnv;
96
- const envConfig = config[env] || config.local || {};
152
+ const { env, envConfig } = selectEnvironmentBlock(config, defaultEnv);
97
153
 
98
154
  // Merge with localConfig (e.g. config.json)
99
155
  if (envConfig.loadLocalConfig) {
@@ -545,11 +545,18 @@ export function resolveServerUrls(input: {
545
545
  *
546
546
  * Resolution priority:
547
547
  * 1. CORS disabled → empty object (no CORS)
548
- * 2. Cookies disabled → empty object (no credentials needed, handled by simple enableCors())
549
- * 3. `cors.allowAll` → `{ credentials: true, origin: true }` (mirror request origin)
550
- * 4. `cors.allowedOrigins` + resolved `appUrl`/`baseUrl` → deduplicated origin list
551
- * 5. Only resolved `appUrl`/`baseUrl` → those origins
552
- * 6. Nothing configured → `{}` (no credentialed CORS — caller decides fallback)
548
+ * 2. `cors.allowAll` → `{ credentials: true, origin: true }` (mirror request origin)
549
+ * 3. `cors.allowedOrigins` + resolved `appUrl`/`baseUrl` → deduplicated origin list
550
+ * 4. Only resolved `appUrl`/`baseUrl` → those origins
551
+ * 5. Nothing configured → `{}` (no credentialed CORS — caller decides fallback)
552
+ *
553
+ * The same in JWT mode (`cookies: false`) since 12.7.0. Until then it answered `{}` there, and callers fell back to
554
+ * `enableCors()` without credentials (`Access-Control-Allow-Origin: *`). A browser refuses `*` on a credentialed
555
+ * request, and JWT mode still makes them: the stack's client sends `credentials: 'include'`, and after a second
556
+ * factor it turns the session cookie Better-Auth set into a JWT through `/iam/token` — so a split app/API deployment
557
+ * in JWT mode could not finish a 2FA sign-in. Credentialed CORS answers only the listed origins — the ones cookie
558
+ * mode already trusts; it lets them READ credentialed responses and grants nothing to any other origin (CORS
559
+ * decides who may read, not what a browser sends; cookie requests from other sites are bounded by `SameSite=Lax`).
553
560
  *
554
561
  * `appUrl`/`baseUrl` are resolved via {@link resolveServerUrls}, the same function BetterAuth
555
562
  * uses, so all three CORS layers (GraphQL, REST, BetterAuth `trustedOrigins`) agree.
@@ -559,7 +566,7 @@ export function resolveServerUrls(input: {
559
566
  * - `main.ts` reference implementation for REST (Express) CORS
560
567
  *
561
568
  * Security notes:
562
- * - When no origins are resolvable AND cookies are enabled, the function returns `{}` rather
569
+ * - When no origins are resolvable, the function returns `{}` rather
563
570
  * than `{ credentials: true, origin: true }`. Returning open CORS with credentials would
564
571
  * allow any website to make credentialed requests. Callers should either configure
565
572
  * `appUrl`/`baseUrl`/`allowedOrigins`, enable `cors.allowAll` explicitly (for development),
@@ -580,10 +587,6 @@ export function buildCorsConfig(options: Partial<IServerOptions>): Record<string
580
587
  return {};
581
588
  }
582
589
 
583
- if (!isCookiesEnabled(options?.cookies)) {
584
- return {};
585
- }
586
-
587
590
  const corsObj = typeof options?.cors === 'object' ? options.cors : {};
588
591
 
589
592
  // allowAll → mirror request origin (explicit opt-in for dev/test)
@@ -0,0 +1,33 @@
1
+ import type { IServerOptions } from '../interfaces/server-options.interface.js';
2
+ import { ConfigService } from '../services/config.service.js';
3
+ import { isLocalEnv } from './cookies.helper.js';
4
+
5
+ /**
6
+ * Whether `setupSwagger()` serves the API documentation (`swagger`, 12.7.0+).
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 12.7.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 12.7.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
+ }
@@ -30,6 +30,7 @@ import { mergeRolesMetadata } from '../../modules/tenant/core-tenant.helpers.js'
30
30
  import { RoleEnum } from '../enums/role.enum.js';
31
31
  import { ConfigService } from '../services/config.service.js';
32
32
  import { isCookiesEnabled } from './cookies.helper.js';
33
+ import { isSwaggerEnabled } from './swagger-enabled.helper.js';
33
34
 
34
35
  import type { INestApplication, Type } from '@nestjs/common';
35
36
  import type {
@@ -154,10 +155,28 @@ const logger = new Logger('Swagger');
154
155
  /**
155
156
  * Build the enriched document and serve it — plus the API-token view, when configured. Both documents are
156
157
  * built on the first request, when every module is initialised.
158
+ *
159
+ * Since 12.7.0 only where `swagger` switches it on ({@link isSwaggerEnabled}): by default in `local`, `ci` and `e2e`,
160
+ * everywhere with `swagger: true`. Otherwise nothing is mounted — no UI, no JSON document — and one line in the log
161
+ * says so.
162
+ *
163
+ * @param config - server configuration; the running configuration by default
157
164
  */
158
- export function setupSwagger(app: INestApplication, options: ISwaggerSetupOptions): void {
165
+ export function setupSwagger(
166
+ app: INestApplication,
167
+ options: ISwaggerSetupOptions,
168
+ config: Partial<IServerOptions> = ConfigService.configFastButReadOnly ?? {},
169
+ ): void {
170
+ if (!isSwaggerEnabled(config)) {
171
+ logger.log(
172
+ `Swagger is off in this environment (${config.env ?? process.env.NODE_ENV ?? 'unknown'}): nothing is served at ` +
173
+ `/${options.path ?? 'swagger'} or ${options.jsonDocumentUrl ?? '/api-docs-json'}. Set \`swagger: true\` ` +
174
+ `(NSC__SWAGGER=true) to serve the API documentation here.`,
175
+ );
176
+ return;
177
+ }
159
178
  let document: OpenAPIObject | undefined;
160
- const fullDocument = () => (document ??= buildSwaggerDocument(app, options));
179
+ const fullDocument = () => (document ??= buildSwaggerDocument(app, options, config));
161
180
 
162
181
  SwaggerModule.setup(options.path ?? 'swagger', app, fullDocument, {
163
182
  ...options.customOptions,
@@ -169,10 +188,15 @@ export function setupSwagger(app: INestApplication, options: ISwaggerSetupOption
169
188
  return;
170
189
  }
171
190
  let viewDocument: OpenAPIObject | undefined;
172
- SwaggerModule.setup(view.path, app, () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view)), {
173
- ...options.customOptions,
174
- jsonDocumentUrl: view.jsonDocumentUrl,
175
- });
191
+ SwaggerModule.setup(
192
+ view.path,
193
+ app,
194
+ () => (viewDocument ??= buildApiTokenSwaggerDocument(fullDocument(), view, config)),
195
+ {
196
+ ...options.customOptions,
197
+ jsonDocumentUrl: view.jsonDocumentUrl,
198
+ },
199
+ );
176
200
  }
177
201
 
178
202
  /**