@lenne.tech/nest-server 12.11.2 → 12.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/rules/architecture.md +3 -0
- package/.claude/rules/configurable-features.md +6 -0
- package/.claude/rules/package-management.md +6 -4
- package/.claude/rules/role-system.md +8 -0
- package/.claude/rules/testing.md +8 -7
- package/CLAUDE.md +2 -1
- package/FRAMEWORK-API.md +15 -1
- package/dist/core/common/decorators/common-error.decorator.d.ts +1 -1
- package/dist/core/common/interfaces/server-options.interface.d.ts +54 -0
- package/dist/core/common/persistence/audit-log.registry.d.ts +19 -0
- package/dist/core/common/persistence/audit-log.registry.js +84 -0
- package/dist/core/common/persistence/audit-log.registry.js.map +1 -0
- package/dist/core/common/persistence/policies/tenant.policy.js +3 -1
- package/dist/core/common/persistence/policies/tenant.policy.js.map +1 -1
- package/dist/core/common/services/core-trust-proxy.initializer.js +1 -1
- package/dist/core/common/services/core-trust-proxy.initializer.js.map +1 -1
- package/dist/core/common/services/crud.service.d.ts +10 -0
- package/dist/core/common/services/crud.service.js +79 -24
- package/dist/core/common/services/crud.service.js.map +1 -1
- package/dist/core/common/services/email.service.d.ts +5 -0
- package/dist/core/common/services/email.service.js +82 -6
- package/dist/core/common/services/email.service.js.map +1 -1
- package/dist/core/common/services/leased-interval.d.ts +22 -0
- package/dist/core/common/services/leased-interval.js +81 -0
- package/dist/core/common/services/leased-interval.js.map +1 -0
- package/dist/core/common/services/mail-outbox.registry.d.ts +26 -0
- package/dist/core/common/services/mail-outbox.registry.js +8 -0
- package/dist/core/common/services/mail-outbox.registry.js.map +1 -0
- package/dist/core/modules/audit-log/audited.decorator.d.ts +2 -0
- package/dist/core/modules/audit-log/audited.decorator.js +10 -0
- package/dist/core/modules/audit-log/audited.decorator.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.d.ts +13 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.js +11 -0
- package/dist/core/modules/audit-log/core-audit-log.constants.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.d.ts +9 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.js +87 -0
- package/dist/core/modules/audit-log/core-audit-log.controller.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.models.d.ts +10 -0
- package/dist/core/modules/audit-log/core-audit-log.models.js +11 -0
- package/dist/core/modules/audit-log/core-audit-log.models.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.module.d.ts +13 -0
- package/dist/core/modules/audit-log/core-audit-log.module.js +41 -0
- package/dist/core/modules/audit-log/core-audit-log.module.js.map +1 -0
- package/dist/core/modules/audit-log/core-audit-log.service.d.ts +49 -0
- package/dist/core/modules/audit-log/core-audit-log.service.js +169 -0
- package/dist/core/modules/audit-log/core-audit-log.service.js.map +1 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +4 -0
- package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.d.ts +22 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js +23 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.d.ts +10 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js +80 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.d.ts +17 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.js +17 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.models.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.d.ts +12 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.js +42 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.module.js.map +1 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.d.ts +59 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.js +280 -0
- package/dist/core/modules/mail-outbox/core-mail-outbox.service.js.map +1 -0
- package/dist/core/modules/migrate/cli/migrate-cli.js +20 -2
- package/dist/core/modules/migrate/cli/migrate-cli.js.map +1 -1
- package/dist/core/modules/throttler/core-throttler.config.d.ts +16 -0
- package/dist/core/modules/throttler/core-throttler.config.js +107 -0
- package/dist/core/modules/throttler/core-throttler.config.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.constants.d.ts +10 -0
- package/dist/core/modules/throttler/core-throttler.constants.js +11 -0
- package/dist/core/modules/throttler/core-throttler.constants.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.decorators.d.ts +1 -0
- package/dist/core/modules/throttler/core-throttler.decorators.js +2 -0
- package/dist/core/modules/throttler/core-throttler.decorators.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.guard.d.ts +15 -0
- package/dist/core/modules/throttler/core-throttler.guard.js +65 -0
- package/dist/core/modules/throttler/core-throttler.guard.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.models.d.ts +1 -0
- package/dist/core/modules/throttler/core-throttler.models.js +11 -0
- package/dist/core/modules/throttler/core-throttler.models.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.module.d.ts +12 -0
- package/dist/core/modules/throttler/core-throttler.module.js +71 -0
- package/dist/core/modules/throttler/core-throttler.module.js.map +1 -0
- package/dist/core/modules/throttler/core-throttler.storages.d.ts +43 -0
- package/dist/core/modules/throttler/core-throttler.storages.js +174 -0
- package/dist/core/modules/throttler/core-throttler.storages.js.map +1 -0
- package/dist/core/modules/user/core-user.service.js +2 -2
- package/dist/core/modules/user/core-user.service.js.map +1 -1
- package/dist/core.module.js +26 -0
- package/dist/core.module.js.map +1 -1
- package/dist/index.d.ts +21 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -1
- package/docs/REQUEST-LIFECYCLE.md +10 -3
- package/docs/security-overrides.md +20 -8
- package/migration-guides/12.11.2-to-12.11.3.md +96 -0
- package/migration-guides/12.11.x-to-12.12.x.md +182 -0
- package/package.json +28 -27
- package/src/core/common/interfaces/server-options.interface.ts +311 -1
- package/src/core/common/persistence/audit-log.registry.ts +150 -0
- package/src/core/common/persistence/policies/tenant.policy.ts +10 -5
- package/src/core/common/services/core-trust-proxy.initializer.ts +5 -4
- package/src/core/common/services/crud.service.ts +128 -33
- package/src/core/common/services/email.service.ts +101 -9
- package/src/core/common/services/leased-interval.ts +123 -0
- package/src/core/common/services/mail-outbox.registry.ts +53 -0
- package/src/core/modules/audit-log/README.md +95 -0
- package/src/core/modules/audit-log/audited.decorator.ts +27 -0
- package/src/core/modules/audit-log/core-audit-log.constants.ts +28 -0
- package/src/core/modules/audit-log/core-audit-log.controller.ts +77 -0
- package/src/core/modules/audit-log/core-audit-log.models.ts +34 -0
- package/src/core/modules/audit-log/core-audit-log.module.ts +54 -0
- package/src/core/modules/audit-log/core-audit-log.service.ts +270 -0
- package/src/core/modules/better-auth/README.md +18 -0
- package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +4 -0
- package/src/core/modules/mail-outbox/README.md +88 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.constants.ts +42 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.controller.ts +60 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.models.ts +46 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.module.ts +52 -0
- package/src/core/modules/mail-outbox/core-mail-outbox.service.ts +390 -0
- package/src/core/modules/migrate/README.md +4 -1
- package/src/core/modules/migrate/cli/migrate-cli.ts +30 -2
- package/src/core/modules/system-setup/README.md +4 -0
- package/src/core/modules/tenant/INTEGRATION-CHECKLIST.md +3 -3
- package/src/core/modules/tenant/README.md +4 -4
- package/src/core/modules/throttler/README.md +107 -0
- package/src/core/modules/throttler/core-throttler.config.ts +162 -0
- package/src/core/modules/throttler/core-throttler.constants.ts +33 -0
- package/src/core/modules/throttler/core-throttler.decorators.ts +14 -0
- package/src/core/modules/throttler/core-throttler.guard.ts +109 -0
- package/src/core/modules/throttler/core-throttler.models.ts +23 -0
- package/src/core/modules/throttler/core-throttler.module.ts +95 -0
- package/src/core/modules/throttler/core-throttler.storages.ts +299 -0
- package/src/core/modules/user/core-user.service.ts +3 -2
- package/src/core.module.ts +46 -0
- package/src/index.ts +36 -0
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createSchema } from '../../common/persistence/mongo/mongoose-compat.js';
|
|
2
|
+
import type { QueuedSmtpMail } from '../../common/services/mail-outbox.registry.js';
|
|
3
|
+
import { MAIL_OUTBOX_COLLECTION } from './core-mail-outbox.constants.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The mails of the outbox as a framework model: registered with `CorePersistenceModule.forFeature()` only when
|
|
7
|
+
* `mailOutbox` is configured, it follows `database` like every other model — a collection on MongoDB, the table
|
|
8
|
+
* `mail_outbox` on SQL.
|
|
9
|
+
*
|
|
10
|
+
* `mail` is the rendered mail (until it was delivered — then it is removed, it may carry a reset link); `to` and
|
|
11
|
+
* `subject` stay for the overview. `lockedBy` / `lockedUntil` are the claim of the replica delivering it.
|
|
12
|
+
*/
|
|
13
|
+
export const MailOutboxEntrySchema = createSchema(
|
|
14
|
+
{
|
|
15
|
+
attempts: { default: 0, type: Number },
|
|
16
|
+
lastAttemptAt: { type: Date },
|
|
17
|
+
lastError: { type: String },
|
|
18
|
+
lockedBy: { type: String },
|
|
19
|
+
lockedUntil: { type: Date },
|
|
20
|
+
mail: { type: Object },
|
|
21
|
+
nextAttemptAt: { index: true, type: Date },
|
|
22
|
+
queuedAt: { index: true, type: Date },
|
|
23
|
+
sentAt: { index: true, type: Date },
|
|
24
|
+
status: { index: true, type: String },
|
|
25
|
+
subject: { type: String },
|
|
26
|
+
to: { default: [], type: [String] },
|
|
27
|
+
},
|
|
28
|
+
{ collection: MAIL_OUTBOX_COLLECTION, versionKey: false },
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
/** A stored mail */
|
|
32
|
+
export interface CoreMailOutboxEntry {
|
|
33
|
+
attempts: number;
|
|
34
|
+
id: string;
|
|
35
|
+
lastAttemptAt?: Date;
|
|
36
|
+
lastError?: string;
|
|
37
|
+
lockedBy?: string;
|
|
38
|
+
lockedUntil?: Date;
|
|
39
|
+
mail?: QueuedSmtpMail | null;
|
|
40
|
+
nextAttemptAt?: Date;
|
|
41
|
+
queuedAt: Date;
|
|
42
|
+
sentAt?: Date;
|
|
43
|
+
status: 'failed' | 'pending' | 'sending' | 'sent';
|
|
44
|
+
subject: string;
|
|
45
|
+
to: string[];
|
|
46
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { DynamicModule, Module, Type } from '@nestjs/common';
|
|
2
|
+
import { PATH_METADATA } from '@nestjs/common/constants';
|
|
3
|
+
|
|
4
|
+
import { RoleEnum } from '../../common/enums/role.enum.js';
|
|
5
|
+
import { CorePersistenceModule } from '../../common/persistence/core-persistence.module.js';
|
|
6
|
+
import { MAIL_OUTBOX_DEFAULTS, MAIL_OUTBOX_MODEL } from './core-mail-outbox.constants.js';
|
|
7
|
+
import { CoreMailOutboxController } from './core-mail-outbox.controller.js';
|
|
8
|
+
import { MailOutboxEntrySchema } from './core-mail-outbox.models.js';
|
|
9
|
+
import { CoreMailOutboxService } from './core-mail-outbox.service.js';
|
|
10
|
+
|
|
11
|
+
/** Options of `CoreMailOutboxModule.forRoot()` */
|
|
12
|
+
export interface CoreMailOutboxModuleOptions {
|
|
13
|
+
/** Custom controller (must extend CoreMailOutboxController) */
|
|
14
|
+
controller?: Type<CoreMailOutboxController>;
|
|
15
|
+
/** Route prefix (`mailOutbox.path`) @default 'mail-outbox' */
|
|
16
|
+
path?: string;
|
|
17
|
+
/** Roles that may use the admin endpoints, in addition to ADMIN (`mailOutbox.roles`) */
|
|
18
|
+
roles?: unknown;
|
|
19
|
+
/** Custom service (must extend CoreMailOutboxService) */
|
|
20
|
+
service?: Type<CoreMailOutboxService>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Mail outbox (`mailOutbox` config, DEV-4433). Registered automatically by `CoreModule.forRoot()` when `mailOutbox`
|
|
25
|
+
* is configured — without it `EmailService` sends directly, as before, and there is no model, no table and no route.
|
|
26
|
+
* Provides the service (it registers itself with `EmailService` at module init), the admin endpoints and the entry
|
|
27
|
+
* model, which follows `database` like every other model.
|
|
28
|
+
*/
|
|
29
|
+
@Module({})
|
|
30
|
+
export class CoreMailOutboxModule {
|
|
31
|
+
static forRoot(options: CoreMailOutboxModuleOptions = {}): DynamicModule {
|
|
32
|
+
const controller = options.controller ?? CoreMailOutboxController;
|
|
33
|
+
Reflect.defineMetadata(PATH_METADATA, options.path || MAIL_OUTBOX_DEFAULTS.path, controller);
|
|
34
|
+
// A project controller that declares @Roles() itself keeps them: that is how a policy is pinned in code
|
|
35
|
+
if (controller === CoreMailOutboxController || !Reflect.hasOwnMetadata('roles', controller)) {
|
|
36
|
+
const extra = Array.isArray(options.roles)
|
|
37
|
+
? options.roles.filter((role): role is string => typeof role === 'string' && !!role)
|
|
38
|
+
: [];
|
|
39
|
+
Reflect.defineMetadata('roles', [...new Set([RoleEnum.ADMIN as string, ...extra])], controller);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
controllers: [controller],
|
|
43
|
+
exports: [CoreMailOutboxService],
|
|
44
|
+
global: true,
|
|
45
|
+
imports: [CorePersistenceModule.forFeature([{ name: MAIL_OUTBOX_MODEL, schema: MailOutboxEntrySchema }])],
|
|
46
|
+
module: CoreMailOutboxModule,
|
|
47
|
+
providers: [
|
|
48
|
+
options.service ? { provide: CoreMailOutboxService, useClass: options.service } : CoreMailOutboxService,
|
|
49
|
+
],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { Injectable, Logger, OnApplicationBootstrap, OnModuleDestroy, OnModuleInit, Optional } from '@nestjs/common';
|
|
2
|
+
|
|
3
|
+
import { maskEmail } from '../../common/helpers/logging.helper.js';
|
|
4
|
+
import type { IMailOutbox } from '../../common/interfaces/server-options.interface.js';
|
|
5
|
+
import type { DataStore, Where } from '../../common/persistence/data-store.interface.js';
|
|
6
|
+
import { InjectStore } from '../../common/persistence/inject-store.decorator.js';
|
|
7
|
+
import { ConfigService } from '../../common/services/config.service.js';
|
|
8
|
+
import { CoreRedisService } from '../../common/services/core-redis.service.js';
|
|
9
|
+
import { EmailService } from '../../common/services/email.service.js';
|
|
10
|
+
import { frameworkJobLeaseStore, LeasedInterval } from '../../common/services/leased-interval.js';
|
|
11
|
+
import {
|
|
12
|
+
getMailOutbox,
|
|
13
|
+
type MailOutbox,
|
|
14
|
+
type QueuedMailReceipt,
|
|
15
|
+
type QueuedSmtpMail,
|
|
16
|
+
setMailOutbox,
|
|
17
|
+
} from '../../common/services/mail-outbox.registry.js';
|
|
18
|
+
import {
|
|
19
|
+
MAIL_OUTBOX_BATCH,
|
|
20
|
+
MAIL_OUTBOX_DEFAULTS,
|
|
21
|
+
MAIL_OUTBOX_ERROR_LENGTH,
|
|
22
|
+
MAIL_OUTBOX_MODEL,
|
|
23
|
+
MAIL_OUTBOX_PURGE_BATCH,
|
|
24
|
+
MAIL_OUTBOX_STATUS,
|
|
25
|
+
} from './core-mail-outbox.constants.js';
|
|
26
|
+
import type { CoreMailOutboxEntry } from './core-mail-outbox.models.js';
|
|
27
|
+
|
|
28
|
+
/** The numbers of `mailOutbox`, each an invalid value replaced by its default */
|
|
29
|
+
export interface ResolvedMailOutboxSettings {
|
|
30
|
+
failedDays: false | number;
|
|
31
|
+
lockSeconds: number;
|
|
32
|
+
maxAttempts: number;
|
|
33
|
+
maxRetryDelaySeconds: number;
|
|
34
|
+
pollIntervalSeconds: number;
|
|
35
|
+
retryDelaySeconds: number;
|
|
36
|
+
sentDays: false | number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function positiveOr(value: unknown, fallback: number): number {
|
|
40
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function daysOr(value: unknown, fallback: number): false | number {
|
|
44
|
+
return value === false ? false : positiveOr(value, fallback);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `mailOutbox` with every default applied. An invalid number falls back to its default, never to "for good" */
|
|
48
|
+
export function resolveMailOutboxSettings(config: IMailOutbox = {}): ResolvedMailOutboxSettings {
|
|
49
|
+
return {
|
|
50
|
+
failedDays: daysOr(config.retention?.failedDays, MAIL_OUTBOX_DEFAULTS.failedDays),
|
|
51
|
+
lockSeconds: positiveOr(config.lockSeconds, MAIL_OUTBOX_DEFAULTS.lockSeconds),
|
|
52
|
+
maxAttempts: Math.floor(positiveOr(config.maxAttempts, MAIL_OUTBOX_DEFAULTS.maxAttempts)) || 1,
|
|
53
|
+
maxRetryDelaySeconds: positiveOr(config.maxRetryDelaySeconds, MAIL_OUTBOX_DEFAULTS.maxRetryDelaySeconds),
|
|
54
|
+
pollIntervalSeconds: positiveOr(config.pollIntervalSeconds, MAIL_OUTBOX_DEFAULTS.pollIntervalSeconds),
|
|
55
|
+
retryDelaySeconds: positiveOr(config.retryDelaySeconds, MAIL_OUTBOX_DEFAULTS.retryDelaySeconds),
|
|
56
|
+
sentDays: daysOr(config.retention?.sentDays, MAIL_OUTBOX_DEFAULTS.sentDays),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A filter of {@link CoreMailOutboxService.list} */
|
|
61
|
+
export interface MailOutboxQuery {
|
|
62
|
+
/** Page size, at most 500 @default 50 */
|
|
63
|
+
limit?: number;
|
|
64
|
+
offset?: number;
|
|
65
|
+
status?: CoreMailOutboxEntry['status'];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** An entry as the overview shows it: everything but the mail's content */
|
|
69
|
+
export type MailOutboxOverview = Omit<CoreMailOutboxEntry, 'mail'>;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The mail outbox (`mailOutbox` config, DEV-4433): every mail of `EmailService` — the framework's auth mails included
|
|
73
|
+
* — is stored first and delivered from the store.
|
|
74
|
+
*
|
|
75
|
+
* - **Delivery:** a new mail is delivered at once; every replica also looks for due mails every `pollIntervalSeconds`.
|
|
76
|
+
* A mail is CLAIMED with one atomic statement (`updateOne`, MongoDB's `findOneAndUpdate`, SQL's
|
|
77
|
+
* `UPDATE … RETURNING`) before it is sent, so with several replicas exactly one delivers it. A claim held longer than
|
|
78
|
+
* `lockSeconds` (a replica died mid-send) is taken over. Every attempt uses the same Message-ID.
|
|
79
|
+
* - **Retries:** a failed attempt is retried after `retryDelaySeconds`, doubled per attempt up to
|
|
80
|
+
* `maxRetryDelaySeconds`; after `maxAttempts` the mail is `failed`, logged as an error and listed for admins
|
|
81
|
+
* (`GET /mail-outbox?status=failed`, `POST /mail-outbox/:id/retry`).
|
|
82
|
+
* - **Retention:** a delivered mail loses its content at once (it may carry a reset link) and its metadata after
|
|
83
|
+
* `retention.sentDays`; a failed one stays `retention.failedDays`. The purge runs hourly on one replica.
|
|
84
|
+
*
|
|
85
|
+
* At least once, not exactly once: a replica that dies after the server accepted the mail and before it recorded the
|
|
86
|
+
* delivery leaves a claim another replica takes over and sends again — with the same Message-ID.
|
|
87
|
+
*
|
|
88
|
+
* Extend it and register the subclass with `CoreModule.forRoot(env, { mailOutbox: { service } })` — e.g. override
|
|
89
|
+
* `retryDelayMs()` for another backoff.
|
|
90
|
+
*/
|
|
91
|
+
@Injectable()
|
|
92
|
+
export class CoreMailOutboxService implements MailOutbox, OnApplicationBootstrap, OnModuleDestroy, OnModuleInit {
|
|
93
|
+
protected readonly logger = new Logger(CoreMailOutboxService.name);
|
|
94
|
+
/** The claim owner of this replica */
|
|
95
|
+
protected readonly owner = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
|
96
|
+
protected readonly settings: ResolvedMailOutboxSettings;
|
|
97
|
+
protected delivering?: Promise<number>;
|
|
98
|
+
/** A mail arrived while a run was busy: run once more afterwards */
|
|
99
|
+
protected deliverAgain = false;
|
|
100
|
+
protected pollTimer?: ReturnType<typeof setInterval>;
|
|
101
|
+
protected purge?: LeasedInterval;
|
|
102
|
+
protected stopped = false;
|
|
103
|
+
/** How often the retention purge runs; a subclass may change it */
|
|
104
|
+
protected purgeIntervalMs = MAIL_OUTBOX_DEFAULTS.purgeIntervalMs;
|
|
105
|
+
|
|
106
|
+
constructor(
|
|
107
|
+
@InjectStore(MAIL_OUTBOX_MODEL) protected readonly store: DataStore<CoreMailOutboxEntry>,
|
|
108
|
+
protected readonly emailService: EmailService,
|
|
109
|
+
@Optional() protected readonly redisService?: CoreRedisService,
|
|
110
|
+
) {
|
|
111
|
+
this.settings = resolveMailOutboxSettings(this.config);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The `mailOutbox` configuration (an object; `true` reads as `{}`) */
|
|
115
|
+
protected get config(): IMailOutbox {
|
|
116
|
+
const value = ConfigService.configFastButReadOnly?.mailOutbox;
|
|
117
|
+
return value && typeof value === 'object' ? value : {};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
onModuleInit(): void {
|
|
121
|
+
// In module init: a mail another module's bootstrap sends (the initial admin, a seed) goes through the outbox too
|
|
122
|
+
setMailOutbox(this);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
onApplicationBootstrap(): void {
|
|
126
|
+
this.logger.log(
|
|
127
|
+
`Mail outbox active: up to ${this.settings.maxAttempts} attempts, retries from ${this.settings.retryDelaySeconds} s`,
|
|
128
|
+
);
|
|
129
|
+
this.pollTimer = setInterval(() => this.kick(), this.settings.pollIntervalSeconds * 1000);
|
|
130
|
+
this.pollTimer.unref?.();
|
|
131
|
+
// Mails left over from a previous run (a restart, an outage) go out now, not at the first poll
|
|
132
|
+
this.kick();
|
|
133
|
+
if (this.settings.sentDays !== false || this.settings.failedDays !== false) {
|
|
134
|
+
this.purge = new LeasedInterval({
|
|
135
|
+
intervalMs: this.purgeIntervalMs,
|
|
136
|
+
lease: () => frameworkJobLeaseStore(this.redisService, 'mail-outbox'),
|
|
137
|
+
name: 'MailOutboxPurge',
|
|
138
|
+
run: () => this.purgeExpired(),
|
|
139
|
+
});
|
|
140
|
+
this.purge.start();
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async onModuleDestroy(): Promise<void> {
|
|
145
|
+
this.stopped = true;
|
|
146
|
+
if (getMailOutbox() === this) {
|
|
147
|
+
setMailOutbox(undefined);
|
|
148
|
+
}
|
|
149
|
+
if (this.pollTimer) {
|
|
150
|
+
clearInterval(this.pollTimer);
|
|
151
|
+
this.pollTimer = undefined;
|
|
152
|
+
}
|
|
153
|
+
await this.purge?.stop();
|
|
154
|
+
// A send in progress finishes and records its outcome; nothing new is claimed
|
|
155
|
+
await this.delivering?.catch(() => undefined);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ===================================================================================================================
|
|
159
|
+
// Storing
|
|
160
|
+
// ===================================================================================================================
|
|
161
|
+
|
|
162
|
+
/** Store a rendered mail and start its delivery; resolves once it is stored */
|
|
163
|
+
async enqueue(mail: QueuedSmtpMail): Promise<QueuedMailReceipt> {
|
|
164
|
+
const now = new Date();
|
|
165
|
+
const entry = await this.store.insert({
|
|
166
|
+
attempts: 0,
|
|
167
|
+
mail,
|
|
168
|
+
nextAttemptAt: now,
|
|
169
|
+
queuedAt: now,
|
|
170
|
+
status: MAIL_OUTBOX_STATUS.pending,
|
|
171
|
+
subject: mail.subject,
|
|
172
|
+
to: mail.to,
|
|
173
|
+
});
|
|
174
|
+
this.kick();
|
|
175
|
+
return { id: entry.id, messageId: this.messageIdOf(entry.id, mail.from) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The Message-ID of a stored mail — the same on every attempt */
|
|
179
|
+
protected messageIdOf(id: string, from: string): string {
|
|
180
|
+
const domain = /@([^>\s]+)>?\s*$/.exec(from ?? '')?.[1] || 'localhost';
|
|
181
|
+
return `<${id}.outbox@${domain}>`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ===================================================================================================================
|
|
185
|
+
// Delivering
|
|
186
|
+
// ===================================================================================================================
|
|
187
|
+
|
|
188
|
+
/** Start a delivery run unless one is running (then it runs once more afterwards). Never rejects. */
|
|
189
|
+
kick(): void {
|
|
190
|
+
if (this.stopped) {
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (this.delivering) {
|
|
194
|
+
this.deliverAgain = true;
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
this.delivering = this.deliverDue()
|
|
198
|
+
.then((attempted) => {
|
|
199
|
+
// A full batch leaves due mails behind: deliver them now instead of at the next poll
|
|
200
|
+
if (attempted >= MAIL_OUTBOX_BATCH) {
|
|
201
|
+
this.deliverAgain = true;
|
|
202
|
+
}
|
|
203
|
+
return attempted;
|
|
204
|
+
})
|
|
205
|
+
.catch((error) => {
|
|
206
|
+
this.logger.warn(`Mail outbox delivery failed, trying again later: ${(error as Error)?.message ?? error}`);
|
|
207
|
+
return 0;
|
|
208
|
+
})
|
|
209
|
+
.finally(() => {
|
|
210
|
+
this.delivering = undefined;
|
|
211
|
+
if (this.deliverAgain) {
|
|
212
|
+
this.deliverAgain = false;
|
|
213
|
+
this.kick();
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Resolves once no delivery run of this replica is busy (tests, shutdown) */
|
|
219
|
+
async whenIdle(): Promise<void> {
|
|
220
|
+
while (this.delivering) {
|
|
221
|
+
await this.delivering.catch(() => undefined);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Deliver the due mails this replica can claim, up to a batch; answers how many were attempted */
|
|
226
|
+
async deliverDue(): Promise<number> {
|
|
227
|
+
let attempted = 0;
|
|
228
|
+
while (attempted < MAIL_OUTBOX_BATCH && !this.stopped) {
|
|
229
|
+
const entry = await this.claimNext();
|
|
230
|
+
if (!entry) {
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
attempted++;
|
|
234
|
+
await this.deliver(entry);
|
|
235
|
+
}
|
|
236
|
+
return attempted;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Claim the next due mail — one atomic statement, so of two replicas exactly one gets it: a pending mail whose time
|
|
241
|
+
* has come, or one whose claim expired (its replica died mid-send)
|
|
242
|
+
*/
|
|
243
|
+
protected async claimNext(): Promise<CoreMailOutboxEntry | null> {
|
|
244
|
+
const now = new Date();
|
|
245
|
+
return (await this.store.updateOne(
|
|
246
|
+
{
|
|
247
|
+
$or: [
|
|
248
|
+
{ nextAttemptAt: { $lte: now }, status: MAIL_OUTBOX_STATUS.pending },
|
|
249
|
+
{ lockedUntil: { $lte: now }, status: MAIL_OUTBOX_STATUS.sending },
|
|
250
|
+
],
|
|
251
|
+
} as Where<CoreMailOutboxEntry>,
|
|
252
|
+
{
|
|
253
|
+
$inc: { attempts: 1 },
|
|
254
|
+
$set: {
|
|
255
|
+
lastAttemptAt: now,
|
|
256
|
+
lockedBy: this.owner,
|
|
257
|
+
lockedUntil: new Date(now.getTime() + this.settings.lockSeconds * 1000),
|
|
258
|
+
status: MAIL_OUTBOX_STATUS.sending,
|
|
259
|
+
},
|
|
260
|
+
},
|
|
261
|
+
)) as CoreMailOutboxEntry | null;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Send one claimed mail and record the outcome */
|
|
265
|
+
protected async deliver(entry: CoreMailOutboxEntry): Promise<void> {
|
|
266
|
+
try {
|
|
267
|
+
if (!entry.mail) {
|
|
268
|
+
throw new Error('the stored mail has no content');
|
|
269
|
+
}
|
|
270
|
+
await this.emailService.deliverQueuedMail(entry.mail, this.messageIdOf(entry.id, entry.mail.from));
|
|
271
|
+
} catch (error) {
|
|
272
|
+
await this.recordFailure(entry, error);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
const recorded = await this.store.updateOne(
|
|
276
|
+
{ id: entry.id, lockedBy: this.owner, status: MAIL_OUTBOX_STATUS.sending } as Where<CoreMailOutboxEntry>,
|
|
277
|
+
{
|
|
278
|
+
$set: { lastError: '', mail: null, sentAt: new Date(), status: MAIL_OUTBOX_STATUS.sent },
|
|
279
|
+
$unset: { lockedBy: '', lockedUntil: '' },
|
|
280
|
+
},
|
|
281
|
+
);
|
|
282
|
+
if (!recorded) {
|
|
283
|
+
this.logger.warn(
|
|
284
|
+
`Mail "${entry.subject}" was delivered after its claim expired — another replica may deliver it again ` +
|
|
285
|
+
'(raise mailOutbox.lockSeconds above the SMTP timeouts)',
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** A failed attempt: another one after the backoff, or `failed` after the last */
|
|
291
|
+
protected async recordFailure(entry: CoreMailOutboxEntry, error: unknown): Promise<void> {
|
|
292
|
+
const message = String((error as Error)?.message ?? error).slice(0, MAIL_OUTBOX_ERROR_LENGTH);
|
|
293
|
+
const recipients = (entry.to ?? []).map(maskEmail).join(', ');
|
|
294
|
+
const final = entry.attempts >= this.settings.maxAttempts;
|
|
295
|
+
const nextAttemptAt = new Date(Date.now() + this.retryDelayMs(entry.attempts));
|
|
296
|
+
await this.store.updateOne({ id: entry.id, lockedBy: this.owner } as Where<CoreMailOutboxEntry>, {
|
|
297
|
+
$set: final
|
|
298
|
+
? { lastError: message, status: MAIL_OUTBOX_STATUS.failed }
|
|
299
|
+
: { lastError: message, nextAttemptAt, status: MAIL_OUTBOX_STATUS.pending },
|
|
300
|
+
$unset: { lockedBy: '', lockedUntil: '' },
|
|
301
|
+
});
|
|
302
|
+
if (final) {
|
|
303
|
+
this.logger.error(
|
|
304
|
+
`Mail "${entry.subject}" to ${recipients} failed for good after ${entry.attempts} attempt(s): ${message}`,
|
|
305
|
+
);
|
|
306
|
+
} else {
|
|
307
|
+
this.logger.warn(
|
|
308
|
+
`Mail "${entry.subject}" to ${recipients}: attempt ${entry.attempts} of ${this.settings.maxAttempts} failed ` +
|
|
309
|
+
`(${message}), next at ${nextAttemptAt.toISOString()}`,
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Delay before the attempt after `attempts` failed ones: `retryDelaySeconds` doubled per attempt, capped */
|
|
315
|
+
protected retryDelayMs(attempts: number): number {
|
|
316
|
+
const seconds = this.settings.retryDelaySeconds * 2 ** Math.max(0, attempts - 1);
|
|
317
|
+
return Math.min(seconds, this.settings.maxRetryDelaySeconds) * 1000;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ===================================================================================================================
|
|
321
|
+
// Administration
|
|
322
|
+
// ===================================================================================================================
|
|
323
|
+
|
|
324
|
+
/** Stored mails without their content, newest first, and how many there are in all */
|
|
325
|
+
async list(query: MailOutboxQuery = {}): Promise<{ items: MailOutboxOverview[]; total: number }> {
|
|
326
|
+
const where: Where<CoreMailOutboxEntry> =
|
|
327
|
+
query.status && (Object.values(MAIL_OUTBOX_STATUS) as string[]).includes(query.status)
|
|
328
|
+
? { status: query.status }
|
|
329
|
+
: {};
|
|
330
|
+
const limit = Math.min(500, Number.isInteger(query.limit) && query.limit! > 0 ? query.limit! : 50);
|
|
331
|
+
const offset = Number.isInteger(query.offset) && query.offset! > 0 ? query.offset! : 0;
|
|
332
|
+
const [items, total] = await Promise.all([
|
|
333
|
+
this.store.find(where, { exclude: ['mail'], limit, skip: offset, sort: { queuedAt: -1 } }),
|
|
334
|
+
this.store.count(where),
|
|
335
|
+
]);
|
|
336
|
+
return { items: items as MailOutboxOverview[], total };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Give a failed mail a new round of attempts; `null` when there is no failed mail with this id */
|
|
340
|
+
async retry(id: string): Promise<MailOutboxOverview | null> {
|
|
341
|
+
const entry = await this.store.updateOne({ id, status: MAIL_OUTBOX_STATUS.failed } as Where<CoreMailOutboxEntry>, {
|
|
342
|
+
$set: { attempts: 0, nextAttemptAt: new Date(), status: MAIL_OUTBOX_STATUS.pending },
|
|
343
|
+
});
|
|
344
|
+
if (!entry) {
|
|
345
|
+
return null;
|
|
346
|
+
}
|
|
347
|
+
this.kick();
|
|
348
|
+
const { mail: _content, ...overview } = entry as CoreMailOutboxEntry;
|
|
349
|
+
return overview;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Remove delivered mails older than `retention.sentDays` and failed ones older than `retention.failedDays`, in
|
|
354
|
+
* batches by id. Runs hourly on one replica; answers how many entries were removed.
|
|
355
|
+
*/
|
|
356
|
+
async purgeExpired(now = new Date()): Promise<number> {
|
|
357
|
+
let removed = 0;
|
|
358
|
+
const { failedDays, sentDays } = this.settings;
|
|
359
|
+
if (sentDays !== false) {
|
|
360
|
+
removed += await this.purgeWhere({
|
|
361
|
+
sentAt: { $lt: new Date(now.getTime() - sentDays * 86_400_000) },
|
|
362
|
+
status: MAIL_OUTBOX_STATUS.sent,
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
if (failedDays !== false) {
|
|
366
|
+
removed += await this.purgeWhere({
|
|
367
|
+
lastAttemptAt: { $lt: new Date(now.getTime() - failedDays * 86_400_000) },
|
|
368
|
+
status: MAIL_OUTBOX_STATUS.failed,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
if (removed) {
|
|
372
|
+
this.logger.log(`Mail outbox: ${removed} entr${removed === 1 ? 'y' : 'ies'} past the retention removed`);
|
|
373
|
+
}
|
|
374
|
+
return removed;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
protected async purgeWhere(where: Where<CoreMailOutboxEntry>): Promise<number> {
|
|
378
|
+
let removed = 0;
|
|
379
|
+
for (;;) {
|
|
380
|
+
const batch = await this.store.find(where, { limit: MAIL_OUTBOX_PURGE_BATCH, select: ['id'] });
|
|
381
|
+
if (!batch.length) {
|
|
382
|
+
return removed;
|
|
383
|
+
}
|
|
384
|
+
removed += await this.store.deleteMany({ ...where, id: { $in: batch.map((entry) => entry.id) } });
|
|
385
|
+
if (batch.length < MAIL_OUTBOX_PURGE_BATCH) {
|
|
386
|
+
return removed;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
@@ -529,7 +529,10 @@ This template automatically imports `getDb()` and `uploadFileToGridFS()` from ne
|
|
|
529
529
|
**Vendor mode (12.0.0+):** a project with the core vendored into `src/core/` has no `@lenne.tech/nest-server` package, so
|
|
530
530
|
`migrate create` rewrites the template's `'@lenne.tech/nest-server'` import to the relative path from the migrations
|
|
531
531
|
directory to the vendored core (e.g. `'../src/core'`). It does so only when the package does not resolve from the
|
|
532
|
-
project and the core it runs from has its own `index`; in npm mode the template is written unchanged.
|
|
532
|
+
project and the core it runs from has its own `index`; in npm mode the template is written unchanged. In an ES module
|
|
533
|
+
project (`"type": "module"` in the package scope of the migrations directory) the path names the entry file,
|
|
534
|
+
`'../src/core/index.js'`, because ESM resolves no directory (12.12.0; before, `migrate up` stopped with
|
|
535
|
+
`ERR_UNSUPPORTED_DIR_IMPORT`). The same applies to `migrate create --sql`.
|
|
533
536
|
|
|
534
537
|
### TypeScript Loader
|
|
535
538
|
|
|
@@ -62,6 +62,12 @@ const FRAMEWORK_PACKAGE = '@lenne.tech/nest-server';
|
|
|
62
62
|
* In npm mode the package resolves, and in this framework repo `src/core/` has no `index`, so neither
|
|
63
63
|
* is rewritten.
|
|
64
64
|
*
|
|
65
|
+
* In an ES module project (`"type": "module"` in the package scope of the migrations directory, the
|
|
66
|
+
* starter's format since 12.0.0) the path names the entry file, `<core>/index.js`: ESM resolves no
|
|
67
|
+
* directory (ERR_UNSUPPORTED_DIR_IMPORT at `migrate up`), and the TypeScript loader maps `.js` to the
|
|
68
|
+
* `index.ts` of a source run. A CommonJS project keeps the directory, so its migrations stay as they
|
|
69
|
+
* were — a loader that maps no `.js` to `.ts` under `require()` (ts-node) keeps working there.
|
|
70
|
+
*
|
|
65
71
|
* @param migrationsDir - Directory the migration is written to, absolute or relative to `cwd`
|
|
66
72
|
* @param cwd - Project directory the package is resolved from
|
|
67
73
|
* @param coreRoot - Root of the core this CLI belongs to
|
|
@@ -80,8 +86,30 @@ export function vendoredFrameworkSpecifier(
|
|
|
80
86
|
if (!['index.ts', 'index.js'].some((entry) => fs.existsSync(path.join(coreRoot, entry)))) {
|
|
81
87
|
return undefined;
|
|
82
88
|
}
|
|
83
|
-
const
|
|
84
|
-
|
|
89
|
+
const absoluteMigrationsDir = path.resolve(cwd, migrationsDir);
|
|
90
|
+
const relativePath = path.relative(absoluteMigrationsDir, coreRoot).split(path.sep).join('/');
|
|
91
|
+
const directory = relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
|
|
92
|
+
return isEsModuleScope(absoluteMigrationsDir) ? `${directory}/index.js` : directory;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Whether files in `directory` are ES modules: the `type` of the nearest `package.json` above it, as Node decides.
|
|
97
|
+
* No `package.json`, or one that cannot be read, means CommonJS (Node's default).
|
|
98
|
+
*/
|
|
99
|
+
function isEsModuleScope(directory: string): boolean {
|
|
100
|
+
for (let dir = directory; ; dir = path.dirname(dir)) {
|
|
101
|
+
const manifest = path.join(dir, 'package.json');
|
|
102
|
+
if (fs.existsSync(manifest)) {
|
|
103
|
+
try {
|
|
104
|
+
return JSON.parse(fs.readFileSync(manifest, 'utf-8'))?.type === 'module';
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (path.dirname(dir) === dir) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
85
113
|
}
|
|
86
114
|
|
|
87
115
|
/**
|
|
@@ -103,6 +103,10 @@ Creates the initial admin user. Only works when zero users exist, and only where
|
|
|
103
103
|
| `password` | string | Yes | Minimum 8 characters |
|
|
104
104
|
| `name` | string | No | Defaults to email prefix |
|
|
105
105
|
|
|
106
|
+
On a project that signs in through a provider alone (`betterAuth.emailAndPassword.enabled: false`) the password is
|
|
107
|
+
required as well but cannot be used for signing in; the administrator signs in through the provider, which must report
|
|
108
|
+
the address as verified. See "The first administrator" in `src/core/modules/better-auth/README.md`.
|
|
109
|
+
|
|
106
110
|
**Success Response (201):**
|
|
107
111
|
|
|
108
112
|
```json
|
|
@@ -194,12 +194,12 @@ See the module README: "Removing a Tenant".
|
|
|
194
194
|
- [ ] Admin user can access any tenant (if adminBypass: true)
|
|
195
195
|
- [ ] Non-member gets 403 `#LTNS_0103: Not a member of this tenant`
|
|
196
196
|
- [ ] Unauthenticated + header → 401 `#LTNS_0100` (re-authentication is the remedy, so it is not a 403)
|
|
197
|
-
- [ ] Public endpoint accessing tenantId-schema without context
|
|
197
|
+
- [ ] Public endpoint accessing tenantId-schema without context is refused by the Safety Net: 401 without a session (an expired one included), 403 when signed in
|
|
198
198
|
- [ ] IAM endpoints work without `X-Tenant-Id` header when `skipTenantCheck: true` (default)
|
|
199
199
|
|
|
200
200
|
## Security
|
|
201
201
|
|
|
202
|
-
> **Defense-in-Depth:** The guard validates membership and sets `req.tenantId`. The Mongoose plugin only uses this validated value (via RequestContext) — never the raw header. Additionally, the plugin's Safety Net
|
|
202
|
+
> **Defense-in-Depth:** The guard validates membership and sets `req.tenantId`. The Mongoose plugin only uses this validated value (via RequestContext) — never the raw header. Additionally, the plugin's Safety Net refuses access to a tenantId-scoped schema without valid tenant context (401 when nobody is signed in, 403 otherwise).
|
|
203
203
|
|
|
204
204
|
> **Tenant overrides user.roles:** When a tenant header is present, only `membership.role` is checked. `user.roles` is ignored (except ADMIN bypass). This prevents users from claiming higher privileges via `user.roles` when operating within a specific tenant.
|
|
205
205
|
|
|
@@ -213,7 +213,7 @@ See the module README: "Removing a Tenant".
|
|
|
213
213
|
| Forgetting `X-Tenant-Id` header | 403 or Safety Net exception | Add header to all tenant-scoped API calls |
|
|
214
214
|
| Using only `@Roles(S_USER)` for tenant endpoints | No tenant membership check | Use `@Roles(DefaultHR.MEMBER)` for tenant-level access |
|
|
215
215
|
| Querying membership without bypass | Empty results due to tenant filter | Use `RequestContext.runWithBypassTenantGuard()` |
|
|
216
|
-
| Public endpoint accessing tenantId-schema | 403 Safety Net exception
|
|
216
|
+
| Public endpoint accessing tenantId-schema | 401 / 403 Safety Net exception | Use `@SkipTenantCheck()` + `RequestContext.runWithBypassTenantGuard()` |
|
|
217
217
|
| Passing user-supplied tenantId to create() | Cross-tenant write possible | Let plugin auto-set tenantId from context |
|
|
218
218
|
| Custom hierarchy doesn't match config | Roles fail unexpectedly | Ensure `createHierarchyRoles()` input matches `multiTenancy.roleHierarchy` |
|
|
219
219
|
| `@SkipTenantCheck()` on BetterAuth handler | Redundant since v11.21.2 | Remove — auto-skip handles this via `betterAuth.skipTenantCheck` (default) |
|
|
@@ -24,7 +24,7 @@ Request + X-Tenant-Id Header
|
|
|
24
24
|
**Defense-in-depth:** Two layers of protection:
|
|
25
25
|
|
|
26
26
|
1. **Guard level:** CoreTenantGuard validates membership and sets `tenantId` (only after successful check)
|
|
27
|
-
2. **Plugin level:** Safety Net —
|
|
27
|
+
2. **Plugin level:** Safety Net — refuses access to a tenantId-scoped schema without valid tenant context: 401 when nobody is signed in (since 12.11.3 — an expired session must reach the sign-in), 403 for a signed-in caller
|
|
28
28
|
|
|
29
29
|
## Configuration
|
|
30
30
|
|
|
@@ -309,8 +309,8 @@ anonymous caller of a public route through.
|
|
|
309
309
|
|
|
310
310
|
| User State | Filter Applied |
|
|
311
311
|
| ----------------------------------------------------- | ------------------------------------------------------------------- |
|
|
312
|
-
| Not authenticated, no context | Safety Net: `
|
|
313
|
-
| Authenticated, no memberships | Safety Net: `ForbiddenException` on tenantId-schemas
|
|
312
|
+
| Not authenticated, no context | Safety Net: 401 `UnauthorizedException` on tenantId-schemas |
|
|
313
|
+
| Authenticated, no memberships | Safety Net: 403 `ForbiddenException` on tenantId-schemas |
|
|
314
314
|
| Authenticated, has memberships | `{ tenantId: { $in: [user's tenant IDs] } }` |
|
|
315
315
|
| Authenticated + hierarchy role | `{ tenantId: { $in: [qualified tenant IDs] } }` (filtered by level) |
|
|
316
316
|
| Admin without header | No filter (sees all data via `isAdminBypass`) |
|
|
@@ -442,7 +442,7 @@ For high-frequency endpoints that don't access tenant-scoped data, use `@SkipTen
|
|
|
442
442
|
|
|
443
443
|
## Security Notes
|
|
444
444
|
|
|
445
|
-
> **Defense-in-Depth:** The Mongoose tenant plugin uses `tenantId` from `RequestContext`, which is only set by `CoreTenantGuard` after successful membership validation. The raw `X-Tenant-Id` header is **never** used directly for filtering. Even if the guard is bypassed (e.g., via `@SkipTenantCheck()`), the plugin's Safety Net
|
|
445
|
+
> **Defense-in-Depth:** The Mongoose tenant plugin uses `tenantId` from `RequestContext`, which is only set by `CoreTenantGuard` after successful membership validation. The raw `X-Tenant-Id` header is **never** used directly for filtering. Even if the guard is bypassed (e.g., via `@SkipTenantCheck()`), the plugin's Safety Net refuses access to a tenantId-scoped schema without valid tenant context (401 when nobody is signed in, 403 otherwise).
|
|
446
446
|
|
|
447
447
|
> **Explicit tenantId on writes:** The plugin only auto-sets `tenantId` on new documents when no explicit value is provided. Service-layer code that accepts user-supplied `tenantId` as a creation parameter could allow cross-tenant writes. Never pass user-supplied `tenantId` directly to `create()` or `new Model()`.
|
|
448
448
|
|