@lenne.tech/nest-server 11.43.10 → 11.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.claude/rules/better-auth.md +44 -4
  2. package/.claude/rules/configurable-features.md +4 -1
  3. package/.claude/rules/testing.md +4 -4
  4. package/FRAMEWORK-API.md +2 -2
  5. package/dist/config.env.js +2 -2
  6. package/dist/config.env.js.map +1 -1
  7. package/dist/core/common/interfaces/server-options.interface.d.ts +3 -0
  8. package/dist/core/common/middlewares/string-cookies.middleware.d.ts +12 -0
  9. package/dist/core/common/middlewares/string-cookies.middleware.js +54 -0
  10. package/dist/core/common/middlewares/string-cookies.middleware.js.map +1 -0
  11. package/dist/core/common/pipes/map-and-validate.pipe.d.ts +2 -0
  12. package/dist/core/common/pipes/map-and-validate.pipe.js +16 -0
  13. package/dist/core/common/pipes/map-and-validate.pipe.js.map +1 -1
  14. package/dist/core/modules/auth/services/core-auth.service.js +3 -0
  15. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  16. package/dist/core/modules/better-auth/better-auth.config.js +2 -0
  17. package/dist/core/modules/better-auth/better-auth.config.js.map +1 -1
  18. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
  19. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  20. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +7 -1
  21. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
  22. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  23. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.d.ts +8 -0
  24. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js +70 -0
  25. package/dist/core/modules/better-auth/core-better-auth-path-guard.middleware.js.map +1 -0
  26. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js +2 -1
  27. package/dist/core/modules/better-auth/core-better-auth-rate-limit.middleware.js.map +1 -1
  28. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.d.ts +1 -1
  29. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js +5 -3
  30. package/dist/core/modules/better-auth/core-better-auth-rate-limiter.service.js.map +1 -1
  31. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
  32. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
  33. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  34. package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
  35. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  36. package/dist/core/modules/better-auth/core-better-auth.module.js +2 -0
  37. package/dist/core/modules/better-auth/core-better-auth.module.js.map +1 -1
  38. package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
  39. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  40. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  41. package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
  42. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  43. package/dist/core/modules/better-auth/index.d.ts +1 -0
  44. package/dist/core/modules/better-auth/index.js +1 -0
  45. package/dist/core/modules/better-auth/index.js.map +1 -1
  46. package/dist/core/modules/error-code/error-codes.d.ts +18 -0
  47. package/dist/core/modules/error-code/error-codes.js +16 -0
  48. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  49. package/dist/core.module.js +2 -0
  50. package/dist/core.module.js.map +1 -1
  51. package/dist/index.d.ts +1 -0
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/server/modules/error-code/error-codes.d.ts +2 -0
  55. package/dist/tsconfig.build.tsbuildinfo +1 -1
  56. package/docs/REQUEST-LIFECYCLE.md +26 -0
  57. package/docs/error-codes.md +14 -0
  58. package/migration-guides/11.13.x-to-11.14.0.md +5 -5
  59. package/migration-guides/11.43.x-to-11.44.x.md +147 -0
  60. package/migration-guides/11.44.0-to-11.44.1.md +152 -0
  61. package/package.json +2 -2
  62. package/src/config.env.ts +6 -2
  63. package/src/core/common/interfaces/server-options.interface.ts +65 -9
  64. package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
  65. package/src/core/common/pipes/map-and-validate.pipe.ts +38 -0
  66. package/src/core/modules/auth/services/core-auth.service.ts +8 -0
  67. package/src/core/modules/better-auth/INTEGRATION-CHECKLIST.md +3 -0
  68. package/src/core/modules/better-auth/README.md +34 -4
  69. package/src/core/modules/better-auth/better-auth.config.ts +9 -0
  70. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
  71. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +45 -9
  72. package/src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts +85 -0
  73. package/src/core/modules/better-auth/core-better-auth-rate-limit.middleware.ts +5 -2
  74. package/src/core/modules/better-auth/core-better-auth-rate-limiter.service.ts +14 -7
  75. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
  76. package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
  77. package/src/core/modules/better-auth/core-better-auth.module.ts +12 -2
  78. package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
  79. package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
  80. package/src/core/modules/better-auth/index.ts +1 -0
  81. package/src/core/modules/error-code/error-codes.ts +22 -0
  82. package/src/core/modules/system-setup/INTEGRATION-CHECKLIST.md +10 -4
  83. package/src/core/modules/system-setup/README.md +5 -5
  84. package/src/core.module.ts +5 -0
  85. package/src/index.ts +1 -0
