@lenne.tech/nest-server 12.12.3 → 12.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/.claude/rules/better-auth.md +4 -1
  2. package/.claude/rules/configurable-features.md +2 -2
  3. package/.claude/rules/package-management.md +1 -1
  4. package/.claude/rules/testing.md +3 -3
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/helpers/meta.helper.d.ts +5 -0
  7. package/dist/core/common/helpers/meta.helper.js +16 -1
  8. package/dist/core/common/helpers/meta.helper.js.map +1 -1
  9. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  10. package/dist/core/modules/file/core-file.controller.js +2 -1
  11. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  12. package/dist/core/modules/file/core-file.resolver.js +2 -1
  13. package/dist/core/modules/file/core-file.resolver.js.map +1 -1
  14. package/dist/core/modules/file/core-file.service.d.ts +12 -0
  15. package/dist/core/modules/file/core-file.service.js +44 -0
  16. package/dist/core/modules/file/core-file.service.js.map +1 -1
  17. package/dist/core/modules/file/file-access.helper.d.ts +1 -0
  18. package/dist/core/modules/file/file-access.helper.js +2 -2
  19. package/dist/core/modules/file/file-access.helper.js.map +1 -1
  20. package/dist/core/modules/file/s3-file.helper.d.ts +14 -0
  21. package/dist/core/modules/file/s3-file.helper.js +34 -1
  22. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  23. package/dist/core/modules/health-check/core-health-check.service.d.ts +8 -0
  24. package/dist/core/modules/health-check/core-health-check.service.js +28 -4
  25. package/dist/core/modules/health-check/core-health-check.service.js.map +1 -1
  26. package/dist/core/modules/tenant/core-tenant-selection.helper.d.ts +14 -0
  27. package/dist/core/modules/tenant/core-tenant-selection.helper.js +71 -0
  28. package/dist/core/modules/tenant/core-tenant-selection.helper.js.map +1 -0
  29. package/dist/core/modules/tenant/core-tenant.decorators.d.ts +2 -0
  30. package/dist/core/modules/tenant/core-tenant.decorators.js +2 -0
  31. package/dist/core/modules/tenant/core-tenant.decorators.js.map +1 -1
  32. package/dist/core/modules/tenant/core-tenant.guard.d.ts +8 -0
  33. package/dist/core/modules/tenant/core-tenant.guard.js +108 -1
  34. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.js +1 -0
  37. package/dist/index.js.map +1 -1
  38. package/docs/REQUEST-LIFECYCLE.md +2 -1
  39. package/migration-guides/12.12.x-to-12.13.x.md +161 -0
  40. package/migration-guides/12.13.x-to-12.14.x.md +132 -0
  41. package/package.json +19 -19
  42. package/src/core/common/helpers/meta.helper.ts +62 -3
  43. package/src/core/common/interfaces/server-options.interface.ts +45 -1
  44. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +6 -3
  45. package/src/core/modules/file/README.md +47 -9
  46. package/src/core/modules/file/core-file.controller.ts +9 -4
  47. package/src/core/modules/file/core-file.resolver.ts +2 -1
  48. package/src/core/modules/file/core-file.service.ts +73 -0
  49. package/src/core/modules/file/file-access.helper.ts +17 -4
  50. package/src/core/modules/file/s3-file.helper.ts +75 -2
  51. package/src/core/modules/health-check/core-health-check.service.ts +69 -12
  52. package/src/core/modules/tenant/README.md +39 -10
  53. package/src/core/modules/tenant/core-tenant-selection.helper.ts +135 -0
  54. package/src/core/modules/tenant/core-tenant.decorators.ts +26 -1
  55. package/src/core/modules/tenant/core-tenant.guard.ts +168 -1
  56. package/src/index.ts +1 -0
