@lenne.tech/nest-server 12.7.3 → 12.8.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 (55) hide show
  1. package/.claude/rules/better-auth.md +13 -0
  2. package/.claude/rules/configurable-features.md +3 -0
  3. package/.claude/rules/testing.md +5 -5
  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/auth/services/core-auth.service.js +3 -0
  13. package/dist/core/modules/auth/services/core-auth.service.js.map +1 -1
  14. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js +2 -1
  15. package/dist/core/modules/better-auth/core-better-auth-api.middleware.js.map +1 -1
  16. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.d.ts +6 -1
  17. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +19 -4
  18. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  19. package/dist/core/modules/better-auth/core-better-auth-user.mapper.d.ts +2 -0
  20. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js +25 -0
  21. package/dist/core/modules/better-auth/core-better-auth-user.mapper.js.map +1 -1
  22. package/dist/core/modules/better-auth/core-better-auth.controller.js +13 -5
  23. package/dist/core/modules/better-auth/core-better-auth.controller.js.map +1 -1
  24. package/dist/core/modules/better-auth/core-better-auth.resolver.js +7 -2
  25. package/dist/core/modules/better-auth/core-better-auth.resolver.js.map +1 -1
  26. package/dist/core/modules/better-auth/core-better-auth.service.d.ts +1 -0
  27. package/dist/core/modules/better-auth/core-better-auth.service.js +14 -0
  28. package/dist/core/modules/better-auth/core-better-auth.service.js.map +1 -1
  29. package/dist/core/modules/error-code/error-codes.d.ts +9 -0
  30. package/dist/core/modules/error-code/error-codes.js +8 -0
  31. package/dist/core/modules/error-code/error-codes.js.map +1 -1
  32. package/dist/core.module.js +2 -0
  33. package/dist/core.module.js.map +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.js +1 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/server/modules/error-code/error-codes.d.ts +1 -0
  38. package/docs/REQUEST-LIFECYCLE.md +27 -0
  39. package/migration-guides/12.7.x-to-12.8.x.md +152 -0
  40. package/migration-guides/12.8.0-to-12.8.1.md +85 -0
  41. package/package.json +2 -2
  42. package/src/core/common/interfaces/server-options.interface.ts +45 -4
  43. package/src/core/common/middlewares/string-cookies.middleware.ts +57 -0
  44. package/src/core/common/pipes/map-and-validate.pipe.ts +40 -0
  45. package/src/core/modules/auth/services/core-auth.service.ts +8 -0
  46. package/src/core/modules/better-auth/README.md +9 -3
  47. package/src/core/modules/better-auth/core-better-auth-api.middleware.ts +8 -3
  48. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +44 -9
  49. package/src/core/modules/better-auth/core-better-auth-user.mapper.ts +41 -0
  50. package/src/core/modules/better-auth/core-better-auth.controller.ts +24 -10
  51. package/src/core/modules/better-auth/core-better-auth.resolver.ts +12 -2
  52. package/src/core/modules/better-auth/core-better-auth.service.ts +28 -0
  53. package/src/core/modules/error-code/error-codes.ts +13 -0
  54. package/src/core.module.ts +5 -0
  55. 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:
