@lenne.tech/nest-server 12.7.2 → 12.8.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 (42) hide show
  1. package/.claude/rules/better-auth.md +11 -0
  2. package/.claude/rules/configurable-features.md +3 -0
  3. package/.claude/rules/testing.md +6 -6
  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 +50 -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 +15 -0
  11. package/dist/core/common/pipes/map-and-validate.pipe.js.map +1 -1
  12. package/dist/core/modules/better-auth/better-auth-token.service.d.ts +1 -1
  13. package/dist/core/modules/better-auth/better-auth-token.service.js +2 -1
  14. package/dist/core/modules/better-auth/better-auth-token.service.js.map +1 -1
  15. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +6 -1
  16. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
  17. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  18. package/dist/core/modules/better-auth/core-better-auth.service.js +2 -1
  19. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  20. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  21. package/dist/core/modules/error-code/error-codes.js +8 -0
  22. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  23. package/dist/core.module.js +2 -0
  24. package/dist/core.module.js.map +1 -1
  25. package/dist/index.d.ts +1 -0
  26. package/dist/index.js +1 -0
  27. package/dist/index.js.map +1 -1
  28. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  29. package/docs/REQUEST-LIFECYCLE.md +27 -0
  30. package/migration-guides/12.6.x-to-12.7.x.md +21 -1
  31. package/migration-guides/12.7.2-to-12.7.3.md +49 -0
  32. package/migration-guides/12.7.x-to-12.8.x.md +152 -0
  33. package/package.json +2 -2
  34. package/src/core/common/interfaces/server-options.interface.ts +45 -4
  35. package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
  36. package/src/core/common/pipes/map-and-validate.pipe.ts +40 -0
  37. package/src/core/modules/better-auth/better-auth-token.service.ts +8 -3
  38. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +44 -9
  39. package/src/core/modules/better-auth/core-better-auth.service.ts +8 -1
  40. package/src/core/modules/error-code/error-codes.ts +13 -0
  41. package/src/core.module.ts +5 -0
  42. package/src/index.ts +1 -0
@@ -100,6 +100,8 @@ JWT-based authentication for existing projects:
100
100
  | Feature | Description |
101
101
  |---------|-------------|
102
102
  | **Input Whitelisting** | `MapAndValidatePipe` strips/rejects unknown properties |
