@lenne.tech/nest-server 11.43.8 → 11.43.10

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.
@@ -0,0 +1,43 @@
1
+ # Migration Guide: 11.43.8 → 11.43.9
2
+
3
+ ## Overview
4
+
5
+ | Category | Details |
6
+ |---|---|
7
+ | **Breaking Changes** | None |
8
+ | **New Features** | None |
9
+ | **Bugfixes** | `POST /iam/revoke-session` with `{ sessionId }` ended nothing for a user the legacy migration linked (§1) |
10
+ | **Migration Effort** | None |
11
+
12
+ 11.43.9 is a patch on the 11.x line, published under the dist-tag `latest-11`. The same fix ships in 12.7.2 (`latest`)
13
+ and 12.6.3 (`latest-12.6`).
14
+
15
+ ## Quick Migration
16
+
17
+ ```bash
18
+ pnpm add @lenne.tech/nest-server@11.43.9
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.9` (without `--target` the updater syncs to the
25
+ latest tag, which is on a newer line).
26
+
27
+ ## 1. `revoke-session` by id for users the legacy migration linked
28
+
29
+ **Why:** since 11.43.8, `POST /iam/revoke-session` accepts `{ sessionId }` and looks the session up among the caller's own
30
+ sessions. It looked the caller up under `user.id`. The session lookup prefers a **stored** `id` field over `_id`. When
31
+ the legacy migration links a user (on its first IAM sign-in, for example a user created through `POST /users` or the
32
+ legacy sign-up), it writes an `id` of its own next to `_id`. Every session references `_id`. So for such a user no
33
+ session was found, nothing was revoked, and the request still answered `{ status: true }`. The error went toward the
34
+ safe side: never another user's session.
35
+
36
+ **What changed:** the caller is looked up under the `userId` of its own session. The ownership check is unchanged.
37
+
38
+ **Your project:** nothing to do. A project that copied `resolveRevokeSessionId()` into its own core takes the session's
39
+ `userId` first (`req.betterAuthSession.session.userId`).
40
+
41
+ ## References
42
+
43
+ - `src/core/modules/better-auth/core-better-auth-api.middleware.ts`: `resolveRevokeSessionId()`
@@ -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`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lenne.tech/nest-server",
3
- "version": "11.43.8",
3
+ "version": "11.43.10",
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",
@@ -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, 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] || request.cookies['token'] || undefined;
81
+ const token = [request.cookies[cookieName], request.cookies['token']].find(isQueryableString);
78
82
 
79
83
  if (token) {
80
84
  return { source: 'cookie', token };
@@ -142,10 +142,18 @@ export class CoreBetterAuthApiMiddleware implements NestMiddleware {
142
142
  return;
143
143
  }
144
144
  const caller = req as unknown as {
145
- betterAuthSession?: { user?: { id?: unknown } };
145
+ betterAuthSession?: { session?: { userId?: unknown }; user?: { id?: unknown } };
146
146
  betterAuthUser?: { id?: unknown };
147
147
  };
148
- const userId = caller.betterAuthSession?.user?.id ?? caller.betterAuthUser?.id;
148
+ // The id the sessions are stored under, from the caller's own session (11.43.9, DEV-4133). `user.id` is not it for
149
+ // every user: the session lookup prefers a STORED `id`, and the legacy migration (`migrateAccountToIam()`) writes
150
+ // one of its own next to `_id`, which is what every session references — so a migrated user's sessions were never
151
+ // found and nothing was revoked. The ownership check stays in sessionTokenOfUser().
152
+ const sessionUserId = caller.betterAuthSession?.session?.userId;
153
+ const userId =
154
+ (typeof sessionUserId === 'string' && sessionUserId ? sessionUserId : undefined) ??
155
+ caller.betterAuthSession?.user?.id ??
156
+ caller.betterAuthUser?.id;
149
157
  const token =
150
158
  typeof userId === 'string' && userId
151
159
  ? await this.betterAuthService.sessionTokenOfUser(userId, sessionId)
@@ -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