@@ -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)
@@ -0,0 +1,85 @@
1
+ # Migration Guide: 12.8.0 → 12.8.1
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | `CoreBetterAuthService.isPersistedUser()`, `CoreBetterAuthUserMapper.mapUnstoredSessionUser()` and `equalizeLegacyPasswordSync()` |
9
+ | **Bugfixes** | Security: a sign-up for an already registered address changed the existing account (§1). Defense in depth: the IAM API middleware decides on the path Better-Auth routes (§2) |
10
+ | **Migration Effort** | Update. Projects that had `requireEmailVerification: true` or `autoSignIn: false` with open sign-up check their accounts (§1) |
11
+
12
+ 12.8.1 is a security patch for 12.8.0. The same fix ships in 12.6.6 (`latest-12.6`) and 11.44.1 (`latest-11`).
13
+
14
+ ## Quick Migration
15
+
16
+ ```bash
17
+ pnpm add @lenne.tech/nest-server@12.8.1
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 sign-up for an already registered address changes nothing
26
+
27
+ **Why:** with `emailAndPassword.requireEmailVerification: true` or `emailAndPassword.autoSignIn: false` (set through
28
+ `betterAuth.options`), Better-Auth 1.5.0 and later answers a sign-up for a known address like a new one, so the
29
+ response does not reveal which addresses have an account. That answer carries a placeholder user: a generated id and
30
+ the given address, stored nowhere. The core's sign-up paths took it for the new user:
31
+
32
+ - **REST `POST /iam/sign-up/email`** (`CoreBetterAuthController.signUp()`, also without a project override) linked the
33
+ placeholder to the real account it found by address. That account's `iamId` then pointed at the placeholder, it got
34
+ `verified: false`, its **legacy password was set to the one the caller chose**, and the answer carried its roles.
35
+ - **GraphQL `betterAuthSignUp`** linked it the same way and answered with the real account's id and roles.
36
+ - **The legacy sign-up with IAM enabled** (`/auth/signup`, GraphQL `signUp`) linked it, overwrote the password and
37
+ returned the real account, and the caller received its tokens.
38
+
39
+ With the legacy endpoints open, the overwritten legacy password let the caller sign in as the account owner. For a
40
+ legacy user without an IAM credential account, the next IAM sign-in with that password migrated the account to it.
41
+
42
+ **What changed:** a user Better-Auth returns from a sign-up is written only once `CoreBetterAuthService.isPersistedUser()`
43
+ confirmed it through Better-Auth's own adapter. For a placeholder, nothing is linked and no password is synced. The
44
+ 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,
45
+ so neither the body nor the response time tells the address exists. The legacy sign-up answers a known address with
46
+ `Email address already in use`, as it always did without IAM.
47
+
48
+ **Who was affected:** a project running better-auth 1.5.0 or later (nest-server 11.18.0 and later pin it) whose
49
+ Better-Auth options set `requireEmailVerification: true` or `autoSignIn: false`, with sign-up open
50
+ (`emailAndPassword.disableSignUp: true` refused the request before it reached Better-Auth). Without those options
51
+ Better-Auth answers a known address with an error, and the core answered `EMAIL_ALREADY_EXISTS` without writing.
52
+
53
+ **Your project:** update. If the conditions above applied, the traces an attack leaves on an account do not list every
54
+ affected one: `iamId` no longer matching the account's own id, and `verified: false` next to `emailVerified: true`, are
55
+ written back by the owner's next IAM sign-in, while the overwritten legacy password stays. Take the time the options
56
+ were active as the window and:
57
+
58
+ - **Accounts that still carry a trace:** remove the legacy `password`, end their sessions (IAM sessions and legacy
59
+ refresh tokens) and send a password reset.
60
+ - **Every account with a Better-Auth credential account:** remove the legacy `password`. IAM sign-in does not read it,
61
+ only the legacy endpoints do. Where `auth.legacyEndpoints` keeps those open (closed by default since 11.38.0), send
62
+ these accounts a password reset instead.
63
+ - **Credential accounts created in the window for a user who existed before it:** a legacy user's first IAM sign-in
64
+ creates one with the password used for that sign-in, after an attack the caller's. End those sessions and send a
65
+ password reset.
66
+
67
+ Better-Auth logs a sign-up for a known address ("Sign-up attempt for existing email") only at `logger.level: 'info'` or
68
+ lower. Its default is `warn`, so there is usually no log trail. A project test that stubs `CoreBetterAuthService` for
69
+ the sign-up needs `isPersistedUser`.
70
+
71
+ ## 2. The IAM API middleware decides on the routed path
72
+
73
+ `CoreBetterAuthApiMiddleware` leaves the routes `CoreBetterAuthController` serves to the controller and hands everything
74
+ else to Better-Auth. It now decides on the canonical path (`canonicalRequestPath()`), the one Better-Auth routes after
75
+ `new URL()` resolved `.`, `..` and `%2e` segments. Before, it decided on the raw URL. On 12.x the path guard (12.3.0)
76
+ already refuses such paths with 400 before this middleware runs. This keeps the middleware correct where the guard is
77
+ not registered, as the rate limiter already does. Nothing to do.
78
+
79
+ ## References
80
+
81
+ - `src/core/modules/better-auth/core-better-auth.service.ts`: `isPersistedUser()`
82
+ - `src/core/modules/better-auth/core-better-auth.controller.ts`, `core-better-auth.resolver.ts`,
83
+ `src/core/modules/auth/services/core-auth.service.ts`: the sign-up paths
84
+ - `tests/unit/better-auth-sign-up-existing-address.spec.ts`, `tests/unit/better-auth-api-middleware-routed-path.spec.ts`
85
+ - `.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": "12.7.3",
3
+ "version": "12.8.1",
4
4
  "type": "module",
5
5
  "description": "Server framework in TypeScript on top of NestJS: GraphQL and REST APIs on MongoDB, PostgreSQL, MySQL or MariaDB, with authentication, field-level permissions, multi-tenancy, offline sync and an AI assistant.",