103
+ | **Primitive Parameter Types** | `MapAndValidatePipe` answers 400 (`#LTNS_0306`) to an object at a parameter declared `string` / `number` / `boolean` — the shape of a MongoDB operator (12.8.0) |
104
+ | **String Cookies Only** | `StringCookiesMiddleware` removes non-string values (cookie-parser's `j:` JSON) from `req.cookies` before any middleware or guard reads them (12.8.0) |
103
105
  | **Input Validation** | `class-validator` integration via `@UnifiedField()` |
104
106
  | **Password Hashing Plugin** | Automatic BCrypt hashing on all Mongoose write operations |
105
107
  | **Role Guard Plugin** | Prevents unauthorized role escalation at database level |
@@ -350,6 +352,9 @@ The following diagram shows the exact order of execution from HTTP request to re
350
352
  | - Lazy currentUser getter (from req.user) |
351
353
  | - Accept-Language for translations |
352
354
  | |
355
+ | 1b. StringCookiesMiddleware [12.8.0] |
356
+ | - Drops non-string cookie values (`j:` JSON) |
357
+ | |
353
358
  | 2. CoreBetterAuthMiddleware |
354
359
  | - Skips API-token credentials entirely |
355
360
  | - Strategy 1: Auth header (JWT/Session) |
@@ -598,6 +603,8 @@ NestJS middleware runs for every request after Express-level middleware. Registr
598
603
  // src/core.module.ts
599
604
  configure(consumer: MiddlewareConsumer) {
600
605
  consumer.apply(RequestContextMiddleware).forRoutes('*');
606
+ consumer.apply(StringCookiesMiddleware).forRoutes('*');
607
+ consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
601
608
  consumer.apply(graphqlUploadExpress()).forRoutes('graphql');
602
609
  }
603
610
  ```
@@ -708,6 +715,14 @@ If authentication succeeds, `req.user` is set with the authenticated user (inclu
708
715
  > sessions). A JWT (`/token`) and other plugins' tokens are left alone. See `.claude/rules/better-auth.md` §7
709
716
  > "Forwarded responses".
710
717
 
718
+ #### 1b. StringCookiesMiddleware (12.8.0)
719
+
720
+ Removes every cookie value that is not a string from `req.cookies`, and from `req.signedCookies` everything but
721
+ strings and `false` (cookie-parser's invalid-signature marker). cookie-parser turns a cookie value starting with `j:`
722
+ into the parsed JSON, so `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as a
723
+ MongoDB operator (DEV-4138); on MySQL / MariaDB a number (`j:7`) did the same. Registered right after the request
724
+ context, before every other middleware and every guard. `security.stringCookiesOnly: false` switches it off.
725
+
711
726
  #### 2b. SecurityHeadersMiddleware
712
727
 
713
728
  Sets the browser security headers on **every** response — `X-Content-Type-Options`,
@@ -857,6 +872,18 @@ The `MapAndValidatePipe` runs on every incoming argument/body:
857
872
  Plain Object --> Transform to Class Instance --> Whitelist Check --> Validation --> Clean Input
858
873
  ```
859
874
 
875
+ #### Primitive parameters (12.8.0)
876
+
877
+ A parameter declared as `string`, `number` or `boolean` (`@Body('token') token: string`, likewise `@Query` and
878
+ `@Param`) has `metatype` `String` / `Number` / `Boolean`, and the pipe used to return its value unchecked — the
879
+ declared type is erased at runtime. Since 12.8.0 a **plain object** there is answered with 400
880
+ (`#LTNS_0306 [<parameter>]`) before the route runs: `{ "token": { "$ne": null } }` is the shape of a MongoDB operator
881
+ (DEV-4143 set somebody else's password with it). `null` and arrays pass. Not covered: parameters typed as a class (the
882
+ DTO validates them), as `any`, or as a union the compiler emits as `Object` (`tsc` with `strictNullChecks` does so for
883
+ `string | undefined`; SWC emits `String`), and a number at a `string` parameter, which MySQL / MariaDB compare
884
+ numerically — guard those values at the query with `isQueryableString()`.
885
+ `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes: false` switches it off.
886
+
860
887
  #### Whitelisting via @UnifiedField()
861
888
 
862
889
  Properties **without** `@UnifiedField()` are subject to the whitelist policy:
@@ -22,7 +22,7 @@ The version number moves only the MINOR digit (the MAJOR follows NestJS). Two de
22
22
  |---|---|
23
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
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) |
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). A `j:` session cookie no longer signs a request in as somebody else (§8, 12.7.3) |
26
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
27
 
28
28
  ## Quick Migration
@@ -259,6 +259,25 @@ Visibility is the same in both: the user's own prompts and the prompts of the us
259
259
 
260
260
  **Your frontend:** the screen that edits and deletes prompts adds the parameter; the chat picker keeps its call.
261
261
 
262
+ ## 8. A session token must be a string (12.7.3, security)
263
+
264
+ **Why:** cookie-parser turns a cookie value starting with `j:` into the parsed JSON. A request with
265
+ `Cookie: iam.session_token=j:{"$ne":null}` and no other credential therefore carried an object. The role guards'
266
+ fallback (`BetterAuthTokenService.extractTokenFromRequest()`) passed it on, and `getSessionByToken()` used it as
267
+ MongoDB filter value, which MongoDB read as an operator: the request was answered as the owner of a stored session.
268
+ Affected since 11.10.0 on MongoDB, and since 12.1.1 on MySQL / MariaDB with a number (`j:7`: MySQL compares
269
+ `token = 7` numerically, so every token starting with `7` and a letter matches); the same applies to the legacy
270
+ `token` cookie. PostgreSQL is not affected.
271
+
272
+ **What changed:** `extractTokenFromRequest()` takes only a non-empty string from a cookie and skips anything else, and
273
+ `getSessionByToken()` answers `{ session: null, user: null }` for a value that is not a non-empty string, before it
274
+ queries. Nothing changes for a string token.
275
+
276
+ **Your project:** update; no code change is needed. Project code that calls `getSessionByToken()` with a cookie value
277
+ is covered by the check in that method. Code of your own that puts a cookie, query or body value into a database
278
+ filter itself checks it with `isQueryableString()` (exported from `@lenne.tech/nest-server`) first, as the framework's
279
+ token lookups do.
280
+
262
281
  ## Compatibility Notes
