@lenne.tech/nest-server 12.11.3 → 12.12.1

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 (132) hide show
  1. package/.claude/rules/architecture.md +3 -0
  2. package/.claude/rules/configurable-features.md +6 -0
  3. package/.claude/rules/package-management.md +6 -4
  4. package/.claude/rules/testing.md +8 -7
  5. package/CLAUDE.md +2 -1
  6. package/FRAMEWORK-API.md +15 -1
  7. package/dist/core/common/decorators/common-error.decorator.d.ts +1 -1
  8. package/dist/core/common/helpers/cookies.helper.js +5 -2
  9. package/dist/core/common/helpers/cookies.helper.js.map +1 -1
  10. package/dist/core/common/interfaces/server-options.interface.d.ts +54 -0
  11. package/dist/core/common/persistence/audit-log.registry.d.ts +19 -0
  12. package/dist/core/common/persistence/audit-log.registry.js +84 -0
  13. package/dist/core/common/persistence/audit-log.registry.js.map +1 -0
  14. package/dist/core/common/services/core-trust-proxy.initializer.js +1 -1
  15. package/dist/core/common/services/core-trust-proxy.initializer.js.map +1 -1
  16. package/dist/core/common/services/crud.service.d.ts +10 -0
  17. package/dist/core/common/services/crud.service.js +79 -24
  18. package/dist/core/common/services/crud.service.js.map +1 -1
  19. package/dist/core/common/services/email.service.d.ts +5 -0
  20. package/dist/core/common/services/email.service.js +82 -6
  21. package/dist/core/common/services/email.service.js.map +1 -1
  22. package/dist/core/common/services/leased-interval.d.ts +22 -0
  23. package/dist/core/common/services/leased-interval.js +81 -0
  24. package/dist/core/common/services/leased-interval.js.map +1 -0
  25. package/dist/core/common/services/mail-outbox.registry.d.ts +26 -0
  26. package/dist/core/common/services/mail-outbox.registry.js +8 -0
  27. package/dist/core/common/services/mail-outbox.registry.js.map +1 -0
  28. package/dist/core/modules/audit-log/audited.decorator.d.ts +2 -0
  29. package/dist/core/modules/audit-log/audited.decorator.js +10 -0
  30. package/dist/core/modules/audit-log/audited.decorator.js.map +1 -0
  31. package/dist/core/modules/audit-log/core-audit-log.constants.d.ts +13 -0
  32. package/dist/core/modules/audit-log/core-audit-log.constants.js +11 -0
  33. package/dist/core/modules/audit-log/core-audit-log.constants.js.map +1 -0
  34. package/dist/core/modules/audit-log/core-audit-log.controller.d.ts +9 -0
  35. package/dist/core/modules/audit-log/core-audit-log.controller.js +87 -0
  36. package/dist/core/modules/audit-log/core-audit-log.controller.js.map +1 -0
  37. package/dist/core/modules/audit-log/core-audit-log.models.d.ts +10 -0
  38. package/dist/core/modules/audit-log/core-audit-log.models.js +11 -0
  39. package/dist/core/modules/audit-log/core-audit-log.models.js.map +1 -0
  40. package/dist/core/modules/audit-log/core-audit-log.module.d.ts +13 -0
  41. package/dist/core/modules/audit-log/core-audit-log.module.js +41 -0
  42. package/dist/core/modules/audit-log/core-audit-log.module.js.map +1 -0
  43. package/dist/core/modules/audit-log/core-audit-log.service.d.ts +49 -0
  44. package/dist/core/modules/audit-log/core-audit-log.service.js +169 -0
  45. package/dist/core/modules/audit-log/core-audit-log.service.js.map +1 -0
  46. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js +4 -0
  47. package/dist/core/modules/better-auth/core-better-auth-email-verification.service.js.map +1 -1
  48. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.d.ts +22 -0
  49. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js +23 -0
  50. package/dist/core/modules/mail-outbox/core-mail-outbox.constants.js.map +1 -0
  51. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.d.ts +10 -0
  52. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js +80 -0
  53. package/dist/core/modules/mail-outbox/core-mail-outbox.controller.js.map +1 -0
  54. package/dist/core/modules/mail-outbox/core-mail-outbox.models.d.ts +17 -0
  55. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js +17 -0
  56. package/dist/core/modules/mail-outbox/core-mail-outbox.models.js.map +1 -0
  57. package/dist/core/modules/mail-outbox/core-mail-outbox.module.d.ts +12 -0
  58. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js +42 -0
  59. package/dist/core/modules/mail-outbox/core-mail-outbox.module.js.map +1 -0
  60. package/dist/core/modules/mail-outbox/core-mail-outbox.service.d.ts +59 -0
  61. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js +280 -0
  62. package/dist/core/modules/mail-outbox/core-mail-outbox.service.js.map +1 -0
  63. package/dist/core/modules/migrate/cli/migrate-cli.js +38 -2
  64. package/dist/core/modules/migrate/cli/migrate-cli.js.map +1 -1
  65. package/dist/core/modules/throttler/core-throttler.config.d.ts +16 -0
  66. package/dist/core/modules/throttler/core-throttler.config.js +107 -0
  67. package/dist/core/modules/throttler/core-throttler.config.js.map +1 -0
  68. package/dist/core/modules/throttler/core-throttler.constants.d.ts +11 -0
  69. package/dist/core/modules/throttler/core-throttler.constants.js +35 -0
  70. package/dist/core/modules/throttler/core-throttler.constants.js.map +1 -0
  71. package/dist/core/modules/throttler/core-throttler.decorators.d.ts +1 -0
  72. package/dist/core/modules/throttler/core-throttler.decorators.js +2 -0
  73. package/dist/core/modules/throttler/core-throttler.decorators.js.map +1 -0
  74. package/dist/core/modules/throttler/core-throttler.guard.d.ts +15 -0
  75. package/dist/core/modules/throttler/core-throttler.guard.js +65 -0
  76. package/dist/core/modules/throttler/core-throttler.guard.js.map +1 -0
  77. package/dist/core/modules/throttler/core-throttler.models.d.ts +1 -0
  78. package/dist/core/modules/throttler/core-throttler.models.js +11 -0
  79. package/dist/core/modules/throttler/core-throttler.models.js.map +1 -0
  80. package/dist/core/modules/throttler/core-throttler.module.d.ts +12 -0
  81. package/dist/core/modules/throttler/core-throttler.module.js +71 -0
  82. package/dist/core/modules/throttler/core-throttler.module.js.map +1 -0
  83. package/dist/core/modules/throttler/core-throttler.storages.d.ts +43 -0
  84. package/dist/core/modules/throttler/core-throttler.storages.js +174 -0
  85. package/dist/core/modules/throttler/core-throttler.storages.js.map +1 -0
  86. package/dist/core/modules/user/core-user.service.js +2 -2
  87. package/dist/core/modules/user/core-user.service.js.map +1 -1
  88. package/dist/core.module.js +26 -0
  89. package/dist/core.module.js.map +1 -1
  90. package/dist/index.d.ts +21 -0
  91. package/dist/index.js +21 -0
  92. package/dist/index.js.map +1 -1
  93. package/docs/REQUEST-LIFECYCLE.md +7 -0
  94. package/docs/security-overrides.md +20 -8
  95. package/migration-guides/12.11.x-to-12.12.x.md +187 -0
  96. package/migration-guides/12.12.0-to-12.12.1.md +100 -0
  97. package/package.json +24 -23
  98. package/src/core/common/helpers/cookies.helper.ts +12 -2
  99. package/src/core/common/interfaces/server-options.interface.ts +311 -1
  100. package/src/core/common/persistence/audit-log.registry.ts +150 -0
  101. package/src/core/common/services/core-trust-proxy.initializer.ts +5 -4
  102. package/src/core/common/services/crud.service.ts +128 -33
  103. package/src/core/common/services/email.service.ts +101 -9
  104. package/src/core/common/services/leased-interval.ts +123 -0
  105. package/src/core/common/services/mail-outbox.registry.ts +53 -0
  106. package/src/core/modules/audit-log/README.md +95 -0
  107. package/src/core/modules/audit-log/audited.decorator.ts +27 -0
  108. package/src/core/modules/audit-log/core-audit-log.constants.ts +28 -0
  109. package/src/core/modules/audit-log/core-audit-log.controller.ts +77 -0
  110. package/src/core/modules/audit-log/core-audit-log.models.ts +34 -0
  111. package/src/core/modules/audit-log/core-audit-log.module.ts +54 -0
  112. package/src/core/modules/audit-log/core-audit-log.service.ts +270 -0
  113. package/src/core/modules/better-auth/core-better-auth-email-verification.service.ts +4 -0
  114. package/src/core/modules/mail-outbox/README.md +88 -0
  115. package/src/core/modules/mail-outbox/core-mail-outbox.constants.ts +42 -0
  116. package/src/core/modules/mail-outbox/core-mail-outbox.controller.ts +60 -0
  117. package/src/core/modules/mail-outbox/core-mail-outbox.models.ts +46 -0
  118. package/src/core/modules/mail-outbox/core-mail-outbox.module.ts +52 -0
  119. package/src/core/modules/mail-outbox/core-mail-outbox.service.ts +390 -0
  120. package/src/core/modules/migrate/README.md +6 -1
  121. package/src/core/modules/migrate/cli/migrate-cli.ts +60 -2
  122. package/src/core/modules/throttler/README.md +115 -0
  123. package/src/core/modules/throttler/core-throttler.config.ts +162 -0
  124. package/src/core/modules/throttler/core-throttler.constants.ts +71 -0
  125. package/src/core/modules/throttler/core-throttler.decorators.ts +14 -0
  126. package/src/core/modules/throttler/core-throttler.guard.ts +109 -0
  127. package/src/core/modules/throttler/core-throttler.models.ts +23 -0
  128. package/src/core/modules/throttler/core-throttler.module.ts +95 -0
  129. package/src/core/modules/throttler/core-throttler.storages.ts +299 -0
  130. package/src/core/modules/user/core-user.service.ts +3 -2
  131. package/src/core.module.ts +46 -0
  132. package/src/index.ts +36 -0