6
6
  "keywords": [
@@ -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) {
@@ -591,6 +591,14 @@ export class CoreAuthService {
591
591
 
592
592
  // Link or create Legacy user with iamId
593
593
  const iamUser = response.user as { email: string; id: string; name?: string };
594
+
595
+ // An already registered address: with `requireEmailVerification` or `autoSignIn: false` Better-Auth answers it
596
+ // with a placeholder user it never stored. Linking it re-pointed the real account, overwrote its password with
597
+ // the caller's, and this method then returned that account — the caller got its tokens (12.8.1). The legacy
598
+ // sign-up has always answered a known address with this error, so the IAM path does the same.
599
+ if (!(await this.betterAuthService.isPersistedUser(iamUser.id))) {
600
+ throw new BadRequestException('Email address already in use');
601
+ }
594
602
  const syncedUser = await this.betterAuthUserMapper.linkOrCreateUser(iamUser as any, {
595
603
  firstName: inputAny.firstName,
596
604
  lastName: inputAny.lastName,
@@ -2099,11 +2099,17 @@ When a user is deleted:
2099
2099
  db.account.findOne({ userId: ObjectId('...'), providerId: 'credential' });
2100
2100
  ```
2101
2101
 
2102
- From better-auth 1.7 the row must ALSO carry `issuer: 'local:credential'`. A row matching only
2103
- `providerId` is not usable — better-auth keys accounts by `(issuer, accountId)` and will not find
2104
- it, so sign-in answers 401 while this query happily reports that the account exists:
2102
+ On better-auth 1.7.3 and later (nest-server requires 1.7.16 or later) that query is the whole
2103
+ check: rows carry no `issuer`, and an `issuer` filter finds nothing for every user — that is
2104
+ expected, not the cause of a 401. Do not write `issuer` fields by hand.
2105
+
2106
+ Only on better-auth 1.7.0–1.7.2 (see [Boot-Time Behaviour](#boot-time-behaviour)) must the row ALSO
2107
+ carry `issuer: 'local:credential'`. There a row matching only `providerId` is not usable — those
2108
+ versions key accounts by `(issuer, accountId)` and will not find it, so sign-in answers 401 while
2109
+ the query above reports that the account exists:
2105
2110
 
2106
2111
  ```javascript
2112
+ // better-auth 1.7.0–1.7.2 only
2107
2113
  db.account.findOne({ issuer: 'local:credential', providerId: 'credential', userId: ObjectId('...') });
2108
2114
  ```
2109
2115
 
@@ -8,6 +8,7 @@ import { BetterAuthCookieHelper, createCookieHelper } from './core-better-auth-c
8
8
  import { wrapBetterAuthErrorResponse } from './core-better-auth-error-codes.helper.js';
9
9
  import { isControllerHandledPath } from './core-better-auth-openapi.helper.js';
10
10
  import { runWithResetPassword } from './core-better-auth-password-reset.registry.js';
11
+ import { canonicalRequestPath } from './core-better-auth-path-guard.middleware.js';
11
12
  import { CoreBetterAuthUserMapper } from './core-better-auth-user.mapper.js';
12
13
  import { extractSessionToken, signCookieValue, toWebRequest } from './core-better-auth-web.helper.js';
13
14
  import { CoreBetterAuthService } from './core-better-auth.service.js';
@@ -314,9 +315,13 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
314
315
  }
315
316
 
316
317
  const basePath = this.betterAuthService.getBasePath();
317
- // Use originalUrl to get full path for IAM endpoints, but fallback to req.path
318
- // The originalUrl contains the original request path as sent by client
319
- const requestPath = req.originalUrl?.split('?')[0] || req.path;
318
+ // The path Better-Auth will ROUTE, not the one the client wrote (12.8.1): the forwarded Web Request is built with
319
+ // `new URL(originalUrl, baseUrl)` (toWebRequest()), which resolves `.`, `..` and `%2e` segments. Compared raw,
320
+ // `/iam/sign-up/%2e/email` counted as "not a controller path" while Better-Auth's own sign-up served it — past the
321
+ // controller's checks and every project override. CoreBetterAuthPathGuardMiddleware refuses such a path before this
322
+ // runs; deciding on the canonical path keeps this middleware right where the guard is not registered, as the rate
323
+ // limiter does.
324
+ const requestPath = canonicalRequestPath(req.originalUrl || req.url || req.path);
320
325
 
321
326
  // Only handle requests that start with the Better Auth base path
322
327
  if (!requestPath.startsWith(basePath)) {