@lenne.tech/nest-server 11.43.10 → 11.44.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 (37) hide show
  1. package/.claude/rules/better-auth.md +4 -0
  2. package/.claude/rules/configurable-features.md +3 -0
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +2 -2
  5. package/dist/core/common/interfaces/server-options.interface.d.ts +2 -0
  6. package/dist/core/common/middlewares/string-cookies.middleware.d.ts +12 -0
  7. package/dist/core/common/middlewares/string-cookies.middleware.js +54 -0
  8. package/dist/core/common/middlewares/string-cookies.middleware.js.map +1 -0
  9. package/dist/core/common/pipes/map-and-validate.pipe.d.ts +2 -0
  10. package/dist/core/common/pipes/map-and-validate.pipe.js +16 -0
  11. package/dist/core/common/pipes/map-and-validate.pipe.js.map +1 -1
  12. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +7 -1
  13. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
  14. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  15. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  16. package/dist/core/modules/error-code/error-codes.js +8 -0
  17. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  18. package/dist/core.module.js +2 -0
  19. package/dist/core.module.js.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  24. package/dist/tsconfig.build.tsbuildinfo +1 -1
  25. package/docs/REQUEST-LIFECYCLE.md +25 -0
  26. package/migration-guides/11.13.x-to-11.14.0.md +5 -5
  27. package/migration-guides/11.43.x-to-11.44.x.md +147 -0
  28. package/package.json +2 -2
  29. package/src/core/common/interfaces/server-options.interface.ts +50 -9
  30. package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
  31. package/src/core/common/pipes/map-and-validate.pipe.ts +38 -0
  32. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +45 -9
  33. package/src/core/modules/error-code/error-codes.ts +13 -0
  34. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +10 -4
  35. package/src/core/modules/system-setup/README.md +5 -5
  36. package/src/core.module.ts +5 -0
  37. package/src/index.ts +1 -0
@@ -99,6 +99,8 @@ JWT-based authentication for existing projects:
99
99
  | Feature | Description |
100
100
  |---------|-------------|
101
101
  | **Input Whitelisting** | `MapAndValidatePipe` strips/rejects unknown properties |