@@ -64,6 +64,7 @@ Modern OAuth-compatible authentication with plugin architecture:
64
64
  | **Social Login** | OAuth providers: Google, GitHub, Apple, Discord, etc. (plugin) |
65
65
  | **Email Verification** | Configurable email verification flow |
66
66
  | **Sign-Up Validation** | Custom validation hooks for registration |
67
+ | **Path Guard** | `CoreBetterAuthPathGuardMiddleware`, the first middleware under the Better-Auth base path (always registered): a path with a `.` / `..` segment (also `%2e`-encoded), a backslash, an encoded `/` / `\` or a `#` is refused with 400 (`#LTNS_0305`) before the rate limiter, the controller routes or the forwarding read it. Every check there reads the path as sent while Better-Auth routes the resolved one, so without the guard `/iam/callback/../sign-in/email` was skipped by the limiter as a callback and ran as a sign-in (12.2.x) |
67
68
  | **Rate Limiting** | Per-endpoint rate limits (`betterAuth.rateLimit`, configurable). Counters live behind a `RateLimitStore`: `RedisRateLimitStore` when `redis` is configured, so `max` is enforced **exactly across replicas** instead of `max × replicas`; otherwise the process-local `InMemoryRateLimitStore` as before. `check()` / `reset()` / `clear()` are **async** since 11.33.0. On a Redis outage it degrades to the in-memory counter and logs once per transition — never a 500, never "allowed". Counters are keyed on `request.ip`, which Express derives from `X-Forwarded-For` only as far as `trust proxy` allows — set `trustProxy` (§ServerOptions) behind a reverse proxy or every client resolves to the proxy and shares ONE bucket; unset with a limiter enabled logs a boot warning |
68
69
  | **Cross-Subdomain Cookies** | Automatic cookie domain configuration |
69
70
  | **Organization / Multi-Tenant** | Teams and organization management (plugin) |
@@ -99,6 +100,8 @@ JWT-based authentication for existing projects:
99
100
  | Feature | Description |
100
101
  |---------|-------------|