263
282
 
264
283
  | Pattern | Status |
@@ -277,6 +296,7 @@ Visibility is the same in both: the user's own prompts and the prompts of the us
277
296
  | A client reading `token` from `list-sessions` | Gets none; use `id` and `revoke-session` with `{ sessionId }` (§6) |
278
297
  | `revoke-session` with `{ token }` | Unchanged (§6) |
279
298
  | `GET /ai/prompts` / `findAiPrompts` without the new parameter | Unchanged: enabled prompts only (§7) |
299
+ | Project code calling `getSessionByToken()` with a cookie value | Protected since 12.7.3: a value that is not a string finds no session (§8) |
280
300
 
281
301
  ## Troubleshooting
282
302
 
@@ -0,0 +1,49 @@
1
+ # Migration Guide: 12.7.2 → 12.7.3
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | Security: a session cookie that is not a string (cookie-parser's `j:` prefix) signed a request in as the owner of a stored session (§1) |
10
+ | **Migration Effort** | None |
11
+
12
+ The same fix ships in 12.6.4 (`latest-12.6`) and 11.43.10 (`latest-11`).
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@12.7.3
18
+ pnpm run update # nest-server-starter based projects
19
+ pnpm run build
20
+ pnpm test
21
+ ```
22
+
23
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
24
+
25
+ ## 1. A session token must be a string
26
+
27
+ **Why:** cookie-parser turns a cookie value starting with `j:` into the parsed JSON. A request with
28
+ `Cookie: iam.session_token=j:{"$ne":null}` and no other credential therefore carried an object. The role guards'
29
+ fallback (`BetterAuthTokenService.extractTokenFromRequest()`) passed it on, and `getSessionByToken()` used it as
30
+ MongoDB filter value, which MongoDB read as an operator: the request was answered as the owner of a stored session.
31
+ Affected since 11.10.0 on MongoDB, and since 12.1.1 on MySQL / MariaDB with a number (`j:7`: MySQL compares
32
+ `token = 7` numerically, so every token starting with `7` and a letter matches); the same applies to the legacy
33
+ `token` cookie. PostgreSQL is not affected.
34
+
35
+ **What changed:** `extractTokenFromRequest()` takes only a non-empty string from a cookie and skips anything else, and
36
+ `getSessionByToken()` answers `{ session: null, user: null }` for a value that is not a non-empty string, before it
37
+ queries. Nothing changes for a string token.
38
+
39
+ **Your project:** update; no code change is needed. Project code that calls `getSessionByToken()` with a cookie value
40
+ is covered by the check in that method. Code of your own that puts a cookie, query or body value into a database
41
+ filter itself checks it with `isQueryableString()` (exported from `@lenne.tech/nest-server`) first, as the framework's
42
+ token lookups do.
43
+
44
+ ## References
45
+
46
+ - `src/core/modules/better-auth/better-auth-token.service.ts`: `extractTokenFromRequest()`
47
+ - `src/core/modules/better-auth/core-better-auth.service.ts`: `getSessionByToken()`
48
+ - `tests/unit/better-auth-session-token-type.spec.ts`, `tests/session-token-cookie-type.e2e-spec.ts`
49
+ - `migration-guides/12.6.x-to-12.7.x.md` §8
@@ -0,0 +1,152 @@
1
+ # Migration Guide: 12.7.x → 12.8.x
2
+
3
+ ## 12.8.0 changes behaviour
4
+
5
+ The version number moves only the MINOR digit (the MAJOR follows NestJS). Two security defaults change what a request
6
+ 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@12.8.0
29
+ pnpm run update # nest-server-starter based projects
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 12.7.3 (DEV-4138). Both were fixed per query; this closes the class for every
43
+ 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` | 12.7.x | 12.8.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 **number** at a `string` parameter (`{ "token": 7 }`): it passes on purpose, because a client may send a numeric
66
+ code as a number. MySQL and MariaDB compare a number numerically (`token = 7` matches every token starting with
67
+ `7`), so a lookup there checks its value with `isQueryableString()`;
68
+ - a parameter typed as a **class** whose DTO field has **no type validator** (`@UnifiedField({ isAny: true })`, a custom
69
+ `validator` that does not check the type) — the DTO decides what it accepts;
70
+ - `any`, and values a project reads from `req.body` / `req.query` itself;
71
+ - values that end up in an **aggregation pipeline** (`$match`, `$lookup` stages built from request data);
72
+ - GraphQL arguments of a JSON scalar type (`String` arguments are safe: the scalar refuses objects).
73
+
74
+ For those, check the value where it reaches the database: `isQueryableString()` is exported from
75
+ `@lenne.tech/nest-server`. The framework's own query guards from 11.39.0 and 12.7.3 stay in place.
76
+
77
+ **Your project:** usually nothing. A client that sends an object into a parameter typed `string`, `number` or
78
+ `boolean` now gets 400 — that was a type mismatch before, and it reached your code unchecked. To find such routes:
79
+
80
+ ```bash
81
+ grep -rnE "@(Body|Query|Param)\('[a-zA-Z_]+'\) [a-zA-Z_]+\??: (string|number|boolean)" src/
82
+ ```
83
+
84
+ Switch: `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes: false` restores the old behaviour (only an
85
+ explicit `false` counts). With `security.mapAndValidatePipe: false` the whole pipe is off, this check included.
86
+
87
+ ## 2. Cookies carry strings only
88
+
89
+ **Why:** cookie-parser turns a cookie value starting with `j:` into the parsed JSON. A client sending
90
+ `iam.session_token=j:{"$ne":null}` therefore put an object into `req.cookies`, and on MySQL / MariaDB a number (`j:7`)
91
+ is compared numerically (`token = 7` matches every token starting with `7`). Until 12.7.3 that signed a request in as
92
+ the owner of a stored session (DEV-4138).
93
+
94
+ **What changed:** `StringCookiesMiddleware`, registered by `CoreModule` for all routes right after the request context,
95
+ removes every non-string value from `req.cookies`, and from `req.signedCookies` everything but strings and `false`
96
+ (cookie-parser's marker for a cookie whose signature did not verify). Every middleware, guard and route after it sees
97
+ string cookies only. The framework writes only string cookies. Nest middleware runs on the routes Nest serves: an
98
+ Express router a project mounts itself with `app.use()`, or a path outside the global prefix, reads `req.cookies` as
99
+ cookie-parser left them — check a cookie value there before it reaches a query.
100
+
101
+ **Your project:** nothing, unless it writes object cookies with `res.cookie(name, { … })` and reads the object back from
102
+ `req.cookies`. Then switch it off with `security.stringCookiesOnly: false`, or — better — write a string
103
+ (`JSON.stringify`) and parse it where it is read.
104
+
105
+ ## 3. The verification link follows the app URL (DEV-4140)
106
+
107
+ **Why:** a relative `betterAuth.emailVerification.callbackURL` (the default `/auth/verify-email`) was resolved against
108
+ `appUrl || 'http://localhost:3001'`. A deployed stage without `NSC__APP_URL` therefore mailed a verification link to
109
+ localhost, although `NSC__BASE_URL` names the app and the password-reset link already derived it from there.
110
+
111
+ **What changed:** the link uses the same resolver as the reset link — explicit `appUrl`, the localhost default in
112
+ `local` / `ci` / `e2e`, else derived from `baseUrl` (`https://api.example.com` → `https://example.com`) unless
113
+ `cors.deriveAppUrl` is `false`. When nothing resolves, the mail keeps Better-Auth's own link to the API (token sealed)
114
+ and the service warns once.
115
+
116
+ **Your project:** nothing. `NSC__APP_URL` still wins where it is set.
117
+ `CoreBetterAuthEmailVerificationService.buildFrontendVerificationUrl()` now returns `string | undefined`; an override
118
+ that returns a string stays compatible.
119
+
120
+ ## Compatibility Notes
121
+
122
+ | Pattern | Status |
123
+ |---|---|
124
+ | `@Body('x') x: string` receiving a string, number or boolean | Unchanged |
125
+ | `@Body() input: SomeInput` (DTO class) | Unchanged — validated by the DTO as before |
126
+ | `@Body() body: any` | Unchanged — not covered by §1, guard at the query |
127
+ | `@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 |
128
+ | `@Body('code') code: string` receiving the number `7` | Unchanged — a number passes; on MySQL / MariaDB guard the lookup (§1) |
129
+ | `@Query('ids') ids: string` with `?ids=a&ids=b` | Unchanged — an array passes |
130
+ | `@Body('x') x?: string` receiving `null` | Unchanged — `null` passes |
131
+ | A multipart form with bracketed field names (`title[a]=x`) into a `string` parameter | 400 — multer builds an object from it |
132
+ | Cookies written by nest-server, nuxt-extensions, ng-base or the starters | Unchanged — all are strings |
133
+ | `req.signedCookies.x === false` (invalid signature) | Unchanged — `false` is kept |
134
+ | Project code reading an object cookie written with `res.cookie(name, {…})` | Gone — see §2 |
135
+ | GraphQL arguments | Unchanged — scalars validate their type |
136
+
137
+ ## Troubleshooting
138
+
139
+ | Symptom | Cause | Fix |
140
+ |---|---|---|
141
+ | `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) |
142
+ | 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) |
143
+ | 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) |
144
+
145
+ ## References
146
+
147
+ - `src/core/common/pipes/map-and-validate.pipe.ts` — `receivesObjectForPrimitive()`
148
+ - `src/core/common/middlewares/string-cookies.middleware.ts` — `StringCookiesMiddleware`, `dropNonStringCookies()`
149
+ - `src/core/common/helpers/input.helper.ts` — `isQueryableString()`
150
+ - `tests/unit/primitive-param-objects.spec.ts`, `tests/primitive-param-objects.e2e-spec.ts`
151
+ - `.claude/rules/configurable-features.md` — rows "Primitive Parameter Types", "String Cookies Only"
152
+ - `migration-guides/11.38.x-to-11.39.x.md` §1 (DEV-4143), `migration-guides/12.6.x-to-12.7.x.md` §8 (DEV-4138)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "12.7.2",
3
+ "version": "12.8.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": [
@@ -99,7 +99,7 @@
99
99
  "node": ">= 22.15",
100
100
  "pnpm": "^11.0.0"
101
101
  },
