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