@@ -0,0 +1,77 @@
1
+ import { BadRequestException, Controller, Get, Query } from '@nestjs/common';
2
+ import { ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
3
+
4
+ import { Roles } from '../../common/decorators/roles.decorator.js';
5
+ import { RoleEnum } from '../../common/enums/role.enum.js';
6
+ import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
7
+ import { CoreAuditLogService } from './core-audit-log.service.js';
8
+
9
+ /** A time from a query parameter, or `undefined`; an unreadable one is a 400, not a silently ignored filter */
10
+ function parseTime(value: string | undefined, name: string): Date | undefined {
11
+ if (value === undefined || value === '') {
12
+ return undefined;
13
+ }
14
+ const time = /^\d+$/.test(value) ? new Date(Number(value)) : new Date(value);
15
+ if (Number.isNaN(time.getTime())) {
16
+ throw new BadRequestException(`${name} must be an ISO date or a timestamp in milliseconds`);
17
+ }
18
+ return time;
19
+ }
20
+
21
+ /** A non-negative integer from a query parameter, or `undefined` */
22
+ function parseCount(value: string | undefined, name: string): number | undefined {
23
+ if (value === undefined || value === '') {
24
+ return undefined;
25
+ }
26
+ if (!/^\d+$/.test(value)) {
27
+ throw new BadRequestException(`${name} must be a non-negative integer`);
28
+ }
29
+ return Number(value);
30
+ }
31
+
32
+ /**
33
+ * Read endpoint of the audit log (`auditLog` config): `GET /audit-log` with the filters `model`, `recordId`, `userId`,
34
+ * `action`, `from`, `to` and the paging `limit` (at most 500) / `offset`, newest first.
35
+ *
36
+ * ADMIN only by default; `auditLog.roles` adds roles (applied at boot onto this class — a subclass that re-declares
37
+ * `@Roles()` keeps its own). The roles are GLOBAL roles (`@SkipTenantCheck()`): the log spans tenants.
38
+ */
39
+ @ApiTags('audit-log')
40
+ @Controller('audit-log')
41
+ @Roles(RoleEnum.ADMIN)
42
+ @SkipTenantCheck()
43
+ export class CoreAuditLogController {
44
+ constructor(protected readonly auditLogService: CoreAuditLogService) {}
45
+
46
+ @ApiOperation({ summary: 'Audit log entries (who, when, what — field names only), newest first' })
47
+ @ApiQuery({ name: 'model', required: false })
48
+ @ApiQuery({ name: 'recordId', required: false })
49
+ @ApiQuery({ name: 'userId', required: false })
50
+ @ApiQuery({ name: 'action', required: false })
51
+ @ApiQuery({ description: 'ISO date or timestamp (ms), inclusive', name: 'from', required: false })
52
+ @ApiQuery({ description: 'ISO date or timestamp (ms), exclusive', name: 'to', required: false })
53
+ @ApiQuery({ name: 'limit', required: false })
54
+ @ApiQuery({ name: 'offset', required: false })
55
+ @Get()
56
+ async find(
57
+ @Query('model') model?: string,
58
+ @Query('recordId') recordId?: string,
59
+ @Query('userId') userId?: string,
60
+ @Query('action') action?: string,
61
+ @Query('from') from?: string,
62
+ @Query('to') to?: string,
63
+ @Query('limit') limit?: string,
64
+ @Query('offset') offset?: string,
65
+ ) {
66
+ return this.auditLogService.find({
67
+ action,
68
+ from: parseTime(from, 'from'),
69
+ limit: parseCount(limit, 'limit'),
70
+ model,
71
+ offset: parseCount(offset, 'offset'),
72
+ recordId,
73
+ to: parseTime(to, 'to'),
74
+ userId,
75
+ });
76
+ }
77
+ }
@@ -0,0 +1,34 @@
1
+ import { createSchema } from '../../common/persistence/mongo/mongoose-compat.js';
2
+ import { AUDIT_LOG_COLLECTION } from './core-audit-log.constants.js';
3
+
4
+ /**
5
+ * The entries of the audit log as a framework model: registered with `CorePersistenceModule.forFeature()` only when
6
+ * `auditLog` is configured, it follows `database` like every other model — a collection on MongoDB, the table
7
+ * `audit_log_entries` on SQL.
8
+ *
9
+ * An entry says who (`userId`) did what (`action`) to which record (`model`, `recordId`) when (`at`), and which fields
10
+ * the write set or changed — by NAME. There is deliberately no field for a value: nothing a value carries can reach
11
+ * the log.
12
+ */
13
+ export const AuditLogEntrySchema = createSchema(
14
+ {
15
+ action: { index: true, type: String },
16
+ at: { index: true, type: Date },
17
+ fields: { default: [], type: [String] },
18
+ model: { index: true, type: String },
19
+ recordId: { index: true, type: String },
20
+ userId: { index: true, type: String },
21
+ },
22
+ { collection: AUDIT_LOG_COLLECTION, versionKey: false },
23
+ );
24
+
25
+ /** A stored entry */
26
+ export interface CoreAuditLogEntry {
27
+ action: string;
28
+ at: Date;
29
+ fields: string[];
30
+ id: string;
31
+ model: string;
32
+ recordId: string;
33
+ userId?: string;
34
+ }
@@ -0,0 +1,54 @@
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 { AUDIT_LOG_DEFAULTS, AUDIT_LOG_MODEL } from './core-audit-log.constants.js';
7
+ import { CoreAuditLogController } from './core-audit-log.controller.js';
8
+ import { AuditLogEntrySchema } from './core-audit-log.models.js';
9
+ import { CoreAuditLogService } from './core-audit-log.service.js';
10
+
11
+ /** Options of `CoreAuditLogModule.forRoot()` */
12
+ export interface CoreAuditLogModuleOptions {
13
+ /** Custom controller (must extend CoreAuditLogController) */
14
+ controller?: Type<CoreAuditLogController>;
15
+ /** Route prefix (`auditLog.path`) @default 'audit-log' */
16
+ path?: string;
17
+ /** Roles that may read, in addition to ADMIN (`auditLog.roles`) */
18
+ roles?: unknown;
19
+ /** Custom service (must extend CoreAuditLogService) */
20
+ service?: Type<CoreAuditLogService>;
21
+ }
22
+
23
+ /** ADMIN and the configured roles; anything that is not a list of strings leaves ADMIN alone */
24
+ export function resolveAuditLogRoles(roles: unknown): string[] {
25
+ const extra = Array.isArray(roles) ? roles.filter((role): role is string => typeof role === 'string' && !!role) : [];
26
+ return [...new Set([RoleEnum.ADMIN as string, ...extra])];
27
+ }
28
+
29
+ /**
30
+ * Audit log (`auditLog` config, DEV-4432). Registered automatically by `CoreModule.forRoot()` when `auditLog` is
31
+ * configured — without it there is no model, no collection or table, no route and no listener `CrudService` reports
32
+ * to. Provides the service (global, so a project's service can inject it to log its own actions), the read endpoint
33
+ * and the entry model, which follows `database` like every other model.
34
+ */
35
+ @Module({})
36
+ export class CoreAuditLogModule {
37
+ static forRoot(options: CoreAuditLogModuleOptions = {}): DynamicModule {
38
+ const controller = options.controller ?? CoreAuditLogController;
39
+ // The configured prefix and roles win over the class's declaration, as for the sync and TUS routes
40
+ Reflect.defineMetadata(PATH_METADATA, options.path || AUDIT_LOG_DEFAULTS.path, controller);
41
+ // A project controller that declares @Roles() itself keeps them: that is how a policy is pinned in code
42
+ if (controller === CoreAuditLogController || !Reflect.hasOwnMetadata('roles', controller)) {
43
+ Reflect.defineMetadata('roles', resolveAuditLogRoles(options.roles), controller);
44
+ }
45
+ return {
46
+ controllers: [controller],
47
+ exports: [CoreAuditLogService],
48
+ global: true,
49
+ imports: [CorePersistenceModule.forFeature([{ name: AUDIT_LOG_MODEL, schema: AuditLogEntrySchema }])],
50
+ module: CoreAuditLogModule,
51
+ providers: [options.service ? { provide: CoreAuditLogService, useClass: options.service } : CoreAuditLogService],
52
+ };
53
+ }
54
+ }
@@ -0,0 +1,270 @@
1
+ import { Injectable, Logger, OnApplicationBootstrap, OnModuleDestroy, OnModuleInit, Optional } from '@nestjs/common';
2
+
3
+ import type { IAuditLog } from '../../common/interfaces/server-options.interface.js';
4
+ import {
5
+ type AuditAction,
6
+ type AuditLogListener,
7
+ type AuditWrite,
8
+ getAuditLogListener,
9
+ setAuditLogListener,
10
+ } from '../../common/persistence/audit-log.registry.js';
11
+ import type { DataStore, Where } from '../../common/persistence/data-store.interface.js';
12
+ import { InjectStore } from '../../common/persistence/inject-store.decorator.js';
13
+ import { resolveAuditActorId } from '../../common/persistence/policies/audit.policy.js';
14
+ import { ConfigService } from '../../common/services/config.service.js';
15
+ import { CoreRedisService } from '../../common/services/core-redis.service.js';
16
+ import { frameworkJobLeaseStore, LeasedInterval } from '../../common/services/leased-interval.js';
17
+ import { isAuditedModelClass } from './audited.decorator.js';
18
+ import {
19
+ AUDIT_LOG_DEFAULTS,
20
+ AUDIT_LOG_MODEL,
21
+ AUDIT_LOG_PAGE,
22
+ AUDIT_LOG_PURGE_BATCH,
23
+ } from './core-audit-log.constants.js';
24
+ import type { CoreAuditLogEntry } from './core-audit-log.models.js';
25
+
26
+ /** A filter of {@link CoreAuditLogService.find} */
27
+ export interface AuditLogQuery {
28
+ action?: string;
29
+ /** Entries at or after this time */
30
+ from?: Date;
31
+ /** Page size, at most 500 @default 50 */
32
+ limit?: number;
33
+ model?: string;
34
+ /** Entries skipped (paging) */
35
+ offset?: number;
36
+ recordId?: string;
37
+ /** Entries before this time */
38
+ to?: Date;
39
+ userId?: string;
40
+ }
41
+
42
+ /** An entry of a project's own (`record()`) or of an import (`importEntries()`) */
43
+ export interface AuditLogEntryInput {
44
+ action: AuditAction;
45
+ /** When it happened — for `importEntries()`; `record()` uses the current time @default now */
46
+ at?: Date | number | string;
47
+ /** Names of the fields the action touched @default [] */
48
+ fields?: string[];
49
+ model: string;
50
+ recordId: string;
51
+ /** Who acted; `record()` takes the current user when not given */
52
+ userId?: string;
53
+ }
54
+
55
+ /** A non-empty trimmed string, or `undefined` */
56
+ function text(value: unknown): string | undefined {
57
+ if (
58
+ typeof value === 'number' ||
59
+ (typeof value === 'object' && value && typeof (value as any).toHexString === 'function')
60
+ ) {
61
+ return String(typeof value === 'number' ? value : (value as any).toHexString());
62
+ }
63
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
64
+ }
65
+
66
+ /**
67
+ * The audit log (`auditLog` config, DEV-4432): who created, changed, deleted or restored which record, and which
68
+ * fields a change touched — names only, never values.
69
+ *
70
+ * Registered by `CoreModule` when `auditLog` is configured. It registers itself as the listener `CrudService` reports
71
+ * its writes to (`audit-log.registry.ts`), so without the configuration nothing is reported and nothing is stored.
72
+ * Logged are the models whose class carries `@Audited()` and those named in `auditLog.models`.
73
+ *
74
+ * Extend it and register the subclass with `CoreModule.forRoot(env, { auditLog: { service } })` — e.g. override
75
+ * `isAudited()` to decide per model at runtime.
76
+ */
77
+ @Injectable()
78
+ export class CoreAuditLogService implements AuditLogListener, OnApplicationBootstrap, OnModuleDestroy, OnModuleInit {
79
+ protected readonly logger = new Logger(CoreAuditLogService.name);
80
+ /** Model names from `auditLog.models` */
81
+ protected readonly auditedNames: ReadonlySet<string>;
82
+ protected purge?: LeasedInterval;
83
+ /** How often the retention purge runs; a subclass may change it */
84
+ protected purgeIntervalMs = AUDIT_LOG_DEFAULTS.purgeIntervalMs;
85
+
86
+ constructor(
87
+ @InjectStore(AUDIT_LOG_MODEL) protected readonly store: DataStore<CoreAuditLogEntry>,
88
+ @Optional() protected readonly redisService?: CoreRedisService,
89
+ ) {
90
+ const models = this.config.models;
91
+ this.auditedNames = new Set(
92
+ (Array.isArray(models) ? models : []).filter((name): name is string => typeof name === 'string' && !!name.trim()),
93
+ );
94
+ }
95
+
96
+ /** The `auditLog` configuration (an object; `true` reads as `{}`) */
97
+ protected get config(): IAuditLog {
98
+ const value = ConfigService.configFastButReadOnly?.auditLog;
99
+ return value && typeof value === 'object' ? value : {};
100
+ }
101
+
102
+ onModuleInit(): void {
103
+ // In module init, not at bootstrap: a write another module's bootstrap makes (a seed, the initial admin) is logged
104
+ setAuditLogListener(this);
105
+ }
106
+
107
+ onApplicationBootstrap(): void {
108
+ const days = this.retentionDays();
109
+ this.logger.log(
110
+ `Audit log for ${this.auditedNames.size ? [...this.auditedNames].join(', ') : 'no configured model'} and every ` +
111
+ `model with @Audited(); entries kept ${days === false ? 'for good' : `${days} days`}`,
112
+ );
113
+ if (days !== false) {
114
+ this.purge = new LeasedInterval({
115
+ intervalMs: this.purgeIntervalMs,
116
+ lease: () => frameworkJobLeaseStore(this.redisService, 'audit-log'),
117
+ name: 'AuditLogPurge',
118
+ run: () => this.purgeExpired(),
119
+ });
120
+ this.purge.start();
121
+ }
122
+ }
123
+
124
+ async onModuleDestroy(): Promise<void> {
125
+ if (getAuditLogListener() === this) {
126
+ setAuditLogListener(undefined);
127
+ }
128
+ await this.purge?.stop();
129
+ }
130
+
131
+ // ===================================================================================================================
132
+ // Writing
133
+ // ===================================================================================================================
134
+
135
+ /** Whether writes of the model are logged: named in `auditLog.models`, or its class carries `@Audited()` */
136
+ isAudited(model: string, modelClass?: Function): boolean {
137
+ return this.auditedNames.has(model) || isAuditedModelClass(modelClass);
138
+ }
139
+
140
+ /** Store one write reported by `CrudService` */
141
+ async recordWrite(write: AuditWrite): Promise<void> {
142
+ await this.store.insert(this.toEntry({ ...write, at: new Date() }, false));
143
+ }
144
+
145
+ /**
146
+ * Log an action of a project's own — a restore, an export, a status change made past `CrudService`. The user is
147
+ * the current one unless given; the time is now.
148
+ *
149
+ * @example
150
+ * ```typescript
151
+ * await this.auditLogService?.record({ action: 'restore', model: 'Institution', recordId: id });
152
+ * ```
153
+ */
154
+ async record(entry: Omit<AuditLogEntryInput, 'at'>): Promise<CoreAuditLogEntry> {
155
+ return (await this.store.insert(
156
+ this.toEntry({ ...entry, at: new Date(), userId: entry.userId ?? resolveAuditActorId() }, false),
157
+ )) as CoreAuditLogEntry;
158
+ }
159
+
160
+ /**
161
+ * Import existing entries (a migration from another system): each keeps its `at`. Only the entry fields are taken —
162
+ * anything else an entry carries (old or new values) is dropped. An entry without action, model, record id or a
163
+ * valid time is refused with the index it had. Answers how many entries were imported.
164
+ */
165
+ async importEntries(entries: readonly AuditLogEntryInput[]): Promise<number> {
166
+ const prepared = entries.map((entry, index) => {
167
+ try {
168
+ return this.toEntry(entry, true);
169
+ } catch (error) {
170
+ throw new Error(`Audit log import, entry ${index}: ${(error as Error).message}`, { cause: error });
171
+ }
172
+ });
173
+ for (const entry of prepared) {
174
+ await this.store.insert(entry);
175
+ }
176
+ return prepared.length;
177
+ }
178
+
179
+ /** An entry as stored — the five fields and the time, nothing else */
180
+ protected toEntry(entry: AuditLogEntryInput, requireTime: boolean): Omit<CoreAuditLogEntry, 'id'> {
181
+ const action = text(entry?.action);
182
+ const model = text(entry?.model);
183
+ const recordId = text(entry?.recordId);
184
+ if (!action || !model || !recordId) {
185
+ throw new Error('action, model and recordId are required');
186
+ }
187
+ const at = entry.at instanceof Date ? entry.at : entry.at === undefined ? undefined : new Date(entry.at);
188
+ if ((requireTime && at === undefined) || (at !== undefined && Number.isNaN(at.getTime()))) {
189
+ throw new Error(`invalid time ${JSON.stringify(entry.at)}`);
190
+ }
191
+ const fields = Array.isArray(entry.fields)
192
+ ? [...new Set(entry.fields.map(text).filter((name): name is string => !!name))].sort()
193
+ : [];
194
+ const userId = text(entry.userId);
195
+ return { action, at: at ?? new Date(), fields, model, recordId, ...(userId ? { userId } : {}) };
196
+ }
197
+
198
+ // ===================================================================================================================
199
+ // Reading
200
+ // ===================================================================================================================
201
+
202
+ /** Entries matching the filter, newest first, and how many there are in all */
203
+ async find(query: AuditLogQuery = {}): Promise<{ items: CoreAuditLogEntry[]; total: number }> {
204
+ const where: Where<CoreAuditLogEntry> = {};
205
+ for (const field of ['action', 'model', 'recordId', 'userId'] as const) {
206
+ const value = text(query[field]);
207
+ if (value) {
208
+ where[field] = value;
209
+ }
210
+ }
211
+ if (query.from || query.to) {
212
+ where.at = {
213
+ ...(query.from ? { $gte: query.from } : {}),
214
+ ...(query.to ? { $lt: query.to } : {}),
215
+ };
216
+ }
217
+ const limit = Math.min(
218
+ AUDIT_LOG_PAGE.max,
219
+ Number.isInteger(query.limit) && query.limit! > 0 ? query.limit! : AUDIT_LOG_PAGE.default,
220
+ );
221
+ const offset = Number.isInteger(query.offset) && query.offset! > 0 ? query.offset! : 0;
222
+ const [items, total] = await Promise.all([
223
+ this.store.find(where, { limit, skip: offset, sort: { at: -1 } }),
224
+ this.store.count(where),
225
+ ]);
226
+ return { items: items as CoreAuditLogEntry[], total };
227
+ }
228
+
229
+ // ===================================================================================================================
230
+ // Retention
231
+ // ===================================================================================================================
232
+
233
+ /** `auditLog.retentionDays`: `false` keeps entries for good, an invalid value → the default, never "for good" */
234
+ retentionDays(): false | number {
235
+ const value = this.config.retentionDays;
236
+ if (value === false) {
237
+ return false;
238
+ }
239
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : AUDIT_LOG_DEFAULTS.retentionDays;
240
+ }
241
+
242
+ /**
243
+ * Remove the entries older than `before` (default: `retentionDays` ago), `AUDIT_LOG_PURGE_BATCH` at a time by id.
244
+ * Runs every hour on one replica; answers how many entries were removed.
245
+ */
246
+ async purgeExpired(before?: Date): Promise<number> {
247
+ const days = this.retentionDays();
248
+ if (!before && days === false) {
249
+ return 0;
250
+ }
251
+ const limit = before ?? new Date(Date.now() - (days as number) * 86_400_000);
252
+ let removed = 0;
253
+ for (;;) {
254
+ const batch = await this.store.find({ at: { $lt: limit } }, { limit: AUDIT_LOG_PURGE_BATCH, select: ['id'] });
255
+ if (!batch.length) {
256
+ break;
257
+ }
258
+ removed += await this.store.deleteMany({ at: { $lt: limit }, id: { $in: batch.map((entry) => entry.id) } });
259
+ if (batch.length < AUDIT_LOG_PURGE_BATCH) {
260
+ break;
261
+ }
262
+ }
263
+ if (removed) {
264
+ this.logger.log(
265
+ `Audit log: ${removed} entr${removed === 1 ? 'y' : 'ies'} older than ${limit.toISOString()} removed`,
266
+ );
267
+ }
268
+ return removed;
269
+ }
270
+ }
@@ -1165,6 +1165,10 @@ export class CoreBetterAuthEmailVerificationService {
1165
1165
  );
1166
1166
  return;
1167
1167
  }
