@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,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,12 @@ 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`. The path always names the source core, also
536
+ while a build lies in `dist/`: `bin/migrate.js` then runs the compiled CLI, and until 12.12.1 the path was computed from
537
+ its location, so such a migration imported `'../dist/src/core/index.js'`.
533
538
 
534
539
  ### TypeScript Loader
535
540
 
@@ -62,6 +62,16 @@ 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
+ *
71
+ * The path always names the SOURCE core (`<project>/src/core`), also when this CLI runs compiled: `bin/migrate.js`
72
+ * prefers a build in `dist/`, and its location (`dist/src/core`) put `'../dist/src/core/index.js'` into every migration
73
+ * created while a build was present (`sourceCoreRoot()`).
74
+ *
65
75
  * @param migrationsDir - Directory the migration is written to, absolute or relative to `cwd`
66
76
  * @param cwd - Project directory the package is resolved from
67
77
  * @param coreRoot - Root of the core this CLI belongs to
@@ -80,8 +90,56 @@ export function vendoredFrameworkSpecifier(
80
90
  if (!['index.ts', 'index.js'].some((entry) => fs.existsSync(path.join(coreRoot, entry)))) {
81
91
  return undefined;
82
92
  }
83
- const relativePath = path.relative(path.resolve(cwd, migrationsDir), coreRoot).split(path.sep).join('/');
84
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
93
+ const absoluteMigrationsDir = path.resolve(cwd, migrationsDir);
94
+ const relativePath = path.relative(absoluteMigrationsDir, sourceCoreRoot(coreRoot)).split(path.sep).join('/');
95
+ const directory = relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
96
+ return isEsModuleScope(absoluteMigrationsDir) ? `${directory}/index.js` : directory;
97
+ }
98
+
99
+ /**
100
+ * The source core a compiled core was built from: `<project>/dist/src/core` → `<project>/src/core` (the layout
101
+ * `lt fullstack convert-mode` builds), `<project>/dist/core` → `<project>/src/core` (a build with `rootDir: 'src'`).
102
+ * A migration lives next to the sources, imports the source core, and is compiled together with it, so the relative
103
+ * path also holds in the build. Without a source core with an `index.ts` beside the build (a deployed image), the core
104
+ * this CLI runs from is the answer.
105
+ */
106
+ function sourceCoreRoot(coreRoot: string): string {
107
+ if (fs.existsSync(path.join(coreRoot, 'index.ts'))) {
108
+ return coreRoot;
109
+ }
110
+ const segments = coreRoot.split(path.sep);
111
+ for (let index = segments.length - 1; index >= 0; index--) {
112
+ if (segments[index] !== 'dist') {
113
+ continue;
114
+ }
115
+ for (const replacement of [[], ['src']]) {
116
+ const candidate = [...segments.slice(0, index), ...replacement, ...segments.slice(index + 1)].join(path.sep);
117
+ if (candidate && fs.existsSync(path.join(candidate, 'index.ts'))) {
118
+ return candidate;
119
+ }
120
+ }
121
+ }
122
+ return coreRoot;
123
+ }
124
+
125
+ /**
126
+ * Whether files in `directory` are ES modules: the `type` of the nearest `package.json` above it, as Node decides.
127
+ * No `package.json`, or one that cannot be read, means CommonJS (Node's default).
128
+ */
129
+ function isEsModuleScope(directory: string): boolean {
130
+ for (let dir = directory; ; dir = path.dirname(dir)) {
131
+ const manifest = path.join(dir, 'package.json');
132
+ if (fs.existsSync(manifest)) {
133
+ try {
134
+ return JSON.parse(fs.readFileSync(manifest, 'utf-8'))?.type === 'module';
135
+ } catch {
136
+ return false;
137
+ }
138
+ }
139
+ if (path.dirname(dir) === dir) {
140
+ return false;
141
+ }
142
+ }
85
143
  }
86
144
 
87
145
  /**