@lenne.tech/nest-server 12.6.0 → 12.7.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 (60) hide show
  1. package/.claude/rules/better-auth.md +36 -0
  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-api.middleware.d.ts +1 -0
  27. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +22 -4
  28. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.d.ts +8 -0
  30. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js +115 -0
  31. package/dist/core/modules/better-auth/core-better-auth-session-token.helper.js.map +1 -0
  32. package/dist/core/modules/better-auth/core-better-auth.controller.js +2 -2
  33. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  34. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +5 -0
  35. package/dist/core/modules/better-auth/core-better-auth.service.js +42 -2
  36. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +1 -0
  39. package/dist/index.js.map +1 -1
  40. package/dist/main.js.map +1 -1
  41. package/docs/REQUEST-LIFECYCLE.md +22 -2
  42. package/migration-guides/12.6.0-to-12.6.1.md +66 -0
  43. package/migration-guides/12.6.x-to-12.7.x.md +299 -0
  44. package/package.json +1 -1
  45. package/src/core/common/helpers/config.helper.ts +58 -2
  46. package/src/core/common/helpers/cookies.helper.ts +13 -10
  47. package/src/core/common/helpers/swagger-enabled.helper.ts +33 -0
  48. package/src/core/common/helpers/swagger.helper.ts +30 -6
  49. package/src/core/common/interfaces/server-options.interface.ts +26 -5
  50. package/src/core/modules/ai/INTEGRATION-CHECKLIST.md +4 -1
  51. package/src/core/modules/ai/core-ai.controller.ts +18 -3
  52. package/src/core/modules/ai/core-ai.resolver.ts +14 -3
  53. package/src/core/modules/ai/services/core-ai-prompt.service.ts +11 -5
  54. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +39 -5
  55. package/src/core/modules/better-auth/core-better-auth-session-token.helper.ts +194 -0
  56. package/src/core/modules/better-auth/core-better-auth.controller.ts +3 -2
  57. package/src/core/modules/better-auth/core-better-auth.service.ts +87 -2
  58. package/src/core/modules/tus/README.md +2 -1
  59. package/src/index.ts +1 -0
  60. package/src/main.ts +3 -2
