@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
@@ -10,6 +10,14 @@ import { mergePlain, prepareServiceOptionsForCreate } from '../helpers/input.hel
10
10
  import { ServiceOptions } from '../interfaces/service-options.interface.js';
11
11
  import type { FindOptions, Where } from '../persistence/data-store.interface.js';
12
12
  import { getModelDescriptor } from '../persistence/model-metadata.registry.js';
13
+ import {
14
+ type AuditAction,
15
+ auditChangedFields,
16
+ auditInputFields,
17
+ auditSnapshot,
18
+ getAuditLogListener,
19
+ } from '../persistence/audit-log.registry.js';
20
+ import { resolveAuditActorId } from '../persistence/policies/audit.policy.js';
13
21
  import { getSyncAccessListener } from '../persistence/sync-access.registry.js';
14
22
  import { UnsupportedCapabilityError } from '../persistence/unsupported-capability.error.js';
15
23
  import { isDuplicateIdError } from '../persistence/mongoose-data-store.js';
@@ -84,43 +92,44 @@ export abstract class CrudService<
84
92
  async create(input: PlainObject<CreateInput>, serviceOptions?: ServiceOptions): Promise<Model> {
85
93
  serviceOptions = prepareServiceOptionsForCreate(serviceOptions);
86
94
  return this.process(
87
- async (data) => {
88
- const currentUserId = serviceOptions?.currentUser?.id;
89
- const createId = serviceOptions?.createId;
90
- if (this.usesNeutralStore) {
91
- return this.syncChanged(
92
- await this.dataStore.insert({
93
- ...data.input,
94
- ...(createId === undefined || createId === null ? {} : { id: createId }),
95
- createdBy: currentUserId,
96
- updatedBy: currentUserId,
97
- } as any),
98
- );
99
- }
100
- const build = (id?: string) =>
101
- new (this.mainDbModel as MongooseModel<Document & Model>)({
102
- ...data.input,
103
- ...(id === undefined ? {} : { _id: id }),
104
- createdBy: currentUserId,
105
- updatedBy: currentUserId,
106
- });
107
- const sync = this.mongoSync;
108
- if (!sync) {
109
- return build(createId ?? undefined).save();
110
- }
111
- // A synchronized model keeps a client's id in its format and replaces a taken server id (plan §3.3, E6)
112
- const supplied = createId ?? suppliedId(data.input ?? {});
113
- if (supplied !== undefined && supplied !== null) {
114
- return this.syncChanged(
115
- await build(assertClientId(supplied, sync.idFormat, this.mainDbModel.modelName)).save(),
116
- );
117
- }
118
- return this.syncChanged(await insertWithServerId(sync.idFormat, (id) => build(id).save(), isDuplicateIdError));
119
- },
95
+ async (data) => this.auditCreated(await this.createInProcess(data, serviceOptions), data.input, serviceOptions),
120
96
  { input, serviceOptions },
121
97
  );
122
98
  }
123
99
 
