@lenne.tech/nest-server 12.12.2 → 12.13.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 (55) hide show
  1. package/.claude/rules/better-auth.md +4 -1
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/package-management.md +6 -0
  4. package/.claude/rules/testing.md +4 -4
  5. package/FRAMEWORK-API.md +2 -1
  6. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  7. package/dist/core/common/persistence/sql/positional-placeholders.d.ts +7 -0
  8. package/dist/core/common/persistence/sql/positional-placeholders.js +18 -0
  9. package/dist/core/common/persistence/sql/positional-placeholders.js.map +1 -0
  10. package/dist/core/common/persistence/sql/sql-executor.factory.js +2 -1
  11. package/dist/core/common/persistence/sql/sql-executor.factory.js.map +1 -1
  12. package/dist/core/modules/file/core-file.controller.js +2 -1
  13. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  14. package/dist/core/modules/file/core-file.resolver.js +2 -1
  15. package/dist/core/modules/file/core-file.resolver.js.map +1 -1
  16. package/dist/core/modules/file/core-file.service.d.ts +12 -0
  17. package/dist/core/modules/file/core-file.service.js +44 -0
  18. package/dist/core/modules/file/core-file.service.js.map +1 -1
  19. package/dist/core/modules/file/file-access.helper.d.ts +1 -0
  20. package/dist/core/modules/file/file-access.helper.js +2 -2
  21. package/dist/core/modules/file/file-access.helper.js.map +1 -1
  22. package/dist/core/modules/file/s3-file.helper.d.ts +14 -0
  23. package/dist/core/modules/file/s3-file.helper.js +34 -1
  24. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  25. package/dist/core/modules/tenant/core-tenant-selection.helper.d.ts +14 -0
  26. package/dist/core/modules/tenant/core-tenant-selection.helper.js +71 -0
  27. package/dist/core/modules/tenant/core-tenant-selection.helper.js.map +1 -0
  28. package/dist/core/modules/tenant/core-tenant.decorators.d.ts +2 -0
  29. package/dist/core/modules/tenant/core-tenant.decorators.js +2 -0
  30. package/dist/core/modules/tenant/core-tenant.decorators.js.map +1 -1
  31. package/dist/core/modules/tenant/core-tenant.guard.d.ts +8 -0
  32. package/dist/core/modules/tenant/core-tenant.guard.js +108 -1
  33. package/dist/core/modules/tenant/core-tenant.guard.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/docs/REQUEST-LIFECYCLE.md +2 -1
  38. package/migration-guides/12.12.2-to-12.12.3.md +73 -0
  39. package/migration-guides/12.12.x-to-12.13.x.md +161 -0
  40. package/package.json +19 -19
  41. package/src/core/common/interfaces/server-options.interface.ts +39 -0
  42. package/src/core/common/persistence/sql/positional-placeholders.ts +48 -0
  43. package/src/core/common/persistence/sql/sql-executor.factory.ts +4 -8
  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/tenant/README.md +39 -10
  52. package/src/core/modules/tenant/core-tenant-selection.helper.ts +135 -0
  53. package/src/core/modules/tenant/core-tenant.decorators.ts +26 -1
  54. package/src/core/modules/tenant/core-tenant.guard.ts +168 -1
  55. package/src/index.ts +1 -0
@@ -776,6 +776,76 @@ export abstract class CoreFileService {
776
776
  return fileInfo;
777
777
  }
778
778
 