@@ -13,6 +13,7 @@ import {
13
13
 
14
14
  import { getBuildInfo } from '../../common/helpers/meta.helper.js';
15
15
  import { isShutdownDraining } from '../../common/helpers/shutdown-state.helper.js';
16
+ import { InjectConnection } from '../../common/persistence/mongo/mongoose-compat.js';
16
17
  import { getPersistenceRuntime } from '../../common/persistence/persistence-runtime.registry.js';
17
18
  import { ConfigService } from '../../common/services/config.service.js';
18
19
  import {
@@ -22,6 +23,22 @@ import {
22
23
  resolveHealthCheckReadiness,
23
24
  } from './core-health-check.helpers.js';
24
25
 
26
+ /**
27
+ * How long a database ping (MongoDB and every SQL source) may take before the health check reports the database as
28
+ * down, unless `healthCheck.configs.database.options.timeout` sets another value.
29
+ *
30
+ * 2 s, not the former 300 ms (MongoDB) / 1000 ms (SQL): the MongoDB ping waits for the driver's server selection
31
+ * (see {@link CoreHealthCheckService.pingMongoDb}), which rides out a replica set that briefly sees no primary; a
32
+ * single slow round trip to a managed database outside the cluster must not report it down either. 2 s still fails a
33
+ * database that does not answer and stays below the readiness probe timeout of the lt charts (3 s).
34
+ */
35
+ export const DEFAULT_DATABASE_PING_TIMEOUT_MS = 2000;
36
+
37
+ /** The part of a Mongoose connection the health check's MongoDB ping uses */
38
+ export interface IHealthCheckMongoConnection {
39
+ db?: { command(command: Record<string, unknown>): Promise<unknown> } | null;
40
+ }
41
+
25
42
  /**
26
43
  * Core health check service
27
44
  * Inspired by https://mobileappcircular.com/marketplace-backend-creating-a-health-check-endpoint-in-nestjs-app-using-terminus-25727e96c7d2
@@ -44,6 +61,14 @@ export class CoreHealthCheckService {
44
61
  @Optional() protected indicators?: HealthIndicatorService,
45
62
  ) {}
46
63
 
64
+ /**
65
+ * The application's Mongoose connection for the MongoDB ping (12.14.0); `null` where no MongoDB is configured.
66
+ * Injected as a property, so a project subclass with its own constructor receives it too.
67
+ */
68
+ @Optional()
69
+ @InjectConnection()
70
+ protected mongoConnection?: IHealthCheckMongoConnection | null;
71
+
47
72
  /**
48
73
  * The liveness check (`GET /health-check`, the `healthCheck` query): every check `healthCheck.configs` enables, then
49
74
  * the project's own (`additionalHealthIndicators('liveness')`). Answers the Terminus result; rejects with 503 when a
@@ -161,26 +186,36 @@ export class CoreHealthCheckService {
161
186
  const healthIndicatorFunctions: HealthIndicatorFunction[] = [];
162
187
  // The MongoDB ping where MongoDB is configured — a project on PostgreSQL alone has no MongoDB to ping
163
188
  if (this.db) {
189
+ const db = this.db;
164
190
  healthIndicatorFunctions.push(() => {
165
191
  // `timeout` stays part of the config contract, but @nestjs/terminus 12 deprecated it on the
166
192
  // indicator in favour of `.withTimeout()` on the returned attempt — translate it here, so the
167
193
  // configuration keeps working once the option is gone from the indicator.
168
- // Same effective timeouts as before: 300 ms without configured options, otherwise the
169
- // configured `timeout`, otherwise Terminus' own default (1000 ms).
170
- const { timeout, ...options } = this.config.get<MongoosePingCheckSettings>(
171
- 'healthCheck.configs.database.options',
172
- ) ?? { timeout: 300 };
173
- const attempt = this.db.pingCheck(
174
- this.config.get<string>('healthCheck.configs.database.key') ?? 'database',
175
- options,
176
- );
177
- return timeout === undefined ? attempt : attempt.withTimeout(timeout);
194
+ const {
195
+ connection,
196
+ timeout = DEFAULT_DATABASE_PING_TIMEOUT_MS,
197
+ ...options
198
+ } = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options') ?? {};
199
+ const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
200
+ const target: IHealthCheckMongoConnection | null | undefined = connection ?? this.mongoConnection;
201
+ if (!this.indicators || !target) {
202
+ // A subclass constructed without the HealthIndicatorService, or without the injected connection: Terminus'
203
+ // own check, with its readyState gate (see pingMongoDb)
204
+ return db.pingCheck(key, { connection, ...options }).withTimeout(timeout);
205
+ }
206
+ return this.indicators
207
+ .check(key)
208
+ .attempt(() => this.pingMongoDb(target))
209
+ .withFailureData((error: unknown) => ({ code: (error as { code?: unknown })?.code }))
210
+ .withTimeout(timeout);
178
211
  });
179
212
  }
180
213
  // Every SQL source answers on its own key, next to the MongoDB ping: `<key>:<source>` (`database:default`). A
181
214
  // database the application cannot reach is down, whichever one it is
182
215
  const key = this.config.get<string>('healthCheck.configs.database.key') ?? 'database';
183
- const timeout = this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ?? 1000;
216
+ const timeout =
217
+ this.config.get<MongoosePingCheckSettings>('healthCheck.configs.database.options')?.timeout ??
218
+ DEFAULT_DATABASE_PING_TIMEOUT_MS;
184
219
  if (this.indicators) {
185
220
  for (const source of getPersistenceRuntime()?.sqlSources() ?? []) {
186
221
  healthIndicatorFunctions.push(() =>
@@ -194,11 +229,33 @@ export class CoreHealthCheckService {
194
229
  return healthIndicatorFunctions;
195
230
  }
196
231
 
232
+ /**
233
+ * Pings the MongoDB the application uses (12.14.0): a real `ping` command, bounded by the check's timeout.
234
+ *
235
+ * Deliberately WITHOUT the `readyState` gate of Terminus' `MongooseHealthIndicator`, which reports "down" before it
236
+ * pings whenever the connection's `readyState` is not 1. Mongoose sets `disconnected` as soon as the driver's
237
+ * topology briefly sees no primary (a replica set without `ReplicaSetWithPrimary`, a single server turning
238
+ * `Unknown`): one lost heartbeat is enough, while the database answers in milliseconds and the application's own
239
+ * queries just wait for the driver's server selection. On a cluster with managed MongoDB replica sets that gate
240
+ * produced far more than 95 % of all "database down" alarms. Here the ping waits for server selection the same way,
241
+ * so the check reports down only when the database does not answer within the timeout.
242
+ *
243
+ * @param connection The Mongoose connection (`healthCheck.configs.database.options.connection` or the injected one)
244
+ */
245
+ protected async pingMongoDb(connection: IHealthCheckMongoConnection): Promise<void> {
246
+ if (!connection.db) {
247
+ // Not connected yet (the initial connect is still running) or never connected
248
+ throw new Error('Not connected to database');
249
+ }
250
+ await connection.db.command({ ping: 1 });
251
+ }
252
+
197
253
  /**
198
254
  * Build identity (commit / version / env) — always reported as "up", so it surfaces under `info`/`details` without
199
255
  * ever affecting the overall health status. Lets ops/monitoring detect a drifted or stale container after a partial
200
256
  * rollout (the same commit-SHA signal the admin UI compares). The commit is baked into the image at build time
201
- * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config. Opt out with
257
+ * (APP_VERSION_COMMIT, fed from the CI commit SHA); `version`/`env` come from the config, and with a build number
258
+ * (APP_VERSION_BUILD, the CI pipeline counter) `build` is reported and `version` becomes <Major>.<Minor>.<Build>. Opt out with
202
259
  * `healthCheck.configs.build.enabled: false`.
203
260
  */
204
261
  protected buildHealthIndicators(): HealthIndicatorFunction[] {
@@ -76,16 +76,17 @@ projects whose users are per-tenant.
76
76
 
77
77
  ## Components
78
78
 
79
- | Component | Purpose |
80
- | ------------------------ | ------------------------------------------------------ |
81
- | `CoreTenantMemberModel` | User-tenant membership (join table with role + status) |
82
- | `CoreTenantGuard` | APP_GUARD validating tenant header + membership |
83
- | `CoreTenantService` | Membership CRUD (add, remove, update role, find) |
84
- | `@SkipTenantCheck()` | Method/class decorator to skip tenant validation |
85
- | `@CurrentTenant()` | Parameter decorator extracting validated tenant ID |
86
- | `TenantMemberStatus` | Enum: ACTIVE, INVITED, SUSPENDED |
87
- | `DefaultHR` | Type-safe constants for default hierarchy roles |
88
- | `createHierarchyRoles()` | Generate type-safe constants from custom hierarchy |
79
+ | Component | Purpose |
80
+ | --------------------------- | -------------------------------------------------------- |
81
+ | `CoreTenantMemberModel` | User-tenant membership (join table with role + status) |
82
+ | `CoreTenantGuard` | APP_GUARD validating tenant header + membership |
83
+ | `CoreTenantService` | Membership CRUD (add, remove, update role, find) |
84
+ | `@SkipTenantCheck()` | Method/class decorator to skip tenant validation |
85
+ | `@ResolveTenantSelection()` | Establish the tenant on a route without header (12.13.0) |
86
+ | `@CurrentTenant()` | Parameter decorator extracting validated tenant ID |
87
+ | `TenantMemberStatus` | Enum: ACTIVE, INVITED, SUSPENDED |
88
+ | `DefaultHR` | Type-safe constants for default hierarchy roles |
89
+ | `createHierarchyRoles()` | Generate type-safe constants from custom hierarchy |
89
90
 
90
91
  ## Usage
91
92
 
@@ -222,6 +223,32 @@ async listMyTenants() { ... }
222
223
  Note: `@SkipTenantCheck()` with hierarchy roles still checks `user.roles` (no tenant context).
223
224
  It also suppresses tenant membership validation for `S_USER`/`S_VERIFIED` system role paths — when set, these roles still enforce authentication/verification but skip the membership check even when a tenant header is present.
224
225
 
226
+ ### Routes Without Tenant Header (`@ResolveTenantSelection()`, `selectionCookie`, 12.13.0)
227
+
228
+ A browser cannot send the tenant header with `<img src>`, a download link or a plain form post, and the
229
+ app's own tenant cookie lives on the app's host. A route carrying `@ResolveTenantSelection()` (the
230
+ framework's file controller and resolver do, also with `@SkipTenantCheck()`) gets its tenant after the
231
+ access decision, in this order:
232
+
233
+ 1. the tenant header: an active membership; a foreign tenant answers 403 (on a public route: no tenant)
234
+ 2. the selection cookie, when configured: an active membership; otherwise ignored and cleared
235
+ 3. the caller's only active membership
236
+
237
+ Every candidate needs an active membership in an active tenant; an administrator under `adminBypass`
238
+ gets the named tenant or none. Several memberships and no selection: no tenant, never a guess.
239
+
240
+ ```typescript
241
+ multiTenancy: {
242
+ selectionCookie: true, // cookie lt-tenant-id, __Host-lt-tenant-id where cookies are Secure
243
+ // selectionCookie: { name: 'my-tenant' } // another base name; `{ enabled: false }` off
244
+ }
245
+ ```
246
+
247
+ The guard writes the cookie whenever a request's tenant header passed its check (HttpOnly,
248
+ SameSite=Lax, Path=/, no Domain, session cookie; `Secure` like the auth cookies). It is a selection, not
249
+ a right. Keep its name apart from the app's tenant cookie (nuxt-extensions: `lt-tenant`): behind
250
+ `apiProxy` both live on one host.
251
+
225
252
  ### Admin Bypass
226
253
 
227
254
  System admins (`RoleEnum.ADMIN`) bypass the membership check by default.
@@ -238,6 +265,8 @@ two paths that went around that promise follow it too:
238
265
  `assertCredentialChangeAllowed()` to adjust.
239
266
  - **AI tools** (chat and MCP): no ADMIN bypass in the tool registry; tenant-role tools need a
240
267
  membership role like anyone's.
268
+ - **Files** (12.13.0): the `file.access: 'tenant'` preset no longer lets an administrator read another
269
+ tenant's files; an administrator reads them as an active member of that tenant.
241
270
 
242
271
  ### Deactivated Tenants (`isTenantActive`, since 11.42.0)
243
272
 
@@ -0,0 +1,135 @@
1
+ /**
2
+ * The tenant SELECTION cookie (`multiTenancy.selectionCookie`, 12.13.0).
3
+ *
4
+ * WHY IT EXISTS: the tenant header is how an app names the tenant a request is for, and a browser
5
+ * cannot send it everywhere — `<img src>`, a download link and a plain form post carry cookies only.
6
+ * The app's own tenant cookie (nuxt-extensions: `lt-tenant`) lives on the APP's host and never
7
+ * reaches a separate API host. So the API remembers the selection itself, on its own host, from the
8
+ * last request whose header it validated, and the routes that need it (`@ResolveTenantSelection()`)
9
+ * read it back.
10
+ *
11
+ * WHAT IT IS NOT: a right. The value is a tenant id the caller chose; the tenant guard checks an
12
+ * active membership for it on every request, exactly as for the header, and ignores (and clears) one
13
+ * the caller no longer belongs to.
14
+ *
15
+ * DELIBERATELY A LEAF next to the guard: it reads configuration through arguments and imports only
16
+ * the cookie defaults helper, so the guard and tests share one definition of name and attributes.
17
+ */
18
+ import { Logger } from '@nestjs/common';
19
+
20
+ import { getDefaultAuthCookieOptions } from '../../common/helpers/cookies.helper.js';
21
+ import type { IMultiTenancy } from '../../common/interfaces/server-options.interface.js';
22
+
23
+ /** Base name of the selection cookie. Not `lt-tenant`: that is nuxt-extensions' app cookie. */
24
+ export const DEFAULT_TENANT_SELECTION_COOKIE = 'lt-tenant-id';
25
+
26
+ /** Letters, digits, `-`, `_`; never a reserved `__` prefix (the framework adds `__Host-` itself). */
27
+ const COOKIE_NAME_PATTERN = /^(?!__)[A-Za-z0-9_-]{1,64}$/;
28
+
29
+ const logger = new Logger('TenantSelectionCookie');
30
+ let warnedInvalidName = false;
31
+
32
+ /** The cookie as the guard writes and reads it. */
33
+ export interface ResolvedTenantSelectionCookie {
34
+ /** Full cookie name, `__Host-` included where the cookie is `Secure`. */
35
+ name: string;
36
+ secure: boolean;
37
+ }
38
+
39
+ /**
40
+ * The selection cookie of this configuration, or `undefined` when it is off.
41
+ *
42
+ * Boolean shorthand: `true` / `{}` on, `{ enabled: false }` / `false` / absent off. A value that is
43
+ * neither boolean nor object counts as not set, so a stray string cannot switch it on.
44
+ *
45
+ * `Secure` follows the auth cookies (`getDefaultAuthCookieOptions()`: an `https://` `baseUrl`, or a
46
+ * production-like environment), and a `Secure` cookie gets the `__Host-` prefix: the browser then
47
+ * refuses it from any other host and with a `Domain`, so a sibling subdomain cannot plant a selection.
48
+ */
49
+ export function resolveTenantSelectionCookie(options: {
50
+ baseUrl?: string;
51
+ env?: string;
52
+ multiTenancy?: IMultiTenancy | null;
53
+ }): ResolvedTenantSelectionCookie | undefined {
54
+ const multiTenancy = options.multiTenancy;
55
+ if (!multiTenancy || multiTenancy.enabled === false) {
56
+ return undefined;
57
+ }
58
+ const raw = multiTenancy.selectionCookie as unknown;
59
+ if (raw !== true && (raw === null || typeof raw !== 'object')) {
60
+ return undefined;
61
+ }
62
+ const settings = raw === true ? {} : (raw as { enabled?: unknown; name?: unknown });
63
+ if (settings.enabled === false) {
64
+ return undefined;
65
+ }
66
+
67
+ let base = DEFAULT_TENANT_SELECTION_COOKIE;
68
+ if (settings.name !== undefined) {
69
+ if (typeof settings.name === 'string' && COOKIE_NAME_PATTERN.test(settings.name)) {
70
+ base = settings.name;
71
+ } else if (!warnedInvalidName) {
72
+ warnedInvalidName = true;
73
+ logger.warn(
74
+ `multiTenancy.selectionCookie.name is not a valid cookie name (letters, digits, "-", "_", no "__" prefix); using "${DEFAULT_TENANT_SELECTION_COOKIE}"`,
75
+ );
76
+ }
77
+ }
78
+
79
+ const { secure } = getDefaultAuthCookieOptions(options.env, options.baseUrl);
80
+ return { name: secure ? `__Host-${base}` : base, secure };
81
+ }
82
+
83
+ /**
84
+ * The value of one cookie from a raw `Cookie` header, or `undefined`.
85
+ *
86
+ * Read from the header rather than `req.cookies`: cookie-parser is loaded only with `cookies`
87
+ * enabled, and it turns a `j:` value into an object. A value that does not decode is ignored.
88
+ */
89
+ export function readCookieValue(cookieHeader: unknown, name: string): string | undefined {
90
+ const header = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader;
91
+ if (typeof header !== 'string' || !header) {
92
+ return undefined;
93
+ }
94
+ for (const part of header.split(';')) {
95
+ const separator = part.indexOf('=');
96
+ if (separator < 0 || part.slice(0, separator).trim() !== name) {
97
+ continue;
98
+ }
99
+ let value = part.slice(separator + 1).trim();
100
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) {
101
+ value = value.slice(1, -1);
102
+ }
103
+ try {
104
+ return decodeURIComponent(value) || undefined;
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ /**
113
+ * Write the selection, or clear it with `null`. A response without Express's `cookie()` (a
114
+ * WebSocket, an agent call) or with headers already sent is left alone.
115
+ */
116
+ export function writeTenantSelectionCookie(
117
+ response: any,
118
+ cookie: ResolvedTenantSelectionCookie,
119
+ tenantId: null | string,
120
+ ): void {
121
+ if (!response || typeof response.cookie !== 'function' || response.headersSent) {
122
+ return;
123
+ }
124
+ const attributes = { httpOnly: true, path: '/', sameSite: 'lax' as const, secure: cookie.secure };
125
+ if (tenantId === null) {
126
+ response.clearCookie(cookie.name, attributes);
127
+ } else {
128
+ response.cookie(cookie.name, tenantId, attributes);
129
+ }
130
+ }
131
+
132
+ /** Reset the once-per-process warning (tests). */
133
+ export function resetTenantSelectionCookieWarnings(): void {
134
+ warnedInvalidName = false;
135
+ }
@@ -24,9 +24,34 @@ export const SKIP_TENANT_CHECK_KEY = 'skipTenantCheck';
24
24
  */
25
25
  export const SkipTenantCheck = () => SetMetadata(SKIP_TENANT_CHECK_KEY, true);
26
26
 
27
+ export const RESOLVE_TENANT_SELECTION_KEY = 'resolveTenantSelection';
28
+
29
+ /**
30
+ * Establish the caller's tenant on a route that cannot rely on the tenant header — typically one a
31
+ * browser reaches through `<img src>` or a download link — also when the route carries
32
+ * `@SkipTenantCheck()`.
33
+ *
34
+ * After the tenant guard allowed the request and set no tenant itself, it resolves one in this order:
35
+ * 1. the tenant header (an active membership; a tenant the caller does not belong to answers 403,
36
+ * unless the route is public)
37
+ * 2. the `multiTenancy.selectionCookie`, when configured (an active membership; otherwise ignored
38
+ * and cleared)
39
+ * 3. the caller's only active membership
40
+ *
41
+ * An administrator under `adminBypass` gets the named tenant without a membership, or the bypass
42
+ * without a tenant. Several memberships and no selection: no tenant — never a guess. An API token
43
+ * gets its tenant from the header (or its restriction) only, never from the cookie or a guess.
44
+ *
45
+ * Applied to the framework's file controller and resolver; inherited by subclasses.
46
+ *
47
+ * @since 12.13.0
48
+ */
49
+ export const ResolveTenantSelection = () => SetMetadata(RESOLVE_TENANT_SELECTION_KEY, true);
50
+
27
51
  /**
28
52
  * Parameter decorator that extracts the validated tenant ID from the current request.
29
- * Returns `undefined` if no tenant header is set or the endpoint has @SkipTenantCheck().
53
+ * Returns `undefined` if no tenant header is set or the endpoint has @SkipTenantCheck() — unless the
54
+ * endpoint also carries @ResolveTenantSelection(), which establishes the tenant there (12.13.0).
30
55
  *
31
56
  * Reads from RequestContext (set by CoreTenantGuard → req.tenantId →
32
57
  * RequestContextMiddleware lazy getter → context.tenantId), so it works
@@ -27,6 +27,7 @@ import { DataSourceConfigError } from '../../common/persistence/data-source.conf
27
27
  import type { DataStore } from '../../common/persistence/data-store.interface.js';
28
28
  import { getStoreToken } from '../../common/persistence/persistence.tokens.js';
29
29
  import { getSyncAccessListener } from '../../common/persistence/sync-access.registry.js';
30
+ import type { IServerOptions } from '../../common/interfaces/server-options.interface.js';
30
31
  import { ConfigService } from '../../common/services/config.service.js';
31
32
  import { ResolvedTenantContext, setTenantContextResolver } from '../../common/services/core-tenant-context.registry.js';
32
33
  import { CoreRedisService } from '../../common/services/core-redis.service.js';
@@ -41,7 +42,13 @@ import { ErrorCode } from '../error-code/error-codes.js';
41
42
  import { CoreTenantMemberModel } from './core-tenant-member.model.js';
42
43
  import { routedMemberStore } from './core-tenant-member.store.js';
43
44
  import { registerActiveTenantGuard } from './core-tenant-guard.registry.js';
44
- import { SKIP_TENANT_CHECK_KEY } from './core-tenant.decorators.js';
45
+ import {
46
+ readCookieValue,
47
+ type ResolvedTenantSelectionCookie,
48
+ resolveTenantSelectionCookie,
49
+ writeTenantSelectionCookie,
50
+ } from './core-tenant-selection.helper.js';
51
+ import { RESOLVE_TENANT_SELECTION_KEY, SKIP_TENANT_CHECK_KEY } from './core-tenant.decorators.js';
45
52
  import { TENANT_MEMBER_MODEL_TOKEN, TenantMemberStatus } from './core-tenant.enums.js';
46
53
  import {
47
54
  checkRoleAccess,
@@ -422,6 +429,166 @@ export class CoreTenantGuard implements CanActivate, OnApplicationBootstrap, OnM
422
429
  }
423
430
 
424
431
  async canActivate(context: ExecutionContext): Promise<boolean> {
432
+ const allowed = await this.decideTenantAccess(context);
433
+ if (allowed) {
434
+ await this.completeTenantSelection(context);
435
+ }
436
+ return allowed;
437
+ }
438
+
439
+ /**
440
+ * After access was granted: establish the tenant on a `@ResolveTenantSelection()` route that the
441
+ * decision left without one, and remember a validated tenant header in the selection cookie.
442
+ *
443
+ * Runs AFTER the decision on purpose. The selection never decides access — a route the decision
444
+ * refused never reaches it, and a 403 never carries a fresh cookie.
445
+ */
446
+ protected async completeTenantSelection(context: ExecutionContext): Promise<void> {
447
+ const serverConfig = ConfigService.configFastButReadOnly;
448
+ const config = serverConfig?.multiTenancy;
449
+ if (!config || config.enabled === false) {
450
+ return;
451
+ }
452
+ const request = this.getRequest(context);
453
+ if (!request) {
454
+ return;
455
+ }
456
+
457
+ const cookie = resolveTenantSelectionCookie({
458
+ baseUrl: serverConfig?.baseUrl,
459
+ env: serverConfig?.env,
460
+ multiTenancy: config,
461
+ });
462
+ const headerTenantId = this.readTenantHeader(request, config);
463
+
464
+ if (
465
+ !request.tenantId &&
466
+ this.reflector.getAllAndOverride<boolean>(RESOLVE_TENANT_SELECTION_KEY, [
467
+ context.getHandler(),
468
+ context.getClass(),
469
+ ])
470
+ ) {
471
+ await this.applyTenantSelection(context, request, config, cookie, headerTenantId);
472
+ }
473
+
474
+ // Remember a header the decision VALIDATED (request.tenantId names it only then). Not for API
475
+ // tokens — no browser holds them — and only when the browser does not already send that value.
476
+ if (
477
+ cookie &&
478
+ headerTenantId &&
479
+ request.tenantId === headerTenantId &&
480
+ !getApiTokenContext(request.user) &&
481
+ readCookieValue(request.headers?.cookie, cookie.name) !== headerTenantId
482
+ ) {
483
+ writeTenantSelectionCookie(request.res, cookie, headerTenantId);
484
+ }
485
+ }
486
+
487
+ /**
488
+ * The tenant of a `@ResolveTenantSelection()` route: header → selection cookie → the caller's only
489
+ * active membership. Every candidate becomes the tenant only through an active membership in an
490
+ * active tenant ({@link memberTenantContext}); an administrator under `adminBypass` needs none.
491
+ */
492
+ protected async applyTenantSelection(
493
+ context: ExecutionContext,
494
+ request: any,
495
+ config: NonNullable<IServerOptions['multiTenancy']>,
496
+ cookie: ResolvedTenantSelectionCookie | undefined,
497
+ headerTenantId: string | undefined,
498
+ ): Promise<void> {
499
+ const user = request.user;
500
+ if (!user?.id) {
501
+ return;
502
+ }
503
+ // A token is no browser: it names its tenant through the header (or its restriction, decided
504
+ // above) and nothing else. A token restricted to one tenant that established none there (its
505
+ // membership ended, the tenant was deactivated) would otherwise be moved by the cookie or the
506
+ // only remaining membership into a tenant it was never restricted to.
507
+ const fromApiToken = !!getApiTokenContext(user);
508
+ const cookieTenantId =
509
+ cookie && !fromApiToken
510
+ ? this.normalizeTenantId(readCookieValue(request.headers?.cookie, cookie.name))
511
+ : undefined;
512
+
513
+ if (config.adminBypass !== false && user.roles?.includes(RoleEnum.ADMIN)) {
514
+ // The guard's own rule for administrators: the named tenant without a membership, or no tenant.
515
+ request.isAdminBypass = true;
516
+ const named = headerTenantId ?? cookieTenantId;
517
+ if (named) {
518
+ request.tenantId = named;
519
+ }
520
+ return;
521
+ }
522
+
523
+ if (headerTenantId) {
524
+ const member = await this.memberTenantContext(user, headerTenantId);
525
+ if (member) {
526
+ request.tenantId = member.tenantId;
527
+ request.tenantRole = member.tenantRole;
528
+ return;
529
+ }
530
+ // An explicit request for a foreign tenant: refused like on every other route, unless the
531
+ // route is public — there it only stays without a tenant. Never a fallback to another tenant.
532
+ if (this.grantsEveryone(context)) {
533
+ return;
534
+ }
535
+ throw new ForbiddenException(ErrorCode.NOT_TENANT_MEMBER);
536
+ }
537
+
538
+ if (cookieTenantId) {
539
+ const member = await this.memberTenantContext(user, cookieTenantId);
540
+ if (member) {
541
+ request.tenantId = member.tenantId;
542
+ request.tenantRole = member.tenantRole;
543
+ return;
544
+ }
545
+ // A stale selection (membership ended, tenant deactivated): ignored, and removed so the browser
546
+ // stops sending it.
547
+ writeTenantSelectionCookie(request.res, cookie, null);
548
+ }
549
+
550
+ // The only membership is the only possible answer. Several and no selection: no tenant.
551
+ if (fromApiToken) {
552
+ return;
553
+ }
554
+ const carrier: { tenantIds?: string[]; user: any } = { user };
555
+ await this.resolveUserTenantIds(carrier);
556
+ if (carrier.tenantIds?.length === 1) {
557
+ const member = await this.memberTenantContext(user, carrier.tenantIds[0]);
558
+ if (member) {
559
+ request.tenantId = member.tenantId;
560
+ request.tenantRole = member.tenantRole;
561
+ }
562
+ }
563
+ }
564
+
565
+ /** The tenant header of a request, trimmed and bounded like everywhere in this guard. */
566
+ private readTenantHeader(request: any, config: NonNullable<IServerOptions['multiTenancy']>): string | undefined {
567
+ const headerName = (config.headerName ?? 'x-tenant-id').toLowerCase();
568
+ return this.normalizeTenantId(request.headers?.[headerName]);
569
+ }
570
+
571
+ private normalizeTenantId(value: unknown): string | undefined {
572
+ if (typeof value !== 'string' || value.length > 128) {
573
+ return undefined;
574
+ }
575
+ const trimmed = value.trim();
576
+ return trimmed || undefined;
577
+ }
578
+
579
+ /** Whether the route is public by its method-level system roles — the rule `decideTenantAccess()` applies. */
580
+ private grantsEveryone(context: ExecutionContext): boolean {
581
+ const rolesMetadata = this.reflector.getAll<string[][]>('roles', [context.getHandler(), context.getClass()]);
582
+ const methodRoles: string[] = rolesMetadata[0] ?? [];
583
+ const systemCheckRoles = methodRoles.length > 0 ? methodRoles : mergeRolesMetadata(rolesMetadata);
584
+ return systemCheckRoles.includes(RoleEnum.S_EVERYONE);
585
+ }
586
+
587
+ /**
588
+ * The access decision. Returns `true` or throws; {@link canActivate} completes the tenant selection
589
+ * afterwards.
590
+ */
591
+ protected async decideTenantAccess(context: ExecutionContext): Promise<boolean> {
425
592
  const config = ConfigService.configFastButReadOnly?.multiTenancy;
426
593
  if (!config || config.enabled === false) {
427
594
  return true;
package/src/index.ts CHANGED
@@ -362,6 +362,7 @@ export * from './core/modules/tenant/core-tenant.enums.js';
362
362
  export * from './core/modules/tenant/core-tenant.guard.js';
363
363
  export * from './core/modules/tenant/core-role-scope.registry.js';
364
364
  export * from './core/modules/tenant/core-tenant-role.helper.js';
365
+ export * from './core/modules/tenant/core-tenant-selection.helper.js';
365
366
  export * from './core/modules/tenant/core-tenant.helpers.js';
366
367
  export * from './core/modules/tenant/core-tenant.module.js';
367
368
  export * from './core/modules/tenant/core-tenant.service.js';