100
+ /** The write of `create()`, inside `process()` */
101
+ protected async createInProcess(data: { input?: any }, serviceOptions?: ServiceOptions): Promise<any> {
102
+ const currentUserId = serviceOptions?.currentUser?.id;
103
+ const createId = serviceOptions?.createId;
104
+ if (this.usesNeutralStore) {
105
+ return this.syncChanged(
106
+ await this.dataStore.insert({
107
+ ...data.input,
108
+ ...(createId === undefined || createId === null ? {} : { id: createId }),
109
+ createdBy: currentUserId,
110
+ updatedBy: currentUserId,
111
+ } as any),
112
+ );
113
+ }
114
+ const build = (id?: string) =>
115
+ new (this.mainDbModel as MongooseModel<Document & Model>)({
116
+ ...data.input,
117
+ ...(id === undefined ? {} : { _id: id }),
118
+ createdBy: currentUserId,
119
+ updatedBy: currentUserId,
120
+ });
121
+ const sync = this.mongoSync;
122
+ if (!sync) {
123
+ return build(createId ?? undefined).save();
124
+ }
125
+ // A synchronized model keeps a client's id in its format and replaces a taken server id (plan §3.3, E6)
126
+ const supplied = createId ?? suppliedId(data.input ?? {});
127
+ if (supplied !== undefined && supplied !== null) {
128
+ return this.syncChanged(await build(assertClientId(supplied, sync.idFormat, this.mainDbModel.modelName)).save());
129
+ }
130
+ return this.syncChanged(await insertWithServerId(sync.idFormat, (id) => build(id).save(), isDuplicateIdError));
131
+ }
132
+
124
133
  /**
125
134
  * Create item without checks or restrictions
126
135
  * Warning: Disables the handling of rights and restrictions!
@@ -718,6 +727,7 @@ export abstract class CrudService<
718
727
  // The same write as on MongoDB: the stored record merged with the input, written back whole — minus
719
728
  // the id, which never changes, and the update time, which the store stamps
720
729
  const before = this.syncAccessSnapshot(stored);
730
+ const auditBefore = this.auditBefore(stored, data.input);
721
731
  const merged = mergePlain(stored, data.input, { updatedBy: serviceOptions?.currentUser?.id });
722
732
  const { _id: _mongoId, id: _id, updatedAt: _updatedAt, ...patch } = merged as Record<string, any>;
723
733
  const updated =
@@ -729,6 +739,7 @@ export abstract class CrudService<
729
739
  if (updated) {
730
740
  await this.reportSyncAccessMove(before, merged);
731
741
  this.reportSyncChange(before, merged);
742
+ await this.auditUpdated(id, auditBefore, merged, serviceOptions);
732
743
  }
733
744
  return updated;
734
745
  },
@@ -744,6 +755,7 @@ export abstract class CrudService<
744
755
  async (data) => {
745
756
  const currentUserId = serviceOptions?.currentUser?.id;
746
757
  const before = this.syncAccessSnapshot(dbObject);
758
+ const auditBefore = this.auditBefore(dbObject, data.input);
747
759
  const merged = mergePlain(dbObject, data.input, { updatedBy: currentUserId });
748
760
  const query =
749
761
  expectedVersion === undefined
@@ -760,6 +772,7 @@ export abstract class CrudService<
760
772
  }
761
773
  await this.reportSyncAccessMove(before, merged);
762
774
  this.reportSyncChange(before, merged);
775
+ await this.auditUpdated(id, auditBefore, merged, serviceOptions);
763
776
  return updated;
764
777
  },
765
778
  { dbObject, input, serviceOptions },
@@ -801,6 +814,7 @@ export abstract class CrudService<
801
814
  async () => {
802
815
  await this.removeOrTombstone(id, expectedVersion);
803
816
  this.reportSyncChange(stored);
817
+ await this.reportAudit('delete', id, [], serviceOptions);
804
818
  return stored;
805
819
  },
806
820
  { dbObject: stored, serviceOptions },
@@ -824,12 +838,93 @@ export abstract class CrudService<
824
838
  } else {
825
839
  await this.mainDbModel.findByIdAndDelete(id).exec();
826
840
  }
841
+ await this.reportAudit('delete', id, [], serviceOptions);
827
842
  return dbObject;
828
843
  },
829
844
  { dbObject, serviceOptions },
830
845
  );
831
846
  }
832
847
 
848
+ // -- audit log (`auditLog` config, DEV-4432) ---------------------------------------------------------------
849
+
850
+ /** The audit log's listener when it logs this model; `undefined` otherwise — one check without the module */
851
+ protected get auditListener() {
852
+ const listener = getAuditLogListener();
853
+ return listener?.isAudited(this.auditModelName, this.mainModelConstructor) ? listener : undefined;
854
+ }
855
+
856
+ /** The name the audit log knows this service's model by: the registered model name */
857
+ protected get auditModelName(): string {
858
+ return this.dataStore?.modelName ?? this.mainDbModel?.modelName ?? this.mainModelConstructor?.name;
859
+ }
860
+
861
+ /** The stored values of the fields an update names, compared after the write; `undefined` when nobody logs */
862
+ protected auditBefore(stored: Record<string, any> | undefined, input: unknown): Map<string, string> | undefined {
863
+ return this.auditListener ? auditSnapshot(stored, input as Record<string, any>) : undefined;
864
+ }
865
+
866
+ /** Log a created record with the names of the fields its input set; answers the record */
867
+ protected async auditCreated<R>(created: R, input: unknown, serviceOptions?: ServiceOptions): Promise<R> {
868
+ const record = created as Record<string, any>;
869
+ const id = record?.id ?? record?._id;
870
+ if (id !== undefined && id !== null) {
871
+ await this.reportAudit(
872
+ 'create',
873
+ String(getStringIds(id)),
874
+ auditInputFields(input as Record<string, any>),
875
+ serviceOptions,
876
+ );
877
+ }
878
+ return created;
879
+ }
880
+
881
+ /** Log an update with the names of the fields whose value changed; an update that changed nothing is not logged */
882
+ protected async auditUpdated(
883
+ id: string,
884
+ before: Map<string, string> | undefined,
885
+ written: Record<string, any>,
886
+ serviceOptions?: ServiceOptions,
887
+ ): Promise<void> {
888
+ if (!before) {
889
+ return;
890
+ }
891
+ const fields = auditChangedFields(before, written);
892
+ if (fields.length) {
893
+ await this.reportAudit('update', id, fields, serviceOptions);
894
+ }
895
+ }
896
+
897
+ /**
898
+ * Hand a successful write to the audit log — names only, never values. A no-op without the module or for a model it
899
+ * does not log; a failure is logged, never thrown: the write it follows has happened.
900
+ */
901
+ protected async reportAudit(
902
+ action: AuditAction,
903
+ recordId: string,
904
+ fields: string[],
905
+ serviceOptions?: ServiceOptions,
906
+ ): Promise<void> {
907
+ const listener = this.auditListener;
908
+ if (!listener) {
909
+ return;
910
+ }
911
+ const model = this.auditModelName;
912
+ try {
913
+ await listener.recordWrite({
914
+ action,
915
+ fields,
916
+ model,
917
+ recordId: String(getStringIds(recordId)),
918
+ userId: serviceOptions?.currentUser?.id ? String(serviceOptions.currentUser.id) : resolveAuditActorId(),
919
+ });
920
+ } catch (error) {
921
+ Logger.error(
922
+ `Audit log entry for ${action} of ${model} ${recordId} not written: ${(error as Error)?.message ?? error}`,
923
+ this.constructor.name,
924
+ );
925
+ }
926
+ }
927
+
833
928
  // -- synchronized models (`@PersistedModel({ sync })`) ------------------------------------------------------