779
+ /**
780
+ * Move GridFS files into S3 storage under their EXISTING ids, for a migration of a project that
781
+ * switches `file.storage` to S3 (12.13.0).
782
+ *
783
+ * Every file keeps its id, filename, content type, upload date and `metadata` (owner, `tenantId`),
784
+ * so links, `{{fileUrl:<id>}}` placeholders and references in other records keep working. Runs
785
+ * per file through {@link S3FileHelper.importFile}: idempotent (a file already in S3 is skipped and
786
+ * not read again), and a failure of one file is reported, not thrown, so one run moves everything
787
+ * it can.
788
+ *
789
+ * `removeSource: true` deletes the GridFS copy once its S3 copy is verified, also for a file an
790
+ * earlier run already imported. Do it: reads find the S3 copy first, but a delete removes only the
791
+ * copy it finds first, so a file deleted while its GridFS copy is still there becomes readable again
792
+ * through that copy. Run once without `removeSource` to check the result, then again with it.
793
+ *
794
+ * A system operation: no rights check, no request context. Call it from a migration or a script,
795
+ * never from a route.
796
+ *
797
+ * @param options.filter a GridFS `files` filter, e.g. `{ 'metadata.tenantId': tenantId }`
798
+ * @since 12.13.0
799
+ */
800
+ async importGridFsFilesToS3(options: { filter?: Record<string, any>; removeSource?: boolean } = {}): Promise<{
801
+ failed: { error: string; id: string }[];
802
+ imported: number;
803
+ removed: number;
804
+ skipped: number;
805
+ }> {
806
+ if (!this.files) {
807
+ throw new Error('importGridFsFilesToS3 needs GridFS, i.e. a MongoDB connection');
808
+ }
809
+ const s3Service = this.options?.s3Service;
810
+ if (!s3Service?.enabled) {
811
+ throw new Error('importGridFsFilesToS3 needs a configured s3 (CoreS3Service is not enabled)');
812
+ }
813
+
814
+ const result = { failed: [] as { error: string; id: string }[], imported: 0, removed: 0, skipped: 0 };
815
+ const cursor = this.files.find(options.filter ?? {}, { sort: { _id: 1 } });
816
+ for await (const doc of cursor) {
817
+ const id = getStringIds(doc._id);
818
+ try {
819
+ const { imported } = await S3FileHelper.importFile(s3Service, this.s3Files, {
820
+ _id: id,
821
+ body: () => this.files.openDownloadStream(doc._id),
822
+ contentLength: doc.length,
823
+ contentType: (doc as any).contentType ?? doc.metadata?.contentType,
824
+ filename: doc.filename,
825
+ metadata: doc.metadata,
826
+ uploadDate: doc.uploadDate,
827
+ });
828
+ if (imported) {
829
+ result.imported++;
830
+ } else {
831
+ result.skipped++;
832
+ }
833
+ if (options.removeSource) {
834
+ // Only once the bytes are verifiably in S3 — for a skipped file that is not proven by the
835
+ // metadata alone, somebody may have removed the object since.
836
+ if (!(await s3Service.statObject(id))) {
837
+ throw new Error('S3 metadata exists but the object is missing; GridFS copy kept');
838
+ }
839
+ await this.files.delete(doc._id);
840
+ result.removed++;
841
+ }
842
+ } catch (error) {
843
+ result.failed.push({ error: error instanceof Error ? error.message : String(error), id });
844
+ }
845
+ }
846
+ return result;
847
+ }
848
+
779
849
  /**
780
850
  * Delete file reference of avatar
781
851
  */