@@ -0,0 +1,299 @@
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
+ Nothing changes on a developer machine: a missing `NODE_ENV` still means `local`, and `lt dev up` / `lt dev test` set
115
+ `NODE_ENV=local`.
116
+
117
+ ## 3. What happens on deploy?
118
+
119
+ The refusal is an error thrown while the configuration loads, so the API process exits before it listens. What the
120
+ stage does then depends on the platform:
121
+
122
+ | Platform | Running stage | What you see |
123
+ |---|---|---|
124
+ | 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 |
125
+ | 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** |
126
+ | deploy.party | **The stage goes down**: there is no health check and no check after the deploy | **Nothing**: the build reports success |
127
+
128
+ On every platform, the **first** deploy of a new stage goes down, because there is no previous version to keep.
129
+ TurboOps can go down too when an api service runs without a health check or updates stop-first (because of a named
130
+ volume, or `updateOrder` set to stop-first).
131
+
132
+ Before you deploy the update:
133
+
134
+ - **deploy.party:** check the stage's `NODE_ENV` against the blocks of `config.env.ts` first. A refused start goes
135
+ unnoticed there until somebody opens the application.
136
+ - **STACKIT:** look at the rollout status after the deploy rather than at the pipeline, which stays green.
137
+ - **TurboOps:** a red pipeline with a rollback is the signal; the previous version keeps serving.
138
+
139
+ ## 4. Swagger only where it is switched on
140
+
141
+ **Why:** `setupSwagger()` mounted the Swagger UI and the JSON document on every stage a project called it on,
142
+ production included. The full API description — every route, the roles it requires, every input shape — was public
143
+ there.
144
+
145
+ **What changed:** `setupSwagger()` asks `isSwaggerEnabled()` first (new server option `swagger`):
146
+
147
+ | `swagger` | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
148
+ |---|---|---|
149
+ | not set | served | **off** |
150
+ | `true` | served | served |
151
+ | `false` | off | off |
152
+
153
+ Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and `/api-docs-api-tokens-json`
154
+ (or the paths you gave `setupSwagger()`); they answer 404. One line in the boot log says Swagger is off. A value that
155
+ is not a boolean counts as not set.
156
+
157
+ **Your project:** nothing to do if the documentation should stay local. To keep it on a stage, set it in that
158
+ stage's block of `config.env.ts`, or through the environment:
159
+
160
+ ```typescript
161
+ // config.env.ts — only the stage that should show the documentation
162
+ develop: {
163
+ // …
164
+ swagger: true,
165
+ },
166
+ ```
167
+
168
+ ```bash
169
+ NSC__SWAGGER=true
170
+ ```
171
+
172
+ A client generator that reads `/api-docs-json` from a deployed stage (`openapi-typescript`, `orval`, …) needs the
173
+ switch on that stage, or reads the document from a local or CI run instead.
174
+
175
+ ## 5. CORS with credentials in JWT mode
176
+
177
+ **Why:** with `cookies: false` the API answered every origin with `Access-Control-Allow-Origin: *` and no
178
+ credentials. Browsers refuse `*` on a credentialed request, and a JWT-mode frontend makes them: the stack's client
179
+ sends `credentials: 'include'`, and after a second factor it turns the session cookie Better-Auth set into a JWT
180
+ through `/iam/token`. With app and API on separate origins, a 2FA sign-in in JWT mode failed in every browser while
181
+ the server answered 200.
182
+
183
+ **What changed:** `buildCorsConfig()` no longer distinguishes the cookie mode. REST (through `main.ts`), GraphQL and
184
+ the tus uploads answer the same origin list in both modes:
185
+
186
+ | `cookies: false`, origins | Until 12.6.x | From 12.7.0 |
187
+ |---|---|---|
188
+ | `appUrl` / `baseUrl` / `cors.allowedOrigins` resolvable | `*`, no credentials, every origin | those origins, with credentials; any other origin gets no CORS grant |
189
+ | `cors.allowAll: true` | `*`, no credentials | the request origin mirrored, with credentials (as in cookie mode) |
190
+ | nothing resolvable | `*`, no credentials | unchanged |
191
+
192
+ Credentialed CORS decides which origins may READ a credentialed response; it does not change what a browser sends.
193
+ The list is the one cookie mode has always trusted, so no other origin gains anything.
194
+
195
+ **Your project:** nothing to change in `main.ts` — it already applies what `buildCorsConfig()` returns. If browser
196
+ pages on further origins call your JWT-mode API (a second frontend, a partner widget), list them:
197
+
198
+ ```typescript
199
+ cors: {
200
+ allowedOrigins: ['https://admin.example.com'],
201
+ },
202
+ ```
203
+
204
+ Server-to-server calls and native apps send no `Origin` and are not affected.
205
+
206
+ ## 6. list-sessions names sessions by id; revoke-session takes the id
207
+
208
+ **Why:** `GET /iam/list-sessions` answered every session of the user with its `token` — the bearer credential of every
209
+ 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
210
+ forwarded answers; this was the last one.
211
+
212
+ **What changed:**
213
+
214
+ | | Until 12.6.x | From 12.7.0 |
215
+ |---|---|---|
216
+ | `GET /iam/list-sessions` | `[{ id, token, userId, expiresAt, … }]` | `[{ id, userId, expiresAt, … }]` — no `token`, in every mode |
217
+ | `POST /iam/revoke-session` | `{ token }` | `{ sessionId }` (new) or `{ token }` (unchanged) |
218
+
219
+ `{ sessionId }` is resolved among the sessions of the signed-in user. An unknown id, or the id of another user's
220
+ session, revokes nothing — the answer is the same as for a foreign token, so it discloses nothing. Revoking by
221
+ `token` stays for clients that hold one; nothing in the stack's frontends uses either route directly.
222
+
223
+ **Your frontend:** a "signed-in devices" screen that revokes a session by the `token` from `list-sessions` sends the
224
+ `id` instead:
225
+
226
+ ```typescript
227
+ await fetch(`${api}/iam/revoke-session`, {
228
+ body: JSON.stringify({ sessionId: session.id }),
229
+ credentials: 'include',
230
+ headers: { 'Content-Type': 'application/json' },
231
+ method: 'POST',
232
+ });
233
+ ```
234
+
235
+ Better-Auth's client (`authClient.revokeSession({ token })`) types the body as `{ token }`; send the request yourself
236
+ as above.
237
+
238
+ ## 7. Disabled AI prompts in the management list
239
+
240
+ **Why:** `GET /ai/prompts` (GraphQL `findAiPrompts`) answered enabled prompts only, for every caller. That is right
241
+ for the chat's prompt picker and wrong for the management screen: a prompt saved with "enabled" switched off
242
+ disappeared from it and could no longer be edited or deleted.
243
+
244
+ **What changed:** a new, optional switch. Without it nothing changes.
245
+
246
+ | Call | Lists |
247
+ |---|---|
248
+ | `GET /ai/prompts` · `findAiPrompts` | enabled prompts — the chat picker (unchanged) |
249
+ | `GET /ai/prompts?includeDisabled=true` · `findAiPrompts(includeDisabled: true)` | enabled and disabled prompts — the management screen |
250
+
251
+ Visibility is the same in both: the user's own prompts and the prompts of the user's tenant.
252
+
253
+ **Your frontend:** the screen that edits and deletes prompts adds the parameter; the chat picker keeps its call.
254
+
255
+ ## Compatibility Notes
256
+
257
+ | Pattern | Status |
258
+ |---|---|
259
+ | `NODE_ENV` unset on a developer machine | Unchanged: the `local` block |
260
+ | `lt dev up` / `lt dev test` | Unchanged: they start the API with `NODE_ENV=local` |
261
+ | 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 |
262
+ | 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) |
263
+ | vitest / jest suites without a `test` block | Keep the `local` block, with one warning per module instance |
264
+ | A project that calls `getEnvironmentConfig({ defaultEnv })` | `defaultEnv` still applies when `NODE_ENV` is unset |
265
+ | 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) |
266
+ | `setupSwagger()` in `main.ts` | Unchanged call; it decides itself whether to mount (§4) |
267
+ | A generator fetching `/api-docs-json` from a deployed stage | 404 there unless `swagger: true` on that stage (§4) |
268
+ | JWT mode, frontend on `appUrl` | Works cross-origin with credentials now, 2FA sign-in included (§5) |
269
+ | JWT mode, a browser page on an origin not listed anywhere | Blocked by the browser; list it in `cors.allowedOrigins` (§5) |
270
+ | A client reading `token` from `list-sessions` | Gets none; use `id` and `revoke-session` with `{ sessionId }` (§6) |
271
+ | `revoke-session` with `{ token }` | Unchanged (§6) |
272
+ | `GET /ai/prompts` / `findAiPrompts` without the new parameter | Unchanged: enabled prompts only (§7) |
273
+
274
+ ## Troubleshooting
275
+
276
+ | Symptom | Cause | Fix |
277
+ |---|---|---|
278
+ | `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) |
279
+ | `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) |
280
+ | `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 |
281
+ | 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) |
282
+ | 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) |
283
+ | 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) |
284
+ | `/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) |
285
+ | 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) |
286
+ | Revoking a device does nothing after the update | The screen sends the `token` from `list-sessions`, which is gone | Send `{ sessionId: session.id }` (§6) |
287
+ | A disabled AI prompt is missing from the management screen | The screen lists without `includeDisabled` | `GET /ai/prompts?includeDisabled=true` (§7) |
288
+
289
+ ## References
290
+
291
+ - `src/core/common/helpers/config.helper.ts` — `getEnvironmentConfig()`, `selectEnvironmentBlock()`
292
+ - `tests/unit/environment-config-node-env.spec.ts`
293
+ - `src/core/common/helpers/swagger-enabled.helper.ts` — `isSwaggerEnabled()`; `swagger.helper.ts` — `setupSwagger()`
294
+ - `tests/unit/swagger-switch.spec.ts`
295
+ - `src/core/common/helpers/cookies.helper.ts` — `buildCorsConfig()`; `tests/unit/cookies-cors-config.spec.ts`,
296
+ `tests/cors-jwt-mode.e2e-spec.ts`
297
+ - `src/core/modules/better-auth/core-better-auth-session-token.helper.ts` — session records;
298
+ `core-better-auth-api.middleware.ts` — `resolveRevokeSessionId()`; `tests/session-token-exposure.e2e-spec.ts`
299
+ - `src/core/modules/ai/services/core-ai-prompt.service.ts` — `listVisible()`; `tests/unit/ai-prompt-list-visible.spec.ts`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.6.0",
3
+ "version": "12.7.0",
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
  /**
@@ -1698,9 +1698,11 @@ export interface IApiTokens {
1698
1698
  *
1699
1699
  * When cookies are enabled, the server:
1700
1700
  * - Loads `cookie-parser` middleware
1701
- * - Sets `credentials: true` in CORS configuration
1702
1701
  * - Sets signed httpOnly session cookies on authentication responses
1703
1702
  *
1703
+ * CORS answers the resolved origins with `credentials: true` in BOTH modes since 12.7.0 (`buildCorsConfig()`);
1704
+ * until then JWT mode got `*` without credentials.
1705
+ *
1704
1706
  * JWT authentication via `Authorization: Bearer` header works independently
1705
1707
  * of the cookie configuration — it is always available regardless of this setting.
1706
1708
  *
@@ -1741,8 +1743,8 @@ export interface ICookiesConfig {
1741
1743
  * - `{ allowedOrigins: [...] }`: Additional origins beyond `appUrl`/`baseUrl`
1742
1744
  * - `{ allowAll: true }`: Allow all origins (mirrors request origin — NOT recommended for production)
1743
1745
  *
1744
- * When cookies are enabled (default), CORS automatically includes `credentials: true`.
1745
- * Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
1746
+ * CORS includes `credentials: true` for the resolved origins — with cookies and, since 12.7.0, in JWT mode
1747
+ * (`cookies: false`) too. Browsers reject `Access-Control-Allow-Origin: *` with credentials, so origins must
1746
1748
  * be explicitly listed or `allowAll` must be set (which mirrors the request origin).
1747
1749
  *
1748
1750
  * @default undefined (enabled, origins auto-derived from appUrl/baseUrl)
@@ -3621,6 +3623,25 @@ export interface IServerOptions {
3621
3623
  */