834
929
 
835
930
  /** The sync declaration of the main model on its MongoDB path, read from the Mongoose schema */
@@ -9,6 +9,7 @@ import { isNonEmptyString, isTrue, returnFalse } from '../helpers/input.helper.j
9
9
  import { MailTransportOptions } from '../interfaces/server-options.interface.js';
10
10
  import { HUB_EMAIL_CAPTURE } from '../../modules/hub/hub.constants.js';
11
11
  import { ConfigService } from './config.service.js';
12
+ import { getMailOutbox, type QueuedMailAttachment, type QueuedSmtpMail } from './mail-outbox.registry.js';
12
13
  import { TemplateService } from './template.service.js';
13
14
  import type { IHubEmailCapture } from '../../modules/hub/interfaces/hub-config.interface.js';
14
15
 
@@ -230,17 +231,28 @@ export class EmailService implements OnModuleDestroy {
230
231
  }
231
232
  }
232
233
 
233
- // Reuse transporter if SMTP config hasn't changed (avoids creating new connections per email)
234
- // Use hash instead of raw JSON to avoid keeping credentials as a string in memory
235
- const smtpKey = createHash('sha256').update(JSON.stringify(smtp)).digest('hex');
236
- if (!this.cachedTransporter || this.cachedSmtpConfig !== smtpKey) {
237
- this.cachedTransporter = createTransport(smtp);
238
- this.cachedSmtpConfig = smtpKey;
239
- }
240
-
241
234
  // Send mail; without a Reply-To the header is left out entirely
242
235
  const replyTo = this.resolveReplyTo(config.replyTo);