1168
+ if ((info as { queued?: unknown } | null | undefined)?.queued === true) {
1169
+ this.logger.debug(`${kind} email for ${masked} stored in the mail outbox for delivery`);
1170
+ return;
1171
+ }
1168
1172
  this.logger.debug(`${kind} email sent to ${masked}`);
1169
1173
  }
1170
1174
 
@@ -0,0 +1,88 @@
1
+ # Mail outbox
2
+
3
+ Mail that cannot go out because the SMTP server or the mail service is briefly unavailable is no longer lost. With
4
+ the outbox every mail of `EmailService` — the framework's auth mails (verification, password reset) included — is
5
+ **stored first** and delivered from the store, retried with backoff on a failure, by **exactly one replica**.
6
+
7
+ Without the outbox `EmailService` sends directly and a failed auth mail is only logged (auth mails are not awaited by
8
+ the request, so the user sees nothing).
9
+
10
+ ## Switching it on
11
+
12
+ ```typescript
13
+ // config.env.ts
14
+ mailOutbox: {}, // the defaults below
15
+ mailOutbox: { maxAttempts: 8, retryDelaySeconds: 60 },
16
+ ```
17
+
18
+ Absent `mailOutbox`: `EmailService` sends directly, as before — no model, no table, no route. `{ enabled: false }`
19
+ pre-configures.
20
+
21
+ ## How a mail travels
22
+
23
+ 1. `EmailService.sendMail()` renders the templates, applies the production `jsonTransport` guard and the Hub mailbox
24
+ (capture mode suppresses the send as before), then **stores** the rendered mail and answers at once:
25
+ `{ accepted, messageId, outboxId, queued: true, rejected }`.
26
+ 2. The replica that stored it starts a delivery run right away; every replica also looks for due mails every
27
+ `pollIntervalSeconds` (and once at boot, for mails left over from a previous run).
28
+ 3. A mail is **claimed** with one atomic statement (`updateOne`: MongoDB's `findOneAndUpdate`, SQL's
29
+ `UPDATE … RETURNING`) — of several replicas exactly one gets it. A claim older than `lockSeconds` (its replica
30
+ died mid-send) is taken over.
31
+ 4. Delivered: status `sent`, the **content is removed at once** (it may carry a reset link), recipients, subject and
32
+ times stay for `retention.sentDays`.
33
+ 5. Failed: the next attempt after `retryDelaySeconds`, doubled per attempt up to `maxRetryDelaySeconds`. After
34
+ `maxAttempts` the mail is `failed`, logged as an error (recipient masked, never the content) and kept for
35
+ `retention.failedDays`.
36
+
37
+ Every attempt carries the same Message-ID (`<entry-id.outbox@sender-domain>`). Delivery is **at least once**: a replica
38
+ that dies after the server accepted the mail and before it recorded the delivery leaves a claim another replica takes
39
+ over — the recipient may get it twice, with the same Message-ID. Keep `lockSeconds` above the SMTP timeouts.
40
+
41
+ **Not through the outbox:** a call with a transport of its own (`sendMail(…, { smtp })` — the outbox never stores
42
+ credentials and always delivers with `email.smtp`), Brevo and Mailjet template mails (sent directly; Better-Auth's
43
+ SMTP fallback after a Brevo failure does go through the outbox).
44
+
45
+ Attachments are stored with the mail: binary and streamed content as base64, `path` / `href` as they are (nodemailer
46
+ reads them at delivery, so the file must still exist then). Large attachments make large rows.
47
+
48
+ ## Storage
49
+
50
+ The framework model `CoreMailOutboxEntry` — collection `mailOutbox` on MongoDB, table `mail_outbox` on SQL — follows
51
+ `database` like every other model (MongoDB, PostgreSQL, MySQL, MariaDB).
52
+
53
+ ## Admin endpoints
54
+
55
+ | Route | |
56
+ | ----------------------------------------------- | ----------------------------------------------------------------------------------------- |
57
+ | `GET /mail-outbox?status=failed&limit=&offset=` | stored mails **without their content**, newest first, `{ items, total }` |
58
+ | `POST /mail-outbox/:id/retry` | a failed mail gets a new round of attempts; 404 when there is no failed mail with this id |
59
+
60
+ `ADMIN` only; `mailOutbox.roles` adds global roles. Path: `mailOutbox.path`. In code: `CoreMailOutboxService.list()`,
61
+ `retry()`, `deliverDue()`, `purgeExpired()`.
62
+
63
+ ## Configuration
64
+
65
+ | Key | Default | |
66
+ | ---------------------- | --------------------------- | ----------------------------------------------------------- |
67
+ | `maxAttempts` | `10` | attempts before a mail is `failed` |
68
+ | `retryDelaySeconds` | `30` | delay before the second attempt, doubled per attempt |
69
+ | `maxRetryDelaySeconds` | `3600` | upper bound of the delay |
70
+ | `pollIntervalSeconds` | `10` | how often each replica looks for due mails |
71
+ | `lockSeconds` | `900` | how long a claim holds before another replica may take over |
72
+ | `retention.sentDays` | `7` | metadata of delivered mails; `false` keeps them |
73
+ | `retention.failedDays` | `30` | failed mails; `false` keeps them |
74
+ | `roles` / `path` | `[ADMIN]` / `'mail-outbox'` | admin endpoints |
75
+
76
+ An invalid number falls back to its default. The retention purge runs every hour on one replica (a lease: Redis, else
77
+ the lease table of the default SQL source, else `cron-locks` in MongoDB).
78
+
79
+ ## Extending
80
+
81
+ `CoreModule.forRoot(env, { mailOutbox: { service, controller } })` — `service` extends `CoreMailOutboxService` (e.g.
82
+ `retryDelayMs(attempts)` for another backoff), `controller` extends `CoreMailOutboxController`.
83
+
84
+ ## Tests
85
+
86
+ `tests/mail-outbox.e2e-spec.ts` — a real SMTP server switched off and on, MongoDB and PostgreSQL: delivery after an
87
+ outage, two replicas delivering every mail once, Better-Auth's reset mail, failed mails for admins and their retry,
88
+ retention, and direct sending without the configuration.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Constants of the mail outbox (`mailOutbox` config, DEV-4433). Import-free leaf.
3
+ */
4
+
5
+ /** The framework model of the stored mails */
6
+ export const MAIL_OUTBOX_MODEL = 'CoreMailOutboxEntry';
7
+
8
+ /** Its collection on MongoDB; a SQL source keeps it as the table `mail_outbox` */
9
+ export const MAIL_OUTBOX_COLLECTION = 'mailOutbox';
10
+
11
+ /** The states of a stored mail */
12
+ export const MAIL_OUTBOX_STATUS = {
13
+ /** Gave up after `maxAttempts`; stays visible until the retention removes it */
14
+ failed: 'failed',
15
+ /** Waiting for its (next) attempt at `nextAttemptAt` */
16
+ pending: 'pending',
17
+ /** Claimed by one replica until `lockedUntil` */
18
+ sending: 'sending',
19
+ /** Delivered; its content was removed */
20
+ sent: 'sent',
21
+ } as const;
22
+
23
+ /** Defaults of `mailOutbox` */
24
+ export const MAIL_OUTBOX_DEFAULTS = {
25
+ failedDays: 30,
26
+ lockSeconds: 900,
27
+ maxAttempts: 10,
28
+ maxRetryDelaySeconds: 3600,
29
+ path: 'mail-outbox',
30
+ pollIntervalSeconds: 10,
31
+ /** How often the retention purge runs (one replica per run) */
32
+ purgeIntervalMs: 60 * 60_000,
33
+ retryDelaySeconds: 30,
34
+ sentDays: 7,
35
+ };
36
+
37
+ /** Mails claimed per delivery run, and entries removed per purge statement */
38
+ export const MAIL_OUTBOX_BATCH = 50;
39
+ export const MAIL_OUTBOX_PURGE_BATCH = 1000;
40
+
41
+ /** Longest error message stored with a failed attempt */
42
+ export const MAIL_OUTBOX_ERROR_LENGTH = 500;
@@ -0,0 +1,60 @@
1
+ import { BadRequestException, Controller, Get, NotFoundException, Param, Post, Query } from '@nestjs/common';
2
+ import { ApiOperation, ApiQuery, ApiTags } from '@nestjs/swagger';
3
+
4
+ import { Roles } from '../../common/decorators/roles.decorator.js';
5
+ import { RoleEnum } from '../../common/enums/role.enum.js';
6
+ import { SkipTenantCheck } from '../tenant/core-tenant.decorators.js';
7
+ import { CoreMailOutboxService } from './core-mail-outbox.service.js';
8
+
9
+ /** A non-negative integer from a query parameter, or `undefined` */
10
+ function parseCount(value: string | undefined, name: string): number | undefined {
11
+ if (value === undefined || value === '') {
12
+ return undefined;
13
+ }
14
+ if (!/^\d+$/.test(value)) {
15
+ throw new BadRequestException(`${name} must be a non-negative integer`);
16
+ }
17
+ return Number(value);
18
+ }
19
+
20
+ /**
21
+ * Admin endpoints of the mail outbox (`mailOutbox` config): `GET /mail-outbox` lists the stored mails WITHOUT their
22
+ * content (filter `status`: `pending`, `sending`, `sent`, `failed`; paging `limit` / `offset`), and
23
+ * `POST /mail-outbox/:id/retry` gives a failed mail a new round of attempts.
24
+ *
25
+ * ADMIN only by default; `mailOutbox.roles` adds roles (applied at boot onto this class — a subclass that re-declares
26
+ * `@Roles()` keeps its own). Global roles (`@SkipTenantCheck()`): the outbox spans tenants.
27
+ */
28
+ @ApiTags('mail-outbox')
29
+ @Controller('mail-outbox')
30
+ @Roles(RoleEnum.ADMIN)
31
+ @SkipTenantCheck()
32
+ export class CoreMailOutboxController {
33
+ constructor(protected readonly mailOutboxService: CoreMailOutboxService) {}
34
+
35
+ @ApiOperation({ summary: 'Stored mails without their content, newest first' })
36
+ @ApiQuery({ enum: ['pending', 'sending', 'sent', 'failed'], name: 'status', required: false })
37
+ @ApiQuery({ name: 'limit', required: false })
38
+ @ApiQuery({ name: 'offset', required: false })
39
+ @Get()
40
+ async list(@Query('status') status?: string, @Query('limit') limit?: string, @Query('offset') offset?: string) {
41
+ if (status !== undefined && status !== '' && !['failed', 'pending', 'sending', 'sent'].includes(status)) {
42
+ throw new BadRequestException('status must be one of pending, sending, sent, failed');
43
+ }
44
+ return this.mailOutboxService.list({
45
+ limit: parseCount(limit, 'limit'),
46
+ offset: parseCount(offset, 'offset'),
47
+ status: (status || undefined) as any,
48
+ });
49
+ }
50
+
51
+ @ApiOperation({ summary: 'Give a failed mail a new round of attempts' })
52
+ @Post(':id/retry')
53
+ async retry(@Param('id') id: string) {
54
+ const entry = await this.mailOutboxService.retry(id);
55
+ if (!entry) {
56
+ throw new NotFoundException('No failed mail with this id');
57
+ }
58
+ return entry;
59
+ }
60
+ }