101
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 (11.44.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 (11.44.0) |
102
105
  | **Input Validation** | `class-validator` integration via `@UnifiedField()` |
103
106
  | **Password Hashing Plugin** | Automatic BCrypt hashing on all Mongoose write operations |
104
107
  | **Role Guard Plugin** | Prevents unauthorized role escalation at database level |
@@ -346,6 +349,9 @@ The following diagram shows the exact order of execution from HTTP request to re
346
349
  | - Lazy currentUser getter (from req.user) |
347
350
  | - Accept-Language for translations |
348
351
  | |
352
+ | 1b. StringCookiesMiddleware [11.44.0] |
353
+ | - Drops non-string cookie values (`j:` JSON) |
354
+ | |
349
355
  | 2. CoreBetterAuthMiddleware |
350
356
  | - Skips API-token credentials entirely |
351
357
  | - Strategy 1: Auth header (JWT/Session) |
@@ -589,6 +595,8 @@ NestJS middleware runs for every request after Express-level middleware. Registr
589
595
  // src/core.module.ts
590
596
  configure(consumer: MiddlewareConsumer) {
591
597
  consumer.apply(RequestContextMiddleware).forRoutes('*');
598
+ consumer.apply(StringCookiesMiddleware).forRoutes('*');
599
+ consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
592
600
  consumer.apply(graphqlUploadExpress()).forRoutes('graphql');
593
601
  }
594
602
  ```
@@ -689,6 +697,13 @@ If authentication succeeds, `req.user` is set with the authenticated user (inclu
689
697
  > sessions). A JWT (`/token`) and other plugins' tokens are left alone. See `.claude/rules/better-auth.md` §7
690
698
  > "Forwarded responses".
691
699
 
700
+ #### 1b. StringCookiesMiddleware (11.44.0)
701
+
702
+ Removes every cookie value that is not a string from `req.cookies`, and from `req.signedCookies` everything but
703
+ strings and `false` (cookie-parser's invalid-signature marker). cookie-parser turns a cookie value starting with `j:`
704
+ into the parsed JSON, so `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as a
705
+ MongoDB operator (DEV-4138). Registered right after the request context, before every other middleware and every guard. `security.stringCookiesOnly: false` switches it off.
706
+
692
707
  #### 2b. SecurityHeadersMiddleware
693
708
 
694
709
  Sets the browser security headers on **every** response — `X-Content-Type-Options`,
@@ -838,6 +853,17 @@ The `MapAndValidatePipe` runs on every incoming argument/body:
838
853
  Plain Object --> Transform to Class Instance --> Whitelist Check --> Validation --> Clean Input
839
854
  ```
840
855
 
856
+ #### Primitive parameters (11.44.0)
857
+
858
+ A parameter declared as `string`, `number` or `boolean` (`@Body('token') token: string`, likewise `@Query` and
859
+ `@Param`) has `metatype` `String` / `Number` / `Boolean`, and the pipe used to return its value unchecked — the
860
+ declared type is erased at runtime. Since 11.44.0 a **plain object** there is answered with 400
861
+ (`#LTNS_0306 [<parameter>]`) before the route runs: `{ "token": { "$ne": null } }` is the shape of a MongoDB operator
862
+ (DEV-4143 set somebody else's password with it). `null` and arrays pass. Not covered: parameters typed as a class (the
863
+ DTO validates them), as `any`, or as a union the compiler emits as `Object` (`tsc` with `strictNullChecks` does so for
864
+ `string | undefined`; SWC emits `String`) — guard those values at the query with `isQueryableString()`.
865
+ `security.mapAndValidatePipe.rejectObjectsForPrimitiveTypes: false` switches it off.
866
+
841
867
  #### Whitelisting via @UnifiedField()
842
868
 
843
869
  Properties **without** `@UnifiedField()` are subject to the whitelist policy:
@@ -346,6 +346,20 @@ All error codes follow the format: `#PREFIX_XXXX: Description`
346
346
  - DE: Die gesendeten Daten sind zu groß und wurden nicht verarbeitet.
347
347
  - EN: The submitted data is too large and was not processed.
348
348
 
349
+ ### LTNS_0305: invalidRequestPath
350
+
351
+ **Message:** Invalid request path
352
+
353
+ **Description:** Answered with HTTP 400 when a request under the Better-Auth base path (`/iam` by default) carries a path segment `.` or `..` (also percent-encoded as `%2e`), a backslash, an encoded `/` or `\` (`%2f`, `%5c`), or a `#`. No route there uses such a path, and the checks in front of Better-Auth would read it as a different route than Better-Auth itself.
354
+
355
+ **Solution:** Send the path in its canonical form. Browsers and HTTP clients do that on their own; the error points at a client that builds paths by hand or sends them unnormalized on purpose.
356
+
357
+ **Parameters:** none
358
+
359
+ **Translations:**
360
+ - DE: Der Anfragepfad ist ungültig.
361
+ - EN: The request path is invalid.
362
+
349
363
  ---
350
364
 
351
365
  ## Resource Errors (LTNS_0400-LTNS_0499)
@@ -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)
@@ -0,0 +1,152 @@
1
+ # Migration Guide: 11.44.0 → 11.44.1
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None in the API. Non-canonical paths under the Better-Auth base path answer 400, the IAM rate limit counts per route (§2). `emailAndPassword.disableSignUp: true` closes social sign-up too (§3) |
8
+ | **New Features** | `CoreBetterAuthService.isPersistedUser()`, `CoreBetterAuthUserMapper.mapUnstoredSessionUser()` and `equalizeLegacyPasswordSync()` (§1). `socialProviders.<name>.disableSignUp` (§3). `CoreBetterAuthPathGuardMiddleware`, `canonicalRequestPath()`, error code `LTNS_0305` (§2) |
9
+ | **Bugfixes** | Security: a sign-up for an already registered address changed the existing account (§1). Dot segments under the IAM base path bypassed the controller and the rate limiter (§2). Social login created accounts while sign-up was switched off (§3) |
10
+ | **Migration Effort** | Update. Projects that had `requireEmailVerification: true` or `autoSignIn: false` with open sign-up check their accounts (§1). A deployment with a tight `betterAuth.rateLimit.max` checks the value (§2). A project that closed sign-up but wants new users through one social provider sets one flag (§3) |
11
+
12
+ 11.44.1 is a security patch for 11.44.0 (`latest-11`). §1 ships in 12.8.1 and 12.6.6 as well. §2 and §3 are backports
13
+ of 12.3.0, where 12.x has had them since.
14
+
15
+ ## Quick Migration
16
+
17
+ ```bash
18
+ pnpm add @lenne.tech/nest-server@11.44.1
19
+ pnpm run update # nest-server-starter based projects (release/11.x)
20
+ pnpm run build
21
+ pnpm test
22
+ ```
23
+
24
+ **Vendor mode**: run `/lt-dev:backend:update-nest-server-core` as usual.
25
+
26
+ ## 1. A sign-up for an already registered address changes nothing
27
+
28
+ **Why:** with `emailAndPassword.requireEmailVerification: true` or `emailAndPassword.autoSignIn: false` (set through
29
+ `betterAuth.options`), Better-Auth 1.5.0 and later answers a sign-up for a known address like a new one, so the
30
+ response does not reveal which addresses have an account. That answer carries a placeholder user: a generated id and
31
+ the given address, stored nowhere. The core's sign-up paths took it for the new user:
32
+
33
+ - **REST `POST /iam/sign-up/email`** (`CoreBetterAuthController.signUp()`, also without a project override) linked the
34
+ placeholder to the real account it found by address. That account's `iamId` then pointed at the placeholder, it got
35
+ `verified: false`, its **legacy password was set to the one the caller chose**, and the answer carried its roles.
36
+ - **GraphQL `betterAuthSignUp`** linked it the same way and answered with the real account's id and roles.
37
+ - **The legacy sign-up with IAM enabled** (`/auth/signup`, GraphQL `signUp`) linked it, overwrote the password and
38
+ returned the real account, and the caller received its tokens.
39
+
40
+ With the legacy endpoints open, the overwritten legacy password let the caller sign in as the account owner. For a
41
+ legacy user without an IAM credential account, the next IAM sign-in with that password migrated the account to it.
42
+
43
+ **What changed:** a user Better-Auth returns from a sign-up is written only once `CoreBetterAuthService.isPersistedUser()`
44
+ confirmed it through Better-Auth's own adapter. For a placeholder, nothing is linked and no password is synced. The
45
+ answer stays that of a new sign-up: its own id, no roles, not verified, and the same bcrypt round as a real sign-up,
46
+ so neither the body nor the response time tells the address exists. The legacy sign-up answers a known address with
47
+ `Email address already in use`, as it always did without IAM.
48
+
49
+ **Who was affected:** a project running better-auth 1.5.0 or later (nest-server 11.18.0 and later pin it) whose
50
+ Better-Auth options set `requireEmailVerification: true` or `autoSignIn: false`, with sign-up open
51
+ (`emailAndPassword.disableSignUp: true` refused the request before it reached Better-Auth). Without those options
52
+ Better-Auth answers a known address with an error, and the core answered `EMAIL_ALREADY_EXISTS` without writing.
53
+
54
+ **Your project:** update. If the conditions above applied, the traces an attack leaves on an account do not list every
55
+ affected one: `iamId` no longer matching the account's own id, and `verified: false` next to `emailVerified: true`, are
56
+ written back by the owner's next IAM sign-in, while the overwritten legacy password stays. Take the time the options
57
+ were active as the window and:
58
+
59
+ - **Accounts that still carry a trace:** remove the legacy `password`, end their sessions (IAM sessions and legacy
60
+ refresh tokens) and send a password reset.
61
+ - **Every account with a Better-Auth credential account:** remove the legacy `password`. IAM sign-in does not read it,
62
+ only the legacy endpoints do. Where `auth.legacyEndpoints` keeps those open (closed by default since 11.38.0), send
63
+ these accounts a password reset instead.
64
+ - **Credential accounts created in the window for a user who existed before it:** a legacy user's first IAM sign-in
65
+ creates one with the password used for that sign-in, after an attack the caller's. End those sessions and send a
66
+ password reset.
67
+
68
+ Better-Auth logs a sign-up for a known address ("Sign-up attempt for existing email") only at `logger.level: 'info'` or
69
+ lower. Its default is `warn`, so there is usually no log trail. A project test that stubs `CoreBetterAuthService` for
70
+ the sign-up needs `isPersistedUser`.
71
+
72
+ ## 2. Requests under the Better-Auth base path
73
+
74
+ ### Non-canonical paths answer 400
75
+
76
+ Every check under the base path (`/iam` by default) — rate limiter, controller routes, the forwarding to Better-Auth —
77
+ read the path as sent, while Better-Auth routes the path after `new URL()` resolved it. `/iam/sign-up/%2e/email`
78
+ therefore reached Better-Auth's own sign-up past the controller and every project override, and
79
+ `/iam/callback/../sign-in/email` passed the rate limiter as a skipped OAuth callback and ran as a sign-in.
80
+
81
+ `CoreBetterAuthPathGuardMiddleware` now runs first under the base path and answers **400** (`#LTNS_0305: Invalid
82
+ request path`) for a path with a `.` or `..` segment (also `%2e`-encoded), a backslash, an encoded `/` or `\`, or a
83
+ `#`. No Better-Auth route needs any of them; a client that sends one has a bug. It is registered by
84
+ `CoreBetterAuthModule` itself, so there is nothing to add. `CoreBetterAuthApiMiddleware` and the rate limiter decide on
85
+ the same canonical path (`canonicalRequestPath()`) as well, so they stay right where the guard is not registered.
86
+
87
+ ### The IAM rate limit tells routes apart
88
+
89
+ The rate-limit middleware read `req.path`, which is `/` for a middleware Nest mounts under the base path. So every IAM
90
+ request of a client shared one counter with the full limit, and the skip list (`/session`, `/callback`) and the halved
91
+ limit for sign-in, sign-up and the password routes never applied over HTTP.
92
+
93
+ Now a client IP has one counter per route NAME — the last path segment — so `/sign-in/email` and `/sign-up/email` (both
94
+ `email`) share one counter. `/session` and `/callback` are not counted, and the strict routes (sign-in, sign-up, the
95
+ password reset and change routes) get half of `betterAuth.rateLimit.max`, rounded up. The skip and strict lists match
96
+ whole path segments, case-insensitively, as Express routes.
97
+
98
+ **What to check:** a deployment that set `betterAuth.rateLimit.max` (the nest-server-starter reads it from
99
+ `IAM_RATE_LIMIT_MAX`) gets half of it for the e-mail sign-in and sign-up now, and the two count together: with
100
+ `max: 10`, five attempts per window for both combined. Behind a shared NAT or proxy, sign-ups use up the same budget as
101
+ sign-ins. Raise the value if that is too tight.
102
+
103
+ ## 3. Social login creates no account while sign-up is switched off
104
+
105
+ Only with `betterAuth.emailAndPassword.disableSignUp: true` and at least one social provider. The flag closed
106
+ `/sign-up/email` only. Better-Auth decides a social sign-up per provider, and each provider got only its `clientId` and
107
+ `clientSecret`, so whoever signed in with Google, GitHub etc. for the first time got an account in a project that had
108
+ closed self-registration.
109
+
110
+ **What changes:** every configured provider now receives the flag, so `disableSignUp: true` closes sign-up through
111
+ every social provider as well, unless that provider sets its own `disableSignUp`. A first sign-in through a provider by
112
+ somebody who has no account is refused (the OAuth callback redirects with `error=signup_disabled`, `/sign-in/social`
113
+ with an `idToken` answers 401 `signup disabled`). Users who already have an account keep signing in, also through a
114
+ provider they have not used before: Better-Auth checks the flag only when no user exists for the address.
115
+
116
+ **What to check:** a project that closed sign-up on purpose needs nothing. A project that closed e-mail sign-up but
117
+ wants new users through a provider opens that one deliberately:
118
+
119
+ ```typescript
120
+ // config.env.ts
121
+ betterAuth: {
122
+ emailAndPassword: { disableSignUp: true },
123
+ socialProviders: {
124
+ google: { clientId: '...', clientSecret: '...', disableSignUp: false }, // new users through Google
125
+ github: { clientId: '...', clientSecret: '...' }, // follows disableSignUp: closed
126
+ },
127
+ },
128
+ ```
129
+
130
+ `disableSignUp: true` on a provider closes sign-up for that provider alone, while sign-up stays open elsewhere. Only a
131
+ boolean counts there: any other value, such as the string `"false"` in `NEST_SERVER_CONFIG`, follows
132
+ `emailAndPassword.disableSignUp`. Plugins a project registers itself through `betterAuth.options.plugins` are not
133
+ covered; set their own sign-up options.
134
+
135
+ ## Troubleshooting
136
+
137
+ | Symptom | Cause | Fix |
138
+ |---|---|---|
139
+ | 400 `#LTNS_0305` on an IAM request | The path carries a dot segment, a backslash, an encoded separator or a `#` | Fix the client's URL |
140
+ | 429 on sign-in or sign-up earlier than before | The strict routes get half of `betterAuth.rateLimit.max`, and sign-in and sign-up share one counter (§2) | Raise `betterAuth.rateLimit.max` |
141
+ | New users land on the error page with `error=signup_disabled` after a social login | `disableSignUp: true` covers social providers (§3) | Expected; or set `disableSignUp: false` on the provider |
142
+ | A project test fails with `SIGNUP_FAILED` | Its stub of `CoreBetterAuthService` has no `isPersistedUser` (§1) | Add `isPersistedUser: async () => true` to the stub |
143
+
144
+ ## References
145
+
146
+ - `src/core/modules/better-auth/core-better-auth.service.ts`: `isPersistedUser()`
147
+ - `src/core/modules/better-auth/core-better-auth.controller.ts`, `core-better-auth.resolver.ts`,
148
+ `src/core/modules/auth/services/core-auth.service.ts`: the sign-up paths
149
+ - `src/core/modules/better-auth/core-better-auth-path-guard.middleware.ts`, `core-better-auth-rate-limiter.service.ts`
150
+ - `src/core/modules/better-auth/better-auth.config.ts`: `buildSocialProviders()`
151
+ - `src/core/modules/better-auth/README.md`, `INTEGRATION-CHECKLIST.md`
152
+ - `.claude/rules/better-auth.md`: security checklist
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.1",
4
4
  "description": "Modern, fast, powerful Node.js web framework in TypeScript based on Nest with a GraphQL API and a connection to MongoDB (or other databases).",