243
- return this.cachedTransporter.sendMail({
236
+ const to = Array.isArray(recipients) ? recipients : [recipients];
237
+
238
+ // Mail outbox (`mailOutbox`, DEV-4433): stored first, delivered from the store and retried on a failure. A call with
239
+ // a transport of its own (`config.smtp`) is sent directly: the outbox delivers with the configured transport and
240
+ // never stores credentials.
241
+ const outbox = config.smtp === undefined ? getMailOutbox() : undefined;
242
+ if (outbox) {
243
+ const receipt = await outbox.enqueue({
244
+ ...(attachments?.length ? { attachments: await this.serializeAttachments(attachments) } : {}),
245
+ from: `"${senderName}" <${senderEmail}>`,
246
+ ...(html === undefined ? {} : { html }),
247
+ ...(replyTo ? { replyTo } : {}),
248
+ subject,
249
+ ...(text === undefined ? {} : { text }),
250
+ to,
251
+ });
252
+ return { accepted: to, messageId: receipt.messageId, outboxId: receipt.id, queued: true, rejected: [] };
253
+ }
254
+
255
+ return this.transporterFor(smtp).sendMail({
244
256
  attachments,
245
257
  from: `"${senderName}" <${senderEmail}>`,
246
258
  html,
@@ -250,4 +262,84 @@ export class EmailService implements OnModuleDestroy {
250
262
  to: recipients,
251
263
  });
252
264
  }
265
+
266
+ /**
267
+ * Deliver a mail the outbox stored, with the configured transport (`email.smtp`) — no template, no Hub capture, no
268
+ * outbox. Throws what the transport throws; the outbox retries. `messageId` is the same on every attempt, so a mail
269
+ * delivered twice after a takeover can be recognised as one.
270
+ */
271
+ public async deliverQueuedMail(mail: QueuedSmtpMail, messageId: string): Promise<any> {
272
+ const smtp = this.configService.get('email.smtp');
273
+ const env = this.configService.getFastButReadOnly<string>('env');
274
+ if (
275
+ (env === 'production' || env === 'staging') &&
276
+ typeof smtp === 'object' &&
277
+ smtp &&
278
+ (smtp as any).jsonTransport
279
+ ) {
280
+ throw new Error('JSONTransport (jsonTransport: true) is not permitted in production/staging environments.');
281
+ }
282
+ this.warnOnImpossibleSmtpTlsCombination(smtp);
283
+ return this.transporterFor(smtp).sendMail({
284
+ ...(mail.attachments?.length ? { attachments: mail.attachments as Attachment[] } : {}),
285
+ from: mail.from,
286
+ ...(mail.html === undefined ? {} : { html: mail.html }),
287
+ messageId,
288
+ ...(mail.replyTo ? { replyTo: mail.replyTo } : {}),
289
+ subject: mail.subject,
290
+ ...(mail.text === undefined ? {} : { text: mail.text }),
291
+ to: mail.to,
292
+ });
293
+ }
294
+
295
+ /**
296
+ * The transporter for a transport configuration, reused as long as the configuration does not change (no new SMTP
297
+ * connection per mail). Keyed by a hash, so the credentials are not kept as a string in memory.
298
+ */
299
+ protected transporterFor(smtp: MailTransportOptions): Transporter {
300
+ const smtpKey = createHash('sha256').update(JSON.stringify(smtp)).digest('hex');
301
+ if (!this.cachedTransporter || this.cachedSmtpConfig !== smtpKey) {
302
+ this.cachedTransporter = createTransport(smtp);
303
+ this.cachedSmtpConfig = smtpKey;
304
+ }
305
+ return this.cachedTransporter;
306
+ }
307
+
308
+ /**
309
+ * Attachments in a form the outbox can store: binary and streamed content as base64, text as it is, a `path` /
310
+ * `href` kept (nodemailer reads it at delivery, so the file must still exist then).
311
+ */
312
+ protected async serializeAttachments(attachments: Attachment[]): Promise<QueuedMailAttachment[]> {
313
+ const serialized: QueuedMailAttachment[] = [];
314
+ for (const attachment of attachments) {
315
+ const entry: QueuedMailAttachment = {
316
+ ...(attachment.cid ? { cid: attachment.cid } : {}),
317
+ ...(attachment.contentType ? { contentType: attachment.contentType } : {}),
318
+ ...(attachment.filename !== undefined ? { filename: attachment.filename } : {}),
319
+ };
320
+ const content = attachment.content as unknown;
321
+ if (Buffer.isBuffer(content)) {
322
+ entry.content = content.toString('base64');
323
+ entry.encoding = 'base64';
324
+ } else if (typeof content === 'string') {
325
+ entry.content = content;
326
+ if (attachment.encoding) {
327
+ entry.encoding = attachment.encoding;
328
+ }
329
+ } else if (content && typeof (content as any)[Symbol.asyncIterator] === 'function') {
330
+ const chunks: Buffer[] = [];
331
+ for await (const chunk of content as AsyncIterable<Buffer | string>) {
332
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
333
+ }
334
+ entry.content = Buffer.concat(chunks).toString('base64');
335
+ entry.encoding = 'base64';
336
+ } else if (typeof attachment.path === 'string') {
337
+ entry.path = attachment.path;
338
+ } else if (typeof (attachment as any).href === 'string') {
339
+ entry.path = (attachment as any).href;
340
+ }
341
+ serialized.push(entry);
342
+ }
343
+ return serialized;
344
+ }
253
345
  }
@@ -0,0 +1,123 @@
1
+ import { Logger } from '@nestjs/common';
2
+
3
+ import { CRON_LOCK_COLLECTION, cronMongoLocks, defaultSqlLockStore } from '../persistence/infrastructure-locks.js';
4
+ import type { LockStore } from '../persistence/lock-store.interface.js';
5
+ import { getCronJobsInfrastructure } from './core-cron-jobs.registry.js';
6
+
7
+ import type { CoreRedisService } from './core-redis.service.js';
8
+
9
+ /**
10
+ * The lease store of a framework job that must run on ONE replica per interval: Redis when configured, else the lease
11
+ * table of the default SQL source, else `cron-locks` in MongoDB — the order of the cron leases. `undefined` without
12
+ * any: the job then runs on every replica, which a job written for it tolerates (it only deletes what is past its
13
+ * horizon, or claims what it works on atomically).
14
+ *
15
+ * The keys are prefixed with `namespace`, so the jobs sharing one lease store cannot collide.
16
+ */
17
+ export async function frameworkJobLeaseStore(
18
+ redisService: CoreRedisService | undefined,
19
+ namespace: string,
20
+ ): Promise<LockStore | undefined> {
21
+ if (redisService?.enabled) {
22
+ const client = redisService.getClient();
23
+ const key = (name: string) => redisService.key('job-lock', namespace, name);
24
+ return {
25
+ release: async (name, owner) => {
26
+ if ((await client.get(key(name))) !== owner) {
27
+ return false;
28
+ }
29
+ await client.del(key(name));
30
+ return true;
31
+ },
32
+ renew: async (name, owner, ttlSeconds) =>
33
+ (await client.get(key(name))) === owner && (await client.expire(key(name), ttlSeconds)) === 1,
34
+ tryAcquire: async (name, owner, ttlSeconds) =>
35
+ (await client.set(key(name), owner, 'EX', ttlSeconds, 'NX')) === 'OK',
36
+ };
37
+ }
38
+ const sqlLocks = await defaultSqlLockStore(namespace);
39
+ if (sqlLocks) {
40
+ return sqlLocks;
41
+ }
42
+ const connection = getCronJobsInfrastructure().connection;
43
+ if (!connection?.db) {
44
+ return undefined;
45
+ }
46
+ const locks = cronMongoLocks(connection.db.collection(CRON_LOCK_COLLECTION));
47
+ const key = (name: string) => `${namespace}:${name}`;
48
+ return {
49
+ release: (name, owner) => locks.release(key(name), owner),
50
+ renew: (name, owner, ttlSeconds) => locks.renew(key(name), owner, ttlSeconds),
51
+ tryAcquire: (name, owner, ttlSeconds) => locks.tryAcquire(key(name), owner, ttlSeconds),
52
+ };
53
+ }
54
+
55
+ /** Options of a {@link LeasedInterval} */
56
+ export interface LeasedIntervalOptions {
57
+ /** How often the job runs */
58
+ intervalMs: number;
59
+ /** The lease store; `undefined` runs the job on every replica */
60
+ lease: () => Promise<LockStore | undefined>;
61
+ /** Lease name and log label */
62
+ name: string;
63
+ /** The work; a throw is logged and the job tried again at the next interval */
64
+ run: () => Promise<unknown>;
65
+ }
66
+
67
+ /**
68
+ * A framework job that runs at once and then every `intervalMs`, on one replica per run: it takes a lease for the
69
+ * interval and never releases it, so the next run on any replica takes it once it expired. A run that is still busy
70
+ * when the interval elapses is skipped, not queued. Fails open: a lease store that cannot be reached is logged and the
71
+ * run tried again later. `stop()` waits for a running run, so a shutdown does not cut one off.
72
+ */
73
+ export class LeasedInterval {
74
+ protected readonly logger: Logger;
75
+ protected readonly owner = `${process.pid}:${Math.random().toString(36).slice(2)}`;
76
+ protected running?: Promise<unknown>;
77
+ protected timer?: ReturnType<typeof setInterval>;
78
+
79
+ constructor(protected readonly options: LeasedIntervalOptions) {
80
+ this.logger = new Logger(options.name);
81
+ }
82
+
83
+ /** Run now and every interval; a second call is a no-op */
84
+ start(): void {
85
+ if (this.timer) {
86
+ return;
87
+ }
88
+ // tick() cannot reject: leasedRun() logs every failure itself
89
+ void this.tick();
90
+ this.timer = setInterval(() => void this.tick(), this.options.intervalMs);
91
+ this.timer.unref?.();
92
+ }
93
+
94
+ /** Stop the timer and wait for a running run */
95
+ async stop(): Promise<void> {
96
+ if (this.timer) {
97
+ clearInterval(this.timer);
98
+ this.timer = undefined;
99
+ }
100
+ await this.running?.catch(() => undefined);
101
+ }
102
+
103
+ /** One run under the lease (also called by tests) */
104
+ tick(): Promise<unknown> {
105
+ this.running ??= this.leasedRun().finally(() => {
106
+ this.running = undefined;
107
+ });
108
+ return this.running;
109
+ }
110
+
111
+ protected async leasedRun(): Promise<void> {
112
+ try {
113
+ const locks = await this.options.lease();
114
+ const ttlSeconds = Math.max(1, Math.floor(this.options.intervalMs / 1000));
115
+ if (locks && !(await locks.tryAcquire(this.options.name, this.owner, ttlSeconds))) {
116
+ return;
117
+ }
118
+ await this.options.run();
119
+ } catch (error) {
120
+ this.logger.warn(`${this.options.name} failed, trying again later: ${(error as Error)?.message ?? error}`);
121
+ }
122
+ }
123
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * How `EmailService` hands a mail to the outbox (`mailOutbox` config, DEV-4433) without importing the module: the
3
+ * module registers itself here when it starts. Nothing is registered without a `mailOutbox` configuration, and
4
+ * `EmailService` then sends directly, as before.
5
+ *
6
+ * Import-free leaf (types only).
7
+ */
8
+
9
+ /** An attachment as stored: serializable, its content base64 when it was binary */
10
+ export interface QueuedMailAttachment {
11
+ cid?: string;
12
+ content?: string;
13
+ contentType?: string;
14
+ encoding?: string;
15
+ filename?: string | false;
16
+ /** A file path or URL nodemailer reads at delivery — it must still exist then */
17
+ path?: string;
18
+ }
19
+
20
+ /** A rendered SMTP mail as the outbox stores it — everything nodemailer needs except the transport */
21
+ export interface QueuedSmtpMail {
22
+ attachments?: QueuedMailAttachment[];
23
+ from: string;
24
+ html?: string;
25
+ replyTo?: string;
26
+ subject: string;
27
+ text?: string;
28
+ to: string[];
29
+ }
30
+
31
+ /** What the outbox answers for a stored mail */
32
+ export interface QueuedMailReceipt {
33
+ /** The outbox entry */
34
+ id: string;
35
+ /** The Message-ID the mail is delivered with — the same on every attempt */
36
+ messageId: string;
37
+ }
38
+
39
+ export interface MailOutbox {
40
+ /** Store a rendered mail for delivery; resolves once it is stored, not once it is delivered */
41
+ enqueue(mail: QueuedSmtpMail): Promise<QueuedMailReceipt>;
42
+ }
43
+
44
+ let outbox: MailOutbox | undefined;
45
+
46
+ /** Set by the mail outbox module when it starts, cleared when it stops */
47
+ export function setMailOutbox(value: MailOutbox | undefined): void {
48
+ outbox = value;
49
+ }
50
+
51
+ export function getMailOutbox(): MailOutbox | undefined {
52
+ return outbox;
53
+ }
@@ -0,0 +1,95 @@
1
+ # Audit log
2
+
3
+ Records who created, changed, deleted or restored which record, and which fields a change touched — **by name only,
4
+ never a value**. Nothing a value carries (a password hash, an e-mail address, an IBAN, a health record) can reach the
5
+ log: the entry model has no field for it, and `CrudService` hands over names only.
6
+
7
+ ## Switching it on
8
+
9
+ ```typescript
10
+ // config.env.ts
11
+ auditLog: {
12
+ models: ['Institution', 'Event'], // and/or @Audited() on the model classes
13
+ retentionDays: 365, // default; false keeps entries for good
14
+ },
15
+ ```
16
+
17
+ ```typescript
18
+ import { Audited } from '@lenne.tech/nest-server';
19
+
20
+ @Audited()
21
+ @ObjectType()
22
+ @Schema({ timestamps: true })
23
+ export class Institution extends CorePersistenceModel { … }
24
+ ```
25
+
26
+ Absent `auditLog`: no model, no collection or table, no route, and no listener `CrudService` reports to — every write
27
+ costs one `undefined` check. `{ enabled: false }` pre-configures.
28
+
29
+ ## What is logged
30
+
31
+ | Write | Entry |
32
+ | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
33
+ | `CrudService.create()` (also `createForce` / `createRaw`, and `CoreUserService.create()`) | `create`, the fields the input set |
34
+ | `CrudService.update()` (and variants) | `update`, the fields whose value changed — an update that changed nothing leaves no entry |
35
+ | `CrudService.delete()` (and variants; a synchronized model's tombstone too) | `delete`, no fields |
36
+ | `CoreAuditLogService.record({ action, model, recordId, fields? })` | anything a project does itself — a restore, an export |
37
+
38
+ Each entry: `action`, `model` (the registered model name), `recordId`, `fields` (sorted names), `userId` (the current
39
+ user; absent for system work — cron, migration, seed) and `at`. Bookkeeping fields (`updatedAt`, `updatedBy`, `id`,
40
+ `version`, …) never count as changed.
41
+
42
+ **Not logged:** writes past `CrudService` — direct Mongoose calls, the data store (`this.dataStore.*`, `@InjectStore()`),
43
+ `pushToArray()` / `pullFromArray()`, native and raw access, migrations. A project that writes a logged model that way
44
+ calls `record()` itself.
45
+
46
+ A failed audit write is logged as an error and never fails the user's write, which has already happened.
47
+
48
+ ```typescript
49
+ // A project's restore of a soft-deleted record
50
+ constructor(@Optional() protected readonly auditLog?: CoreAuditLogService) { … }
51
+
52
+ await this.auditLog?.record({ action: 'restore', fields: ['deletedAt'], model: 'Institution', recordId: id });
53
+ ```
54
+
55
+ ## Storage
56
+
57
+ The framework model `CoreAuditLogEntry` — collection `auditLogEntries` on MongoDB, table `audit_log_entries` on SQL —
58
+ follows `database` like every other model (MongoDB, PostgreSQL, MySQL, MariaDB). It is not tenant-scoped: the log
59
+ spans tenants and is read by platform administrators.
60
+
61
+ ## Reading
62
+
63
+ `GET /audit-log` (path: `auditLog.path`) — filters `model`, `recordId`, `userId`, `action`, `from` (inclusive), `to`
64
+ (exclusive; ISO date or ms timestamp), paging `limit` (default 50, at most 500) and `offset`. Newest first.
65
+ Answers `{ items, total }`.
66
+
67
+ Readable by `ADMIN`; `auditLog.roles` adds roles. The roles are global roles (`user.roles`), the route carries
68
+ `@SkipTenantCheck()`. REST only. In code: `CoreAuditLogService.find(query)`.
69
+
70
+ ## Retention
71
+
72
+ Entries older than `retentionDays` (default 365) are removed every hour, on one replica per run (a lease: Redis, else
73
+ the lease table of the default SQL source, else `cron-locks` in MongoDB), 1000 at a time. `false` keeps entries for
74
+ good; an invalid value falls back to 365, never to "for good". `purgeExpired(before?)` runs it by hand.
75
+
76
+ ## Importing entries of another system
77
+
78
+ ```typescript
79
+ await auditLogService.importEntries([
80
+ { action: 'update', at: '2025-03-01T10:00:00Z', fields: ['name'], model: 'Institution', recordId: id, userId },
81
+ ]);
82
+ ```
83
+
84
+ Every entry keeps its `at`. Only the entry fields are taken — anything else an entry carries (old or new values) is
85
+ dropped. An entry without action, model, record id or a valid time is refused with its index.
86
+
87
+ ## Extending
88
+
89
+ `CoreModule.forRoot(env, { auditLog: { service, controller } })` — `service` extends `CoreAuditLogService` (e.g.
90
+ `isAudited(model, modelClass)` to decide at runtime), `controller` extends `CoreAuditLogController`.
91
+
92
+ ## Tests
93
+
94
+ `tests/audit-log.e2e-spec.ts` — the reference `/users` routes on MongoDB and PostgreSQL: entries per write, no values,
95
+ admin-only reading, retention, import, and nothing registered without the configuration.
@@ -0,0 +1,27 @@
1
+ import { AUDITED_METADATA } from './core-audit-log.constants.js';
2
+
3
+ /**
4
+ * Log every write of this model through `CrudService` in the audit log (`auditLog` config, DEV-4432): who created,
5
+ * changed or deleted which record, and which fields a change touched — names only, never values. Without an
6
+ * `auditLog` configuration the decorator does nothing. A subclass of an audited model is audited too.
7
+ *
8
+ * The alternative to the decorator is `auditLog.models: ['<ModelName>']` in the configuration.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * @Audited()
13
+ * @ObjectType()
14
+ * @Schema({ timestamps: true })
15
+ * export class Institution extends CorePersistenceModel { … }
16
+ * ```
17
+ */
18
+ export function Audited(): ClassDecorator {
19
+ return (target) => {
20
+ Reflect.defineMetadata(AUDITED_METADATA, true, target);
21
+ };
22
+ }
23
+
24
+ /** Whether the class (or a parent class) carries `@Audited()` */
25
+ export function isAuditedModelClass(modelClass: Function | undefined): boolean {
26
+ return !!modelClass && Reflect.getMetadata(AUDITED_METADATA, modelClass) === true;
27
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Constants of the audit log (`auditLog` config, DEV-4432). Import-free leaf.
3
+ */
4
+
5
+ /** The framework model of the entries */
6
+ export const AUDIT_LOG_MODEL = 'CoreAuditLogEntry';
7
+
8
+ /** Its collection on MongoDB; a SQL source keeps it as the table `audit_log_entries` */
9
+ export const AUDIT_LOG_COLLECTION = 'auditLogEntries';
10
+
11
+ /** Metadata key of `@Audited()` on a model class */
12
+ export const AUDITED_METADATA = 'lt:audit-log:audited';
13
+
14
+ /** Defaults of `auditLog` */
15
+ export const AUDIT_LOG_DEFAULTS = {
16
+ /** Route prefix of the read endpoint */
17
+ path: 'audit-log',
18
+ /** How often expired entries are removed (one replica per run) */
19
+ purgeIntervalMs: 60 * 60_000,
20
+ /** Days an entry is kept */
21
+ retentionDays: 365,
22
+ };
23
+
24
+ /** Entries removed per statement by the purge — one `DELETE … WHERE at < ?` would lock every row it passes */
25
+ export const AUDIT_LOG_PURGE_BATCH = 1000;
26
+
27
+ /** Page size of the read endpoint: default and upper bound */
28
+ export const AUDIT_LOG_PAGE = { default: 50, max: 500 };