@@ -1055,7 +1125,10 @@ export abstract class CoreFileService {
1055
1125
  : await this.getRawFileInfoByName(input)
1056
1126
  : undefined;
1057
1127
 
1128
+ const multiTenancy = ConfigService.configFastButReadOnly?.multiTenancy;
1058
1129
  return decideFileAccess({
1130
+ // Only while multi-tenancy is active: without it there is no tenant authority to withhold.
1131
+ adminBypass: multiTenancy && multiTenancy.enabled !== false ? multiTenancy.adminBypass : undefined,
1059
1132
  checkInputType: options?.checkInputType,
1060
1133
  currentUser: options?.currentUser,
1061
1134
  force: options?.force,
@@ -21,7 +21,10 @@
21
21
  * | `'public'` | open: anyone may read and write, the role gate is the whole policy |
22
22
  * | `'authenticated'` | login-restricted: every signed-in user may use every file |
23
23
  * | `'owner'` | per-user: only the uploader (plus ADMIN) |
24
- * | `'tenant'` | per-tenant: only within one's own validated tenant (plus ADMIN) |
24
+ * | `'tenant'` | per-tenant: only within one's own validated tenant (plus ADMIN*) |
25
+ *
26
+ * (*) Not under `multiTenancy.adminBypass: false` (12.13.0): an administrator then needs an active
27
+ * membership in the file's tenant, like everybody else.
25
28
  *
26
29
  * NOTHING CHANGES FOR AN EXISTING PROJECT. `'custom'` is the default and returns `true` for every
27
30
  * input, which is byte-for-byte what `CoreFileService.checkRights()` did before. A project that
@@ -90,6 +93,12 @@ export function fileAccessNeedsRawDocument(preset: FileAccessPreset, checkInputT
90
93
  * never a raw header — an unvalidated header would be worse than no tenant at all.
91
94
  */
92
95
  export function decideFileAccess(options: {
96
+ /**
97
+ * `multiTenancy.adminBypass`. Only an explicit `false` counts: it withholds the ADMIN pass from the
98
+ * `'tenant'` preset, so a platform administrator reads a tenant's files only as an active member of
99
+ * that tenant — what `adminBypass: false` promises for every other tenant-scoped read.
100
+ */
101
+ adminBypass?: boolean;
93
102
  checkInputType?: CheckInputType;
94
103
  currentUser?: { hasRole?: (roles: string[]) => boolean; id?: any };
95
104
  force?: boolean;
@@ -97,7 +106,7 @@ export function decideFileAccess(options: {
97
106
  raw?: null | Record<string, any>;
98
107
  tenantId?: string;
99
108
  }): boolean {
100
- const { checkInputType, currentUser, force, preset, raw, tenantId } = options;
109
+ const { adminBypass, checkInputType, currentUser, force, preset, raw, tenantId } = options;
101
110
 
102
111
  // A system caller says so explicitly. This is the documented alternative to the
103
112
  // `if (!currentUser) return true` shortcut: the exemption is stated at the call site, in the diff,
@@ -117,8 +126,12 @@ export function decideFileAccess(options: {
117
126
  return !!currentUser?.id;
118
127
  }
119
128
 
120
- // ADMIN is platform authority and is never locked out — the same union the role guards apply.
121
- if (currentUser?.hasRole?.([RoleEnum.ADMIN])) {
129
+ // ADMIN is platform authority — the same union the role guards apply. Under
130
+ // `multiTenancy.adminBypass: false` that authority stops at tenant content: the `'tenant'` preset
131
+ // then asks an administrator the same question as everybody else (an active membership in the
132
+ // file's tenant). Until 12.12.3 the pass here ignored the setting, so the one tenant-scoped surface
133
+ // the framework decides outside Mongoose let administrators read every tenant's files.
134
+ if (currentUser?.hasRole?.([RoleEnum.ADMIN]) && !(preset === 'tenant' && adminBypass === false)) {
122
135
  return true;
123
136
  }
124
137
 
@@ -142,6 +142,70 @@ export class S3FileHelper {
142
142
  });
143
143
  }
144
144
 
145
+ /**
146
+ * Import a file that already has an id elsewhere (GridFS, another system) into S3 storage under
147
+ * THAT id — so links, `{{fileUrl:<id>}}` placeholders and references in other records keep working.
148
+ *
149
+ * Idempotent: a file whose metadata already exists under this id is skipped (`imported: false`) and
150
+ * its source is not even opened, so a migration can simply run again after an interruption. An
151
+ * object left in the bucket by an interrupted run without its metadata is overwritten.
152
+ *
153
+ * `metadata` (owner, `tenantId`, anything else) and `uploadDate` are taken over unchanged; the
154
+ * object is verified with a HEAD before the metadata is written, as for every other S3 write.
155
+ *
156
+ * @param options.body the bytes — a stream, or a function opening one (called only when the file
157
+ * is actually imported); `buffer` instead for bytes already in memory
158
+ * @since 12.13.0
159
+ */
160
+ static async importFile(
161
+ s3Service: CoreS3Service,
162
+ collection: FileCollection,
163
+ options: {
164
+ _id: string | Types.ObjectId;
165
+ body?: (() => Promise<Readable> | Readable) | Readable;
166
+ buffer?: Buffer;
167
+ contentLength?: number;
168
+ contentType?: string;
169
+ filename: string;
170
+ metadata?: Record<string, any>;
171
+ uploadDate?: Date;
172
+ },
173
+ ): Promise<{ fileInfo: S3FileInfo; imported: boolean }> {
174
+ const hex = typeof options._id === 'string' ? options._id : options._id?.toHexString?.();
175
+ if (!hex || !/^[0-9a-f]{24}$/i.test(hex)) {
176
+ throw new Error('S3FileHelper.importFile needs the 24-hex id the file already has');
177
+ }
178
+ if (!s3Service?.enabled) {
179
+ throw new Error('S3FileHelper.importFile needs a configured s3 (CoreS3Service is not enabled)');
180
+ }
181
+
182
+ const existing = await findMetadataById(collection, hex);
183
+ if (existing) {
184
+ if (options.body && typeof options.body !== 'function') {
185
+ // A stream the caller opened in advance would otherwise hold its source (a GridFS cursor) open.
186
+ options.body.destroy();
187
+ }
188
+ return { fileInfo: existing, imported: false };
189
+ }
190
+
191
+ const body = typeof options.body === 'function' ? await options.body() : (options.body ?? options.buffer);
192
+ if (!body) {
193
+ throw new Error('S3FileHelper.importFile needs either a body stream or a buffer');
194
+ }
195
+ const contentLength = isKnownUploadSize(options.contentLength) ? options.contentLength : options.buffer?.length;
196
+ const _id = newObjectId(hex);
197
+ await s3Service.putObject(hex, body, options.contentType, contentLength);
198
+
199
+ const fileInfo = await S3FileHelper.recordFile(s3Service, collection, _id, {
200
+ contentType: options.contentType,
201
+ filename: options.filename,
202
+ length: contentLength,
203
+ metadata: options.metadata,
204
+ uploadDate: options.uploadDate,
205
+ });
206
+ return { fileInfo, imported: true };
207
+ }
208
+
145
209
  /**
146
210
  * Verify the object arrived and record its metadata.
147
211
  *
@@ -152,7 +216,13 @@ export class S3FileHelper {
152
216
  s3Service: CoreS3Service,
153
217
  collection: FileCollection,
154
218
  _id: Types.ObjectId,
155
- options: { contentType?: string; filename: string; length?: number; metadata?: Record<string, any> },
219
+ options: {
220
+ contentType?: string;
221
+ filename: string;
222
+ length?: number;
223
+ metadata?: Record<string, any>;
224
+ uploadDate?: Date;
225
+ },
156
226
  ): Promise<S3FileInfo> {
157
227
  // One HEAD answers both questions: whether the bytes arrived, and — for a stream whose length
158
228
  // nobody knew up front — how many there are. The stored object is the authority on its size;
@@ -176,7 +246,10 @@ export class S3FileHelper {
176
246
  // Records WHERE the bytes went, so a reader never has to probe all three
177
247
  // stores to find out. Legacy documents lack it and are handled by probing.
178
248
  storage: 's3',
179
- uploadDate: new Date(),
249
+ uploadDate:
250
+ options.uploadDate instanceof Date && !Number.isNaN(options.uploadDate.getTime())
251
+ ? options.uploadDate
252
+ : new Date(),
180
253
  };
181
254
  await collection.insertOne(fileInfo);
182
255
  return fileInfo;
@@ -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';