102
+ | **Primitive Parameter Types** | `MapAndValidatePipe` answers 400 (`#LTNS_0306`) to an object at a parameter declared `string` / `number` / `boolean` — the shape of a MongoDB operator (11.44.0) |
103
+ | **String Cookies Only** | `StringCookiesMiddleware` removes non-string values (cookie-parser's `j:` JSON) from `req.cookies` before any middleware or guard reads them (11.44.0) |
102
104
  | **Input Validation** | `class-validator` integration via `@UnifiedField()` |
103
105
  | **Password Hashing Plugin** | Automatic BCrypt hashing on all Mongoose write operations |
104
106
  | **Role Guard Plugin** | Prevents unauthorized role escalation at database level |
@@ -346,6 +348,9 @@ The following diagram shows the exact order of execution from HTTP request to re
346
348
  | - Lazy currentUser getter (from req.user) |
347
349
  | - Accept-Language for translations |
348
350
  | |
351
+ | 1b. StringCookiesMiddleware [11.44.0] |
352
+ | - Drops non-string cookie values (`j:` JSON) |
353
+ | |
349
354
  | 2. CoreBetterAuthMiddleware |
350
355
  | - Skips API-token credentials entirely |
351
356
  | - Strategy 1: Auth header (JWT/Session) |
@@ -589,6 +594,8 @@ NestJS middleware runs for every request after Express-level middleware. Registr
589
594
  // src/core.module.ts
590
595
  configure(consumer: MiddlewareConsumer) {
591
596
  consumer.apply(RequestContextMiddleware).forRoutes('*');
597
+ consumer.apply(StringCookiesMiddleware).forRoutes('*');
598
+ consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
592
599
  consumer.apply(graphqlUploadExpress()).forRoutes('graphql');
593
600
  }
594
601
  ```
@@ -689,6 +696,13 @@ If authentication succeeds, `req.user` is set with the authenticated user (inclu
689
696
  > sessions). A JWT (`/token`) and other plugins' tokens are left alone. See `.claude/rules/better-auth.md` §7
690
697
  > "Forwarded responses".
691
698
 
699
+ #### 1b. StringCookiesMiddleware (11.44.0)
700
+
701
+ Removes every cookie value that is not a string from `req.cookies`, and from `req.signedCookies` everything but
702
+ strings and `false` (cookie-parser's invalid-signature marker). cookie-parser turns a cookie value starting with `j:`
703
+ into the parsed JSON, so `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as a
704
+ MongoDB operator (DEV-4138). Registered right after the request context, before every other middleware and every guard. `security.stringCookiesOnly: false` switches it off.
705
+
692
706
  #### 2b. SecurityHeadersMiddleware
693
707
 
694
708
  Sets the browser security headers on **every** response — `X-Content-Type-Options`,
@@ -838,6 +852,17 @@ The `MapAndValidatePipe` runs on every incoming argument/body:
838
852
  Plain Object --> Transform to Class Instance --> Whitelist Check --> Validation --> Clean Input
839
853
  ```
840
854
 
855
+ #### Primitive parameters (11.44.0)
856
+
857
+ A parameter declared as `string`, `number` or `boolean` (`@Body('token') token: string`, likewise `@Query` and
858
+ `@Param`) has `metatype` `String` / `Number` / `Boolean`, and the pipe used to return its value unchecked — the
859
+ declared type is erased at runtime. Since 11.44.0 a **plain object** there is answered with 400
860
+ (`#LTNS_0306 [<parameter>]`) before the route runs: `{ "token": { "$ne": null } }` is the shape of a MongoDB operator
861
+ (DEV-4143 set somebody else's password with it). `null` and arrays pass. Not covered: parameters typed as a class (the
862
+ DTO validates them), as `any`, or as a union the compiler emits as `Object` (`tsc` with `strictNullChecks` does so for
863
+ `string | undefined`; SWC emits `String`) — guard those values at the query with `isQueryableString()`.
864
+ `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes: false` switches it off.
865
+
841
866
  #### Whitelisting via @UnifiedField()
842
867
 
843
868
  Properties **without** `@UnifiedField()` are subject to the whitelist policy:
@@ -49,9 +49,9 @@ New module for creating the first admin user on fresh deployments, especially us
49
49
 
50
50
  ```bash
51
51
  # .env or Docker environment
52
- NSC__systemSetup__initialAdmin__email=admin@example.com
53
- NSC__systemSetup__initialAdmin__password=YourSecurePassword123!
54
- NSC__systemSetup__initialAdmin__name=Admin # optional
52
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
53
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
54
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME=Admin # optional
55
55
  ```
56
56
 
57
57
  Or in `config.env.ts`:
@@ -190,8 +190,8 @@ betterAuth: {
190
190
 
191
191
  ```bash
192
192
  # .env
193
- NSC__systemSetup__initialAdmin__email=admin@example.com
194
- NSC__systemSetup__initialAdmin__password=YourSecurePassword123!
193
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
194
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
195
195
  ```
196
196
 
197
197
  ### Step 4: Build and Test
@@ -0,0 +1,147 @@
1
+ # Migration Guide: 11.43.x → 11.44.x
2
+
3
+ ## 11.44.0 changes behaviour
4
+
5
+ The version number moves only the MINOR digit (the MAJOR follows NestJS). This is the 11.x counterpart of 12.8.0.
6
+ Two security defaults change what a request may carry:
7
+
8
+ - A request value that is a plain **object** where a route declares `string`, `number` or `boolean`
9
+ (`@Body('token') token: string`, likewise `@Query` and `@Param`) is answered with **400** (`#LTNS_0306`) before the
10
+ route runs (§1).
11
+ - Cookie values that are not strings — what cookie-parser makes of a `j:`-prefixed cookie — are removed from
12
+ `req.cookies` before any middleware or guard reads them (§2).
13
+
14
+ Neither affects a client that sends what the route declares. Both have a switch.
15
+
16
+ ## Overview
17
+
18
+ | Category | Details |
19
+ |---|---|
20
+ | **Breaking Changes** | An object at a `string` / `number` / `boolean` parameter answers 400 instead of reaching the route (§1). Non-string cookie values are dropped (§2) |
21
+ | **New Features** | `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes` and `security.stringCookiesOnly` (both default `true`); error code `LTNS_0306` `INVALID_PARAMETER_TYPE`; `receivesObjectForPrimitive()`, `dropNonStringCookies()`, `StringCookiesMiddleware` exported |
22
+ | **Bugfixes** | The email-verification link derives the app URL from `baseUrl` instead of pointing at `http://localhost:3001` when `appUrl` is not set (§3) |
23
+ | **Migration Effort** | Usually none. Check that no client sends an object into a parameter typed `string` / `number` / `boolean`, and that the project writes no object cookies (§1, §2) |
24
+
25
+ ## Quick Migration
26
+
27
+ ```bash
28
+ pnpm add @lenne.tech/nest-server@11.44.0
29
+ pnpm run update # nest-server-starter based projects (release/11.x)
30
+ pnpm run build
31
+ pnpm test
32
+ ```
33
+
34
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
35
+
36
+ ## 1. An object at a primitive parameter answers 400
37
+
38
+ **Why:** a controller parameter declared `@Body('token') token: string` has the metatype `String`, and
39
+ `MapAndValidatePipe` returned basic-type values unchecked — TypeScript types are erased at runtime. A JSON body
40
+ `{ "token": { "$ne": null } }` therefore reached the service as an object, and a MongoDB filter read it as an operator.
41
+ That is how a password-reset token set somebody else's password before 11.39.0 (DEV-4143), and the same shape reached
42
+ the session lookup through a cookie until 11.43.10 (DEV-4138). Both were fixed per query; this closes the class for
43
+ every route at once, including routes in your project.
44
+
45
+ **What changed:** the pipe answers `400 Bad Request` with `#LTNS_0306: Invalid parameter type [<parameter>]` when the
46
+ value is a **plain object** and the parameter is declared `string`, `number` or `boolean` — for `@Body(…)`, `@Query(…)`
47
+ and `@Param(…)`, and for a whole-body `@Body() body: string`.
48
+
49
+ | Value at `@Body('x') x: string` | 11.43.x | 11.44.0 |
50
+ |---|---|---|
51
+ | `"abc"`, `7`, `true` | passed | passed |
52
+ | `null`, missing | passed | passed |
53
+ | `["a", "b"]` (also a repeated query key) | passed | passed |
54
+ | `{ "$ne": null }`, `{}` | **passed to the route** | **400 `#LTNS_0306`** |
55
+
56
+ `null` passes on purpose (clearing an optional field is legitimate), and so do arrays (a repeated query key arrives as
57
+ one, and an array selects nothing as a filter value). Express 5's default query parser cannot produce an object from a
58
+ query string; JSON and form bodies can.
59
+
60
+ **Not covered — keep the guards at the query:**
61
+
62
+ - a parameter typed as a **union** the compiler emits as `Object`: `tsc` with `strictNullChecks` does so for
63
+ `locale: string | undefined`, and the pipe cannot tell (SWC and `tsc` without `strictNullChecks` emit `String`, and
64
+ the parameter is covered);
65
+ - a parameter typed as a **class** whose DTO field has **no type validator** (`@UnifiedField({ isAny: true })`, a custom
66
+ `validator` that does not check the type) — the DTO decides what it accepts;
67
+ - `any`, and values a project reads from `req.body` / `req.query` itself;
68
+ - values that end up in an **aggregation pipeline** (`$match`, `$lookup` stages built from request data);
69
+ - GraphQL arguments of a JSON scalar type (`String` arguments are safe: the scalar refuses objects).
70
+
71
+ For those, check the value where it reaches the database: `isQueryableString()` is exported from
72
+ `@lenne.tech/nest-server`. The framework's own query guards from 11.39.0 and 11.43.10 stay in place.
73
+
74
+ **Your project:** usually nothing. A client that sends an object into a parameter typed `string`, `number` or
75
+ `boolean` now gets 400 — that was a type mismatch before, and it reached your code unchecked. To find such routes:
76
+
77
+ ```bash
78
+ grep -rnE "@(Body|Query|Param)\('[a-zA-Z_]+'\) [a-zA-Z_]+\??: (string|number|boolean)" src/
79
+ ```
80
+
81
+ Switch: `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes: false` restores the old behaviour (only an
82
+ explicit `false` counts). With `security.mapAndValidatePipe: false` the whole pipe is off, this check included.
83
+
84
+ ## 2. Cookies carry strings only
85
+
86
+ **Why:** cookie-parser turns a cookie value starting with `j:` into the parsed JSON. A client sending
87
+ `iam.session_token=j:{"$ne":null}` therefore put an object into `req.cookies`. Until 11.43.10 that signed a request in
88
+ as the owner of a stored session (DEV-4138).
89
+
90
+ **What changed:** `StringCookiesMiddleware`, registered by `CoreModule` for all routes right after the request context,
91
+ removes every non-string value from `req.cookies`, and from `req.signedCookies` everything but strings and `false`
92
+ (cookie-parser's marker for a cookie whose signature did not verify). Every middleware, guard and route after it sees
93
+ string cookies only. The framework writes only string cookies. Nest middleware runs on the routes Nest serves: an
94
+ Express router a project mounts itself with `app.use()`, or a path outside the global prefix, reads `req.cookies` as
95
+ cookie-parser left them — check a cookie value there before it reaches a query.
96
+
97
+ **Your project:** nothing, unless it writes object cookies with `res.cookie(name, { … })` and reads the object back from
98
+ `req.cookies`. Then switch it off with `security.stringCookiesOnly: false`, or — better — write a string
99
+ (`JSON.stringify`) and parse it where it is read.
100
+
101
+ ## 3. The verification link follows the app URL (DEV-4140)
102
+
103
+ **Why:** a relative `betterAuth.emailVerification.callbackURL` was resolved against `appUrl || 'http://localhost:3001'`.
104
+ A deployed stage without `NSC__APP_URL` therefore mailed a verification link to localhost, although `NSC__BASE_URL`
105
+ names the app and the password-reset link already derived it from there.
106
+
107
+ **What changed:** the link uses the same resolver as the reset link — explicit `appUrl`, the localhost default in
108
+ `local` / `ci` / `e2e`, else derived from `baseUrl` (`https://api.example.com` → `https://example.com`) unless
109
+ `cors.deriveAppUrl` is `false`. When nothing resolves, the mail keeps Better-Auth's own link to the API (token sealed)
110
+ and the service warns once. The `email` query parameter is still appended.
111
+
112
+ **Your project:** nothing. `NSC__APP_URL` still wins where it is set.
113
+ `CoreBetterAuthEmailVerificationService.buildFrontendVerificationUrl()` now returns `string | undefined`; an override
114
+ that returns a string stays compatible.
115
+
116
+ ## Compatibility Notes
117
+
118
+ | Pattern | Status |
119
+ |---|---|
120
+ | `@Body('x') x: string` receiving a string, number or boolean | Unchanged |
121
+ | `@Body() input: SomeInput` (DTO class) | Unchanged — validated by the DTO as before |
122
+ | `@Body() body: any` | Unchanged — not covered by §1, guard at the query |
123
+ | `@Query('x') x: string \| undefined` receiving an object | Depends on the compiler (§1): 400 under SWC and `tsc` without `strictNullChecks`, unchanged under `tsc` with it — guard at the query either way |
124
+ | `@Query('ids') ids: string` with `?ids=a&ids=b` | Unchanged — an array passes |
125
+ | `@Body('x') x?: string` receiving `null` | Unchanged — `null` passes |
126
+ | A multipart form with bracketed field names (`title[a]=x`) into a `string` parameter | 400 — multer builds an object from it |
127
+ | Cookies written by nest-server, nuxt-extensions, ng-base or the starters | Unchanged — all are strings |
128
+ | `req.signedCookies.x === false` (invalid signature) | Unchanged — `false` is kept |
129
+ | Project code reading an object cookie written with `res.cookie(name, {…})` | Gone — see §2 |
130
+ | GraphQL arguments | Unchanged — scalars validate their type |
131
+
132
+ ## Troubleshooting
133
+
134
+ | Symptom | Cause | Fix |
135
+ |---|---|---|
136
+ | `400 #LTNS_0306: Invalid parameter type [x]` after the update | A client sends an object for a parameter typed `string` / `number` / `boolean` | Send the declared type, or declare the parameter as a DTO class that describes the object (§1) |
137
+ | A cookie the project set is `undefined` in `req.cookies` | It was written as an object (`res.cookie(name, {…})`) | Write a string and parse it, or `security.stringCookiesOnly: false` (§2) |
138
+ | The verification link points at the API instead of the app | No `appUrl`, and `baseUrl` gives none (or `cors.deriveAppUrl: false`) | Set `NSC__APP_URL`; the boot log carries a warning (§3) |
139
+
140
+ ## References
141
+
142
+ - `src/core/common/pipes/map-and-validate.pipe.ts` — `receivesObjectForPrimitive()`
143
+ - `src/core/common/middlewares/string-cookies.middleware.ts` — `StringCookiesMiddleware`, `dropNonStringCookies()`
144
+ - `src/core/common/helpers/input.helper.ts` — `isQueryableString()`
145
+ - `tests/unit/primitive-param-objects.spec.ts`, `tests/primitive-param-objects.e2e-spec.ts`
146
+ - `.claude/rules/configurable-features.md` — rows "Primitive Parameter Types", "String Cookies Only"
147
+ - `migration-guides/11.38.x-to-11.39.x.md` §1 (DEV-4143), `migration-guides/11.43.9-to-11.43.10.md` (DEV-4138)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.43.10",
3
+ "version": "11.44.0",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -87,7 +87,7 @@
87
87
  "node": ">= 22.15",
88
88
  "pnpm": "^11.0.0"
89
89
  },
90
- "packageManager": "pnpm@11.28.5+sha512.484563d30b4c2ad27cb48aa94ff2b302dbcebc8ff6bf28816c2589886e146ce7f76f354f3bc1a438e6f5e9768c302aa0a6f7add8232903cd4cf81426cbc14d9e",
90
+ "packageManager": "pnpm@11.28.10+sha512.672216f06e15c109b85471d49d3fbed17e6f03ead258df08c2bf5b4a5c33321ebfbf59476bce81325efada16ace0ac78548fd0bfcd7a51369e939182a3dd50e4",
91
91
  "dependencies": {
92
92
  "@apollo/server": "5.5.1",
93
93
  "@as-integrations/express5": "1.1.2",
@@ -540,10 +540,14 @@ export interface IBetterAuthEmailVerificationConfig {
540
540
  *
541
541
  * Supports both absolute URLs and relative paths:
542
542
  * - Absolute: `https://example.com/auth/verify-email`
543
- * - Relative: `/auth/verify-email` (resolved against `appUrl`)
543
+ * - Relative: `/auth/verify-email` (the default), resolved against the app URL the rest of the framework uses:
544
+ * `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from `baseUrl`
545
+ * (`https://api.example.com` → `https://example.com`) unless `cors.deriveAppUrl` is `false`. When none resolves,
546
+ * the mail keeps the backend link below and the service warns once. Until DEV-4140 a relative path without
547
+ * `appUrl` resolved against `http://localhost:3001` on every stage.
544
548
  *
545
- * When not set, the verification link points directly to the backend
546
- * endpoint which handles verification and redirects.
549
+ * An empty value keeps the backend link: it points directly to the backend
550
+ * endpoint, which handles verification and redirects.
547
551
  *
548
552
  * Since 11.38.0 the generated link carries the recipient's address as well —
549
553
  * `{callbackURL}?token=<token>&email=<address>`. The verification page needs it to offer
@@ -551,7 +555,7 @@ export interface IBetterAuthEmailVerificationConfig {
551
555
  * that value lives inside the token's JWT payload, and reading it there would mean rendering
552
556
  * data from an unverified signature.
553
557
  *
554
- * @default undefined (backend-handled verification)
558
+ * @default '/auth/verify-email'
555
559
  * @since 11.13.0
556
560
  */
557
561
  callbackURL?: string;
@@ -3187,8 +3191,44 @@ export interface IServerOptions {
3187
3191
  * @default 'strip'
3188
3192
  */
3189
3193
  nonWhitelistedFields?: 'strip' | 'error' | false;
3194
+
3195
+ /**
3196
+ * Answer 400 (`#LTNS_0306`) when a request value arrives as an object where the route declares a
3197
+ * string, number or boolean: `@Body('token') token: string`, likewise `@Query(…)` and `@Param(…)`.
3198
+ *
3199
+ * Such a parameter used to receive the value unchecked — the declared type is erased at runtime — so
3200
+ * `{ "token": { "$ne": null } }` reached the service as a MongoDB operator (DEV-4143: a password-reset
3201
+ * token that set somebody else's password). Only a plain object is refused; `null` and arrays pass.
3202
+ * Not covered: parameters typed as a class (validated by their DTO), as `any`, or as a union the
3203
+ * compiler emits as `Object` (`tsc` with `strictNullChecks` does so for `string | undefined`; SWC does
3204
+ * not). Guard those values at the query with `isQueryableString()`.
3205
+ *
3206
+ * Only an explicit `false` switches the check off.
3207
+ *
3208
+ * @default true
3209
+ * @since 11.44.0
3210
+ */
3211
+ rejectObjectsForPrimitiveTypes?: boolean;
3190
3212
  };
3191
3213
 
3214
+ /**
3215
+ * Remove every cookie value that is not a string from `req.cookies` (and from `req.signedCookies`
3216
+ * everything but strings and `false`, cookie-parser's invalid-signature marker) before any middleware or
3217
+ * guard reads it.
3218
+ *
3219
+ * cookie-parser turns a cookie value starting with `j:` into the parsed JSON, so
3220
+ * `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as an operator
3221
+ * (DEV-4138). The framework writes only string cookies.
3222
+ * Implemented by `StringCookiesMiddleware`, registered by `CoreModule` for all routes.
3223
+ *
3224
+ * Only an explicit `false` switches it off (for a project that deliberately writes object cookies with
3225
+ * `res.cookie(name, object)` and reads them back).
3226
+ *
3227
+ * @default true
3228
+ * @since 11.44.0
3229
+ */
3230
+ stringCookiesOnly?: boolean;
3231
+
3192
3232
  /**
3193
3233
  * Answer a Mongoose `CastError` caused by the client as a client error instead of a 500.
3194
3234
  * See @lenne.tech/nest-server/src/core/common/filters/mongoose-cast-error.filter.ts
@@ -3419,7 +3459,7 @@ export interface IServerOptions {
3419
3459
  *
3420
3460
  * Auto-creation via config/ENV (no REST call needed):
3421
3461
  * - `{ initialAdmin: { email: '...', password: '...' } }`
3422
- * - `NSC__systemSetup__initialAdmin__email` + `NSC__systemSetup__initialAdmin__password`
3462
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL` + `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3423
3463
  *
3424
3464
  * @since 11.14.0
3425
3465
  *
@@ -3744,10 +3784,11 @@ export interface ISystemSetup {
3744
3784
  * during application bootstrap if zero users exist. This is useful for
3745
3785
  * automated deployments (Docker, CI/CD) where no manual REST call is possible.
3746
3786
  *
3747
- * Can be provided via environment variables:
3748
- * - `NSC__systemSetup__initialAdmin__email`
3749
- * - `NSC__systemSetup__initialAdmin__password`
3750
- * - `NSC__systemSetup__initialAdmin__name` (optional)
3787
+ * Can be provided via environment variables, every segment in SCREAMING_SNAKE_CASE. A camelCase spelling such as
3788
+ * `NSC__systemSetup__…` is never read: the environment reader lowercases every segment it does not split at `_`.
3789
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL`
3790
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3791
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME` (optional)
3751
3792
  *
3752
3793
  * Security: Same zero-user guard applies - only works when no users exist.
3753
3794
  */
@@ -0,0 +1,57 @@
1
+ import { Injectable, NestMiddleware } from '@nestjs/common';
2
+ import type { NextFunction, Request, Response } from 'express';
3
+
4
+ import { ConfigService } from '../services/config.service';
5
+
6
+ /**
7
+ * Removes every cookie value that is not a string from `req.cookies`, and from `req.signedCookies` every value that
8
+ * is neither a string nor `false` (cookie-parser's marker for a cookie whose signature did not verify).
9
+ *
10
+ * cookie-parser turns a cookie value starting with `j:` into the parsed JSON, so a client sending
11
+ * `iam.session_token=j:{"$ne":null}` puts an OBJECT into `req.cookies` — the shape a MongoDB filter reads as an operator.
12
+ * That signed requests in as the owner of a stored session until 11.43.10 (DEV-4138). The framework writes only
13
+ * string cookies, so a non-string value is never one of its own.
14
+ *
15
+ * @returns the names of the removed cookies (for logging and tests)
16
+ */
17
+ export function dropNonStringCookies(req: { cookies?: unknown; signedCookies?: unknown }): string[] {
18
+ const removed: string[] = [];
19
+ for (const [store, keepFalse] of [
20
+ [req.cookies, false],
21
+ [req.signedCookies, true],
22
+ ] as const) {
23
+ if (!store || typeof store !== 'object') {
24
+ continue;
25
+ }
26
+ const jar = store as Record<string, unknown>;
27
+ for (const name of Object.keys(jar)) {
28
+ const value = jar[name];
29
+ if (typeof value === 'string' || (keepFalse && value === false)) {
30
+ continue;
31
+ }
32
+ delete jar[name];
33
+ removed.push(name);
34
+ }
35
+ }
36
+ return removed;
37
+ }
38
+
39
+ /**
40
+ * Keeps non-string values out of the parsed cookies of every request (DEV-4144), so no code path — framework or
41
+ * project — can hand a `j:` cookie to a query as an object. Registered by `CoreModule` for all routes, right after the
42
+ * request context; cookie-parser (registered in `main.ts`) has parsed the cookies by then.
43
+ *
44
+ * Switch: `security.stringCookiesOnly` (default `true`; only an explicit `false` turns it off). The guards at the
45
+ * individual queries (`isQueryableString()`) stay — this middleware covers cookies, not body or query values.
46
+ */
47
+ @Injectable()
48
+ export class StringCookiesMiddleware implements NestMiddleware {
49
+ constructor(protected readonly configService: ConfigService) {}
50
+
51
+ use(req: Request, _res: Response, next: NextFunction): void {
52
+ if (this.configService.getFastButReadOnly<boolean>('security.stringCookiesOnly') !== false) {
53
+ dropNonStringCookies(req);
54
+ }
55
+ next();
56
+ }
57
+ }
@@ -695,15 +695,47 @@ function processNonWhitelistedFields(
695
695
  return forbiddenKeys;
696
696
  }
697
697
 
698
+ /** The declared parameter types a request value must not arrive as an object for */
699
+ const PRIMITIVE_METATYPES: readonly unknown[] = [String, Number, Boolean];
700
+
701
+ /**
702
+ * Whether a request value is an object where the route declares a string, number or boolean (DEV-4144).
703
+ *
704
+ * `@Body('token') token: string` has `metatype === String`, and the pipe used to return a basic-type value unchecked —
705
+ * the declared type is erased at runtime. `{ "token": { "$ne": null } }` therefore reached the service as an object,
706
+ * and a MongoDB filter read it as an operator (DEV-4143: a reset token that set somebody else's password). Only a
707
+ * PLAIN OBJECT is refused: an operator always is one. `null` passes (clearing an optional field is legitimate; the
708
+ * query guards handle it), and so does an array (a repeated query key, `?tag=a&tag=b`, arrives as one and selects
709
+ * nothing in a filter). A parameter typed as a class, as `any` or as a union the compiler emits as `Object` is not
710
+ * covered — its value is validated by its DTO or by the guard at the query. (`tsc` with `strictNullChecks` emits
711
+ * `string | undefined` as `Object`; SWC and `tsc` without it emit `String`, and the parameter is covered.)
712
+ *
713
+ * Exported for tests and for project pipes that replace this one.
714
+ */
715
+ export function receivesObjectForPrimitive(value: unknown, metadata: ArgumentMetadata): boolean {
716
+ return (
717
+ (metadata.type === 'body' || metadata.type === 'query' || metadata.type === 'param') &&
718
+ PRIMITIVE_METATYPES.includes(metadata.metatype) &&
719
+ value !== null &&
720
+ typeof value === 'object' &&
721
+ !Array.isArray(value)
722
+ );
723
+ }
724
+
698
725
  @Injectable()
699
726
  export class MapAndValidatePipe implements PipeTransform {
700
727
  private readonly nonWhitelistedFieldsMode: 'strip' | 'error' | false = 'strip';
728
+ private readonly rejectObjectsForPrimitiveTypes: boolean = true;
701
729
 
702
730
  constructor() {
703
731
  const pipeConfig = ConfigService.getFastButReadOnly('security.mapAndValidatePipe');
704
732
  if (typeof pipeConfig === 'object' && pipeConfig?.nonWhitelistedFields !== undefined) {
705
733
  this.nonWhitelistedFieldsMode = pipeConfig.nonWhitelistedFields;
706
734
  }
735
+ // Only an explicit `false` switches the check off — a security default must not fall to a typo or a string
736
+ if (typeof pipeConfig === 'object' && pipeConfig?.rejectObjectsForPrimitiveTypes === false) {
737
+ this.rejectObjectsForPrimitiveTypes = false;
738
+ }
707
739
  }
708
740
 
709
741
  async transform(value: any, metadata: ArgumentMetadata) {
@@ -713,6 +745,12 @@ export class MapAndValidatePipe implements PipeTransform {
713
745
  return value;
714
746
  }
715
747
 
748
+ // An object where the route declares a string, number or boolean is the shape of a MongoDB operator
749
+ // ({ "$ne": null }) and never a value the route can use — refused before anything reaches a query (DEV-4144)
750
+ if (this.rejectObjectsForPrimitiveTypes && receivesObjectForPrimitive(value, metadata)) {
751
+ throw new BadRequestException(`${ErrorCode.INVALID_PARAMETER_TYPE} [${metadata.data ?? metadata.type}]`);
752
+ }
753
+
716
754
  const { metatype } = metadata;
717
755
 
718
756
  if (DEBUG_VALIDATION) {
@@ -220,10 +220,8 @@ export class CoreBetterAuthEmailVerificationService {
220
220
  let sent = false;
221
221
 
222
222
  try {
223
- // Override URL if callbackURL is configured (frontend-based verification)
224
- if (this.config.callbackURL) {
225
- url = this.buildFrontendVerificationUrl(token, user.email);
226
- }
223
+ // The app's verification page when callbackURL is configured, Better-Auth's own link otherwise
224
+ url = this.verificationMailUrl({ email: user.email, token, url });
227
225
 
228
226
  this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
229
227
 
@@ -707,20 +705,58 @@ export class CoreBetterAuthEmailVerificationService {
707
705
  }
708
706
  }
709
707
 
708
+ /**
709
+ * The link the verification mail carries: the app's verification page when `callbackURL` is configured and resolves
710
+ * ({@link buildFrontendVerificationUrl}), otherwise the link Better-Auth built (`<baseUrl>/<basePath>/verify-email`,
711
+ * token sealed), which verifies on the API and redirects from there.
712
+ *
713
+ * A relative `callbackURL` with no resolvable app URL keeps Better-Auth's link and warns once — a guessed host
714
+ * would 404 (DEV-4140).
715
+ */
716
+ protected verificationMailUrl(options: { email?: string; token: string; url: string }): string {
717
+ if (!this.config.callbackURL) {
718
+ return options.url;
719
+ }
720
+ const frontendUrl = this.buildFrontendVerificationUrl(options.token, options.email);
721
+ if (frontendUrl === undefined && !this.warnedAboutMissingAppUrl) {
722
+ this.warnedAboutMissingAppUrl = true;
723
+ this.logger.warn(
724
+ `No app URL resolves for the verification link (callbackURL "${this.config.callbackURL}" is relative, appUrl is ` +
725
+ 'unset and baseUrl gives none): the mail links to the API instead of the app page. Set NSC__APP_URL, or ' +
726
+ 'NSC__BASE_URL to derive it from.',
727
+ );
728
+ }
729
+ return frontendUrl ?? options.url;
730
+ }
731
+
732
+ /** Whether {@link verificationMailUrl} already warned that no app URL resolves (once per process) */
733
+ protected warnedAboutMissingAppUrl = false;
734
+
710
735
  /**
711
736
  * Build the frontend verification URL from the configured callbackURL and token.
712
737
  *
713
- * Resolves relative paths against `appUrl`. Appends the token as a query parameter.
738
+ * Resolves a relative `callbackURL` against the app URL the rest of the framework uses
739
+ * (`resolveAppUrlFromConfig()`: explicit `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from
740
+ * `baseUrl` unless `cors.deriveAppUrl` is `false`). Appends the token as a query parameter.
741
+ *
742
+ * Until DEV-4140 a relative value was resolved against `appUrl || 'http://localhost:3001'`, so every deployed stage
743
+ * without `NSC__APP_URL` mailed a link to localhost — while the password-reset link next to it already derived the
744
+ * app from `baseUrl`.
714
745
  *
715
746
  * @param token - The verification token from Better-Auth
716
- * @returns The full frontend URL with token query parameter
747
+ * @param email - The recipient's address, appended so the page can offer "send a new email"
748
+ * @returns The full frontend URL with token query parameter, or `undefined` for a relative `callbackURL` when no app
749
+ * URL resolves (the caller then keeps Better-Auth's own link)
717
750
  */
718
- protected buildFrontendVerificationUrl(token: string, email?: string): string {
751
+ protected buildFrontendVerificationUrl(token: string, email?: string): string | undefined {
719
752
  let baseUrl = this.config.callbackURL!;
720
753
 
721
- // Resolve relative paths against appUrl
754
+ // Resolve relative paths against the app URL — the SAME resolver as the password-reset link
722
755
  if (baseUrl.startsWith('/')) {
723
- const appUrl = this.configService.getFastButReadOnly<string>('appUrl') || 'http://localhost:3001';
756
+ const appUrl = resolveAppUrlFromConfig(this.configService);
757
+ if (!appUrl) {
758
+ return undefined;
759
+ }
724
760
  baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
725
761
  }
726
762
 
@@ -493,6 +493,19 @@ export const LtnsErrors = {
493
493
  },
494
494
  },
495
495
 
496
+ /**
497
+ * An object arrived where the route declares a string, number or boolean (`@Body('token') token: string`) — the
498
+ * shape a MongoDB operator takes (`{ "$ne": null }`). Answered by `MapAndValidatePipe` (11.44.0 / 12.8.0, DEV-4144).
499
+ */
500
+ INVALID_PARAMETER_TYPE: {
501
+ code: 'LTNS_0306',
502
+ message: 'Invalid parameter type',
503
+ translations: {
504
+ de: 'Ein Parameter hat einen ungültigen Typ.',
505
+ en: 'A parameter has an invalid type.',
506
+ },
507
+ },
508
+
496
509
  // =====================================================
497
510
  // Resource Errors (LTNS_0400-LTNS_0499)
498
511
  // =====================================================
@@ -35,12 +35,17 @@ https://github.com/lenneTech/nest-server/tree/develop/src/core/modules/system-se
35
35
  For automated deployments where no manual REST call is possible:
36
36
 
37
37
  ```bash
38
- # .env or Docker environment
39
- NSC__systemSetup__initialAdmin__email=admin@example.com
40
- NSC__systemSetup__initialAdmin__password=YourSecurePassword123!
41
- NSC__systemSetup__initialAdmin__name=Admin # optional
38
+ # .env or Docker environment — every segment in SCREAMING_SNAKE_CASE
39
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
40
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
41
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME=Admin # optional
42
42
  ```
43
43
 
44
+ **WHY SCREAMING_SNAKE_CASE?** The environment reader lowercases every segment it does not split at `_`. The camelCase
45
+ form `NSC__systemSetup__initialAdmin__email`, which this checklist showed before, is therefore read as
46
+ `systemsetup.initialadmin.email` and never reaches `systemSetup.initialAdmin`: no admin is created, and nothing reports
47
+ it.
48
+
44
49
  Or in `config.env.ts`:
45
50
 
46
51
  ```typescript
@@ -99,6 +104,7 @@ export class SystemSetupController extends CoreSystemSetupController {
99
104
  | Re-running init after a successful setup | 403, even with an empty `users` | The claim marker in `system-setup-locks` outlives a SUCCESSFUL setup (it is released only on failure) — drop that collection too, or wait 5 min for it to go stale |
100
105
  | Password too short | 400 validation error | Password must be at least 8 characters |
101
106
  | Missing ENV password | Auto-creation silently skipped | Set both `email` and `password` ENV vars |
107
+ | camelCase ENV names (`NSC__systemSetup__…`) | Auto-creation silently skipped | Write every segment in SCREAMING_SNAKE_CASE: `NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL` |
102
108
  | `systemSetup: { enabled: false }` in config | 404 on endpoints | Remove the explicit disable |
103
109
 
104
110
  ---
@@ -9,8 +9,8 @@ System setup is **enabled by default** when BetterAuth is active. No configurati
9
9
  For automated deployments (Docker, CI/CD), set initial admin credentials via ENV:
10
10
 
11
11
  ```bash
12
- NSC__systemSetup__initialAdmin__email=admin@example.com
13
- NSC__systemSetup__initialAdmin__password=YourSecurePassword123!
12
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
13
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
14
14
  ```
15
15
 
16
16
  **Quick Links:** [Integration Checklist](./INTEGRATION-CHECKLIST.md) | [Endpoints](#endpoints) | [Configuration](#configuration) | [Security](#security)
@@ -136,9 +136,9 @@ For automated deployments where no manual REST call is possible (Docker, CI/CD,
136
136
  ### Via NSC Environment Variables
137
137
 
138
138
  ```bash
139
- NSC__systemSetup__initialAdmin__email=admin@example.com
140
- NSC__systemSetup__initialAdmin__password=YourSecurePassword123!
141
- NSC__systemSetup__initialAdmin__name=Admin # optional
139
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL=admin@example.com
140
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD=YourSecurePassword123!
141
+ NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME=Admin # optional
142
142
  ```
143
143
 
144
144
  ### Via config.env.ts
@@ -40,6 +40,7 @@ import {
40
40
  } from './core/common/interfaces/server-options.interface';
41
41
  import { RequestContextMiddleware } from './core/common/middleware/request-context.middleware';
42
42
  import { SecurityHeadersMiddleware } from './core/common/middlewares/security-headers.middleware';
43
+ import { StringCookiesMiddleware } from './core/common/middlewares/string-cookies.middleware';
43
44
  import { MapAndValidatePipe } from './core/common/pipes/map-and-validate.pipe';
44
45
  import { ComplexityPlugin } from './core/common/plugins/complexity.plugin';
45
46
  import { mongooseIdPlugin } from './core/common/plugins/mongoose-id.plugin';
@@ -99,6 +100,10 @@ export class CoreModule implements NestModule {
99
100
  // RequestContext middleware must run for all routes to provide AsyncLocalStorage context
100
101
  consumer.apply(RequestContextMiddleware).forRoutes('*');
101
102
 
103
+ // No non-string values in the parsed cookies (cookie-parser turns `j:{...}` into an object, the shape of a MongoDB
104
+ // operator — DEV-4138 / DEV-4144). Before every other middleware and every guard, so none of them sees one.
105
+ consumer.apply(StringCookiesMiddleware).forRoutes('*');
106
+
102
107
  // Security headers on EVERY response, guards' rejections included. Middleware rather than an
103
108
  // interceptor for exactly that reason: an interceptor never runs for a request a guard turns
104
109
  // away, and those are the ones an attacker generates most of. The middleware itself decides
package/src/index.ts CHANGED
@@ -80,6 +80,7 @@ export * from './core/common/interfaces/swagger-setup-options.interface';
80
80
  export * from './core/common/middleware/request-context.middleware';
81
81
  export * from './core/common/middlewares/to-lower-case.middleware';
82
82
  export * from './core/common/middlewares/security-headers.middleware';
83
+ export * from './core/common/middlewares/string-cookies.middleware';
83
84
  export * from './core/common/models/core-model.model';
84
85
  export * from './core/common/models/core-persistence.model';
85
86
  export * from './core/common/models/pagination-info.model';