@lenne.tech/nest-server 12.12.3 → 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 (46) hide show
  1. package/.claude/rules/better-auth.md +4 -1
  2. package/.claude/rules/configurable-features.md +1 -1
  3. package/.claude/rules/testing.md +3 -3
  4. package/FRAMEWORK-API.md +2 -1
  5. package/dist/core/common/interfaces/server-options.interface.d.ts +5 -0
  6. package/dist/core/modules/file/core-file.controller.js +2 -1
  7. package/dist/core/modules/file/core-file.controller.js.map +1 -1
  8. package/dist/core/modules/file/core-file.resolver.js +2 -1
  9. package/dist/core/modules/file/core-file.resolver.js.map +1 -1
  10. package/dist/core/modules/file/core-file.service.d.ts +12 -0
  11. package/dist/core/modules/file/core-file.service.js +44 -0
  12. package/dist/core/modules/file/core-file.service.js.map +1 -1
  13. package/dist/core/modules/file/file-access.helper.d.ts +1 -0
  14. package/dist/core/modules/file/file-access.helper.js +2 -2
  15. package/dist/core/modules/file/file-access.helper.js.map +1 -1
  16. package/dist/core/modules/file/s3-file.helper.d.ts +14 -0
  17. package/dist/core/modules/file/s3-file.helper.js +34 -1
  18. package/dist/core/modules/file/s3-file.helper.js.map +1 -1
  19. package/dist/core/modules/tenant/core-tenant-selection.helper.d.ts +14 -0
  20. package/dist/core/modules/tenant/core-tenant-selection.helper.js +71 -0
  21. package/dist/core/modules/tenant/core-tenant-selection.helper.js.map +1 -0
  22. package/dist/core/modules/tenant/core-tenant.decorators.d.ts +2 -0
  23. package/dist/core/modules/tenant/core-tenant.decorators.js +2 -0
  24. package/dist/core/modules/tenant/core-tenant.decorators.js.map +1 -1
  25. package/dist/core/modules/tenant/core-tenant.guard.d.ts +8 -0
  26. package/dist/core/modules/tenant/core-tenant.guard.js +108 -1
  27. package/dist/core/modules/tenant/core-tenant.guard.js.map +1 -1
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.js +1 -0
  30. package/dist/index.js.map +1 -1
  31. package/docs/REQUEST-LIFECYCLE.md +2 -1
  32. package/migration-guides/12.12.x-to-12.13.x.md +161 -0
  33. package/package.json +19 -19
  34. package/src/core/common/interfaces/server-options.interface.ts +39 -0
  35. package/src/core/modules/file/INTEGRATION-CHECKLIST.md +6 -3
  36. package/src/core/modules/file/README.md +47 -9
  37. package/src/core/modules/file/core-file.controller.ts +9 -4
  38. package/src/core/modules/file/core-file.resolver.ts +2 -1
  39. package/src/core/modules/file/core-file.service.ts +73 -0
  40. package/src/core/modules/file/file-access.helper.ts +17 -4
  41. package/src/core/modules/file/s3-file.helper.ts +75 -2
  42. package/src/core/modules/tenant/README.md +39 -10
  43. package/src/core/modules/tenant/core-tenant-selection.helper.ts +135 -0
  44. package/src/core/modules/tenant/core-tenant.decorators.ts +26 -1
  45. package/src/core/modules/tenant/core-tenant.guard.ts +168 -1
  46. package/src/index.ts +1 -0
@@ -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';