102
- "packageManager": "pnpm@11.28.5+sha512.484563d30b4c2ad27cb48aa94ff2b302dbcebc8ff6bf28816c2589886e146ce7f76f354f3bc1a438e6f5e9768c302aa0a6f7add8232903cd4cf81426cbc14d9e",
102
+ "packageManager": "pnpm@11.28.10+sha512.672216f06e15c109b85471d49d3fbed17e6f03ead258df08c2bf5b4a5c33321ebfbf59476bce81325efada16ace0ac78548fd0bfcd7a51369e939182a3dd50e4",
103
103
  "dependencies": {
104
104
  "@apollo/server": "5.5.1",
105
105
  "@as-integrations/express5": "1.1.2",
@@ -546,10 +546,14 @@ export interface IBetterAuthEmailVerificationConfig {
546
546
  *
547
547
  * Supports both absolute URLs and relative paths:
548
548
  * - Absolute: `https://example.com/auth/verify-email`
549
- * - Relative: `/auth/verify-email` (resolved against `appUrl`)
549
+ * - Relative: `/auth/verify-email` (the default), resolved against the app URL the rest of the framework uses:
550
+ * `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from `baseUrl`
551
+ * (`https://api.example.com` → `https://example.com`) unless `cors.deriveAppUrl` is `false`. When none resolves,
552
+ * the mail keeps the backend link below and the service warns once. Until DEV-4140 a relative path without
553
+ * `appUrl` resolved against `http://localhost:3001` on every stage.
550
554
  *
551
- * When not set, the verification link points directly to the backend
552
- * endpoint which handles verification and redirects.
555
+ * An empty value keeps the backend link: it points directly to the backend
556
+ * endpoint, which handles verification and redirects.
553
557
  *
554
558
  * Since 12.6.0 the link carries the token only, and sealed — `{callbackURL}?token=<sealed>`: no `email`
555
559
  * parameter, and the token is encrypted, because Better-Auth's own token is a readable JWT with the
@@ -558,7 +562,7 @@ export interface IBetterAuthEmailVerificationConfig {
558
562
  * masked (`GET /iam/features` → `resendVerificationByToken`). From 11.38.0 to 12.5.x the link carried
559
563
  * `&email=<address>`.
560
564
  *
561
- * @default undefined (backend-handled verification)
565
+ * @default '/auth/verify-email'
562
566
  * @since 11.13.0
563
567
  */
564
568
  callbackURL?: string;
@@ -3392,8 +3396,45 @@ export interface IServerOptions {
3392
3396
  * @default 'strip'
3393
3397
  */
3394
3398
  nonWhitelistedFields?: 'strip' | 'error' | false;
3399
+
3400
+ /**
3401
+ * Answer 400 (`#LTNS_0306`) when a request value arrives as an object where the route declares a
3402
+ * string, number or boolean: `@Body('token') token: string`, likewise `@Query(…)` and `@Param(…)`.
3403
+ *
3404
+ * Such a parameter used to receive the value unchecked — the declared type is erased at runtime — so
3405
+ * `{ "token": { "$ne": null } }` reached the service as a MongoDB operator (DEV-4143: a password-reset
3406
+ * token that set somebody else's password). Only a plain object is refused; `null` and arrays pass.
3407
+ * Not covered: parameters typed as a class (validated by their DTO), as `any`, or as a union the
3408
+ * compiler emits as `Object` (`tsc` with `strictNullChecks` does so for `string | undefined`; SWC does
3409
+ * not), and a number at a `string` parameter (MySQL / MariaDB compare it numerically). Guard those
3410
+ * values at the query with `isQueryableString()`.
3411
+ *
3412
+ * Only an explicit `false` switches the check off.
3413
+ *
3414
+ * @default true
3415
+ * @since 12.8.0
3416
+ */
3417
+ rejectObjectsForPrimitiveTypes?: boolean;
3395
3418
  };
3396
3419
 
3420
+ /**
3421
+ * Remove every cookie value that is not a string from `req.cookies` (and from `req.signedCookies`
3422
+ * everything but strings and `false`, cookie-parser's invalid-signature marker) before any middleware or
3423
+ * guard reads it.
3424
+ *
3425
+ * cookie-parser turns a cookie value starting with `j:` into the parsed JSON, so
3426
+ * `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as an operator
3427
+ * (DEV-4138); on MySQL / MariaDB a number (`j:7`) did the same. The framework writes only string cookies.
3428
+ * Implemented by `StringCookiesMiddleware`, registered by `CoreModule` for all routes.
3429
+ *
3430
+ * Only an explicit `false` switches it off (for a project that deliberately writes object cookies with
3431
+ * `res.cookie(name, object)` and reads them back).
3432
+ *
3433
+ * @default true
3434
+ * @since 12.8.0
3435
+ */
3436
+ stringCookiesOnly?: boolean;
3437
+
3397
3438
  /**
3398
3439
  * Answer a Mongoose `CastError` caused by the client as a client error instead of a 500.
3399
3440
  * See @lenne.tech/nest-server/src/core/common/filters/mongoose-cast-error.filter.ts
@@ -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.js';
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 12.7.3 (DEV-4138); on MySQL / MariaDB a number
13
+ * (`j:7`) did the same. The framework writes only 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,49 @@ 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.) A number
712
+ * at a `string` parameter passes on purpose — a client may send a numeric code as a number — so a lookup on MySQL /
713
+ * MariaDB, which compare a number numerically, still checks its value with `isQueryableString()`.
714
+ *
715
+ * Exported for tests and for project pipes that replace this one.
716
+ */
717
+ export function receivesObjectForPrimitive(value: unknown, metadata: ArgumentMetadata): boolean {
718
+ return (
719
+ (metadata.type === 'body' || metadata.type === 'query' || metadata.type === 'param') &&
720
+ PRIMITIVE_METATYPES.includes(metadata.metatype) &&
721
+ value !== null &&
722
+ typeof value === 'object' &&
723
+ !Array.isArray(value)
724
+ );
725
+ }
726
+
698
727
  @Injectable()
699
728
  export class MapAndValidatePipe implements PipeTransform {
700
729
  private readonly nonWhitelistedFieldsMode: 'strip' | 'error' | false = 'strip';
730
+ private readonly rejectObjectsForPrimitiveTypes: boolean = true;
701
731
 
702
732
  constructor() {
703
733
  const pipeConfig = ConfigService.getFastButReadOnly('security.mapAndValidatePipe');
704
734
  if (typeof pipeConfig === 'object' && pipeConfig?.nonWhitelistedFields !== undefined) {
705
735
  this.nonWhitelistedFieldsMode = pipeConfig.nonWhitelistedFields;
706
736
  }
737
+ // Only an explicit `false` switches the check off — a security default must not fall to a typo or a string
738
+ if (typeof pipeConfig === 'object' && pipeConfig?.rejectObjectsForPrimitiveTypes === false) {
739
+ this.rejectObjectsForPrimitiveTypes = false;
740
+ }
707
741
  }
708
742
 
709
743
  async transform(value: any, metadata: ArgumentMetadata) {
@@ -713,6 +747,12 @@ export class MapAndValidatePipe implements PipeTransform {
713
747
  return value;
714
748
  }
715
749
 
750
+ // An object where the route declares a string, number or boolean is the shape of a MongoDB operator
751
+ // ({ "$ne": null }) and never a value the route can use — refused before anything reaches a query (DEV-4144)
752
+ if (this.rejectObjectsForPrimitiveTypes && receivesObjectForPrimitive(value, metadata)) {
753
+ throw new BadRequestException(`${ErrorCode.INVALID_PARAMETER_TYPE} [${metadata.data ?? metadata.type}]`);
754
+ }
755
+
716
756
  const { metatype } = metadata;
717
757
 
718
758
  if (DEBUG_VALIDATION) {
@@ -2,6 +2,7 @@ import { Injectable, Logger, Optional } from '@nestjs/common';
2
2
  import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
3
3
  import type { Connection } from 'mongoose';
4
4
 
5
+ import { isQueryableString } from '../../common/helpers/input.helper.js';
5
6
  import { BetterAuthenticatedUser } from './better-auth.types.js';
6
7
  import { BetterAuthMongoUsers, type IamUserLookup } from './core-better-auth-mongo.users.js';
7
8
  import { getBetterAuthSqlStore } from './core-better-auth-sql.registry.js';
@@ -60,7 +61,7 @@ export class BetterAuthTokenService {
60
61
  * @returns Token extraction result with token and source
61
62
  */
62
63
  extractTokenFromRequest(request: {
63
- cookies?: Record<string, string>;
64
+ cookies?: Record<string, unknown>;
64
65
  headers?: Record<string, string | string[] | undefined>;
65
66
  }): TokenExtractionResult {
66
67
  // Try Authorization header first
@@ -73,10 +74,14 @@ export class BetterAuthTokenService {
73
74
  }
74
75
  }
75
76
 
76
- // Try cookies - Better-Auth native cookie first, then legacy
77
+ // Try cookies - Better-Auth native cookie first, then legacy.
78
+ // Only a non-empty string is a token (DEV-4138): cookie-parser turns a value starting with `j:` into the parsed
79
+ // JSON, so `iam.session_token=j:{"$ne":null}` arrives here as an object — which the session lookup would read as a
80
+ // MongoDB operator and answer with somebody else's session (a number, `j:7`, does the same on MySQL / MariaDB).
81
+ // A non-string cookie is skipped, never passed on.
77
82
  if (request.cookies && this.betterAuthService) {
78
83
  const cookieName = this.betterAuthService.getSessionCookieName();
79
- const token = request.cookies[cookieName] || request.cookies['token'] || undefined;
84
+ const token = [request.cookies[cookieName], request.cookies['token']].find(isQueryableString);
80
85
 
81
86
  if (token) {
82
87
  return { source: 'cookie', token };
@@ -233,10 +233,8 @@ export class CoreBetterAuthEmailVerificationService {
233
233
  let sent = false;
234
234
 
235
235
  try {
236
- // Override URL if callbackURL is configured (frontend-based verification)
237
- if (this.config.callbackURL) {
238
- url = this.buildFrontendVerificationUrl(token);
239
- }
236
+ // The app's verification page when callbackURL is configured, Better-Auth's own link otherwise
237
+ url = this.verificationMailUrl({ token, url });
240
238
 
241
239
  this.logAuthUrlForDevelopment('EMAIL VERIFICATION', user.email, url);
242
240
 
@@ -731,20 +729,57 @@ export class CoreBetterAuthEmailVerificationService {
731
729
  }
732
730
  }
733
731
 
732
+ /**
733
+ * The link the verification mail carries: the app's verification page when `callbackURL` is configured and resolves
734
+ * ({@link buildFrontendVerificationUrl}), otherwise the link Better-Auth built (`<baseUrl>/<basePath>/verify-email`,
735
+ * token sealed), which verifies on the API and redirects from there.
736
+ *
737
+ * A relative `callbackURL` with no resolvable app URL keeps Better-Auth's link and warns once — a guessed host
738
+ * would 404 (DEV-4140).
739
+ */
740
+ protected verificationMailUrl(options: { token: string; url: string }): string {
741
+ if (!this.config.callbackURL) {
742
+ return options.url;
743
+ }
744
+ const frontendUrl = this.buildFrontendVerificationUrl(options.token);
745
+ if (frontendUrl === undefined && !this.warnedAboutMissingAppUrl) {
746
+ this.warnedAboutMissingAppUrl = true;
747
+ this.logger.warn(
748
+ `No app URL resolves for the verification link (callbackURL "${this.config.callbackURL}" is relative, appUrl is ` +
749
+ 'unset and baseUrl gives none): the mail links to the API instead of the app page. Set NSC__APP_URL, or ' +
750
+ 'NSC__BASE_URL to derive it from.',
751
+ );
752
+ }
753
+ return frontendUrl ?? options.url;
754
+ }
755
+
756
+ /** Whether {@link verificationMailUrl} already warned that no app URL resolves (once per process) */
757
+ protected warnedAboutMissingAppUrl = false;
758
+
734
759
  /**
735
760
  * Build the frontend verification URL from the configured callbackURL and token.
736
761
  *
737
- * Resolves relative paths against `appUrl`. Appends the token as a query parameter.
762
+ * Resolves a relative `callbackURL` against the app URL the rest of the framework uses
763
+ * (`resolveAppUrlFromConfig()`: explicit `appUrl`, the localhost default in `local` / `ci` / `e2e`, else derived from
764
+ * `baseUrl` unless `cors.deriveAppUrl` is `false`). Appends the token as a query parameter.
765
+ *
766
+ * Until DEV-4140 a relative value was resolved against `appUrl || 'http://localhost:3001'`, so every deployed stage
767
+ * without `NSC__APP_URL` mailed a link to localhost — while the password-reset link next to it already derived the
768
+ * app from `baseUrl`.
738
769
  *
739
770
  * @param token - The verification token from Better-Auth
740
- * @returns The full frontend URL with token query parameter
771
+ * @returns The full frontend URL with token query parameter, or `undefined` for a relative `callbackURL` when no app
772
+ * URL resolves (the caller then keeps Better-Auth's own link)
741
773
  */
742
- protected buildFrontendVerificationUrl(token: string): string {
774
+ protected buildFrontendVerificationUrl(token: string): string | undefined {
743
775
  let baseUrl = this.config.callbackURL!;
744
776
 
745
- // Resolve relative paths against appUrl
777
+ // Resolve relative paths against the app URL — the SAME resolver as the password-reset link
746
778
  if (baseUrl.startsWith('/')) {
747
- const appUrl = this.configService.getFastButReadOnly<string>('appUrl') || 'http://localhost:3001';
779
+ const appUrl = resolveAppUrlFromConfig(this.configService);
780
+ if (!appUrl) {
781
+ return undefined;
782
+ }
748
783
  baseUrl = `${appUrl.replace(/\/$/, '')}${baseUrl}`;
749
784
  }
750
785