5
5
  "keywords": [
6
6
  "node",
@@ -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",
package/src/config.env.ts CHANGED
@@ -59,7 +59,9 @@ const config: { [env: string]: IServerOptions } = {
59
59
  rpId: 'localhost',
60
60
  rpName: 'Nest Server Local',
61
61
  },
62
- rateLimit: { enabled: true, max: 100, windowSeconds: 60 },
62
+ // 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
63
+ // counted every IAM request of a client on one shared counter of 100
64
+ rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
63
65
  secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
64
66
  // Social providers disabled in local environment (no credentials)
65
67
  socialProviders: {
@@ -368,7 +370,9 @@ const config: { [env: string]: IServerOptions } = {
368
370
  rpId: 'localhost',
369
371
  rpName: 'Nest Server Local',
370
372
  },
371
- rateLimit: { enabled: true, max: 100, windowSeconds: 60 },
373
+ // 200: sign-in and sign-up get the strict half (100), the headroom the suites had while the limiter
374
+ // counted every IAM request of a client on one shared counter of 100
375
+ rateLimit: { enabled: true, max: 200, windowSeconds: 60 },
372
376
  secret: process.env.BETTER_AUTH_SECRET || 'BETTER_AUTH_SECRET_LOCAL_32_CHARS_M',
373
377
  // Social providers disabled in local environment (no credentials)
374
378
  socialProviders: {
@@ -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;
@@ -974,6 +978,17 @@ export interface IBetterAuthSocialProvider {
974
978
  */
975
979
  clientSecret: string;
976
980
 
981
+ /**
982
+ * Whether a first sign-in through this provider may create an account.
983
+ *
984
+ * Unset, the provider follows `betterAuth.emailAndPassword.disableSignUp`: with that set to `true` (since 12.3.0)
985
+ * nobody gets a new account through any provider, while existing users keep signing in. `false` opens sign-up
986
+ * through this provider although `disableSignUp` closes it otherwise; `true` closes it for this provider alone.
987
+ * Only a boolean counts: any other value follows `emailAndPassword.disableSignUp`.
988
+ * @default emailAndPassword.disableSignUp
989
+ */
990
+ disableSignUp?: boolean;
991
+
977
992
  /**
978
993
  * Whether this provider is enabled.
979
994
  * Defaults to true when clientId and clientSecret are provided.
@@ -3187,8 +3202,44 @@ export interface IServerOptions {
3187
3202
  * @default 'strip'
3188
3203
  */
3189
3204
  nonWhitelistedFields?: 'strip' | 'error' | false;
3205
+
3206
+ /**
3207
+ * Answer 400 (`#LTNS_0306`) when a request value arrives as an object where the route declares a
3208
+ * string, number or boolean: `@Body('token') token: string`, likewise `@Query(…)` and `@Param(…)`.
3209
+ *
3210
+ * Such a parameter used to receive the value unchecked — the declared type is erased at runtime — so
3211
+ * `{ "token": { "$ne": null } }` reached the service as a MongoDB operator (DEV-4143: a password-reset
3212
+ * token that set somebody else's password). Only a plain object is refused; `null` and arrays pass.
3213
+ * Not covered: parameters typed as a class (validated by their DTO), as `any`, or as a union the
3214
+ * compiler emits as `Object` (`tsc` with `strictNullChecks` does so for `string | undefined`; SWC does
3215
+ * not). Guard those values at the query with `isQueryableString()`.
3216
+ *
3217
+ * Only an explicit `false` switches the check off.
3218
+ *
3219
+ * @default true
3220
+ * @since 11.44.0
3221
+ */
3222
+ rejectObjectsForPrimitiveTypes?: boolean;
3190
3223
  };
3191
3224
 
3225
+ /**
3226
+ * Remove every cookie value that is not a string from `req.cookies` (and from `req.signedCookies`
3227
+ * everything but strings and `false`, cookie-parser's invalid-signature marker) before any middleware or
3228
+ * guard reads it.
3229
+ *
3230
+ * cookie-parser turns a cookie value starting with `j:` into the parsed JSON, so
3231
+ * `iam.session_token=j:{"$ne":null}` arrived as an object and a session lookup read it as an operator
3232
+ * (DEV-4138). The framework writes only string cookies.
3233
+ * Implemented by `StringCookiesMiddleware`, registered by `CoreModule` for all routes.
3234
+ *
3235
+ * Only an explicit `false` switches it off (for a project that deliberately writes object cookies with
3236
+ * `res.cookie(name, object)` and reads them back).
3237
+ *
3238
+ * @default true
3239
+ * @since 11.44.0
3240
+ */
3241
+ stringCookiesOnly?: boolean;
3242
+
3192
3243
  /**
3193
3244
  * Answer a Mongoose `CastError` caused by the client as a client error instead of a 500.
3194
3245
  * See @lenne.tech/nest-server/src/core/common/filters/mongoose-cast-error.filter.ts
@@ -3419,7 +3470,7 @@ export interface IServerOptions {
3419
3470
  *
3420
3471
  * Auto-creation via config/ENV (no REST call needed):
3421
3472
  * - `{ initialAdmin: { email: '...', password: '...' } }`
3422
- * - `NSC__systemSetup__initialAdmin__email` + `NSC__systemSetup__initialAdmin__password`
3473
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL` + `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3423
3474
  *
3424
3475
  * @since 11.14.0
3425
3476
  *
@@ -3744,10 +3795,11 @@ export interface ISystemSetup {
3744
3795
  * during application bootstrap if zero users exist. This is useful for
3745
3796
  * automated deployments (Docker, CI/CD) where no manual REST call is possible.
3746
3797
  *
3747
- * Can be provided via environment variables:
3748
- * - `NSC__systemSetup__initialAdmin__email`
3749
- * - `NSC__systemSetup__initialAdmin__password`
3750
- * - `NSC__systemSetup__initialAdmin__name` (optional)
3798
+ * Can be provided via environment variables, every segment in SCREAMING_SNAKE_CASE. A camelCase spelling such as
3799
+ * `NSC__systemSetup__…` is never read: the environment reader lowercases every segment it does not split at `_`.
3800
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__EMAIL`
3801
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__PASSWORD`
3802
+ * - `NSC__SYSTEM_SETUP__INITIAL_ADMIN__NAME` (optional)
3751
3803
  *
3752
3804
  * Security: Same zero-user guard applies - only works when no users exist.
3753
3805
  */
@@ -4157,6 +4209,10 @@ interface IBetterAuthBase {
4157
4209
  * Disable user registration (sign-up) via BetterAuth.
4158
4210
  * Passed through to better-auth's native emailAndPassword.disableSignUp.
4159
4211
  * Custom endpoints (GraphQL + REST) also check this flag early.
4212
+ * Since 11.44.1 (12.3.0 on 12.x) it closes social sign-up too: every configured social provider receives it as its own
4213
+ * `disableSignUp`, so a first sign-in through Google, GitHub etc. creates no account, while existing users keep
4214
+ * signing in. `socialProviders.<name>.disableSignUp: false` opens one provider deliberately. Plugins a project
4215
+ * registers itself through `options.plugins` are not covered.
4160
4216
  * The Swagger document built by `setupSwagger()` then leaves out `POST /iam/sign-up/email`,
4161
4217
  * which would answer `SIGNUP_DISABLED` to every caller.
4162
4218
  * @default false
@@ -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
+ }