3622
3624
  sync?: boolean | ISync;
3623
3625
 
3626
+ /**
3627
+ * Whether `setupSwagger()` serves the API documentation (12.7.0+), decided by `isSwaggerEnabled()`.
3628
+ *
3629
+ * | Value | `local` / `ci` / `e2e` | every other environment (`develop`, `test`, `production`, …) |
3630
+ * |-------|------------------------|---------------------------------------------------------------|
3631
+ * | not set | served | **off** |
3632
+ * | `true` | served | served |
3633
+ * | `false` | off | off |
3634
+ *
3635
+ * Off mounts nothing: neither `/swagger` and `/swagger-api-tokens` nor `/api-docs-json` and
3636
+ * `/api-docs-api-tokens-json` (or the paths `setupSwagger()` was given) — they answer 404. Before 12.7.0 every
3637
+ * project that called `setupSwagger()` published its full API description on every stage. A value that is not a
3638
+ * boolean counts as not set. Environment variable: `NSC__SWAGGER=true`.
3639
+ *
3640
+ * @default undefined (served only in `local`, `ci` and `e2e`)
3641
+ * @since 12.7.0
3642
+ */
3643
+ swagger?: boolean;
3644
+
3624
3645
  /**
3625
3646
  * System setup configuration for initial admin creation.
3626
3647
  *
@@ -4186,8 +4207,8 @@ export interface ITusConfig {
4186
4207
  *
4187
4208
  * Unset, they come from the API's own CORS configuration — `buildCorsConfig()`, the function REST,
4188
4209
  * GraphQL and Better-Auth share (`appUrl`, `baseUrl`, `cors.allowedOrigins`, `cors.allowAll`).
4189
- * Without credentialed CORS configured (cookies off, or no origin resolvable) the tus server keeps
4190
- * its own default, `*`.
4210
+ * Without credentialed CORS configured (no origin resolvable) the tus server keeps its own default,
4211
+ * `*`. Since 12.7.0 JWT mode (`cookies: false`) gets the origin list too.
4191
4212
  *
4192
4213
  * The wildcard is what broke browser uploads with cookie authentication and separate app/API
4193
4214
  * origins before 11.42.1: a credentialed response with `Access-Control-Allow-Origin: *` is refused
@@ -161,7 +161,10 @@ ai: {
161
161
  permissions.
162
162
  - **User prompts ("Vorlagen"):** users author re-usable short prompts for themselves
163
163
  (private) or their tenant (public) via `aiPrompts` (`/ai/prompts`, `useLtAiPrompts`).
164
- Inserted into the chat input by a picker.
164
+ Inserted into the chat input by a picker. The list answers ENABLED prompts only — what the
165
+ picker offers; a management screen asks `GET /ai/prompts?includeDisabled=true` (GraphQL
166
+ `findAiPrompts(includeDisabled: true)`, 12.7.0), or a prompt saved with "enabled" off
167
+ disappears from it.
165
168
  - **Placeholders:** `{{placeholder}}` tokens in both system slots AND user prompts are
166
169
  resolved at run time by `CoreAiPlaceholderRegistry`. The current list is served via
167
170
  `GET /ai/placeholders` (`useLtAiPlaceholders`) — your slot/prompt editors should render
@@ -1,4 +1,5 @@
1
1
  import { Body, Controller, Delete, Get, Inject, Optional, Param, Post, Put, Query, Res } from '@nestjs/common';
2
+ import { ApiQuery } from '@nestjs/swagger';
2
3
  import type { Response } from 'express';
3
4
 
4
5
  import { RESTServiceOptions } from '../../common/decorators/rest-service-options.decorator.js';
@@ -580,11 +581,25 @@ export class CoreAiController {
580
581
  // User-facing user prompts ("Vorlagen") — own / tenant / global
581
582
  // ===================================================================================================================
582
583
 
583
- /** List user prompts visible to the current user (own + tenant + global). */
584
+ /**
585
+ * List user prompts visible to the current user (own + tenant + global). Enabled ones only — what the chat offers;
586
+ * `?includeDisabled=true` lists disabled ones too, for the management screen (12.7.0).
587
+ */
584
588
  @Get('prompts')
585
589
  @Roles(RoleEnum.S_USER)
586
- async findPrompts(@RESTServiceOptions() serviceOptions: ServiceOptions): Promise<CoreAiPrompt[]> {
587
- return this.promptService.listVisible(serviceOptions);
590
+ @ApiQuery({
591
+ description: 'Also list disabled prompts (for managing them); default: enabled prompts only',
592
+ name: 'includeDisabled',
593
+ required: false,
594
+ type: Boolean,
595
+ })
596
+ async findPrompts(
597
+ @RESTServiceOptions() serviceOptions: ServiceOptions,
598
+ @Query('includeDisabled') includeDisabled?: string,
599
+ ): Promise<CoreAiPrompt[]> {
600
+ return this.promptService.listVisible(serviceOptions, {
601
+ includeDisabled: includeDisabled === 'true' || includeDisabled === '1',
602
+ });
588
603
  }
589
604
 
590
605
  /** Create a user prompt for the current user / tenant (global requires admin). */